Compare commits
89 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ed644384cc | |||
| ee613db05b | |||
| dc3e7f3b37 | |||
| db71803430 | |||
| 848fef3b03 | |||
| 5c7a310ee7 | |||
| 764eeb2914 | |||
| 0f8b37e279 | |||
| 71b19e4f69 | |||
| aff6c88a7d | |||
| 3279b779e6 | |||
| 9d7da26c26 | |||
| 47fc0e0850 | |||
| cac5b8ae7d | |||
| 7067d5380d | |||
| 61ab844e5d | |||
| e621deea58 | |||
| 61c361222d | |||
| 8413cd335e | |||
| 5aab38cfa9 | |||
| 8c81546aa7 | |||
| 79eb7a7f16 | |||
| a5e390750b | |||
| c9ecae6e6d | |||
| 7b853a605e | |||
| 3bccc97698 | |||
| 9b6f00a2dc | |||
| 301e3c5ecb | |||
| d680a0beca | |||
| 2a4598216a | |||
| dca5d6f554 | |||
| 3cbaf06583 | |||
| 562e81df81 | |||
| 9e3f28079b | |||
| 8b4f7a3a6b | |||
| 9f869b2e81 | |||
| 46a334004a | |||
| ee3ff6fe8c | |||
| 4506253989 | |||
| 6818f9777b | |||
| d0aa93759d | |||
| e175e85973 | |||
| 91cf5dfaf7 | |||
| b9b66bcb0b | |||
| 84a4bc38b5 | |||
| dea9891e19 | |||
| 7a117187b7 | |||
| 5d5330d0c9 | |||
| 700e7c8518 | |||
| 1c3395869e | |||
| ab6e49b5e2 | |||
| 9c8926068d | |||
| edc1772683 | |||
| 45d0989ada | |||
| 55f4f17480 | |||
| 85f8ebc3c7 | |||
| 402447af70 | |||
| 8d8c88a5f3 | |||
| 47278ee425 | |||
| 36e110d27c | |||
| 05e5c35539 | |||
| 796ec2130f | |||
| edeffc26c4 | |||
| ff859d25bc | |||
| 6ce995f19e | |||
| 53e176ba7c | |||
| a429191edd | |||
| 334ed2cadd | |||
| 10d73994f5 | |||
| 64e94458c9 | |||
| f5f40cd2ea | |||
| ad33b7d54c | |||
| a940cd227f | |||
| 4d008608b1 | |||
| f7b206474d | |||
| faa08a6138 | |||
| 5390503f7a | |||
| ef78608a64 | |||
| a17d8edc9e | |||
| 691b29da7e | |||
| 7a69210967 | |||
| c00f8c6e1c | |||
| bfd8ceac52 | |||
| 3dec8d41ed | |||
| e1767faff5 | |||
| 2a2e276c32 | |||
| 3cfca462ce | |||
| f218766a55 | |||
| a5bd4011e2 |
@@ -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 逐字一致。 */
|
||||
@@ -63,4 +63,9 @@ export const COMPANY_SCOPED_PAGES: readonly CompanyScopedPage[] = [
|
||||
// 外观专利无侵权数据(2026-11-10 v1.3):出表成功自动同步的只读明细,归属物化在行 company_id 列
|
||||
// (V189,同店铺密钥形状)⇒ 后端正门 readCompanyIdOrOwn(超管显式传才收窄,非超管强制本公司)。
|
||||
{ menuKey: 'admin_appearance_patent_clean_items', apiFiles: ['src/pages/patent/appearance-patent-clean-api.ts'], pageFiles: ['src/pages/patent/AppearancePatentCleanItemsPage.vue'] },
|
||||
// 京东数据库(2026-11-14 v1.4)已于 2026-11-16 退出注册表(用户定案「删除掉公司 tab,参考品牌
|
||||
// 数据库」=品牌库 2026-10-06 先例同形):数据全平台公共(行 company_id 只剩"哪家公司客户端
|
||||
// 同步的"来源标记),摘的不只是 tab——页面/api 的 company_id 发送口与后端读侧 company_id 谓词
|
||||
// (superAdminScopedCompanyId)同窗一起摘。反向钉在 tests/company-tab-wiring.test.ts 的
|
||||
// 「公司维度不得回流」清单里,再加回来必须先推翻这条定案。
|
||||
]
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/** 平台 tab 口径的唯一清单(2026-11-16 用户定案「亚马逊/京东不混一起」)。
|
||||
* 仿 company-scope.ts 的形状:单独成文件而不是塞进 routes.ts——护栏用例要从这里
|
||||
* 反读清单与注册表对撞,放在一起会成环。 */
|
||||
|
||||
export type PlatformTabId = 'amazon' | 'jd'
|
||||
|
||||
export interface PlatformTabDef {
|
||||
id: PlatformTabId
|
||||
label: string
|
||||
}
|
||||
|
||||
/** 侧边栏顶部平台 tab 的固定顺序:亚马逊在前(存量主体),京东在后。 */
|
||||
export const PLATFORM_TABS: readonly PlatformTabDef[] = [
|
||||
{ id: 'amazon', label: '亚马逊' },
|
||||
{ id: 'jd', label: '京东' },
|
||||
]
|
||||
|
||||
/** 京东侧独占菜单的 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',
|
||||
]
|
||||
|
||||
/** 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']
|
||||
}
|
||||
@@ -6,6 +6,10 @@ import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
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, platformsOfMenuKey } from '@/config/platform-scope'
|
||||
import { usePlatformTabStore } from '@/stores/platform-tab'
|
||||
import { firstVisiblePath } from '@/router/helpers'
|
||||
import {
|
||||
EMPTY_MENU_DESCRIPTION,
|
||||
EMPTY_MENU_TITLE,
|
||||
@@ -31,7 +35,15 @@ const router = useRouter()
|
||||
const session = useAdminSessionStore()
|
||||
|
||||
const activePath = computed(() => route.path)
|
||||
const menuEntries = computed(() => toSidebarEntries(session.menuTree))
|
||||
const platformTab = usePlatformTabStore()
|
||||
// 平台 tab(亚马逊/京东,2026-11-16「不混」定案)只做显示分组:准入仍是 session.menuTree
|
||||
// (后端按权限裁剪)+路由守卫,这里只把当前用户已被授权的菜单按平台分侧展示。
|
||||
const menuEntries = computed(() =>
|
||||
toSidebarEntries(filterMenuTreeByPlatform(session.menuTree, platformTab.active)),
|
||||
)
|
||||
const visibleTabIds = computed(() => visiblePlatformsFor(session.menuTree))
|
||||
const visibleTabDefs = computed(() => PLATFORM_TABS.filter((tab) => visibleTabIds.value.includes(tab.id)))
|
||||
const showPlatformTabs = computed(() => visibleTabIds.value.length > 1)
|
||||
const openedKeys = computed(() => groupKeysForActive(menuEntries.value, route.path))
|
||||
const emptyMenu = computed(() => shouldShowEmptyMenu(menuEntries.value.length > 0, session.loading, session.initialized))
|
||||
const pageTitle = computed(() => pageTitleOf(route.meta.title))
|
||||
@@ -45,6 +57,34 @@ watch(
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// 直达 URL/面包屑跳到另一平台的页面时,tab 指示自动跟过去(与侧边栏保持一致)。
|
||||
// 双侧清单里的页面(账号域三页)两个 tab 都算归属:当前 tab 已含它就不动。
|
||||
watch(
|
||||
() => route.meta.menuKey as string | undefined,
|
||||
(menuKey) => {
|
||||
if (!menuKey) return
|
||||
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)
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// 切到另一侧 tab 时当前页多半不在那边:跳到该侧第一个可见页;该侧为空(tab 不可见)则不动。
|
||||
// 双侧清单里的页面(账号域三页)切 tab 不跳转——页面自己按当前平台过滤数据。
|
||||
watch(
|
||||
() => platformTab.active,
|
||||
(tab) => {
|
||||
const menuKey = route.meta.menuKey as string | undefined
|
||||
if (!menuKey || platformsOfMenuKey(menuKey).includes(tab)) return
|
||||
const first = firstVisiblePath(filterMenuTreeByPlatform(session.menuTree, tab))
|
||||
if (first) void router.replace(first)
|
||||
},
|
||||
)
|
||||
|
||||
async function signOut() {
|
||||
try {
|
||||
await runLogout({
|
||||
@@ -77,6 +117,19 @@ async function signOut() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav v-if="showPlatformTabs" class="admin-platform-tabs" role="tablist" aria-label="按平台切换菜单">
|
||||
<button
|
||||
v-for="tab in visibleTabDefs"
|
||||
:key="tab.id"
|
||||
type="button"
|
||||
role="tab"
|
||||
class="admin-platform-tab"
|
||||
:class="{ 'is-active': tab.id === platformTab.active }"
|
||||
:aria-selected="tab.id === platformTab.active"
|
||||
@click="platformTab.setActive(tab.id)"
|
||||
>{{ tab.label }}</button>
|
||||
</nav>
|
||||
|
||||
<el-scrollbar class="admin-menu-scroll">
|
||||
<el-menu :default-active="activePath" :default-openeds="openedKeys" router class="admin-menu">
|
||||
<template v-for="entry in menuEntries" :key="entry.key">
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -98,7 +98,7 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
|
||||
steps: ['上传教程压缩包', '到工具台核对下载', '清理历史包'],
|
||||
},
|
||||
admin_workbench_client_package: {
|
||||
text: '上传新的工作台客户端 ZIP 包后即刻生效:客户端从 /api/workbench-client/version/latest 自动检测版本并升级;服务端会复算 sha256 供客户端校验。确认旧包不再需要后再删除。',
|
||||
text: '上传新的工作台客户端 ZIP 包后即刻生效;服务端会复算 sha256 供客户端校验。确认旧包不再需要后再删除。',
|
||||
steps: ['填写版本号并上传 ZIP', '核对版本与 sha256', '清理历史包'],
|
||||
},
|
||||
digital_human_version: {
|
||||
@@ -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: ['选择日期范围', '筛选用户或分组', '核对各模块次数'],
|
||||
@@ -125,6 +121,12 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
|
||||
text: '本页只读:出表成功后「结论=无侵权」的明细自动同步到这里,按分公司隔离分页展示;支持任务号/ASIN/国家/同步日期筛选,下载原表请到任务中心取结果文件。',
|
||||
steps: ['筛选记录', '核对结论明细', '到任务中心下载原表'],
|
||||
},
|
||||
admin_jd_database: {
|
||||
// 2026-11-17 分类管理子菜单并入本页(用户口径「京东分类管理并到京东数据库分类编辑里」,
|
||||
// 原 admin_jd_category_manage 条目随之摘除):分类建/改名/删在工具栏「分类管理」。
|
||||
text: '本页只读:客户端采集的京东店铺商品自动同步到这里(同店铺同商品只保留最新一次),按分公司隔离分页展示;点行查看全部属性与图片;分类的新建/改名/删除在工具栏「分类管理」,给商品归类先勾选再「批量编辑分类」。',
|
||||
steps: ['筛选商品记录', '查看属性与图片明细', '用「分类管理」维护分类并批量归类'],
|
||||
},
|
||||
}
|
||||
|
||||
/** 全部有独立/兜底提示的后台业务菜单 key。 */
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { AdminMenuNode } from '../types/admin'
|
||||
import { PLATFORM_TABS, platformsOfMenuKey } from '../config/platform-scope.ts'
|
||||
import type { PlatformTabId } from '../config/platform-scope.ts'
|
||||
import { firstVisiblePath } from '../router/helpers.ts'
|
||||
|
||||
/**
|
||||
* 按平台 tab 过滤后端菜单树(2026-11-16「亚马逊/京东不混」):**只做显示分组,不做鉴权**——
|
||||
* 准入仍由 session.menuTree(后端按权限裁剪)与路由守卫负责,这里只是把当前用户已被授权的
|
||||
* 菜单按平台分到两个 tab 下展示。
|
||||
* 规则:叶子按 platformsOfMenuKey(key) 是否包含当前平台留下(双侧清单里的账号域三页两个
|
||||
* tab 都显示);分组节点(admin_group_*)自身的 key 不参与平台判定,按「留住的子项数 > 0」
|
||||
* 决定去留——否则京东 tab 下「账号与权限」这类混合分组会被整组误剪。节点的 key/name/
|
||||
* route/children 形状原样透传(浅拷贝不改写),toSidebarEntries、groupKeysForActive 与
|
||||
* 面包屑都不受影响。
|
||||
*/
|
||||
export function filterMenuTreeByPlatform(
|
||||
nodes: AdminMenuNode[] | null | undefined,
|
||||
platform: PlatformTabId,
|
||||
): AdminMenuNode[] {
|
||||
const filtered: AdminMenuNode[] = []
|
||||
for (const node of nodes || []) {
|
||||
const children = filterMenuTreeByPlatform(node.children, platform)
|
||||
if (children.length > 0) {
|
||||
filtered.push({ ...node, children })
|
||||
continue
|
||||
}
|
||||
if ((node.children || []).length > 0) continue
|
||||
if (platformsOfMenuKey(node.key || '').includes(platform)) filtered.push({ ...node })
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
/** 当前用户在哪些平台下至少有一个可点页面(tab 显示依据);顺序固定随 PLATFORM_TABS。
|
||||
* 「可点」沿用 firstVisiblePath 这一把尺子(有 route 即可点),不另写第二处判定。 */
|
||||
export function visiblePlatformsFor(nodes: AdminMenuNode[] | null | undefined): PlatformTabId[] {
|
||||
return PLATFORM_TABS
|
||||
.filter((tab) => firstVisiblePath(filterMenuTreeByPlatform(nodes, tab.id)) !== '')
|
||||
.map((tab) => tab.id)
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
<script setup lang="ts">
|
||||
/** 批量编辑分类对话框(2026-11-17 用户口径「店铺分类弹窗删了,加个批量编辑分类」):
|
||||
* 京东数据库页勾选商品(翻页累计,由页面持有勾选集)→ 本对话框选目标分类或移出分类 →
|
||||
* 一次批量归类。归属写「本组」的归属行(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'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
/** 当前数据权限分组(归类的落点组;V203 同一商品在其他组可另归一类)。 */
|
||||
ownerGroupId: number
|
||||
ownerGroupName: string
|
||||
/** 当前分组的分类选项(含商品数徽标;由页面在打开时刷新)。 */
|
||||
categories: JdProductGroup[]
|
||||
/** 页面持有的勾选集(跨页累计),展开成 id 数组传入。 */
|
||||
selectedIds: number[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'close'): void; (event: 'done', updated: number, targetName: string | null): void }>()
|
||||
|
||||
/** 选中的目标分类 id;0=移出分类(回到未分类)。 */
|
||||
const pickedId = ref(0)
|
||||
const assigning = ref(false)
|
||||
const errorText = ref('')
|
||||
|
||||
const picked = computed(() => props.categories.find((group) => group.id === pickedId.value) || null)
|
||||
const confirmText = computed(() => (picked.value ? `归入「${picked.value.name}」` : '移出分类'))
|
||||
/** 提交条件:有勾选、未在提交中,且选了目标分类(pickedId>0)或选了移出(pickedId=0,
|
||||
* 但本组得有分类可移——全组无分类时移出是无谓操作,整对话框只留提示)。 */
|
||||
const canSubmit = computed(() => props.selectedIds.length > 0 && !assigning.value
|
||||
&& (picked.value ? true : props.categories.length > 0))
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(visible) => {
|
||||
if (visible) {
|
||||
pickedId.value = 0
|
||||
errorText.value = ''
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
async function submit(): Promise<void> {
|
||||
if (!canSubmit.value) return
|
||||
const target = picked.value
|
||||
assigning.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
// target null=移出分类(groupId 传 null,后端只解挂本组归属行)。
|
||||
const updated = await batchAssignJdProductGroup(
|
||||
props.selectedIds,
|
||||
target ? target.id : null,
|
||||
props.ownerGroupId,
|
||||
)
|
||||
emit('done', updated, target ? target.name : null)
|
||||
emit('close')
|
||||
} catch (error) {
|
||||
errorText.value = requestErrorMessage(error) || '批量归类失败'
|
||||
} finally {
|
||||
assigning.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="modal-mask" @click.self="emit('close')">
|
||||
<div class="batch-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">
|
||||
已勾选 {{ selectedIds.length }} 个商品(翻页累计)。选目标分类后确认;
|
||||
归类只记在分类归属上,不影响采集对价格/库存的更新。
|
||||
</p>
|
||||
<p v-if="errorText" class="group-error">{{ errorText }}</p>
|
||||
|
||||
<div v-if="!categories.length" class="batch-empty">本组暂无分类,先用工具栏「分类管理」新建一个</div>
|
||||
<ul v-else class="option-list">
|
||||
<li
|
||||
v-for="group in categories"
|
||||
:key="group.id"
|
||||
class="option-row"
|
||||
:class="{ active: pickedId === group.id }"
|
||||
@click="pickedId = group.id"
|
||||
>
|
||||
<span class="option-radio" aria-hidden="true"></span>
|
||||
<span class="option-name" :title="group.name">{{ group.name }}</span>
|
||||
<span class="option-meta">{{ group.productCount }}</span>
|
||||
</li>
|
||||
<li class="option-row option-detach" :class="{ active: pickedId === 0 }" @click="pickedId = 0">
|
||||
<span class="option-radio" aria-hidden="true"></span>
|
||||
<span class="option-name">移出分类</span>
|
||||
<span class="option-meta">回到未分类</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="modal-foot">
|
||||
<button class="btn btn-secondary" type="button" @click="emit('close')">取消</button>
|
||||
<button class="btn" type="button" :disabled="!canSubmit" @click="submit">
|
||||
{{ assigning ? '提交中...' : confirmText }}
|
||||
</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);
|
||||
}
|
||||
.batch-modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(430px, 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;
|
||||
}
|
||||
.group-error {
|
||||
margin: 0 0 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #f0c9c2;
|
||||
border-radius: 10px;
|
||||
background: #fdf1ef;
|
||||
color: #a04432;
|
||||
font-size: 13px;
|
||||
}
|
||||
.batch-empty {
|
||||
padding: 26px 12px;
|
||||
border: 1px dashed #cbd9e6;
|
||||
border-radius: 10px;
|
||||
color: #8293a5;
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
}
|
||||
.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: 10px 8px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.option-row:hover {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
/* 点亮=归类目标:与旧弹窗左栏同款左缘蓝条。 */
|
||||
.option-row.active {
|
||||
background: #e8f1fa;
|
||||
box-shadow: inset 3px 0 0 #4f78a5;
|
||||
}
|
||||
.option-radio {
|
||||
flex: none;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 1.6px solid #9fb7cd;
|
||||
border-radius: 50%;
|
||||
background: #ffffff;
|
||||
}
|
||||
.option-row.active .option-radio {
|
||||
border-color: #4f78a5;
|
||||
background: radial-gradient(circle, #4f78a5 0 4px, #ffffff 4.6px);
|
||||
}
|
||||
.option-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: #24384d;
|
||||
}
|
||||
.option-detach .option-name {
|
||||
color: #a04432;
|
||||
}
|
||||
.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;
|
||||
}
|
||||
.option-detach .option-meta {
|
||||
background: transparent;
|
||||
color: #8293a5;
|
||||
}
|
||||
.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: 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;
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border-color: #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,469 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东数据库「类目」筛选的京麦同款级联面板(2026-11-16 客户口径「京麦类目是这些 我们
|
||||
* 后台的现在的不对」+「你直接爬」→ 树数据换成京麦授权类目真树,见 ./jd-category-tree.ts
|
||||
* 头注释的取证来源与边界)。
|
||||
*
|
||||
* 交互(京麦真机同款,2026-11-16 面板逐级点开取证):面板按点亮路径动态出栏——第一栏
|
||||
* 一级(3 个)、后续栏=点亮节点的 children(最深 4 栏);**非末级行点击=下钻**(推进
|
||||
* 路径)、**末级行(children 空)点击=选中**(radio 蓝,emit change→按 category_path
|
||||
* 等值过滤,后端契约零改动)。搜索框搜**树内全部末级**(名称或路径命中,行 title 带
|
||||
* 全路径);树外命中(已落库但京麦类目体系变更后的历史名)从 options 兜底段选,语义
|
||||
* 同旧版第三栏。「全部类目」行=清选;触发框已选时出 × 清除;面板外点透明遮罩关闭。
|
||||
* 零依赖自绘(radio 圆点/箭头都是 CSS),无 element 依赖。 */
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import {
|
||||
jdCategoryChildren,
|
||||
jdCategoryRoots,
|
||||
jdCategorySearchLeaves,
|
||||
type JdCategoryNode,
|
||||
} from './jd-category-tree.ts'
|
||||
import { clampPanelLeftX } from './jd-category-cascader-position.ts'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 已落库末级类目全集(/categories 现算,页面传入)——只作**树外兜底**(搜索无树内
|
||||
* 命中时列出「已落库类目(树外历史)」段),不再默认铺第三栏。 */
|
||||
options?: { name: string; productCount: number }[]
|
||||
/** 当前选中末级类目名;'' = 全部类目。 */
|
||||
modelValue: string
|
||||
groups?: { id: number; name: string; productCount: number }[]
|
||||
groupId?: string
|
||||
createVersion?: number
|
||||
busy?: boolean
|
||||
treeOnly?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'change', value: string): void
|
||||
(event: 'group', value: string): void
|
||||
(event: 'create-group', value: string): void
|
||||
(event: 'delete-group', id: number): void
|
||||
}>()
|
||||
const newGroupName = ref('')
|
||||
watch(() => props.createVersion, () => { newGroupName.value = '' })
|
||||
function createGroup(): void {
|
||||
const name = newGroupName.value.trim()
|
||||
if (name) emit('create-group', name)
|
||||
}
|
||||
function pickGroup(id: number): void {
|
||||
emit('group', String(id))
|
||||
close()
|
||||
}
|
||||
|
||||
const open = ref(false)
|
||||
/** 已下钻的节点名路径(非末级行点击推进)。 */
|
||||
const activePath = ref<string[]>([])
|
||||
const searchText = ref('')
|
||||
|
||||
/** 面板水平定位钳制(2026-11-16「超出视窗了」):触发框在筛选行中部偏右时,锚 left:0
|
||||
* 的多栏面板会伸出视窗右缘。打开与栏数/搜索态变化后用真实 rect 重算 left 偏移——
|
||||
* 右缘贴齐视口后继续下钻即向左生长,不再截掉末栏。钳制数学在
|
||||
* ./jd-category-cascader-position.ts(纯函数,tests/jd-category-cascader-position.test.ts)。 */
|
||||
const hostRef = ref<HTMLElement | null>(null)
|
||||
const panelRef = ref<HTMLElement | null>(null)
|
||||
const panelOffsetX = ref(0)
|
||||
|
||||
function reposition(): void {
|
||||
const host = hostRef.value
|
||||
const panel = panelRef.value
|
||||
if (!host || !panel) return
|
||||
panelOffsetX.value = clampPanelLeftX({
|
||||
hostLeft: host.getBoundingClientRect().left,
|
||||
panelWidth: panel.offsetWidth,
|
||||
viewportWidth: window.innerWidth,
|
||||
})
|
||||
}
|
||||
|
||||
const roots = jdCategoryRoots()
|
||||
/** 树内全部末级名集合(判定 options 哪些是「树外历史」)。 */
|
||||
const treeLeafNames = new Set(
|
||||
jdCategorySearchLeaves('').map((leaf) => leaf.name),
|
||||
)
|
||||
|
||||
/** 面板各栏内容:第 0 栏一级,第 i+1 栏=点亮路径前 i+1 个的 children(路径推进到
|
||||
* 末级时末栏是叶子所在栏,children 空不出栏——栏数随路径动态 1~4)。 */
|
||||
const columns = computed<JdCategoryNode[][]>(() => {
|
||||
const cols: JdCategoryNode[][] = [roots]
|
||||
for (let i = 0; i < activePath.value.length; i++) {
|
||||
const children = jdCategoryChildren(activePath.value.slice(0, i + 1))
|
||||
if (!children.length) break
|
||||
cols.push(children)
|
||||
}
|
||||
return cols
|
||||
})
|
||||
|
||||
/** 搜索激活=搜索词非空:面板切换成扁平末级结果列表。 */
|
||||
const searching = computed(() => searchText.value.trim().length > 0)
|
||||
|
||||
/** 树内命中末级(名称或路径段命中)。 */
|
||||
const searchLeaves = computed(() =>
|
||||
searching.value ? jdCategorySearchLeaves(searchText.value) : [],
|
||||
)
|
||||
|
||||
/** 树外兜底:options 里不在树名集的行按搜索词过滤(历史行仍可选中过滤)。 */
|
||||
const fallbackOptions = computed(() => {
|
||||
if (!searching.value) return []
|
||||
const keyword = searchText.value.trim().toLowerCase()
|
||||
return (props.options ?? [])
|
||||
.filter((option) => !treeLeafNames.has(option.name))
|
||||
.filter((option) => option.name.toLowerCase().includes(keyword))
|
||||
})
|
||||
|
||||
/** 栏数随下钻动态 1~4、搜索态切单栏 ⇒ 面板宽度变,开着就要重算偏移(下钻向左生长)。 */
|
||||
watch(
|
||||
() => [columns.value.length, searching.value] as const,
|
||||
() => {
|
||||
if (open.value) nextTick(reposition)
|
||||
},
|
||||
)
|
||||
|
||||
function toggle(): void {
|
||||
if (open.value) {
|
||||
close()
|
||||
return
|
||||
}
|
||||
activePath.value = []
|
||||
searchText.value = ''
|
||||
open.value = true
|
||||
nextTick(reposition)
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
open.value = false
|
||||
activePath.value = []
|
||||
}
|
||||
|
||||
/** 非末级行点击=下钻;末级行点击=选中并收面板。 */
|
||||
function pick(node: JdCategoryNode, depth: number): void {
|
||||
if (node.children && node.children.length) {
|
||||
activePath.value = [...activePath.value.slice(0, depth), node.name]
|
||||
return
|
||||
}
|
||||
emit('change', node.name)
|
||||
close()
|
||||
}
|
||||
|
||||
function pickAll(): void {
|
||||
emit('change', '')
|
||||
close()
|
||||
}
|
||||
|
||||
/** 搜索结果行点击(树内末级或树外兜底行)=按名选中。 */
|
||||
function pickName(name: string): void {
|
||||
emit('change', name)
|
||||
close()
|
||||
}
|
||||
|
||||
function clear(): void {
|
||||
emit('change', '')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="hostRef" class="cat-cascader">
|
||||
<button
|
||||
class="cat-trigger"
|
||||
type="button"
|
||||
:class="{ open, filled: !!modelValue || !!groupId }"
|
||||
@click="toggle"
|
||||
>
|
||||
<span class="cat-trigger-text" :title="modelValue || ''">{{ groups?.find(group => String(group.id) === groupId)?.name || modelValue || '全部类目' }}</span>
|
||||
<span
|
||||
v-if="modelValue || groupId"
|
||||
class="cat-clear"
|
||||
role="button"
|
||||
aria-label="清除类目"
|
||||
@click.stop="clear"
|
||||
>×</span>
|
||||
<span class="cat-chevron" aria-hidden="true"></span>
|
||||
</button>
|
||||
|
||||
<!-- 面板外点透明遮罩关闭(零 document 监听器,无泄漏面)。 -->
|
||||
<div v-if="open" class="cat-mask" @click="close"></div>
|
||||
<div v-if="open" ref="panelRef" class="cat-panel" :style="{ left: `${panelOffsetX}px` }">
|
||||
<div v-if="!treeOnly" class="cat-custom cat-col-custom">
|
||||
<div class="cat-seg">自定义分类</div>
|
||||
<form class="cat-create" @submit.prevent="createGroup">
|
||||
<input v-model="newGroupName" class="cat-search" placeholder="新建分类" aria-label="新建分类名称" />
|
||||
<button type="submit" :disabled="busy || !newGroupName.trim()">添加</button>
|
||||
</form>
|
||||
<div v-for="group in groups || []" :key="group.id" class="cat-row" :class="{ active: groupId === String(group.id) }">
|
||||
<button type="button" class="cat-group-pick" :title="group.name" @click="pickGroup(group.id)">{{ group.name }}({{ group.productCount }})</button>
|
||||
<button type="button" :aria-label="`删除分类 ${group.name}`" @click.stop="emit('delete-group', group.id)">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 搜索态:树内末级命中+树外兜底段(扁平列表,行 title 带全路径)。 -->
|
||||
<template v-if="searching">
|
||||
<div class="cat-col cat-col-search">
|
||||
<div class="cat-search-row"><input v-model="searchText" type="text" class="cat-search" placeholder="搜索类目" /></div>
|
||||
<template v-if="searchLeaves.length || fallbackOptions.length">
|
||||
<div
|
||||
v-for="leaf in searchLeaves"
|
||||
:key="`tree-${leaf.path.join('/')}`"
|
||||
class="cat-row"
|
||||
:class="{ active: modelValue === leaf.name }"
|
||||
:title="leaf.path.join(' > ')"
|
||||
@click="pickName(leaf.name)"
|
||||
>
|
||||
<span class="cat-dot" :class="{ on: modelValue === leaf.name }" aria-hidden="true"></span>
|
||||
<span class="cat-name">{{ leaf.name }}</span>
|
||||
<span class="cat-path">{{ leaf.path.slice(0, -1).join(' › ') }}</span>
|
||||
</div>
|
||||
<div v-if="fallbackOptions.length" class="cat-seg">已落库类目(树外历史)</div>
|
||||
<div
|
||||
v-for="option in fallbackOptions"
|
||||
:key="`db-${option.name}`"
|
||||
class="cat-row"
|
||||
:class="{ active: modelValue === option.name }"
|
||||
:title="option.name"
|
||||
@click="pickName(option.name)"
|
||||
>
|
||||
<span class="cat-dot" :class="{ on: modelValue === option.name }" aria-hidden="true"></span>
|
||||
<span class="cat-name">{{ option.name }}</span>
|
||||
<span class="cat-count">{{ option.productCount }}</span>
|
||||
</div>
|
||||
</template>
|
||||
<div v-else class="cat-empty">未找到类目</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 下钻态:逐级动态栏;首栏顶部「全部类目」行=清选。 -->
|
||||
<template v-else>
|
||||
<div
|
||||
v-for="(col, depth) in columns"
|
||||
:key="depth"
|
||||
class="cat-col"
|
||||
>
|
||||
<div v-if="depth === 0" class="cat-search-row">
|
||||
<input
|
||||
v-model="searchText"
|
||||
type="text"
|
||||
class="cat-search"
|
||||
placeholder="搜索类目"
|
||||
@click.stop
|
||||
/>
|
||||
</div>
|
||||
<div v-if="depth === 0" class="cat-row cat-row-all" :class="{ active: !modelValue }" @click="pickAll">
|
||||
<span class="cat-dot" :class="{ on: !modelValue }" aria-hidden="true"></span>
|
||||
<span class="cat-name">全部类目</span>
|
||||
</div>
|
||||
<div
|
||||
v-for="node in col"
|
||||
:key="`${depth}-${node.name}`"
|
||||
class="cat-row"
|
||||
:class="{ active: activePath[depth] === node.name || (depth === 0 && modelValue === node.name) }"
|
||||
:title="node.name"
|
||||
@click="pick(node, depth)"
|
||||
>
|
||||
<span class="cat-dot" aria-hidden="true"></span>
|
||||
<span class="cat-name">{{ node.name }}</span>
|
||||
<span v-if="node.children && node.children.length" class="cat-arrow" aria-hidden="true">›</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.cat-custom { flex: none; width: 200px; max-height: 340px; overflow-y: auto; border-right: 1px solid #e7eef5; }
|
||||
.cat-create { display: flex; gap: 4px; padding: 6px 8px; }
|
||||
.cat-create input { min-width: 0; }
|
||||
.cat-group-pick { flex: 1; min-width: 0; text-align: left; border: 0; background: transparent; color: inherit; cursor: pointer; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.cat-cascader {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
}
|
||||
/* 触发框像素对齐页面 .form-group select(42 高/9 圆角/#cbd9e6 边框/#f8fbfd 底)。 */
|
||||
.cat-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.cat-trigger:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.cat-trigger.open,
|
||||
.cat-trigger:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.cat-trigger-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
text-align: left;
|
||||
}
|
||||
.cat-trigger:not(.filled) .cat-trigger-text {
|
||||
color: #8293a5;
|
||||
}
|
||||
.cat-clear {
|
||||
flex: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
background: #e7eef5;
|
||||
color: #5b6f83;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
}
|
||||
.cat-clear:hover {
|
||||
background: #dbe7f1;
|
||||
color: #24384d;
|
||||
}
|
||||
/* 下拉箭头:CSS 三角(京麦同款向下 chevron,展开翻向上)。 */
|
||||
.cat-chevron {
|
||||
flex: none;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-left: 5px solid transparent;
|
||||
border-right: 5px solid transparent;
|
||||
border-top: 6px solid #7b8a99;
|
||||
transition: transform 160ms ease;
|
||||
}
|
||||
.cat-trigger.open .cat-chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
.cat-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2550;
|
||||
}
|
||||
.cat-panel {
|
||||
position: absolute;
|
||||
top: calc(100% + 4px);
|
||||
left: 0;
|
||||
z-index: 2560;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
max-width: min(820px, 90vw);
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 16px 44px rgba(39, 67, 94, 0.18);
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
}
|
||||
.cat-col {
|
||||
flex: none;
|
||||
width: 200px;
|
||||
max-height: 340px;
|
||||
overflow-y: auto;
|
||||
padding: 6px 0;
|
||||
border-right: 1px solid #e7eef5;
|
||||
}
|
||||
.cat-col:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
.cat-col-search {
|
||||
width: 300px;
|
||||
}
|
||||
/* 行=京麦同款:圆点 radio + 名称 + 右箭头;hover 浅蓝底。 */
|
||||
.cat-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
font-size: 13.5px;
|
||||
color: #24384d;
|
||||
cursor: pointer;
|
||||
}
|
||||
.cat-row:hover,
|
||||
.cat-row.active {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.cat-row.active {
|
||||
color: #2f5d8b;
|
||||
font-weight: 550;
|
||||
}
|
||||
.cat-dot {
|
||||
flex: none;
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
border: 1px solid #c0ccda;
|
||||
border-radius: 50%;
|
||||
background: #ffffff;
|
||||
}
|
||||
/* radio 选中=京麦同款蓝芯。 */
|
||||
.cat-dot.on {
|
||||
border-color: #3b82c4;
|
||||
background: radial-gradient(circle, #3b82c4 0 4px, #ffffff 4.6px);
|
||||
}
|
||||
.cat-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* 搜索态行尾的路径灰字(同名跨支时定位用)。 */
|
||||
.cat-path {
|
||||
flex: none;
|
||||
max-width: 110px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: #9fb0c0;
|
||||
font-size: 12px;
|
||||
}
|
||||
.cat-arrow {
|
||||
flex: none;
|
||||
color: #9fb0c0;
|
||||
font-size: 15px;
|
||||
line-height: 1;
|
||||
}
|
||||
.cat-count {
|
||||
flex: none;
|
||||
color: #8293a5;
|
||||
font-size: 12px;
|
||||
}
|
||||
.cat-seg {
|
||||
padding: 8px 12px 4px;
|
||||
color: #8293a5;
|
||||
font-size: 11.5px;
|
||||
border-top: 1px solid #e7eef5;
|
||||
}
|
||||
.cat-search-row {
|
||||
padding: 4px 8px 6px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
}
|
||||
.cat-search {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-height: 30px;
|
||||
padding: 4px 10px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 8px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 12.5px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.cat-search:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.cat-empty {
|
||||
padding: 16px 12px;
|
||||
color: #8293a5;
|
||||
font-size: 12.5px;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,526 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东公共商品库:支持分类和京麦类目组合筛选。
|
||||
* V203(2026-11-16 用户口径):分类按「数据权限分组」隔离——不同组看不到彼此的分类,
|
||||
* 能看多组的人用筛选行「分组」下拉切换当前组(只有一组时锁定显示)。
|
||||
* 2026-11-17 用户口径:店铺分类弹窗下线,本页工具栏改「批量编辑分类」——勾选商品
|
||||
* (翻页累计记忆)后选目标分类归入或移出;同日第二刀「京东分类管理并到京东数据库分类
|
||||
* 编辑里」:V204 独立子菜单页(JdCategoryManagerPage)下线,建/改名/删分类收进工具栏
|
||||
* 「分类管理」对话框(JdCategoryManageDialog,带名称搜索)。 */
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import {
|
||||
deleteJdProducts,
|
||||
fetchJdCategoryScope,
|
||||
fetchJdProductCategories,
|
||||
fetchJdProductGroups,
|
||||
fetchJdProductList,
|
||||
type JdCategoryGroupOption,
|
||||
type JdProductCategoryOption,
|
||||
type JdProductGroup,
|
||||
} from './jd-product-api.ts'
|
||||
import type { JdProductItem } from './jd-product-model.ts'
|
||||
import { jdPriceRange } from './jd-product-model.ts'
|
||||
import { createJdProductFilterState } from './jd-product-filter.ts'
|
||||
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'
|
||||
import { loadFailureMessage } from '@/components/load-failure-model'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { formatDateTime, orderedPair } from '@/utils/datetime'
|
||||
|
||||
/** 写权限口径(2026-11-16 用户口径):商品行写(编辑/删除/勾选批量删)只对平台超级管理员渲染;
|
||||
* 分类写(建/改名/删除、归类)由 scope 的每组 editable 决定(本组管理员/公司超管/平台超管)。 */
|
||||
const session = useAdminSessionStore()
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<JdProductItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const filter = reactive(createJdProductFilterState())
|
||||
/** 分类作用域(V203):可见分组 + 每组可写标记。失败静默回空作用域(分类列全空但商品照常)。 */
|
||||
const categoryScope = ref<JdCategoryGroupOption[]>([])
|
||||
const scopeDefaultGroupId = ref(0)
|
||||
/** 当前分组(数据权限分组 id):分类列/分类筛选/分类管理的共同作用域。 */
|
||||
const ownerGroupId = ref(0)
|
||||
/** 当前分组的分类下拉选项(按 ownerGroupId 取,切组即换)。 */
|
||||
const groupOptions = ref<JdProductGroup[]>([])
|
||||
/** 类目下拉选项(京麦末级类目):与当前行集同源(公共库全量);失败静默回空。 */
|
||||
const categoryOptions = ref<JdProductCategoryOption[]>([])
|
||||
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)
|
||||
const editVisible = ref(false)
|
||||
|
||||
/** 当前分组的下拉项(带 editable)——分类写入口与「店铺分类」弹窗的可管理档都读它。 */
|
||||
const currentGroupOption = computed<JdCategoryGroupOption | null>(() =>
|
||||
categoryScope.value.find((group) => group.id === ownerGroupId.value) || null)
|
||||
const currentGroupName = computed(() => currentGroupOption.value?.name || '')
|
||||
/** 分类可管理(建/改名/删除/归类):本组管理员、公司超管、平台超管(后端 scope 判)。 */
|
||||
const canManageCategories = computed(() => currentGroupOption.value?.editable === true)
|
||||
/** 勾选列服务两类写:批量删除(只超管)+批量编辑分类(本组可写分类的管理员也要勾)。
|
||||
* 2026-11-17 弹窗下线后管理员失去弹窗右栏的勾选面 ⇒ 勾选列必须对「本组可写」放开,
|
||||
* 否则本组管理员没有归类入口。商品行按钮(编辑/删除/删除勾选)仍只归平台超管。 */
|
||||
const hasSelectionColumn = computed(() => isSuperAdmin.value || canManageCategories.value)
|
||||
/** 空态行 colspan:勾选列有无决定 5/6/7 列三种形状(超管含操作列)。 */
|
||||
const emptyColspan = computed(() => (isSuperAdmin.value ? 7 : hasSelectionColumn.value ? 6 : 5))
|
||||
/** 分组下拉只在能看多组时才渲染;只有一组(含无可见组)时按锁定态展示。 */
|
||||
const canSwitchGroup = computed(() => categoryScope.value.length > 1)
|
||||
|
||||
function openEdit(item: JdProductItem): void {
|
||||
editItem.value = item
|
||||
editVisible.value = true
|
||||
}
|
||||
|
||||
function closeEdit(): void {
|
||||
editVisible.value = false
|
||||
editItem.value = null
|
||||
}
|
||||
|
||||
/** 编辑保存成功:刷新列表(该行已置人工编辑锁,标题/价格等即时可见且不再被采集覆盖)。 */
|
||||
async function onEditSaved(): Promise<void> {
|
||||
await load()
|
||||
}
|
||||
|
||||
/** min/max 挡不住手输,落值后把倒挂的起止交换回来。 */
|
||||
function clampJdSyncedRange(): void {
|
||||
const [s, e] = orderedPair(filter.syncedFrom, filter.syncedTo)
|
||||
filter.syncedFrom = s
|
||||
filter.syncedTo = e
|
||||
}
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
|
||||
/** 作用域 → 分组列表 → 该组分类:失败一律静默降级(分类只是筛选/归类面,不拦首屏行集)。 */
|
||||
async function loadCategoryScope(): 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 loadGroupOptions()
|
||||
}
|
||||
|
||||
/** 当前分组的分类选项:按 ownerGroupId 取(跨组不可见);失败静默回空下拉。 */
|
||||
async function loadGroupOptions(): Promise<void> {
|
||||
try {
|
||||
groupOptions.value = await fetchJdProductGroups(ownerGroupId.value)
|
||||
} catch {
|
||||
groupOptions.value = []
|
||||
}
|
||||
}
|
||||
|
||||
/** 类目选项同分组口径:失败静默回空下拉(可见「全部类目」),不拦首屏行集。 */
|
||||
async function loadCategoryOptions(): Promise<void> {
|
||||
try {
|
||||
categoryOptions.value = await fetchJdProductCategories()
|
||||
} catch {
|
||||
categoryOptions.value = []
|
||||
}
|
||||
}
|
||||
|
||||
/** 切换「分组」下拉:分类筛选(属于上一组的分类)清空,分类选项换成本组,回第一页重取。
|
||||
* 勾选集是按商品 id 记的(跨页累计),切组不清——归类的落点组随 ownerGroupId 走,
|
||||
* 误跨组批量归类由批量对话框里的组名标注防住。 */
|
||||
async function changeOwnerGroup(next: number): Promise<void> {
|
||||
if (next === ownerGroupId.value) return
|
||||
ownerGroupId.value = next
|
||||
filter.groupId = ''
|
||||
await loadGroupOptions()
|
||||
page.value = 1
|
||||
await load()
|
||||
}
|
||||
|
||||
/** 打开批量编辑分类:先刷一遍当前组分类(商品数徽标要新鲜),再亮对话框。 */
|
||||
async function openBatchEdit(): Promise<void> {
|
||||
await loadGroupOptions()
|
||||
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> {
|
||||
showAdminFeedback(
|
||||
targetName ? `已把 ${updated} 个商品归入「${targetName}」` : `已把 ${updated} 个商品移出分类`,
|
||||
'success',
|
||||
)
|
||||
selectedIds.value = new Set()
|
||||
await load()
|
||||
}
|
||||
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchJdProductList({
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
productCode: filter.productCode,
|
||||
titleKeyword: filter.titleKeyword,
|
||||
category: filter.category,
|
||||
groupId: filter.groupId,
|
||||
ownerGroupId: ownerGroupId.value,
|
||||
syncedFrom: filter.syncedFrom,
|
||||
syncedTo: filter.syncedTo,
|
||||
})
|
||||
rows.value = result.items
|
||||
total.value = result.total
|
||||
if (result.page >= 1) page.value = result.page
|
||||
// 勾选跨页记忆(2026-11-17 用户口径「支持勾选翻页也要记住」):翻页/重取/改筛选都
|
||||
// 不清勾选集——批量编辑分类与批量删除都按累计 id 提交,操作前的确认弹窗点名数量;
|
||||
// 「清除勾选」按钮同日用户口径删除,勾选只在批量操作成功后自动清。
|
||||
} catch (error) {
|
||||
loadFailure.value = loadFailureMessage(error, '京东商品列表加载失败')
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function apply(): void {
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
/** 类目级联面板点末级即查:选完立刻按该类目过滤刷新(回第一页),同分组下拉口径;
|
||||
* 点「全部类目」/触发框 × = 清选重查。 */
|
||||
function onCategoryPicked(name: string): void {
|
||||
filter.category = name
|
||||
apply()
|
||||
}
|
||||
|
||||
/** 重置:筛选面回出厂空态,回第一页重取。 */
|
||||
function reset(): void {
|
||||
Object.assign(filter, createJdProductFilterState())
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
function changePage(next: number): void {
|
||||
if (next < 1 || next > totalPages.value) return
|
||||
page.value = next
|
||||
void load()
|
||||
}
|
||||
|
||||
function changeSize(size: number) {
|
||||
pageSize.value = size
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
function openDetail(item: JdProductItem): void {
|
||||
detailItem.value = item
|
||||
detailVisible.value = true
|
||||
}
|
||||
|
||||
function closeDetail(): void {
|
||||
detailVisible.value = false
|
||||
detailItem.value = null
|
||||
}
|
||||
|
||||
/** 商品编码一键复制(京麦同款 ⧉):@click.stop 防冒泡开抽屉;剪贴板不可用(非安全上下文)时弹失败文案。 */
|
||||
async function copyText(text: string): Promise<void> {
|
||||
if (!text) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
showAdminFeedback(`已复制 ${text}`, 'success')
|
||||
} catch {
|
||||
showAdminFeedback('复制失败,请手动选择复制', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- 删除(先删桶、全成功才删库行,语义在后端 JdProductDeleteService) ----------------
|
||||
|
||||
/** 勾选集(按商品 id,跨页累计记忆,2026-11-17 用户口径)。翻页/重取不清;显式出口
|
||||
* 曾是工具栏「清除勾选」,同日用户口径「清除勾选这个按钮删除」后只剩批量删除/
|
||||
* 批量归类成功后自动清。 */
|
||||
const selectedIds = ref<Set<number>>(new Set())
|
||||
const deleting = ref(false)
|
||||
|
||||
const selectedCount = computed(() => selectedIds.value.size)
|
||||
|
||||
function toggleSelect(row: JdProductItem, checked: boolean): void {
|
||||
const next = new Set(selectedIds.value)
|
||||
if (checked) next.add(row.id)
|
||||
else next.delete(row.id)
|
||||
selectedIds.value = next
|
||||
}
|
||||
|
||||
const allSelected = computed(() => rows.value.length > 0 && rows.value.every((row) => selectedIds.value.has(row.id)))
|
||||
|
||||
function toggleSelectAll(checked: boolean): void {
|
||||
const next = new Set(selectedIds.value)
|
||||
for (const row of rows.value) {
|
||||
if (checked) next.add(row.id)
|
||||
else next.delete(row.id)
|
||||
}
|
||||
selectedIds.value = next
|
||||
}
|
||||
|
||||
/** 单行删除入口(行内按钮):确认弹窗点名商品编码与「桶内图片一并删除」。 */
|
||||
async function removeOne(row: JdProductItem): Promise<void> {
|
||||
await removeMany([row.id], `确定删除商品「${row.productCode || row.title}」吗?`)
|
||||
}
|
||||
|
||||
/** 批量删除入口(工具栏按钮):按累计勾选 id 直删(跨页的行也在内),确认弹窗点名总数。 */
|
||||
async function removeSelected(): Promise<void> {
|
||||
await removeMany([...selectedIds.value], `确定删除勾选的 ${selectedIds.value.size} 个商品吗?`)
|
||||
}
|
||||
|
||||
/** 删除主流程:二次确认 → 先删桶、全成功才删库行(后端保证)→ 刷新列表并清勾选。 */
|
||||
async function removeMany(ids: number[], message: string): Promise<void> {
|
||||
if (!ids.length || deleting.value) return
|
||||
const ok = await openAdminConfirm({ title: '删除京东商品', message: `${message}删除后该商品的 SKU、图片登记与 jd-products 桶内图片文件一并删除(被其他商品共用的图片会保留);此操作不可恢复。`, confirmText: '确认删除', danger: true })
|
||||
if (!ok) return
|
||||
deleting.value = true
|
||||
try {
|
||||
const receipt = await deleteJdProducts(ids)
|
||||
showAdminFeedback(`已删除 ${receipt.deleted} 个商品,清理 ${receipt.objectsDeleted} 个图片文件` +
|
||||
(receipt.objectsKept ? `(${receipt.objectsKept} 个共用图片保留)` : ''), 'success')
|
||||
selectedIds.value = new Set()
|
||||
if (ids.length >= rows.value.length && page.value > 1) page.value -= 1
|
||||
await load()
|
||||
} catch (error) {
|
||||
const text = error instanceof Error && error.message ? error.message : '删除失败,请稍后重试'
|
||||
showAdminFeedback(text, 'error')
|
||||
} finally {
|
||||
deleting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
// 先解析作用域再取列表:首屏的 owner_group_id 必须与分类下拉同一个组(铁律 30 同形——
|
||||
// 不要先发一条不带 owner_group_id 的列表请求再补,两次请求会落在不同默认组上)。
|
||||
await loadCategoryScope()
|
||||
void loadCategoryOptions()
|
||||
await load()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="jd-database-view">
|
||||
<section class="panel-box">
|
||||
<div class="jd-panel-head">
|
||||
<h3>京东数据库</h3>
|
||||
</div>
|
||||
|
||||
<div class="jd-filter-row">
|
||||
<div class="form-group">
|
||||
<label>商品编码</label>
|
||||
<input v-model="filter.productCode" type="text" placeholder="输入商品编码" @keyup.enter="apply" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>标题关键字</label>
|
||||
<input v-model="filter.titleKeyword" type="text" placeholder="输入标题关键字" @keyup.enter="apply" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>类目</label>
|
||||
<!-- 类目(京麦末级类目)京麦同款级联面板(2026-11-16 客户口径):一/二级为静态导航
|
||||
(采集链无层级数据),第三栏已落库末级+搜索,点行选中即查(回第一页)。 -->
|
||||
<JdCategoryCascader
|
||||
:options="categoryOptions"
|
||||
:model-value="filter.category"
|
||||
tree-only
|
||||
@change="onCategoryPicked"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="categoryScope.length" class="form-group">
|
||||
<label>分组</label>
|
||||
<!-- 当前分组(V203):能看多组的人(平台超管/公司超管)下拉切换;只有一组时锁定显示组名。
|
||||
2026-11-16 用户口径「做成分组」:从工具栏裸下拉上移进筛选行,做成带标签的表单控件
|
||||
(与其他筛选同壳同圆角)。分组是分类列/分类筛选/分类管理的作用域,不是筛选条件
|
||||
⇒ 放在筛选行也只是占位,「重置」不清它(挂载测试钉住)。 -->
|
||||
<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 class="jd-group-locked" title="你的数据权限内只有这一个分组">{{ currentGroupName }}</span>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>同步开始日期</label>
|
||||
<input v-model="filter.syncedFrom" type="date" :max="filter.syncedTo" @change="clampJdSyncedRange" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>同步结束日期</label>
|
||||
<input v-model="filter.syncedTo" type="date" :min="filter.syncedFrom" @change="clampJdSyncedRange" />
|
||||
</div>
|
||||
<div class="jd-filter-actions">
|
||||
<button class="btn" type="button" @click="apply">查询</button>
|
||||
<button class="btn btn-secondary" type="button" @click="reset">重置</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="jd-toolbar">
|
||||
<span class="jd-summary">共 {{ total }} 条京东商品</span>
|
||||
<!-- 批量编辑分类(2026-11-17 用户口径「店铺分类弹窗删了,加个批量编辑分类」):
|
||||
只对当前分组可写档(本组管理员/公司超管/平台超管)渲染;勾选 0 时置灰(与
|
||||
删除勾选同款常显口径),打开后按累计勾选(跨页)提交归入/移出。 -->
|
||||
<button
|
||||
v-if="canManageCategories"
|
||||
class="btn btn-secondary"
|
||||
type="button"
|
||||
:disabled="!selectedCount"
|
||||
@click="openBatchEdit"
|
||||
>批量编辑分类</button>
|
||||
<!-- 商品行写只对平台超管;分类写由当前分组 editable 决定(本组管理员/公司超管/平台超管)。
|
||||
非超管看到只读提示,分类维护入口=工具栏「分类管理」(只读可看,写控件按 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 用户口径「京东分类管理并到京东数据库分类编辑里」):V204 独立
|
||||
子菜单页整体并入本对话框(搜索+新建+改名+删除)。入口对所有人渲染(同组普通号
|
||||
只读可看,V203),写控件由对话框按当前分组 editable 分档。 -->
|
||||
<button
|
||||
class="btn btn-secondary jd-manage-btn"
|
||||
type="button"
|
||||
@click="openManage"
|
||||
>分类管理</button>
|
||||
<!-- 批量删除 2026-11-16 客户口径「不要勾选后才显示」:常显,勾选 0 时置灰。
|
||||
同日写权限收窄到超管:非超管整颗按钮不渲染(勾选列 2026-11-17 起对本组可写
|
||||
分类管理员开放,服务批量归类)。 -->
|
||||
<button
|
||||
v-if="isSuperAdmin"
|
||||
class="btn btn-danger jd-delete-btn"
|
||||
type="button"
|
||||
:disabled="deleting || !selectedCount"
|
||||
@click="removeSelected"
|
||||
>
|
||||
{{ deleting ? '删除中...' : `删除勾选(${selectedCount})` }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="table-scroll jd-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-if="hasSelectionColumn" style="width: 42px"><input type="checkbox" :checked="allSelected" @change="toggleSelectAll(($event.target as HTMLInputElement).checked)" /></th>
|
||||
<th style="width: 92px">分类</th>
|
||||
<th style="width: 520px">商品信息</th>
|
||||
<th style="width: 76px">总库存</th>
|
||||
<th style="width: 120px">价格</th>
|
||||
<!-- 同步时间收尾(创建/修改两列 2026-11-16 客户口径「不要」下线,仍收详情抽屉);
|
||||
操作列 2026-11-16「操作放最后一列」口径置末;同日写权限收窄到超管 ⇒ 非超管不渲染。 -->
|
||||
<th style="width: 170px">同步时间</th>
|
||||
<th v-if="isSuperAdmin" style="width: 138px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="rows.length">
|
||||
<tr v-for="row in rows" :key="row.id" class="jd-row" @click="openDetail(row)">
|
||||
<td v-if="hasSelectionColumn" @click.stop><input type="checkbox" :checked="selectedIds.has(row.id)" @change="toggleSelect(row, ($event.target as HTMLInputElement).checked)" /></td>
|
||||
<td :title="row.groupName || ''">{{ row.groupName || '未分类' }}</td>
|
||||
<td class="jd-info-cell">
|
||||
<div class="jd-info-wrap">
|
||||
<div class="jd-info-figure">
|
||||
<img v-if="row.mainImageUrl" class="jd-thumb" :src="row.mainImageUrl" alt="" loading="lazy" />
|
||||
<span v-else class="jd-thumb jd-thumb-empty">无图</span>
|
||||
<span v-if="row.healthScore !== null" class="jd-health">信息分 {{ row.healthScore }}</span>
|
||||
</div>
|
||||
<div class="jd-info-body">
|
||||
<div class="jd-info-title" :title="row.title">{{ row.title || '-' }}</div>
|
||||
<div class="jd-info-meta">
|
||||
商品编码:<span class="jd-info-code">{{ row.productCode || '-' }}</span>
|
||||
<button v-if="row.productCode" class="jd-copy-btn" type="button" title="复制商品编码" @click.stop="copyText(row.productCode)">⧉</button>
|
||||
</div>
|
||||
<div class="jd-info-meta">货号:<span class="jd-info-code">{{ row.itemNum || '-' }}</span></div>
|
||||
<!-- 品牌·类目行:京麦列表同款(末级类目名紧随品牌),字段与顺序 2026-11-15 对齐京麦。 -->
|
||||
<div v-if="row.brand || row.categoryPath" class="jd-info-meta jd-brand-cat">
|
||||
<span class="jd-brand-name">{{ row.brand || '' }}</span> {{ row.categoryPath || '' }}
|
||||
</div>
|
||||
<div v-if="row.skuCount" class="jd-info-tags"><span class="jd-tag">{{ row.skuCount }}个SKU</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td>{{ row.stockTotal ?? '-' }}</td>
|
||||
<td>{{ jdPriceRange(row) || '-' }}</td>
|
||||
<td>{{ formatDateTime(row.syncedAt || '') }}</td>
|
||||
<!-- 操作列(2026-11-15 用户口径):编辑/删除;@click.stop 防冒泡开详情抽屉。
|
||||
2026-11-16「操作放最后一列」口径置末;「上架时间 / 商品状态」列同日整列下线;
|
||||
同日写权限收窄到超管 ⇒ 非超管不渲染该列。 -->
|
||||
<td v-if="isSuperAdmin" class="jd-ops-cell" @click.stop>
|
||||
<button class="btn btn-sm" type="button" @click="openEdit(row)">编辑</button>
|
||||
<button class="btn btn-sm btn-danger" type="button" :disabled="deleting" @click="removeOne(row)">删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td :colspan="emptyColspan" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td :colspan="emptyColspan" class="empty-tip">暂无京东商品数据</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<OldPagination :total="total" :page="page" :page-size="pageSize" @change="changePage" @size-change="changeSize" />
|
||||
</section>
|
||||
|
||||
<JdBatchAssignDialog
|
||||
:visible="batchEditVisible"
|
||||
:owner-group-id="ownerGroupId"
|
||||
:owner-group-name="currentGroupName"
|
||||
:categories="groupOptions"
|
||||
:selected-ids="[...selectedIds]"
|
||||
@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"
|
||||
@close="closeDetail"
|
||||
/>
|
||||
<JdProductEditDrawer
|
||||
:item="editItem"
|
||||
:visible="editVisible"
|
||||
@close="closeEdit"
|
||||
@saved="onEditSaved"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped src="./jd-database-page.css"></style>
|
||||
@@ -0,0 +1,685 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东商品详情抽屉(v1.4 Phase 5):点行打开,展示基本信息 + attrGroups 分块表格 +
|
||||
* 图片网格(MAIN/ATTR/DETAIL 三区,attr 图按 attrName 归并)。
|
||||
* 基本信息=商品全部字段(B104:列表只摆部分字段,类目/信息分/SKU 数/上架时间/京东创建/
|
||||
* 修改时间/店铺/分组都在这里看)。
|
||||
* 图片点击放大预览用自绘 modal-mask(先例:RecordsHistoryPage 的 thumb + modal-mask +
|
||||
* 原图新标签;不用 element-plus)。数据由本组件按 id 自取(公共库无公司维度),失败条内提示可重试。 */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { fetchJdProductDetail } from './jd-product-api.ts'
|
||||
import type {
|
||||
JdProductImage,
|
||||
JdProductItem,
|
||||
JdProductAttrGroup,
|
||||
JdProductSku,
|
||||
} from './jd-product-model.ts'
|
||||
import { jdPriceRange, jdSkuDimensions, jdSkuSummary } from './jd-product-model.ts'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { requestErrorMessage } from '../../api/envelope.ts'
|
||||
|
||||
const props = defineProps<{
|
||||
item: JdProductItem | null
|
||||
visible: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'close'): void }>()
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const attrGroups = ref<JdProductAttrGroup[]>([])
|
||||
const images = ref<JdProductImage[]>([])
|
||||
const skus = ref<JdProductSku[]>([])
|
||||
const attrJsonRaw = ref('')
|
||||
|
||||
/** SKU 矩阵维度(京麦「颜色 / 尺码」两列)与表头汇总。 */
|
||||
const skuDimensions = computed(() => jdSkuDimensions(skus.value))
|
||||
const skuSummary = computed(() => jdSkuSummary(skus.value))
|
||||
|
||||
function skuAttrValue(sku: JdProductSku, dimension: string): string {
|
||||
return sku.saleAttrs.find((attr) => attr.name === dimension)?.value || '-'
|
||||
}
|
||||
|
||||
/** 图片三区:MAIN / ATTR / DETAIL;未知类型归 DETAIL 之外的「其他」,不丢。 */
|
||||
const mainImages = computed(() => images.value.filter((image) => image.imageType === 'MAIN'))
|
||||
|
||||
/** 顶部画廊(2026-11-16 客户口径「详情页样式和京麦商品详情一样」=左图右信息):
|
||||
* 左侧主图大图+缩略图切换(MAIN 档),右侧关键信息。 */
|
||||
const galleryImages = computed(() => mainImages.value)
|
||||
const activeImageUrl = ref('')
|
||||
|
||||
function switchGallery(image: JdProductImage): void {
|
||||
activeImageUrl.value = image.url
|
||||
}
|
||||
const attrImageGroups = computed(() => {
|
||||
const buckets = new Map<string, JdProductImage[]>()
|
||||
for (const image of images.value) {
|
||||
if (image.imageType !== 'ATTR') continue
|
||||
const key = image.attrName || '属性图'
|
||||
const bucket = buckets.get(key)
|
||||
if (bucket) bucket.push(image)
|
||||
else buckets.set(key, [image])
|
||||
}
|
||||
return [...buckets.entries()].map(([attrName, list]) => ({ attrName, list }))
|
||||
})
|
||||
const detailImages = computed(() => images.value.filter((image) => image.imageType === 'DETAIL'))
|
||||
const otherImages = computed(() =>
|
||||
images.value.filter((image) => image.imageType !== 'MAIN' && image.imageType !== 'ATTR' && image.imageType !== 'DETAIL'),
|
||||
)
|
||||
|
||||
/** 放大预览:点缩略图弹自绘 modal-mask,原图可新标签打开。 */
|
||||
const previewVisible = ref(false)
|
||||
const previewUrl = ref('')
|
||||
|
||||
function openPreview(url: string): void {
|
||||
previewUrl.value = url
|
||||
previewVisible.value = true
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
previewVisible.value = false
|
||||
emit('close')
|
||||
}
|
||||
|
||||
async function loadDetail(): Promise<void> {
|
||||
const item = props.item
|
||||
if (!item) return
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
attrGroups.value = []
|
||||
images.value = []
|
||||
skus.value = []
|
||||
attrJsonRaw.value = ''
|
||||
try {
|
||||
const detail = await fetchJdProductDetail(item.id)
|
||||
attrGroups.value = detail.attrGroups
|
||||
images.value = detail.images
|
||||
skus.value = detail.skus
|
||||
attrJsonRaw.value = detail.attrJsonRaw
|
||||
activeImageUrl.value = detail.images.find((image) => image.imageType === 'MAIN')?.url || ''
|
||||
if (!detail.attrGroups.length && detail.attrJsonRaw) {
|
||||
// 结构化解析失败但原文在:兜底展示原文,不静默吞
|
||||
loadFailure.value = ''
|
||||
}
|
||||
} catch (error) {
|
||||
loadFailure.value = requestErrorMessage(error) || '商品详情加载失败'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.visible, props.item?.id] as const,
|
||||
([visible]) => {
|
||||
previewVisible.value = false
|
||||
previewUrl.value = ''
|
||||
activeImageUrl.value = ''
|
||||
if (visible && props.item) void loadDetail()
|
||||
},
|
||||
)
|
||||
|
||||
function dash(value: string | number | null | undefined): string {
|
||||
const text = value === null || value === undefined ? '' : String(value).trim()
|
||||
return text || '-'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="drawer-mask" @click.self="close">
|
||||
<aside class="drawer">
|
||||
<header class="drawer-head">
|
||||
<h3>商品详情{{ item?.productCode ? ` · ${item.productCode}` : '' }}</h3>
|
||||
<button class="drawer-close" type="button" aria-label="关闭" @click="close">×</button>
|
||||
</header>
|
||||
|
||||
<div class="drawer-body">
|
||||
<div v-if="loadFailure" class="drawer-failure">
|
||||
<span>{{ loadFailure }}</span>
|
||||
<button class="btn btn-secondary" type="button" @click="loadDetail">重试</button>
|
||||
</div>
|
||||
<p v-else-if="loading" class="drawer-tip">加载中...</p>
|
||||
|
||||
<template v-else>
|
||||
<!-- 顶部「左图右信息」(2026-11-16 客户口径「详情页的样式要和京麦商品详情一样的布局样式」):
|
||||
左侧主图大图+缩略图切换,右侧关键信息;属性/SKU/详情图等区块保持下方。 -->
|
||||
<section class="detail-block">
|
||||
<div class="detail-hero">
|
||||
<div class="hero-gallery">
|
||||
<img
|
||||
v-if="activeImageUrl"
|
||||
class="hero-main"
|
||||
:src="activeImageUrl"
|
||||
alt=""
|
||||
title="点击放大预览"
|
||||
@click="openPreview(activeImageUrl)"
|
||||
/>
|
||||
<div v-else class="hero-empty">无图</div>
|
||||
<div v-if="galleryImages.length > 1" class="hero-thumbs">
|
||||
<img
|
||||
v-for="image in galleryImages"
|
||||
:key="image.id"
|
||||
:src="image.url"
|
||||
alt=""
|
||||
loading="lazy"
|
||||
:class="{ active: image.url === activeImageUrl }"
|
||||
title="切换主图"
|
||||
@click="switchGallery(image)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<dl class="hero-info">
|
||||
<div class="info-item info-item-wide hero-title">
|
||||
<dt>标题</dt>
|
||||
<dd :title="item?.title || ''">{{ dash(item?.title) }}</dd>
|
||||
</div>
|
||||
<div class="info-item"><dt>价格区间</dt><dd>{{ dash(jdPriceRange(item ?? { priceMin: '', priceMax: '' })) }}</dd></div>
|
||||
<div class="info-item"><dt>总库存</dt><dd>{{ dash(item?.stockTotal) }}</dd></div>
|
||||
<div class="info-item"><dt>状态</dt><dd>{{ dash(item?.saleStatus) }}</dd></div>
|
||||
<div class="info-item"><dt>信息分</dt><dd>{{ dash(item?.healthScore) }}</dd></div>
|
||||
<div class="info-item"><dt>SKU 数</dt><dd>{{ dash(item?.skuCount) }}</dd></div>
|
||||
<div class="info-item"><dt>商品编码</dt><dd>{{ dash(item?.productCode) }}</dd></div>
|
||||
<div class="info-item"><dt>货号</dt><dd>{{ dash(item?.itemNum) }}</dd></div>
|
||||
<div class="info-item"><dt>SKU</dt><dd>{{ dash(item?.skuId) }}</dd></div>
|
||||
<div class="info-item"><dt>品牌</dt><dd>{{ dash(item?.brand) }}</dd></div>
|
||||
<div class="info-item"><dt>店铺</dt><dd :title="item?.shopName || ''">{{ dash(item?.shopName) }}</dd></div>
|
||||
<div class="info-item"><dt>分类</dt><dd>{{ dash(item?.groupName || '未分类') }}</dd></div>
|
||||
<div class="info-item info-item-wide"><dt>类目</dt><dd :title="item?.categoryPath || ''">{{ dash(item?.categoryPath) }}</dd></div>
|
||||
<div class="info-item"><dt>上架时间</dt><dd>{{ item?.jdOnlineAt ? formatDateTime(item.jdOnlineAt) : '-' }}</dd></div>
|
||||
<div class="info-item"><dt>同步时间</dt><dd>{{ formatDateTime(item?.syncedAt || '') }}</dd></div>
|
||||
<div class="info-item"><dt>京东创建时间</dt><dd>{{ item?.jdCreatedAt ? formatDateTime(item.jdCreatedAt) : '-' }}</dd></div>
|
||||
<div class="info-item"><dt>京东修改时间</dt><dd>{{ item?.jdUpdatedAt ? formatDateTime(item.jdUpdatedAt) : '-' }}</dd></div>
|
||||
</dl>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="attrGroups.length" class="detail-block">
|
||||
<h4>属性与设置(按京麦 Tab 分组)</h4>
|
||||
<div v-for="group in attrGroups" :key="group.groupName" class="attr-group">
|
||||
<h5>{{ group.groupName }}</h5>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr v-for="(attr, index) in group.attrs" :key="`${attr.key}-${index}`">
|
||||
<th>{{ attr.label || attr.key || '-' }}</th>
|
||||
<td>{{ attr.value || '-' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<section v-else-if="attrJsonRaw" class="detail-block">
|
||||
<h4>属性(原始 JSON)</h4>
|
||||
<pre class="attr-raw">{{ attrJsonRaw }}</pre>
|
||||
</section>
|
||||
|
||||
<section class="detail-block">
|
||||
<h4>销售属性 / SKU 矩阵</h4>
|
||||
<template v-if="skus.length">
|
||||
<p class="sku-summary">{{ skuSummary }}</p>
|
||||
<div class="sku-table-wrap">
|
||||
<table class="sku-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>序号</th>
|
||||
<th v-for="dimension in skuDimensions" :key="dimension">{{ dimension }}</th>
|
||||
<th>京东价</th>
|
||||
<th>库存</th>
|
||||
<th>SKU ID</th>
|
||||
<th>SKU 名称</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(sku, index) in skus" :key="sku.skuId">
|
||||
<td>{{ sku.skuSeq || index + 1 }}</td>
|
||||
<td v-for="dimension in skuDimensions" :key="dimension">{{ skuAttrValue(sku, dimension) }}</td>
|
||||
<td>{{ sku.price ? `¥${sku.price}` : '-' }}</td>
|
||||
<td>{{ dash(sku.stock) }}</td>
|
||||
<td class="sku-id">{{ sku.skuId }}</td>
|
||||
<td :title="sku.skuName">{{ dash(sku.skuName) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
<p v-else class="drawer-tip">暂无 SKU 矩阵(V198 之前采集的旧行需重新采集)</p>
|
||||
</section>
|
||||
|
||||
<section class="detail-block">
|
||||
<h4>主图</h4>
|
||||
<div v-if="mainImages.length" class="image-grid">
|
||||
<img
|
||||
v-for="image in mainImages"
|
||||
:key="image.url"
|
||||
:src="image.url"
|
||||
alt=""
|
||||
title="点击放大预览"
|
||||
@click="openPreview(image.url)"
|
||||
/>
|
||||
</div>
|
||||
<p v-else class="drawer-tip">暂无主图</p>
|
||||
</section>
|
||||
|
||||
<section v-for="bucket in attrImageGroups" :key="bucket.attrName" class="detail-block">
|
||||
<h4>属性图 · {{ bucket.attrName }}</h4>
|
||||
<div class="image-grid">
|
||||
<img
|
||||
v-for="image in bucket.list"
|
||||
:key="image.url"
|
||||
:src="image.url"
|
||||
alt=""
|
||||
title="点击放大预览"
|
||||
@click="openPreview(image.url)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="detail-block">
|
||||
<h4>详情图</h4>
|
||||
<div v-if="detailImages.length" class="image-grid">
|
||||
<img
|
||||
v-for="image in detailImages"
|
||||
:key="image.url"
|
||||
:src="image.url"
|
||||
alt=""
|
||||
title="点击放大预览"
|
||||
@click="openPreview(image.url)"
|
||||
/>
|
||||
</div>
|
||||
<p v-else class="drawer-tip">暂无详情图</p>
|
||||
</section>
|
||||
|
||||
<section v-if="otherImages.length" class="detail-block">
|
||||
<h4>其他图</h4>
|
||||
<div class="image-grid">
|
||||
<img
|
||||
v-for="image in otherImages"
|
||||
:key="image.url"
|
||||
:src="image.url"
|
||||
alt=""
|
||||
title="点击放大预览"
|
||||
@click="openPreview(image.url)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div v-if="previewVisible" class="modal-mask" @click.self="previewVisible = false">
|
||||
<div class="preview-modal">
|
||||
<div class="preview-head">
|
||||
<h3>图片预览</h3>
|
||||
<button class="drawer-close" type="button" aria-label="关闭" @click="previewVisible = false">×</button>
|
||||
</div>
|
||||
<img class="preview-image" :src="previewUrl" alt="" />
|
||||
<div class="preview-foot">
|
||||
<a :href="previewUrl" target="_blank" rel="noopener">新标签打开原图</a>
|
||||
<button class="btn btn-secondary" type="button" @click="previewVisible = false">关闭</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.drawer-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2600;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
background: rgba(45, 66, 86, 0.36);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
.drawer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(920px, 100%);
|
||||
height: 100%;
|
||||
background: #ffffff;
|
||||
box-shadow: -18px 0 40px rgba(39, 67, 94, 0.18);
|
||||
}
|
||||
.drawer-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid #dbe5ee;
|
||||
}
|
||||
.drawer-head h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
}
|
||||
.drawer-close {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 9px;
|
||||
background: none;
|
||||
color: #5b6f83;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.drawer-close:hover {
|
||||
border-color: #cbd9e6;
|
||||
background: #eef4fa;
|
||||
color: #24384d;
|
||||
}
|
||||
.drawer-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 16px 20px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
.drawer-tip {
|
||||
margin: 0;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.drawer-failure {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid #f0c9c2;
|
||||
border-radius: 10px;
|
||||
background: #fdf1ef;
|
||||
color: #a04432;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.detail-block h4 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 13.5px;
|
||||
font-weight: 650;
|
||||
color: #4e6479;
|
||||
}
|
||||
/* 顶部「左图右信息」(京麦详情布局):左侧主图大图+缩略图切换,右侧关键信息网格。 */
|
||||
.detail-hero {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
}
|
||||
.hero-gallery {
|
||||
flex: 0 0 300px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.hero-main {
|
||||
display: block;
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
object-fit: cover;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 10px;
|
||||
background: #f2f7fb;
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.hero-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
border: 1px dashed #c7d7e5;
|
||||
border-radius: 10px;
|
||||
background: #f8fbfd;
|
||||
color: #8293a5;
|
||||
font-size: 13px;
|
||||
}
|
||||
.hero-thumbs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.hero-thumbs img {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
object-fit: cover;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
opacity: 0.85;
|
||||
}
|
||||
.hero-thumbs img.active {
|
||||
outline: 2px solid #2f5d8b;
|
||||
opacity: 1;
|
||||
}
|
||||
.hero-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px 16px;
|
||||
margin: 0;
|
||||
}
|
||||
.hero-info dt {
|
||||
color: #5b6f83;
|
||||
font-size: 12px;
|
||||
margin-bottom: 3px;
|
||||
}
|
||||
.hero-info dd {
|
||||
margin: 0;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.hero-title dd {
|
||||
font-size: 14.5px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
white-space: normal;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.detail-hero {
|
||||
flex-direction: column;
|
||||
}
|
||||
.hero-gallery {
|
||||
flex-basis: auto;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
.info-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 10px 16px;
|
||||
margin: 0;
|
||||
}
|
||||
.info-item {
|
||||
min-width: 0;
|
||||
}
|
||||
.info-item-wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.info-item dt {
|
||||
color: #5b6f83;
|
||||
font-size: 12px;
|
||||
margin-bottom: 3px;
|
||||
}
|
||||
.info-item dd {
|
||||
margin: 0;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.attr-group {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.attr-group h5 {
|
||||
margin: 0 0 6px;
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.attr-group table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.attr-group th,
|
||||
.attr-group td {
|
||||
padding: 7px 10px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
font-size: 13px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
.attr-group th {
|
||||
width: 180px;
|
||||
background: #f2f7fb;
|
||||
color: #4e6479;
|
||||
font-weight: 600;
|
||||
}
|
||||
.attr-group tr:last-child th,
|
||||
.attr-group tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.attr-raw {
|
||||
margin: 0;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 8px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 12px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.sku-summary {
|
||||
margin: 0 0 8px;
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.sku-table-wrap {
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.sku-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sku-table th,
|
||||
.sku-table td {
|
||||
padding: 7px 10px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
text-align: left;
|
||||
color: #24384d;
|
||||
}
|
||||
.sku-table th {
|
||||
background: #f2f7fb;
|
||||
color: #4e6479;
|
||||
font-weight: 600;
|
||||
}
|
||||
.sku-table tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.sku-table .sku-id {
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
color: #4e6479;
|
||||
}
|
||||
.image-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.image-grid img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
object-fit: cover;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 8px;
|
||||
background: #f2f7fb;
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.modal-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 3000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 40px 20px;
|
||||
background: rgba(45, 66, 86, 0.36);
|
||||
backdrop-filter: blur(6px);
|
||||
}
|
||||
.preview-modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(880px, 100%);
|
||||
max-height: 88vh;
|
||||
padding: 16px 20px;
|
||||
border: 1px solid #c7d7e5;
|
||||
border-radius: 14px;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 22px 60px rgba(39, 67, 94, 0.2);
|
||||
}
|
||||
.preview-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.preview-head h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
color: #24384d;
|
||||
}
|
||||
.preview-image {
|
||||
display: block;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
max-height: 68vh;
|
||||
margin: 12px 0;
|
||||
object-fit: contain;
|
||||
background: #f2f7fb;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.preview-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.preview-foot a {
|
||||
color: #2f5d8b;
|
||||
font-size: 13px;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 38px;
|
||||
padding: 7px 16px;
|
||||
border-radius: 9px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border: 1px solid #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,616 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东商品编辑抽屉(2026-11-15 用户口径「每一条数据后面 需要编辑或者删除;编辑的话
|
||||
* 这里面都是可以编辑的」):详情抽屉的可编辑版——基本信息/属性与设置/SKU 矩阵(价格、
|
||||
* 库存)/图片(标删)四块。形状照 JdProductDetailDrawer(自绘 drawer + 分块 + attr-group
|
||||
* 表格 + image-grid,零 element-plus)。
|
||||
* 保存语义在后端 JdProductUpdateService(PUT /api/admin/jd-products/{id}):主字段全量提交
|
||||
* +可选块(attrGroups 重建 attr_json 的 tabs 段、skus 按 skuId 改价格库存、deleteImageIds
|
||||
* 删图——先删桶、共用对象保留)。保存即置人工编辑锁 manual_locked=1:后续采集不再覆盖该行,
|
||||
* 底部常驻提示点名这件事。
|
||||
* V203(2026-11-16):分类<b>不在本抽屉编辑</b>(分类按数据权限分组隔离,归属存
|
||||
* biz_jd_product_group_assign,归类只走「店铺分类」弹窗)——原「分类」下拉与 groupId 负载已下线,
|
||||
* 避免写遗留的 biz_jd_product.group_id 列造成「界面改了、列表分组没变」。
|
||||
* 图片区拆在 JdProductImageManager 子组件(2026-11-16:× 右上角标删+替换/新增本地图,
|
||||
* B109-01 落地;标删集合经 update:deleteIds 上抛进保存负载,上传立即生效由子组件自理)。
|
||||
* 京东时间/信息分/商品编码只读。
|
||||
* 数据自取 fetchJdProductDetail 回填,保存成功用返回的刷新详情直接回填并 emit('saved')。 */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import {
|
||||
fetchJdProductDetail,
|
||||
updateJdProduct,
|
||||
} from './jd-product-api.ts'
|
||||
import JdProductImageManager from './JdProductImageManager.vue'
|
||||
import type {
|
||||
JdProductAttrEntry,
|
||||
JdProductAttrGroup,
|
||||
JdProductImage,
|
||||
JdProductItem,
|
||||
JdProductSku,
|
||||
} from './jd-product-model.ts'
|
||||
import { jdSkuDimensions } from './jd-product-model.ts'
|
||||
import { requestErrorMessage } from '../../api/envelope.ts'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
|
||||
const props = defineProps<{
|
||||
item: JdProductItem | null
|
||||
visible: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ (event: 'close'): void; (event: 'saved'): void }>()
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const saving = ref(false)
|
||||
/** 保存失败红条(后端校验/业务文案原样展示,如价格倒挂、SKU 行不存在)。 */
|
||||
const saveError = ref('')
|
||||
|
||||
// ---------------- 草稿(基本信息 + 属性 + SKU + 删图标记) ----------------
|
||||
|
||||
interface DraftAttrGroup {
|
||||
groupName: string
|
||||
attrs: JdProductAttrEntry[]
|
||||
}
|
||||
|
||||
const form = ref({
|
||||
title: '',
|
||||
brand: '',
|
||||
categoryPath: '',
|
||||
itemNum: '',
|
||||
priceMin: '',
|
||||
priceMax: '',
|
||||
stockTotal: '' as string,
|
||||
saleStatus: '',
|
||||
})
|
||||
const draftAttrGroups = ref<DraftAttrGroup[]>([])
|
||||
const draftSkus = ref<JdProductSku[]>([])
|
||||
const images = ref<JdProductImage[]>([])
|
||||
/** 图片子组件上抛的标删行 id(保存时一次提交 deleteImageIds)。 */
|
||||
const managerDeleteIds = ref<number[]>([])
|
||||
/** attr_json 解析失败(attrJsonRaw 兜底行):属性块禁用,防保存把原文形状弄丢。 */
|
||||
const attrJsonRaw = ref('')
|
||||
|
||||
const skuDimensions = computed(() => jdSkuDimensions(draftSkus.value))
|
||||
|
||||
function skuAttrValue(sku: JdProductSku, dimension: string): string {
|
||||
return sku.saleAttrs.find((attr) => attr.name === dimension)?.value || '-'
|
||||
}
|
||||
|
||||
function removeAttrRow(group: DraftAttrGroup, index: number): void {
|
||||
group.attrs.splice(index, 1)
|
||||
}
|
||||
|
||||
// ---------------- 取数与保存 ----------------
|
||||
|
||||
async function loadDetail(): Promise<void> {
|
||||
const item = props.item
|
||||
if (!item) return
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
saveError.value = ''
|
||||
try {
|
||||
const detail = await fetchJdProductDetail(item.id)
|
||||
const row = detail.item
|
||||
form.value = {
|
||||
title: row.title,
|
||||
brand: row.brand,
|
||||
categoryPath: row.categoryPath,
|
||||
itemNum: row.itemNum,
|
||||
priceMin: row.priceMin,
|
||||
priceMax: row.priceMax,
|
||||
stockTotal: row.stockTotal === null ? '' : String(row.stockTotal),
|
||||
saleStatus: row.saleStatus,
|
||||
}
|
||||
// 深拷贝草稿:直接改副本,保存前才拼负载。
|
||||
draftAttrGroups.value = detail.attrGroups.map((group: JdProductAttrGroup) => ({
|
||||
groupName: group.groupName,
|
||||
attrs: group.attrs.map((attr) => ({ ...attr })),
|
||||
}))
|
||||
draftSkus.value = detail.skus.map((sku) => ({ ...sku }))
|
||||
images.value = detail.images
|
||||
managerDeleteIds.value = []
|
||||
attrJsonRaw.value = detail.attrJsonRaw
|
||||
} catch (error) {
|
||||
loadFailure.value = requestErrorMessage(error) || '商品详情加载失败'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function close(): void {
|
||||
emit('close')
|
||||
}
|
||||
|
||||
/** 保存:主字段全量 + 有改动的可选块。前端先拦「标题为空」(后端 @NotBlank 同判),失败红条。 */
|
||||
async function save(): Promise<void> {
|
||||
if (!props.item || saving.value) return
|
||||
saveError.value = ''
|
||||
if (!form.value.title.trim()) {
|
||||
saveError.value = '标题不能为空'
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
try {
|
||||
const detail = await updateJdProduct(props.item.id, {
|
||||
title: form.value.title.trim(),
|
||||
brand: form.value.brand.trim() || null,
|
||||
categoryPath: form.value.categoryPath.trim() || null,
|
||||
itemNum: form.value.itemNum.trim() || null,
|
||||
priceMin: form.value.priceMin.trim() || null,
|
||||
priceMax: form.value.priceMax.trim() || null,
|
||||
stockTotal: form.value.stockTotal.trim() === '' ? null : Number(form.value.stockTotal),
|
||||
saleStatus: form.value.saleStatus.trim() || null,
|
||||
// 属性块:原文兜底行(解析失败)不提交,防保存把解析不出的原文形状弄丢。
|
||||
attrGroups: attrJsonRaw.value
|
||||
? null
|
||||
: draftAttrGroups.value.map((group) => ({
|
||||
groupName: group.groupName,
|
||||
attrs: group.attrs.map((attr) => ({
|
||||
key: attr.key,
|
||||
label: attr.label,
|
||||
value: attr.value,
|
||||
})),
|
||||
})),
|
||||
skus: draftSkus.value.length
|
||||
? draftSkus.value.map((sku) => ({
|
||||
skuId: sku.skuId,
|
||||
price: sku.price || null,
|
||||
stock: sku.stock,
|
||||
}))
|
||||
: null,
|
||||
deleteImageIds: managerDeleteIds.value.length ? [...managerDeleteIds.value] : null,
|
||||
})
|
||||
// 保存成功:用返回的刷新详情直接回填(图片行集已扣掉删掉的行、计数已刷新)。
|
||||
form.value.title = detail.item.title
|
||||
form.value.brand = detail.item.brand
|
||||
form.value.categoryPath = detail.item.categoryPath
|
||||
form.value.itemNum = detail.item.itemNum
|
||||
form.value.priceMin = detail.item.priceMin
|
||||
form.value.priceMax = detail.item.priceMax
|
||||
form.value.stockTotal = detail.item.stockTotal === null ? '' : String(detail.item.stockTotal)
|
||||
form.value.saleStatus = detail.item.saleStatus
|
||||
draftAttrGroups.value = detail.attrGroups.map((group) => ({
|
||||
groupName: group.groupName,
|
||||
attrs: group.attrs.map((attr) => ({ ...attr })),
|
||||
}))
|
||||
draftSkus.value = detail.skus.map((sku) => ({ ...sku }))
|
||||
images.value = detail.images
|
||||
managerDeleteIds.value = []
|
||||
showAdminFeedback('已保存,该商品已转为人工维护(采集不再覆盖)', 'success')
|
||||
emit('saved')
|
||||
} catch (error) {
|
||||
saveError.value = requestErrorMessage(error) || '保存失败,请稍后重试'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.visible, props.item?.id] as const,
|
||||
([visible]) => {
|
||||
if (visible && props.item) void loadDetail()
|
||||
},
|
||||
)
|
||||
|
||||
function dash(value: string | number | null | undefined): string {
|
||||
const text = value === null || value === undefined ? '' : String(value).trim()
|
||||
return text || '-'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="visible" class="drawer-mask" @click.self="close">
|
||||
<aside class="drawer">
|
||||
<header class="drawer-head">
|
||||
<h3>编辑商品{{ item?.productCode ? ` · ${item.productCode}` : '' }}</h3>
|
||||
<button class="drawer-close" type="button" aria-label="关闭" @click="close">×</button>
|
||||
</header>
|
||||
|
||||
<div class="drawer-body">
|
||||
<div v-if="loadFailure" class="drawer-failure">
|
||||
<span>{{ loadFailure }}</span>
|
||||
<button class="btn btn-secondary" type="button" @click="loadDetail">重试</button>
|
||||
</div>
|
||||
<p v-else-if="loading" class="drawer-tip">加载中...</p>
|
||||
|
||||
<template v-else>
|
||||
<section class="detail-block">
|
||||
<h4>基本信息</h4>
|
||||
<div class="edit-grid">
|
||||
<div class="edit-item edit-item-wide">
|
||||
<label>标题</label>
|
||||
<input v-model="form.title" type="text" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>品牌</label>
|
||||
<input v-model="form.brand" type="text" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>类目</label>
|
||||
<input v-model="form.categoryPath" type="text" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>货号(系统生成=行号,可改)</label>
|
||||
<input v-model="form.itemNum" type="text" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>状态</label>
|
||||
<input v-model="form.saleStatus" type="text" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>价格下限</label>
|
||||
<input v-model="form.priceMin" type="text" inputmode="decimal" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>价格上限</label>
|
||||
<input v-model="form.priceMax" type="text" inputmode="decimal" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>总库存</label>
|
||||
<input v-model="form.stockTotal" type="text" inputmode="numeric" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>商品编码(只读)</label>
|
||||
<input type="text" :value="dash(item?.productCode)" readonly class="readonly" />
|
||||
</div>
|
||||
<div class="edit-item">
|
||||
<label>信息分(只读)</label>
|
||||
<input type="text" :value="dash(item?.healthScore)" readonly class="readonly" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="draftAttrGroups.length" class="detail-block">
|
||||
<h4>属性与设置(键值可改,行可删)</h4>
|
||||
<div v-for="group in draftAttrGroups" :key="group.groupName" class="attr-group">
|
||||
<h5>{{ group.groupName }}</h5>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr v-for="(attr, index) in group.attrs" :key="`${attr.key}-${index}`">
|
||||
<th>{{ attr.label || attr.key || '-' }}</th>
|
||||
<td><input v-model="attr.value" type="text" class="attr-input" /></td>
|
||||
<td class="attr-remove-cell">
|
||||
<button class="attr-remove" type="button" title="删除该属性行" @click="removeAttrRow(group, index)">删</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<p v-else-if="attrJsonRaw" class="drawer-tip">属性原文解析失败(原始 JSON 兜底),属性区不可编辑以防丢失原文;可照常改基本信息。</p>
|
||||
<p v-else class="drawer-tip">暂无属性</p>
|
||||
|
||||
<section class="detail-block">
|
||||
<h4>SKU 矩阵(京东价 / 库存可改)</h4>
|
||||
<template v-if="draftSkus.length">
|
||||
<div class="sku-table-wrap">
|
||||
<table class="sku-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-for="dimension in skuDimensions" :key="dimension">{{ dimension }}</th>
|
||||
<th>京东价</th>
|
||||
<th>库存</th>
|
||||
<th>SKU ID</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="sku in draftSkus" :key="sku.skuId">
|
||||
<td v-for="dimension in skuDimensions" :key="dimension">{{ skuAttrValue(sku, dimension) }}</td>
|
||||
<td><input v-model="sku.price" type="text" inputmode="decimal" class="sku-input" /></td>
|
||||
<td>
|
||||
<input
|
||||
:value="sku.stock === null ? '' : String(sku.stock)"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
class="sku-input"
|
||||
@input="sku.stock = ($event.target as HTMLInputElement).value === '' ? null : Number(($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
</td>
|
||||
<td class="sku-id">{{ sku.skuId }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
<p v-else class="drawer-tip">暂无 SKU 矩阵(V198 之前采集的旧行需重新采集)</p>
|
||||
</section>
|
||||
|
||||
<JdProductImageManager
|
||||
:product-id="item?.id ?? 0"
|
||||
:images="images"
|
||||
:disabled="loading"
|
||||
@update:images="images = $event"
|
||||
@update:delete-ids="managerDeleteIds = $event"
|
||||
@saved="emit('saved')"
|
||||
/>
|
||||
|
||||
<div v-if="saveError" class="drawer-failure">{{ saveError }}</div>
|
||||
<p class="save-hint">保存后该商品转为人工维护,后续采集不再覆盖它的数据(含本单重爬);删除的图片文件一并从存储桶清理(共用的保留);替换 / 新增图片立即生效并同样置锁。</p>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<footer class="drawer-foot">
|
||||
<button class="btn btn-secondary" type="button" :disabled="saving" @click="close">取消</button>
|
||||
<button class="btn" type="button" :disabled="saving || loading" @click="save">
|
||||
{{ saving ? '保存中...' : '保存' }}
|
||||
</button>
|
||||
</footer>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.drawer-mask {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2600;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
background: rgba(45, 66, 86, 0.36);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
.drawer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(920px, 100%);
|
||||
height: 100%;
|
||||
background: #ffffff;
|
||||
box-shadow: -18px 0 40px rgba(39, 67, 94, 0.18);
|
||||
}
|
||||
.drawer-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid #dbe5ee;
|
||||
}
|
||||
.drawer-head h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
}
|
||||
.drawer-close {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 9px;
|
||||
background: none;
|
||||
color: #5b6f83;
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.drawer-close:hover {
|
||||
border-color: #cbd9e6;
|
||||
background: #eef4fa;
|
||||
color: #24384d;
|
||||
}
|
||||
.drawer-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 16px 20px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
.drawer-foot {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
padding: 14px 20px;
|
||||
border-top: 1px solid #dbe5ee;
|
||||
background: #f8fbfd;
|
||||
}
|
||||
.drawer-tip {
|
||||
margin: 0;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.drawer-failure {
|
||||
padding: 12px 14px;
|
||||
border: 1px solid #f0c9c2;
|
||||
border-radius: 10px;
|
||||
background: #fdf1ef;
|
||||
color: #a04432;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.detail-block h4 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 13.5px;
|
||||
font-weight: 650;
|
||||
color: #4e6479;
|
||||
}
|
||||
.edit-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 10px 16px;
|
||||
}
|
||||
.edit-item {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
.edit-item-wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.edit-item label {
|
||||
color: #5b6f83;
|
||||
font-size: 12px;
|
||||
}
|
||||
.edit-item input,
|
||||
.edit-item select {
|
||||
min-width: 0;
|
||||
min-height: 36px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.edit-item input:focus,
|
||||
.edit-item select:focus {
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.edit-item input.readonly {
|
||||
background: #f2f7fb;
|
||||
color: #5b6f83;
|
||||
}
|
||||
.attr-group {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.attr-group h5 {
|
||||
margin: 0 0 6px;
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.attr-group table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.attr-group th,
|
||||
.attr-group td {
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
font-size: 13px;
|
||||
text-align: left;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.attr-group th {
|
||||
width: 180px;
|
||||
background: #f2f7fb;
|
||||
color: #4e6479;
|
||||
font-weight: 600;
|
||||
}
|
||||
.attr-group tr:last-child th,
|
||||
.attr-group tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.attr-input {
|
||||
width: 100%;
|
||||
min-height: 32px;
|
||||
padding: 5px 8px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 7px;
|
||||
background: #ffffff;
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.attr-input:focus {
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.attr-remove-cell {
|
||||
width: 44px;
|
||||
text-align: center;
|
||||
}
|
||||
.attr-remove {
|
||||
border: 1px solid #e4b3a8;
|
||||
border-radius: 6px;
|
||||
background: #ffffff;
|
||||
color: #a04432;
|
||||
font-size: 12px;
|
||||
padding: 3px 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.attr-remove:hover {
|
||||
background: #fdf1ef;
|
||||
}
|
||||
.sku-table-wrap {
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.sku-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sku-table th,
|
||||
.sku-table td {
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid #e7eef5;
|
||||
text-align: left;
|
||||
color: #24384d;
|
||||
}
|
||||
.sku-table th {
|
||||
background: #f2f7fb;
|
||||
color: #4e6479;
|
||||
font-weight: 600;
|
||||
}
|
||||
.sku-table tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.sku-input {
|
||||
width: 110px;
|
||||
min-height: 32px;
|
||||
padding: 5px 8px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 7px;
|
||||
background: #ffffff;
|
||||
color: #24384d;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.sku-input:focus {
|
||||
border-color: #5f85ad;
|
||||
}
|
||||
.sku-id {
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
font-size: 12px;
|
||||
color: #4e6479;
|
||||
}
|
||||
.save-hint {
|
||||
margin: 0;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid #cfe3f5;
|
||||
border-radius: 10px;
|
||||
background: #eef5fc;
|
||||
color: #3b6d99;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 38px;
|
||||
padding: 7px 16px;
|
||||
border-radius: 9px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border: 1px solid #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
.btn:not(.btn-secondary) {
|
||||
border: 1px solid #4f78a5;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
}
|
||||
.btn:not(.btn-secondary):hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,300 @@
|
||||
<script setup lang="ts">
|
||||
/** 京东商品编辑抽屉「图片区」子组件(2026-11-16 从 JdProductEditDrawer 拆出:编辑抽屉
|
||||
* 856 行超后管 800 报警线,图片区自洽成件——× 右上角标删+hover 替换+新增主图,
|
||||
* B109-01 落地,2026-11-16 客户口径「删除做成打叉的 icon 放图右上角,也要支持编辑
|
||||
* 替换本地的图」)。
|
||||
*
|
||||
* 交互语义:× 标删=前端标记、随父级「保存」一并提交(deleteImageIds 上抛);替换/新增
|
||||
* =multipart 立即生效(服务端置锁+刷投影),上传成功用返回详情回填本区并上抛 saved。
|
||||
* objectKey 由服务端按上传字节 sha256 内容寻址生成(铁律 32),前端不自造 key。
|
||||
* 形状照 JdProductEditDrawer 原图片区(image-grid + image-cell,零 element-plus)。 */
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { uploadJdProductImage } from './jd-product-api.ts'
|
||||
import type { JdProductImage } from './jd-product-model.ts'
|
||||
import { requestErrorMessage } from '../../api/envelope.ts'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
|
||||
const props = defineProps<{
|
||||
productId: number
|
||||
images: JdProductImage[]
|
||||
/** 父级 loading 中禁上传入口。 */
|
||||
disabled: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'update:images', images: JdProductImage[]): void
|
||||
(event: 'update:deleteIds', ids: number[]): void
|
||||
(event: 'saved'): void
|
||||
}>()
|
||||
|
||||
/** 标删的图片行 id(前端只标记,父级保存时一次提交 deleteImageIds)。 */
|
||||
const deleteImageIds = ref<Set<number>>(new Set())
|
||||
|
||||
function toggleDeleteImage(image: JdProductImage): void {
|
||||
const next = new Set(deleteImageIds.value)
|
||||
if (next.has(image.id)) next.delete(image.id)
|
||||
else next.add(image.id)
|
||||
deleteImageIds.value = next
|
||||
emit('update:deleteIds', [...next])
|
||||
}
|
||||
|
||||
// ---------------- 图片上传/替换(立即生效,与标删的「保存时生效」不同) ----------------
|
||||
|
||||
/** 文件选择上下文:null=新增主图;有值=替换该登记行(档位继承原行,后端语义)。 */
|
||||
const pendingReplaceImageId = ref<number | null>(null)
|
||||
const fileInputRef = ref<HTMLInputElement | null>(null)
|
||||
/** 上传中的图行 id(0=新增上传中);上传期间防重复点。 */
|
||||
const uploadingImageId = ref<number | null>(null)
|
||||
const uploadError = ref('')
|
||||
|
||||
function pickImage(replaceImageId: number | null): void {
|
||||
if (uploadingImageId.value !== null || props.disabled) return
|
||||
uploadError.value = ''
|
||||
pendingReplaceImageId.value = replaceImageId
|
||||
// 同选一张图也要重触发 change:先清值再弹窗。
|
||||
if (fileInputRef.value) {
|
||||
fileInputRef.value.value = ''
|
||||
fileInputRef.value.click()
|
||||
}
|
||||
}
|
||||
|
||||
async function onFileChosen(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
if (!file || props.disabled) return
|
||||
uploadingImageId.value = pendingReplaceImageId.value ?? 0
|
||||
try {
|
||||
const detail = await uploadJdProductImage(props.productId, file, pendingReplaceImageId.value
|
||||
? { replaceImageId: pendingReplaceImageId.value }
|
||||
: { imageType: 'MAIN' })
|
||||
// 立即生效:用返回详情回填图片区(标删集合里已不存在的行 id 由 images watch 清理)。
|
||||
emit('update:images', detail.images)
|
||||
showAdminFeedback(pendingReplaceImageId.value ? '图片已替换(该商品已转为人工维护)' : '图片已新增(该商品已转为人工维护)', 'success')
|
||||
emit('saved')
|
||||
} catch (error) {
|
||||
uploadError.value = requestErrorMessage(error) || '图片上传失败,请稍后重试'
|
||||
} finally {
|
||||
uploadingImageId.value = null
|
||||
pendingReplaceImageId.value = null
|
||||
input.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
/** 换商品打开时标删集合必须清零(父级 loadDetail 换 item.id)。 */
|
||||
watch(() => props.productId, () => {
|
||||
deleteImageIds.value = new Set()
|
||||
emit('update:deleteIds', [])
|
||||
})
|
||||
|
||||
/** 行集变化时清掉已不存在的标删 id(保存删行回填/上传回填两路共用;不清理的话
|
||||
* 下次保存会把已删的 id 再提交一遍=后端按「图片不存在」整笔拒绝)。 */
|
||||
watch(() => props.images, (images) => {
|
||||
const live = new Set(images.map((image) => image.id))
|
||||
const next = new Set([...deleteImageIds.value].filter((id) => live.has(id)))
|
||||
if (next.size !== deleteImageIds.value.size) {
|
||||
deleteImageIds.value = next
|
||||
emit('update:deleteIds', [...next])
|
||||
}
|
||||
})
|
||||
|
||||
const markedCount = computed(() => deleteImageIds.value.size)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="detail-block">
|
||||
<div class="image-head">
|
||||
<h4>图片(右上角 × 标记删除,保存时一并删除;替换 / 新增立即生效)</h4>
|
||||
<button class="btn-add-image" type="button" :disabled="uploadingImageId !== null || disabled" @click="pickImage(null)">
|
||||
{{ uploadingImageId === 0 ? '上传中...' : '+ 新增主图' }}
|
||||
</button>
|
||||
</div>
|
||||
<input ref="fileInputRef" type="file" accept="image/jpeg,image/png,image/webp,image/gif" hidden @change="onFileChosen" />
|
||||
<div v-if="images.length" class="image-grid">
|
||||
<div
|
||||
v-for="image in images"
|
||||
:key="`${image.id}-${image.url}`"
|
||||
class="image-cell"
|
||||
:class="{ marked: deleteImageIds.has(image.id) }"
|
||||
>
|
||||
<img
|
||||
:src="image.url"
|
||||
alt=""
|
||||
loading="lazy"
|
||||
:class="{ dimmed: deleteImageIds.has(image.id) || uploadingImageId === image.id }"
|
||||
/>
|
||||
<!-- 右上角 × 删除标记(京麦样式,2026-11-16 客户口径):点 × 标记,再点撤销。 -->
|
||||
<button
|
||||
class="image-x"
|
||||
type="button"
|
||||
:title="deleteImageIds.has(image.id) ? '撤销删除标记' : '标记删除(保存时一并删除)'"
|
||||
@click="toggleDeleteImage(image)"
|
||||
>×</button>
|
||||
<!-- 标删遮罩(整格可点撤销),未标删时 hover 底部出现「替换」条。 -->
|
||||
<button
|
||||
v-if="deleteImageIds.has(image.id)"
|
||||
class="image-marked-mask"
|
||||
type="button"
|
||||
title="点击撤销删除标记"
|
||||
@click="toggleDeleteImage(image)"
|
||||
>已标记删除 · 点击撤销</button>
|
||||
<button
|
||||
v-else
|
||||
class="image-replace"
|
||||
type="button"
|
||||
:disabled="uploadingImageId !== null"
|
||||
@click="pickImage(image.id)"
|
||||
>{{ uploadingImageId === image.id ? '上传中...' : '替换' }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-else class="drawer-tip">暂无图片(可点右上「+ 新增主图」上传本地图)</p>
|
||||
<p v-if="uploadError" class="drawer-failure">{{ uploadError }}</p>
|
||||
<p v-if="markedCount" class="delete-count">已标记删除 {{ markedCount }} 张,保存后剩余 {{ images.length - markedCount }} 张</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.image-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.image-head h4 {
|
||||
margin: 0 0 10px;
|
||||
font-size: 13.5px;
|
||||
font-weight: 650;
|
||||
color: #4e6479;
|
||||
}
|
||||
.btn-add-image {
|
||||
min-height: 30px;
|
||||
padding: 4px 12px;
|
||||
border: 1px solid #95b1cb;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
color: #2f5d8b;
|
||||
font-size: 12.5px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.btn-add-image:hover {
|
||||
background: #edf5fb;
|
||||
}
|
||||
.btn-add-image:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.image-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.image-cell {
|
||||
position: relative;
|
||||
}
|
||||
.image-cell img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
aspect-ratio: 1;
|
||||
object-fit: cover;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 8px;
|
||||
background: #f2f7fb;
|
||||
}
|
||||
.image-cell img.dimmed {
|
||||
opacity: 0.35;
|
||||
}
|
||||
.image-cell.marked img {
|
||||
outline: 2px solid #d08a7b;
|
||||
}
|
||||
/* 右上角 × 删除标记(京麦样式):hover 格子时出现;已标删常显。 */
|
||||
.image-x {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
background: rgba(38, 50, 63, 0.72);
|
||||
color: #ffffff;
|
||||
font-size: 15px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.image-cell:hover .image-x,
|
||||
.image-cell.marked .image-x {
|
||||
display: flex;
|
||||
}
|
||||
.image-x:hover {
|
||||
background: #a04432;
|
||||
}
|
||||
/* 标删态:整格遮罩可点撤销。 */
|
||||
.image-marked-mask {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 6px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: rgba(160, 68, 50, 0.32);
|
||||
color: #ffffff;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
cursor: pointer;
|
||||
}
|
||||
.image-marked-mask:hover {
|
||||
background: rgba(160, 68, 50, 0.5);
|
||||
}
|
||||
/* hover 底部替换条(京麦替换入口);上传中常显。 */
|
||||
.image-replace {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 26px;
|
||||
border: none;
|
||||
border-radius: 0 0 8px 8px;
|
||||
background: rgba(38, 50, 63, 0.72);
|
||||
color: #ffffff;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.image-cell:hover .image-replace {
|
||||
display: flex;
|
||||
}
|
||||
.image-cell .image-replace:disabled {
|
||||
display: flex;
|
||||
background: rgba(38, 50, 63, 0.55);
|
||||
cursor: wait;
|
||||
}
|
||||
.image-replace:hover {
|
||||
background: #2f5d8b;
|
||||
}
|
||||
.delete-count {
|
||||
margin: 10px 0 0;
|
||||
color: #a04432;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.drawer-tip {
|
||||
margin: 0;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.drawer-failure {
|
||||
margin: 10px 0 0;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid #f0c9c2;
|
||||
border-radius: 10px;
|
||||
background: #fdf1ef;
|
||||
color: #a04432;
|
||||
font-size: 13px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,29 @@
|
||||
/** 类目级联面板的水平定位钳制(2026-11-16 客户截图「超出视窗了」:面板锚在触发框
|
||||
* left:0,下钻到 3~4 栏时宽 600~800px,而「类目」筛选框在 jd-filter-row 流式布局里
|
||||
* 常落在页面中部偏右 ⇒ 面板右半截伸出视窗,末栏被窗缘裁到只剩一列 radio 圆点)。
|
||||
*
|
||||
* 本文件是**纯钳制数学**(零依赖,node --test 可直测):默认锚左(偏移 0);视口右缘
|
||||
* 装不下时整体左移到右缘贴齐(留 margin),左移后越出左缘则贴左缘为止。组件侧在面板
|
||||
* 打开与栏数/搜索态变化后用真实 rect 调它(JdCategoryCascader.vue),栏数随下钻动态
|
||||
* 1~4,宽度变了要重算——右贴齐后继续下钻即向左生长,不会再伸出右缘。 */
|
||||
|
||||
export interface PanelClampInput {
|
||||
/** 触发框(.cat-cascader)的视口左缘 x。 */
|
||||
hostLeft: number
|
||||
/** 面板当前实际渲染宽(含边框;栏数不同宽度不同)。 */
|
||||
panelWidth: number
|
||||
/** 视口宽(window.innerWidth)。 */
|
||||
viewportWidth: number
|
||||
/** 视口两侧最小留白,默认 8px。 */
|
||||
margin?: number
|
||||
}
|
||||
|
||||
/** 返回面板相对触发框左缘应加的 left 偏移(px;负=左移、0=默认锚左即可、正=触发框
|
||||
* 本身已贴近视口左缘时把面板推回 margin 内,物理上只在窄窗极端值出现)。 */
|
||||
export function clampPanelLeftX(input: PanelClampInput): number {
|
||||
const margin = input.margin ?? 8
|
||||
const overflowRight = input.hostLeft + input.panelWidth - (input.viewportWidth - margin)
|
||||
if (overflowRight <= 0) return 0
|
||||
const desiredLeft = Math.max(margin, input.hostLeft - overflowRight)
|
||||
return desiredLeft - input.hostLeft
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,402 @@
|
||||
/* 像素复刻「外观专利数据库」页样式(panel-box + 自绘表格 + 旧式分页);列表只摆部分字段,全量属性在详情抽屉。 */
|
||||
.jd-database-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);
|
||||
}
|
||||
h3 {
|
||||
margin: 0 0 16px;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
color: #24384d;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
.jd-panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.jd-panel-head h3 {
|
||||
margin: 0;
|
||||
}
|
||||
.jd-filter-row {
|
||||
/* 可换行流式布局:固定 6 列 minmax(140px) 的网格在窄面板下最小宽超出容器,
|
||||
把查询/重置挤出面板右缘(与「管理分组」重叠)。flex-wrap 让放不下的项自然折行。 */
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
align-items: flex-end;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.jd-filter-row .form-group {
|
||||
flex: 1 1 160px;
|
||||
min-width: 150px;
|
||||
max-width: 260px;
|
||||
}
|
||||
.jd-filter-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input,
|
||||
.form-group select {
|
||||
min-width: 0;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
color-scheme: light;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.form-group input:hover,
|
||||
.form-group select:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.form-group input[type="date"] {
|
||||
color-scheme: light;
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 18px -14px rgba(79, 120, 165, 0.72);
|
||||
transition: background 160ms ease, box-shadow 160ms ease, transform 120ms ease;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
box-shadow: 0 11px 22px -14px rgba(79, 120, 165, 0.8);
|
||||
}
|
||||
.btn:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border-color: #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
.jd-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
/* 工具栏里的下拉与按钮统一 42px 外壳(2026-11-16 用户口径「样式要统一」):
|
||||
这一行此前只有 .btn 有壳,原生 <select> 落成 28px 灰框、字号也不跟,
|
||||
与旁边按钮同排时高矮不齐(分组下拉同日上移进筛选行,本行只剩分类筛选一颗)。
|
||||
数值与 .form-group select / .btn 同一套(42px 高、
|
||||
9px 圆角、#cbd9e6 描边、#f8fbfd 底),箭头用内联 SVG 自绘,避免各浏览器原生
|
||||
箭头粗细不一(appearance:none 后必须补 padding-right 给箭头留位)。 */
|
||||
.jd-toolbar select {
|
||||
min-height: 42px;
|
||||
max-width: 220px;
|
||||
padding: 0 34px 0 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background-color: #f8fbfd;
|
||||
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;
|
||||
color: #24384d;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
|
||||
}
|
||||
.jd-toolbar select:hover {
|
||||
border-color: #9fb7cd;
|
||||
}
|
||||
.jd-toolbar select:focus {
|
||||
background-color: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
/* 危险动作(删除勾选)推到行尾:留在「批量编辑分类/分类筛选」旁边会被读成同一组动作。 */
|
||||
.jd-delete-btn {
|
||||
margin-left: auto;
|
||||
}
|
||||
/* 分类管理(2026-11-17 独立分类管理页并入本页的对话框入口):贴着分类筛选下拉。 */
|
||||
.jd-manage-btn {
|
||||
margin-left: 6px;
|
||||
}
|
||||
/* 危险动作(删除勾选):与全站 .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);
|
||||
}
|
||||
.jd-summary {
|
||||
color: #5b6f83;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* 非超管只读提示(2026-11-16 写权限收窄):紧跟汇总的一句话,不冒充可点按钮。 */
|
||||
.jd-readonly-tip {
|
||||
color: #8293a5;
|
||||
font-size: 12.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
/* 只有一个可见分组时锁定的组名(不可切):筛选行「分组」标签下的静态芯片(2026-11-16 用户口径
|
||||
「做成分组」把下拉从工具栏上移进筛选行后跟着搬),与同排 select 同高同壳(42px/9px 圆角),
|
||||
"一组锁定"和"多组下拉"两种形态占位一致;组名超宽省略号收口,不把筛选行撑破。 */
|
||||
.jd-group-locked {
|
||||
display: 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;
|
||||
}
|
||||
.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;
|
||||
}
|
||||
/* 列宽收口(2026-11-16 用户口径「列表间距有点大」):1500px 的 min-width 让宽屏下
|
||||
唯一的弹性列(商品信息)独吞剩余宽度,标题右侧留出近 800px 空白,价格/库存被推到最右。
|
||||
商品信息改固定 520px 后各列按比例分摊余量,min-width 降到 1180px 即可无横向滚动。 */
|
||||
.jd-table-scroll > table {
|
||||
min-width: 1180px;
|
||||
}
|
||||
/* 操作列(编辑/删除):双小按钮需 138px(ops-cell-must-wrap 实测口径:两字按钮 53×2+24 padding)。
|
||||
overflow 显式放开:td 全局是 overflow:hidden(611 行),压线时第二颗(删除)会被裁成
|
||||
「编辑+…」的形状——2026-11-16 用户报「删除没了」的真因,列宽 120px < 实测 138px。 */
|
||||
.jd-ops-cell {
|
||||
white-space: nowrap;
|
||||
text-overflow: clip;
|
||||
overflow: visible;
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 28px;
|
||||
padding: 3px 10px;
|
||||
font-size: 12.5px;
|
||||
margin-right: 6px;
|
||||
}
|
||||
.btn-sm:last-child {
|
||||
margin-right: 0;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
/* 单元格左右内距 12→10px(同上「间距有点大」):列与列之间少 4px,行内更紧凑。 */
|
||||
padding: 10px 10px;
|
||||
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;
|
||||
}
|
||||
/* 首列勾选格:checkbox 的 UA 默认 margin(3px 3px 3px 4px)使其 margin-box 溢出
|
||||
42px 格的内容盒(42−24 padding=18px),配合上面的 overflow:hidden,Chromium 在
|
||||
首次渲染时会把被裁的 checkbox 碎片留在裁剪边缘,看起来像格子右边多出 ".."。
|
||||
margin 归零后 margin-box 收进内容盒,首渲染即干净(playwright 三次冷加载已验)。 */
|
||||
.table-scroll th:first-child input,
|
||||
.table-scroll td:first-child input {
|
||||
margin: 0;
|
||||
}
|
||||
.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;
|
||||
}
|
||||
/* 点行开详情抽屉:行级 hover 已有底色反馈,光标再点一下提示可点。 */
|
||||
.jd-row {
|
||||
cursor: pointer;
|
||||
}
|
||||
.jd-thumb {
|
||||
display: block;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
object-fit: cover;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 6px;
|
||||
background: #f2f7fb;
|
||||
}
|
||||
/* 商品信息列=京麦同款合并布局:td 的全局 nowrap/ellipsis 与多行内容冲突,本列放开换行,
|
||||
截断交给内部各行(标题两行 line-clamp、编码/货号单行 ellipsis)。 */
|
||||
.jd-info-cell {
|
||||
white-space: normal;
|
||||
text-overflow: clip;
|
||||
}
|
||||
.jd-info-wrap {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
.jd-info-figure {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.jd-thumb-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #8293a5;
|
||||
font-size: 12px;
|
||||
}
|
||||
.jd-health {
|
||||
color: #2e9e6b;
|
||||
font-size: 11px;
|
||||
line-height: 1.2;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.jd-info-body {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
.jd-info-title {
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-weight: 500;
|
||||
line-height: 1.45;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
word-break: break-all;
|
||||
}
|
||||
.jd-info-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: #7b8a99;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
.jd-info-code {
|
||||
font-family: "Cascadia Mono", "SF Mono", Consolas, "Courier New", monospace;
|
||||
color: #4e6479;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.jd-copy-btn {
|
||||
flex-shrink: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #8aa5bf;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
padding: 0 2px;
|
||||
line-height: 1;
|
||||
}
|
||||
.jd-copy-btn:hover {
|
||||
color: #3b82c4;
|
||||
}
|
||||
.jd-info-tags {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
/* 品牌·类目行(京麦列表同款深色文字):信息 meta 是灰色,这行按京麦用主文字色。 */
|
||||
.jd-brand-cat {
|
||||
color: #3d5368;
|
||||
font-weight: 550;
|
||||
}
|
||||
.jd-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 18px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid #cfe3f5;
|
||||
border-radius: 3px;
|
||||
background: #eef5fc;
|
||||
color: #3b82c4;
|
||||
font-size: 11.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.empty-tip {
|
||||
padding: 44px 24px;
|
||||
text-align: center;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
/** 京东数据库查询适配(v1.4 Phase 5):GET /api/admin/jd-products + 删除(DELETE /{id} +
|
||||
* POST /batch-delete)+ 分组端点 /api/admin/jd-product-groups。
|
||||
* 公司口径(2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」):全页零公司维度——
|
||||
* 只读列表与类目下拉的 company_id 发送口已随公司 tab 摘除(后端读侧谓词同窗撤,重上时
|
||||
* 从 git 历史找回),详情/编辑/删除/分组管理本就不带;行 company_id 列仍是同步来源标记、
|
||||
* 随详情下发。反向钉在 company-tab-wiring「公司维度不得回流」清单。
|
||||
* 导出发送口已随 2026-11-15 客户口径「导出也不用」从前端下线(后端 /export 端点保留)。 */
|
||||
import { http } from '@/api/http'
|
||||
import { errorTextOf, unwrap } from '../../api/envelope.ts'
|
||||
import {
|
||||
toJdProductListParams,
|
||||
type JdProductListParams,
|
||||
} from './jd-product-filter.ts'
|
||||
import {
|
||||
parseJdProductDetail,
|
||||
parseJdProductPage,
|
||||
type JdProductPageResult,
|
||||
} from './jd-product-model.ts'
|
||||
|
||||
export const JD_PRODUCT_ENDPOINT = '/api/admin/jd-products'
|
||||
export const JD_PRODUCT_GROUP_ENDPOINT = '/api/admin/jd-product-groups'
|
||||
|
||||
export async function fetchJdProductList(
|
||||
params: JdProductListParams,
|
||||
): Promise<JdProductPageResult> {
|
||||
const query = toJdProductListParams(
|
||||
{
|
||||
productCode: params.productCode ?? '',
|
||||
titleKeyword: params.titleKeyword ?? '',
|
||||
category: params.category ?? '',
|
||||
groupId: params.groupId ?? '',
|
||||
syncedFrom: params.syncedFrom ?? '',
|
||||
syncedTo: params.syncedTo ?? '',
|
||||
},
|
||||
params.page,
|
||||
params.pageSize,
|
||||
params.ownerGroupId ?? null,
|
||||
)
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_ENDPOINT, { params: query })
|
||||
return parseJdProductPage(data)
|
||||
}
|
||||
|
||||
/** 详情:GET /api/admin/jd-products/{id}(信封 data=主字段 + attrGroups + attrJsonRaw + images)。
|
||||
* 公共库无公司维度,按 id 直取;分类字段按「当前分组」(owner_group_id)取(V203)。 */
|
||||
export async function fetchJdProductDetail(
|
||||
id: number,
|
||||
ownerGroupId?: number | null,
|
||||
): Promise<ReturnType<typeof parseJdProductDetail>> {
|
||||
const params = typeof ownerGroupId === 'number' && ownerGroupId > 0
|
||||
? { owner_group_id: ownerGroupId }
|
||||
: undefined
|
||||
const { data } = await http.get<unknown>(`${JD_PRODUCT_ENDPOINT}/${id}`, { params })
|
||||
return parseJdProductDetail(data)
|
||||
}
|
||||
|
||||
/** 删除回执(后端 JdProductDeleteVo):三个对象计数分开报——真删的、共用的、前缀外不敢动的。 */
|
||||
export interface JdProductDeleteResult {
|
||||
deleted: number
|
||||
imagesDeleted: number
|
||||
objectsDeleted: number
|
||||
objectsKept: number
|
||||
objectsSkipped: number
|
||||
}
|
||||
|
||||
/** 删除是先删桶、全成功才删库行(后端 JdProductDeleteService);失败文案原样抛给页面。
|
||||
* 公共库写侧无公司维度(2026-11-15 用户定案)。 */
|
||||
export async function deleteJdProducts(
|
||||
ids: number[],
|
||||
): Promise<JdProductDeleteResult> {
|
||||
if (ids.length === 1) {
|
||||
const { data } = await http.delete<unknown>(`${JD_PRODUCT_ENDPOINT}/${ids[0]}`)
|
||||
return unwrap<JdProductDeleteResult>(data)
|
||||
}
|
||||
const { data } = await http.post<unknown>(`${JD_PRODUCT_ENDPOINT}/batch-delete`, { ids })
|
||||
return unwrap<JdProductDeleteResult>(data)
|
||||
}
|
||||
|
||||
/** 编辑提交负载(PUT /api/admin/jd-products/{id} body,后端 JdProductUpdateRequest):
|
||||
* 主字段全量提交;attrGroups/skus/deleteImageIds 可选——null=不修改该块
|
||||
* (后端对 null 块零触碰)。分类不在本负载里(V203:分类按数据权限分组归属存
|
||||
* biz_jd_product_group_assign,编辑面不写 group_id,归类只走列表页「批量编辑分类」)。 */
|
||||
export interface JdProductUpdatePayload {
|
||||
title: string
|
||||
brand: string | null
|
||||
categoryPath: string | null
|
||||
itemNum: string | null
|
||||
priceMin: string | null
|
||||
priceMax: string | null
|
||||
stockTotal: number | null
|
||||
saleStatus: string | null
|
||||
attrGroups: { groupName: string; attrs: { key: string; label: string; value: string }[] }[] | null
|
||||
skus: { skuId: string; price: string | null; stock: number | null }[] | null
|
||||
deleteImageIds: number[] | null
|
||||
}
|
||||
|
||||
/** 编辑保存(PUT):主字段保存即置人工编辑锁(V199 manual_locked=1,后续采集不再覆盖该行);
|
||||
* 失败文案原样抛给抽屉红条。公共库写侧无公司维度。返回刷新后的详情(与
|
||||
* fetchJdProductDetail 同一信封),抽屉用它回填。 */
|
||||
export async function updateJdProduct(
|
||||
id: number,
|
||||
payload: JdProductUpdatePayload,
|
||||
): Promise<ReturnType<typeof parseJdProductDetail>> {
|
||||
const { data } = await http.put<unknown>(`${JD_PRODUCT_ENDPOINT}/${id}`, payload)
|
||||
return parseJdProductDetail(data)
|
||||
}
|
||||
|
||||
/** 图片上传参数(POST /{id}/images multipart):replaceImageId 有值=替换该登记行
|
||||
* (后端继承原行档位,imageType/attrName 忽略);缺省=新增(imageType=MAIN/DETAIL,
|
||||
* ATTR 需带 attrName)。objectKey 由服务端按上传字节 sha256 内容寻址生成(铁律 32),
|
||||
* 前端不自造 key。返回刷新后的详情(与 fetchJdProductDetail 同一信封)。 */
|
||||
export interface JdProductImageUploadParams {
|
||||
replaceImageId?: number
|
||||
imageType?: 'MAIN' | 'ATTR' | 'DETAIL'
|
||||
attrName?: string
|
||||
}
|
||||
|
||||
/** 上传/替换商品图片(multipart 后端中转):上传/替换即生效(服务端立即落库并置
|
||||
* 人工编辑锁),与「删图保存时批量生效」不同。失败文案原样抛给抽屉。 */
|
||||
export async function uploadJdProductImage(
|
||||
id: number,
|
||||
file: File,
|
||||
params: JdProductImageUploadParams,
|
||||
): Promise<ReturnType<typeof parseJdProductDetail>> {
|
||||
const body = new FormData()
|
||||
body.append('file', file)
|
||||
if (params.replaceImageId != null) {
|
||||
body.append('replace_image_id', String(params.replaceImageId))
|
||||
}
|
||||
if (params.imageType) body.append('image_type', params.imageType)
|
||||
if (params.attrName) body.append('attr_name', params.attrName)
|
||||
const { data } = await http.post<unknown>(`${JD_PRODUCT_ENDPOINT}/${id}/images`, body, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
})
|
||||
return parseJdProductDetail(data)
|
||||
}
|
||||
|
||||
/** 分组行(GET 列表返回:[{id,name,ownerGroupId,sortOrder,productCount}])。 */
|
||||
export interface JdProductGroup {
|
||||
id: number
|
||||
name: string
|
||||
ownerGroupId: number
|
||||
sortOrder: number
|
||||
productCount: number
|
||||
}
|
||||
|
||||
/** 分组管理的写入负载(POST / PUT body:{name, sortOrder, ownerGroupId?})。 */
|
||||
export interface JdProductGroupPayload {
|
||||
name: string
|
||||
sortOrder: number
|
||||
/** 新建时归属的数据权限分组(缺省=操作者自己带的组,后端 requireWritableGroup 收敛)。 */
|
||||
ownerGroupId?: number | null
|
||||
}
|
||||
|
||||
/** 「当前分组」下拉的一项(GET /scope 的 groups[],V203):editable=本账号对该组分类可写
|
||||
* (建/改名/删除/归类)。跨公司的组名由后端拼进 label,前端不解析公司字段。 */
|
||||
export interface JdCategoryGroupOption {
|
||||
id: number
|
||||
name: string
|
||||
label: string
|
||||
editable: boolean
|
||||
}
|
||||
|
||||
/** 分类作用域回执(GET /api/admin/jd-product-groups/scope):分组下拉 + 平台超管标记。 */
|
||||
export interface JdCategoryScope {
|
||||
platformSuperAdmin: boolean
|
||||
defaultGroupId: number | null
|
||||
groups: JdCategoryGroupOption[]
|
||||
}
|
||||
|
||||
/** 分组信封是 `{code, message, data}` 三段式:code 非 0 =业务失败,message 是中文文案
|
||||
* (重名等),用 errorTextOf 取出来抛给界面展示(unwrap 只认 success=false,不认 code)。 */
|
||||
function groupDataOf<T>(payload: unknown): T {
|
||||
const record = payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : null
|
||||
if (record && typeof record.code === 'number' && record.code !== 0) {
|
||||
throw new Error(errorTextOf(payload))
|
||||
}
|
||||
return unwrap<T>(payload)
|
||||
}
|
||||
|
||||
function numberOr(value: unknown, fallback: number): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback
|
||||
}
|
||||
|
||||
/** 分组下拉/管理列表:按「当前分组」(owner_group_id)取该组的分类(V203,跨组不可见);
|
||||
* 缺省=后端按作用域默认分组取。失败由页面自己兜(分类只是筛选项,不拦首屏行集)。 */
|
||||
export async function fetchJdProductGroups(ownerGroupId?: number | null): Promise<JdProductGroup[]> {
|
||||
const params = typeof ownerGroupId === 'number' && ownerGroupId > 0
|
||||
? { owner_group_id: ownerGroupId }
|
||||
: undefined
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_GROUP_ENDPOINT, { params })
|
||||
const core = unwrap<unknown>(data)
|
||||
if (!Array.isArray(core)) return []
|
||||
const out: JdProductGroup[] = []
|
||||
for (const raw of core) {
|
||||
if (!raw || typeof raw !== 'object') continue
|
||||
const record = raw as Record<string, unknown>
|
||||
const id = numberOr(record.id, 0)
|
||||
if (id <= 0) continue
|
||||
out.push({
|
||||
id,
|
||||
name: typeof record.name === 'string' ? record.name.trim() : '',
|
||||
ownerGroupId: numberOr(record.ownerGroupId ?? record.owner_group_id, 0),
|
||||
sortOrder: numberOr(record.sortOrder ?? record.sort_order, 0),
|
||||
productCount: numberOr(record.productCount ?? record.product_count, 0),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 分类作用域(GET /scope):本账号可见的数据权限分组 + 每组可写标记。
|
||||
* 页面用它渲染「分组」下拉并按 editable 渲染分类写入口;失败由页面自己兜(回空作用域=
|
||||
* 分类列全空、分类管理页提示不属于任何分组,但商品列表照常可用)。 */
|
||||
export async function fetchJdCategoryScope(): Promise<JdCategoryScope> {
|
||||
const { data } = await http.get<unknown>(`${JD_PRODUCT_GROUP_ENDPOINT}/scope`)
|
||||
const core = groupDataOf<unknown>(data)
|
||||
const record = core && typeof core === 'object' ? (core as Record<string, unknown>) : {}
|
||||
const rawGroups = Array.isArray(record.groups) ? record.groups : []
|
||||
const groups: JdCategoryGroupOption[] = []
|
||||
for (const raw of rawGroups) {
|
||||
if (!raw || typeof raw !== 'object') continue
|
||||
const row = raw as Record<string, unknown>
|
||||
const id = numberOr(row.id, 0)
|
||||
if (id <= 0) continue
|
||||
const name = typeof row.name === 'string' ? row.name.trim() : ''
|
||||
groups.push({
|
||||
id,
|
||||
name,
|
||||
label: typeof row.label === 'string' && row.label.trim() ? row.label.trim() : name,
|
||||
editable: row.editable === true,
|
||||
})
|
||||
}
|
||||
return {
|
||||
platformSuperAdmin: record.platformSuperAdmin === true || record.platform_super_admin === true,
|
||||
defaultGroupId: numberOr(record.defaultGroupId ?? record.default_group_id, 0) || null,
|
||||
groups,
|
||||
}
|
||||
}
|
||||
|
||||
/** 类目下拉选项(GET /categories 返回 [{name, productCount}],name=京麦末级类目即
|
||||
* 落库的 category_path;等值过滤)。失败由页面自己兜(类目只是筛选项,不拦首屏行集)。 */
|
||||
export interface JdProductCategoryOption {
|
||||
name: string
|
||||
productCount: number
|
||||
}
|
||||
|
||||
export async function fetchJdProductCategories(): Promise<JdProductCategoryOption[]> {
|
||||
const { data } = await http.get<unknown>(`${JD_PRODUCT_ENDPOINT}/categories`)
|
||||
const core = unwrap<unknown>(data)
|
||||
if (!Array.isArray(core)) return []
|
||||
const out: JdProductCategoryOption[] = []
|
||||
for (const raw of core) {
|
||||
if (!raw || typeof raw !== 'object') continue
|
||||
const record = raw as Record<string, unknown>
|
||||
const name = typeof record.name === 'string' ? record.name.trim() : ''
|
||||
if (!name) continue
|
||||
out.push({ name, productCount: numberOr(record.productCount ?? record.product_count, 0) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 新建分类(归属当前分组,V203):ownerGroupId 缺省=后端取操作者自己带的组;
|
||||
* 同一分组内重名等业务失败把后端中文文案抛回(页面直接展示)。 */
|
||||
export async function createJdProductGroup(
|
||||
payload: JdProductGroupPayload,
|
||||
): Promise<JdProductGroup | null> {
|
||||
const body: Record<string, unknown> = { name: payload.name, sortOrder: payload.sortOrder }
|
||||
if (typeof payload.ownerGroupId === 'number' && payload.ownerGroupId > 0) {
|
||||
body.ownerGroupId = payload.ownerGroupId
|
||||
}
|
||||
const { data } = await http.post<unknown>(JD_PRODUCT_GROUP_ENDPOINT, body)
|
||||
return groupDataOf<JdProductGroup | null>(data)
|
||||
}
|
||||
|
||||
/** 改名/改排序;业务失败文案同上。 */
|
||||
export async function updateJdProductGroup(
|
||||
id: number,
|
||||
payload: JdProductGroupPayload,
|
||||
): Promise<JdProductGroup | null> {
|
||||
const body: Record<string, unknown> = { name: payload.name, sortOrder: payload.sortOrder }
|
||||
const { data } = await http.put<unknown>(`${JD_PRODUCT_GROUP_ENDPOINT}/${id}`, body)
|
||||
return groupDataOf<JdProductGroup | null>(data)
|
||||
}
|
||||
|
||||
/** 删除分组;业务失败文案同上。 */
|
||||
export async function deleteJdProductGroup(id: number): Promise<void> {
|
||||
const { data } = await http.delete<unknown>(`${JD_PRODUCT_GROUP_ENDPOINT}/${id}`)
|
||||
groupDataOf<unknown>(data)
|
||||
}
|
||||
|
||||
/** 批量人工归类(2026-11-17 起唯一入口=京东数据库页工具栏「批量编辑分类」;
|
||||
* 旧「店铺分类弹窗+工具栏移除分类」已随同日口径下线):勾选商品行(跨页累计)
|
||||
* → 归入当前分组(ownerGroupId)的指定分类或移出分类(V203:归属写
|
||||
* biz_jd_product_group_assign 的 (product_id, owner_group_id) 一行,同一商品各组可各自归类)。
|
||||
* groupId 传 null=移出本组分类;返回实际写入/解挂的归属行数。
|
||||
* 归类<b>不再置人工编辑锁</b>(2026-11-16 用户拍板):分类不在商品行上,采集冲不掉它。
|
||||
* 业务失败(分类不存在/不属于当前分组)把中文文案抛回,对话框红条原样展示。 */
|
||||
export async function batchAssignJdProductGroup(
|
||||
ids: number[],
|
||||
groupId: number | null,
|
||||
ownerGroupId: number,
|
||||
): Promise<number> {
|
||||
const body: Record<string, unknown> = { ids, groupId, ownerGroupId }
|
||||
const { data } = await http.post<unknown>(`${JD_PRODUCT_ENDPOINT}/batch-assign-group`, body)
|
||||
return groupDataOf<number>(data)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/** 京东数据库页筛选纯函数(v1.4 Phase 5):商品编码/标题关键字/类目/分组/同步起止 + snake 分页参数。
|
||||
* 产出与后端契约 §列表 query 逐字对撞:`page`/`page_size`(默认 20、上限 100)、
|
||||
* `product_code`、`title_keyword`、`category`(京麦末级类目等值过滤,2026-11-15 增)、
|
||||
* `group_id`(当前分组下的分类 id)、`owner_group_id`(当前数据权限分组,V203)、
|
||||
* `synced_from`/`synced_to`(ISO yyyy-MM-dd;空白不下发)。
|
||||
* 商品状态筛选与导出(2026-11-15 客户口径「这两个不要/导出也不用」)已从前端下线;
|
||||
* 店铺筛选同日客户口径「店铺不需要」从前端下线(后端 shop_name 参数同窗撤,DB 列与详情不动)。
|
||||
* 后端 `sale_status` 参数与 `/export` 端点保留(无 UI 入口),重上时从 git 历史找回取值口。
|
||||
* 分页钳制(铁律 15):page < 1 归 1、上限 10_000(后端 CR-18 同值),(page-1)*page_size
|
||||
* 最大 999_900,Number.MAX_SAFE_INTEGER 也不会把乘积顶出安全整数。纯逻辑,node --test 直测。
|
||||
* 公司维已整页摘除(2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」):归一化构造器
|
||||
* 与入参类型都不认识 company_id——读侧发送口已随公司 tab 撤下(品牌库 2026-10-06 先例同形)。
|
||||
* 日期默认空字符串:同步台账是累计数据,默认当天会让首屏只剩今天同步的行
|
||||
* (date-filter-default-today 护栏 EXEMPT 口径,外观专利页同款)。 */
|
||||
import { validIsoDateOrUndefined } from '../asin/asin-filter.ts'
|
||||
|
||||
/** 每页条数默认 20(v1.4 §3.4),上限 100。 */
|
||||
export const JD_PRODUCT_PAGE_SIZE = 20
|
||||
export const JD_PRODUCT_MAX_PAGE_SIZE = 100
|
||||
/** 页码上限:与后端 MAX_PAGE(CR-18 先例,外观专利同值)对齐,两侧不漂。 */
|
||||
export const JD_PRODUCT_MAX_PAGE = 10_000
|
||||
|
||||
export interface JdProductFilterState {
|
||||
/** 商品编码,空串不限。 */
|
||||
productCode: string
|
||||
/** 标题关键字,空串不限。 */
|
||||
titleKeyword: string
|
||||
/** 类目(京麦末级类目名,等值过滤;选项来自 GET /categories),空串=全部类目。 */
|
||||
category: string
|
||||
/** 分组 id 文本(分组管理里那一行),空串=全部分组。 */
|
||||
groupId: string
|
||||
/** 同步开始日期(ISO yyyy-MM-dd;空串不限)。 */
|
||||
syncedFrom: string
|
||||
/** 同步结束日期(ISO yyyy-MM-dd;空串不限)。 */
|
||||
syncedTo: string
|
||||
}
|
||||
|
||||
export function createJdProductFilterState(): JdProductFilterState {
|
||||
return { productCode: '', titleKeyword: '', category: '', groupId: '', syncedFrom: '', syncedTo: '' }
|
||||
}
|
||||
|
||||
/** 是否有任一激活筛选条件。 */
|
||||
export function jdProductFilterActive(state: JdProductFilterState): boolean {
|
||||
if ((state.productCode || '').trim()) return true
|
||||
if ((state.titleKeyword || '').trim()) return true
|
||||
if ((state.category || '').trim()) return true
|
||||
if ((state.groupId || '').trim()) return true
|
||||
if (validIsoDateOrUndefined(state.syncedFrom) || validIsoDateOrUndefined(state.syncedTo)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/** 序列化到后端的列表查询参数(snake_case,仅下发非空字段)。 */
|
||||
export interface JdProductQuery {
|
||||
page: number
|
||||
page_size: number
|
||||
product_code?: string
|
||||
title_keyword?: string
|
||||
/** 京麦末级类目等值过滤(后端 JdProductQueryService.Filter.category)。 */
|
||||
category?: string
|
||||
/** 自定义分类 id(当前分组下的一个分类;V203 起按归属表 EXISTS 过滤)。 */
|
||||
group_id?: number
|
||||
/** 当前数据权限分组 id(分类列/分类筛选都按它取;V203「不同组不能看到跨组的分类」)。 */
|
||||
owner_group_id?: number
|
||||
synced_from?: string
|
||||
synced_to?: string
|
||||
}
|
||||
|
||||
/** api 模块的入参:筛选态 + 分页 + 当前分组(公共库无公司维度)。 */
|
||||
export interface JdProductListParams {
|
||||
page: number
|
||||
pageSize: number
|
||||
productCode?: string
|
||||
titleKeyword?: string
|
||||
category?: string
|
||||
groupId?: string
|
||||
/** 当前分组(数据权限分组 id):分类列/分类筛选的作用域,非筛选条件(重置不清它)。 */
|
||||
ownerGroupId?: number | null
|
||||
syncedFrom?: string
|
||||
syncedTo?: string
|
||||
}
|
||||
|
||||
/** 过滤态 → 过滤面参数(snake_case,仅下发非空字段)。 */
|
||||
function toJdProductFilterQuery(state: JdProductFilterState): Omit<JdProductQuery, 'page' | 'page_size'> {
|
||||
const query: Omit<JdProductQuery, 'page' | 'page_size'> = {}
|
||||
const productCode = (state.productCode || '').trim()
|
||||
if (productCode) query.product_code = productCode
|
||||
const titleKeyword = (state.titleKeyword || '').trim()
|
||||
if (titleKeyword) query.title_keyword = titleKeyword
|
||||
const category = (state.category || '').trim()
|
||||
if (category) query.category = category
|
||||
const groupId = Number.parseInt((state.groupId || '').trim(), 10)
|
||||
if (Number.isFinite(groupId) && groupId > 0) query.group_id = groupId
|
||||
const syncedFrom = validIsoDateOrUndefined(state.syncedFrom)
|
||||
if (syncedFrom) query.synced_from = syncedFrom
|
||||
const syncedTo = validIsoDateOrUndefined(state.syncedTo)
|
||||
if (syncedTo) query.synced_to = syncedTo
|
||||
return query
|
||||
}
|
||||
|
||||
/** 过滤态 + 分页 → 列表查询参数;空白/非法日期不下发,分页钳制在此单出口(不含公司维)。
|
||||
* {@code ownerGroupId} 是「当前分组」(分类列/分类筛选作用域,V203),不是筛选条件:
|
||||
* >0 时下发 `owner_group_id`,缺省/0 不下发=后端按作用域默认分组取。 */
|
||||
export function toJdProductListParams(
|
||||
state: JdProductFilterState,
|
||||
page: number,
|
||||
pageSize: number,
|
||||
ownerGroupId?: number | null,
|
||||
): JdProductQuery {
|
||||
const safePage = Math.min(Math.max(Math.floor(page) || 1, 1), JD_PRODUCT_MAX_PAGE)
|
||||
const rawSize = Math.floor(pageSize) || JD_PRODUCT_PAGE_SIZE
|
||||
const safeSize = Math.min(Math.max(rawSize, 1), JD_PRODUCT_MAX_PAGE_SIZE)
|
||||
const query: JdProductQuery = {
|
||||
page: safePage,
|
||||
page_size: safeSize,
|
||||
...toJdProductFilterQuery(state),
|
||||
}
|
||||
if (typeof ownerGroupId === 'number' && Number.isFinite(ownerGroupId) && ownerGroupId > 0) {
|
||||
query.owner_group_id = Math.floor(ownerGroupId)
|
||||
}
|
||||
return query
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
/** 京东数据库列表查询模型(v1.4 Phase 5):解析 JdProductPageVo(camel),纯逻辑零依赖。
|
||||
* camel 为正、snake 容错(与外观专利/去重页模型同形),缺 id 弃行。
|
||||
* 纯函数、无框架依赖(envelope 只借纯 unwrap),node --test 可直测。 */
|
||||
import { unwrap } from '../../api/envelope.ts'
|
||||
|
||||
/** 京东商品列表行(后端 JdProductItemVo,camel 为正)。 */
|
||||
export interface JdProductItem {
|
||||
id: number
|
||||
shopId: number | null
|
||||
shopName: string
|
||||
productCode: string
|
||||
skuId: string
|
||||
/** 货号(京麦后台「货号」列,与 SKU 不是同一个值)。 */
|
||||
itemNum: string
|
||||
/** SKU 数(京麦后台「12个SKU」列)。 */
|
||||
skuCount: number | null
|
||||
/** 信息分(京麦后台「信息分」列)。 */
|
||||
healthScore: number | null
|
||||
title: string
|
||||
brand: string
|
||||
categoryPath: string
|
||||
/** 价格区间下限(京麦 priceDetailVO.minJdPrice):后端 BigDecimal 序列化成 JSON number,
|
||||
* decimalText 数值/字符串都收——2026-11-16 实录:text() 把 number 丢成空串=生产库
|
||||
* 273/273 行 price_min 全有值而列表价格全显示「-」(用户报「价格没采集到」的真因)。 */
|
||||
priceMin: string
|
||||
/** 价格区间上限(京麦 priceDetailVO.maxJdPrice),解析口径同 priceMin。 */
|
||||
priceMax: string
|
||||
stockTotal: number | null
|
||||
/** 上架中/已下架/审核中/草稿。 */
|
||||
saleStatus: string
|
||||
listTab: string
|
||||
jdCreatedAt: string
|
||||
/** 上架时间(京麦后台「上架时间」列,与创建时间不是同一个值)。 */
|
||||
jdOnlineAt: string
|
||||
jdUpdatedAt: string
|
||||
mainImageUrl: string
|
||||
attrCount: number | null
|
||||
imageCount: number | null
|
||||
groupId: number | null
|
||||
groupName: string
|
||||
syncedAt?: string
|
||||
}
|
||||
|
||||
export interface JdProductPageResult {
|
||||
items: JdProductItem[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/** 前端首屏默认容量(与 filter 侧 JD_PRODUCT_PAGE_SIZE 同值 20)。 */
|
||||
export const JD_PRODUCT_DEFAULT_SIZE = 20
|
||||
|
||||
export function emptyJdProductPage(): JdProductPageResult {
|
||||
return { items: [], total: 0, page: 1, pageSize: JD_PRODUCT_DEFAULT_SIZE }
|
||||
}
|
||||
|
||||
function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null
|
||||
}
|
||||
|
||||
/** 价格区间展示:min/max 都空为 -,只空一侧给单值。输入数值/字符串都收
|
||||
* (后端 BigDecimal 序列化成 JSON number;列表行解析层之外,mount 测试 mock
|
||||
* 绕过解析层时 number 会原样进这里——对 number 直接 .trim() 抛 TypeError
|
||||
* 炸整页渲染,2026-11-16 实录),统一 decimalText 归一后再拼。 */
|
||||
export function jdPriceRange(item: Pick<JdProductItem, 'priceMin' | 'priceMax'>): string {
|
||||
const min = decimalText(item.priceMin).trim()
|
||||
const max = decimalText(item.priceMax).trim()
|
||||
if (min && max) return min === max ? min : `${min} ~ ${max}`
|
||||
return min || max || ''
|
||||
}
|
||||
|
||||
/** 解析单行;缺 id 视为无效。camel 为正、snake 容错。 */
|
||||
export function toJdProductItem(raw: unknown): JdProductItem | null {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const record = raw as Record<string, unknown>
|
||||
const id = numberOrNull(record.id)
|
||||
if (id === null) return null
|
||||
return {
|
||||
id,
|
||||
shopId: numberOrNull(record.shopId ?? record.shop_id),
|
||||
shopName: text(record.shopName ?? record.shop_name),
|
||||
productCode: text(record.productCode ?? record.product_code),
|
||||
skuId: text(record.skuId ?? record.sku_id),
|
||||
itemNum: text(record.itemNum ?? record.item_num),
|
||||
skuCount: numberOrNull(record.skuCount ?? record.sku_count),
|
||||
healthScore: numberOrNull(record.healthScore ?? record.health_score),
|
||||
title: text(record.title),
|
||||
brand: text(record.brand),
|
||||
categoryPath: text(record.categoryPath ?? record.category_path),
|
||||
// 价格必须走 decimalText(数值/字符串都收):后端 BigDecimal 序列化成 JSON number,
|
||||
// text() 对非字符串一律回空串=采集到的价格在解析层被丢掉(2026-11-16 生产库 273 行
|
||||
// price_min 全有值、列表全「-」实录)。与详情 SKU 价(decimalText)同一出口。
|
||||
priceMin: decimalText(record.priceMin ?? record.price_min),
|
||||
priceMax: decimalText(record.priceMax ?? record.price_max),
|
||||
stockTotal: numberOrNull(record.stockTotal ?? record.stock_total),
|
||||
saleStatus: text(record.saleStatus ?? record.sale_status),
|
||||
listTab: text(record.listTab ?? record.list_tab),
|
||||
jdCreatedAt: text(record.jdCreatedAt ?? record.jd_created_at),
|
||||
jdOnlineAt: text(record.jdOnlineAt ?? record.jd_online_at),
|
||||
jdUpdatedAt: text(record.jdUpdatedAt ?? record.jd_updated_at),
|
||||
mainImageUrl: text(record.mainImageUrl ?? record.main_image_url),
|
||||
attrCount: numberOrNull(record.attrCount ?? record.attr_count),
|
||||
imageCount: numberOrNull(record.imageCount ?? record.image_count),
|
||||
groupId: numberOrNull(record.groupId ?? record.group_id),
|
||||
groupName: text(record.groupName ?? record.group_name),
|
||||
syncedAt: text(record.syncedAt ?? record.synced_at) || undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/** 归一化分页负载(信封或已解包 VO)为前端结果;缺省字段回默认。 */
|
||||
export function parseJdProductPage(payload: unknown): JdProductPageResult {
|
||||
const out = emptyJdProductPage()
|
||||
const core = unwrap<unknown>(payload)
|
||||
if (!core || typeof core !== 'object') return out
|
||||
const record = core as Record<string, unknown>
|
||||
if (Array.isArray(record.items)) {
|
||||
out.items = record.items
|
||||
.map((raw) => toJdProductItem(raw))
|
||||
.filter((item): item is JdProductItem => item !== null)
|
||||
}
|
||||
if (typeof record.total === 'number') out.total = Math.floor(record.total)
|
||||
if (typeof record.page === 'number' && record.page >= 1) out.page = Math.floor(record.page)
|
||||
const rawSize = record.pageSize ?? record.page_size
|
||||
if (typeof rawSize === 'number' && rawSize >= 1) out.pageSize = Math.floor(rawSize)
|
||||
return out
|
||||
}
|
||||
|
||||
/** 详情属性块:attrGroups[{groupName, attrs:[{key,label,value}]}]。 */
|
||||
export interface JdProductAttrEntry {
|
||||
key: string
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export interface JdProductAttrGroup {
|
||||
groupName: string
|
||||
attrs: JdProductAttrEntry[]
|
||||
}
|
||||
|
||||
/** 详情图片:images[{id, imageType, attrName, sortNo, url, byteSize, width, height}]
|
||||
* (id=biz_jd_product_image 行号,编辑抽屉按它提交删图;旧后端不带 id 时按缺 0 弃行口径不拦展示)。 */
|
||||
export interface JdProductImage {
|
||||
id: number
|
||||
imageType: string
|
||||
attrName: string
|
||||
sortNo: number
|
||||
url: string
|
||||
byteSize: number | null
|
||||
width: number | null
|
||||
height: number | null
|
||||
}
|
||||
|
||||
/** 销售属性组合的一项(颜色=上衣 / 尺码=S,京麦详情页「销售属性」)。 */
|
||||
export interface JdProductSkuAttr {
|
||||
name: string
|
||||
value: string
|
||||
}
|
||||
|
||||
/** 详情 SKU 行(后端 JdProductDetailVo.SkuVo,V198;京麦 12 行矩阵的一行)。 */
|
||||
export interface JdProductSku {
|
||||
skuId: string
|
||||
skuName: string
|
||||
/** 商家自定义序号(京麦 skuSeq)。 */
|
||||
skuSeq: string
|
||||
/** 京东价(后端 BigDecimal,前端按文本展示,不做金额运算)。 */
|
||||
price: string
|
||||
stock: number | null
|
||||
saleAttrs: JdProductSkuAttr[]
|
||||
sortNo: number
|
||||
}
|
||||
|
||||
export interface JdProductDetail {
|
||||
item: JdProductItem
|
||||
attrGroups: JdProductAttrGroup[]
|
||||
images: JdProductImage[]
|
||||
/** SKU 矩阵(京麦详情页「销售属性」区,V198;旧数据为空数组)。 */
|
||||
skus: JdProductSku[]
|
||||
/** attrGroups 解析失败时的原始 JSON 兜底(界面原样展示,不静默吞)。 */
|
||||
attrJsonRaw: string
|
||||
}
|
||||
|
||||
/** 归一化 attrGroups(camel/snake 同级容错),非法项跳过、块名缺省归「属性」。 */
|
||||
function toAttrGroups(raw: unknown): JdProductAttrGroup[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: JdProductAttrGroup[] = []
|
||||
for (const groupRaw of raw) {
|
||||
if (!groupRaw || typeof groupRaw !== 'object') continue
|
||||
const group = groupRaw as Record<string, unknown>
|
||||
const groupName = text(group.groupName ?? group.group_name) || '属性'
|
||||
const attrsRaw = group.attrs
|
||||
if (!Array.isArray(attrsRaw)) continue
|
||||
const attrs: JdProductAttrEntry[] = []
|
||||
for (const attrRaw of attrsRaw) {
|
||||
if (!attrRaw || typeof attrRaw !== 'object') continue
|
||||
const attr = attrRaw as Record<string, unknown>
|
||||
attrs.push({
|
||||
key: text(attr.key),
|
||||
label: text(attr.label),
|
||||
value: text(attr.value),
|
||||
})
|
||||
}
|
||||
out.push({ groupName, attrs })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 归一化 images;缺 url 弃行(界面没有可展示/可打开的目标),sortNo 缺省 0。 */
|
||||
function toImages(raw: unknown): JdProductImage[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: JdProductImage[] = []
|
||||
for (const imageRaw of raw) {
|
||||
if (!imageRaw || typeof imageRaw !== 'object') continue
|
||||
const image = imageRaw as Record<string, unknown>
|
||||
const url = text(image.url)
|
||||
if (!url) continue
|
||||
out.push({
|
||||
id: numberOrNull(image.id) ?? 0,
|
||||
imageType: text(image.imageType ?? image.image_type),
|
||||
attrName: text(image.attrName ?? image.attr_name),
|
||||
sortNo: numberOrNull(image.sortNo ?? image.sort_no) ?? 0,
|
||||
url,
|
||||
byteSize: numberOrNull(image.byteSize ?? image.byte_size),
|
||||
width: numberOrNull(image.width),
|
||||
height: numberOrNull(image.height),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 数值/字符串都收(后端 BigDecimal 序列化成 JSON number),去尾零后展示:
|
||||
* 京麦详情页写 `162`,不给 `162.00`;数字形状之外的原文照原样回(不吞异常值)。 */
|
||||
function decimalText(value: unknown): string {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
return String(Math.round(value * 100) / 100)
|
||||
}
|
||||
const raw = text(value)
|
||||
if (!/^\d+(?:\.\d+)?$/.test(raw)) return raw
|
||||
return String(Math.round(Number(raw) * 100) / 100)
|
||||
}
|
||||
|
||||
/** 归一化 SKU 矩阵(camel/snake 容错);缺 skuId 弃行(京麦每一行都以 skuId 为身份)。 */
|
||||
function toSkus(raw: unknown): JdProductSku[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
const out: JdProductSku[] = []
|
||||
for (const skuRaw of raw) {
|
||||
if (!skuRaw || typeof skuRaw !== 'object') continue
|
||||
const sku = skuRaw as Record<string, unknown>
|
||||
const skuId = text(sku.skuId ?? sku.sku_id)
|
||||
if (!skuId) continue
|
||||
const saleAttrs: JdProductSkuAttr[] = []
|
||||
const attrsRaw = sku.saleAttrs ?? sku.sale_attrs
|
||||
if (Array.isArray(attrsRaw)) {
|
||||
for (const attrRaw of attrsRaw) {
|
||||
if (!attrRaw || typeof attrRaw !== 'object') continue
|
||||
const attr = attrRaw as Record<string, unknown>
|
||||
const value = text(attr.value)
|
||||
if (!value) continue
|
||||
saleAttrs.push({ name: text(attr.name) || '属性', value })
|
||||
}
|
||||
}
|
||||
out.push({
|
||||
skuId,
|
||||
skuName: text(sku.skuName ?? sku.sku_name),
|
||||
skuSeq: text(sku.skuSeq ?? sku.sku_seq),
|
||||
price: decimalText(sku.price),
|
||||
stock: numberOrNull(sku.stock),
|
||||
saleAttrs,
|
||||
sortNo: numberOrNull(sku.sortNo ?? sku.sort_no) ?? 0,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 销售属性维度名(按首次出现顺序):京麦详情页「颜色 / 尺码」两列。 */
|
||||
export function jdSkuDimensions(skus: JdProductSku[]): string[] {
|
||||
const order: string[] = []
|
||||
for (const sku of skus) {
|
||||
for (const attr of sku.saleAttrs) {
|
||||
if (!order.includes(attr.name)) order.push(attr.name)
|
||||
}
|
||||
}
|
||||
return order
|
||||
}
|
||||
|
||||
/** SKU 矩阵汇总:`12 个 SKU · ¥162 ~ ¥168 · 库存 2400`(缺项不硬凑)。 */
|
||||
export function jdSkuSummary(skus: JdProductSku[]): string {
|
||||
if (!skus.length) return ''
|
||||
const prices = skus
|
||||
.map((sku) => Number(sku.price))
|
||||
.filter((value) => Number.isFinite(value) && value > 0)
|
||||
const priceText = prices.length
|
||||
? Math.min(...prices) === Math.max(...prices)
|
||||
? `¥${Math.min(...prices)}`
|
||||
: `¥${Math.min(...prices)} ~ ¥${Math.max(...prices)}`
|
||||
: ''
|
||||
const stocks = skus.map((sku) => sku.stock).filter((value): value is number => typeof value === 'number')
|
||||
const stockText = stocks.length ? `库存 ${stocks.reduce((sum, value) => sum + value, 0)}` : ''
|
||||
return [`${skus.length} 个 SKU`, priceText, stockText].filter(Boolean).join(' · ')
|
||||
}
|
||||
|
||||
/** 解析详情负载(信封或已解包 VO);attrGroups 解析不出时回 attrJsonRaw 原文兜底。 */
|
||||
export function parseJdProductDetail(payload: unknown): JdProductDetail {
|
||||
const core = unwrap<unknown>(payload)
|
||||
const record = core && typeof core === 'object' ? (core as Record<string, unknown>) : {}
|
||||
const item = toJdProductItem(record) ?? {
|
||||
id: 0,
|
||||
shopId: null,
|
||||
shopName: '',
|
||||
productCode: '',
|
||||
skuId: '',
|
||||
itemNum: '',
|
||||
skuCount: null,
|
||||
healthScore: null,
|
||||
title: '',
|
||||
brand: '',
|
||||
categoryPath: '',
|
||||
priceMin: '',
|
||||
priceMax: '',
|
||||
stockTotal: null,
|
||||
saleStatus: '',
|
||||
listTab: '',
|
||||
jdCreatedAt: '',
|
||||
jdOnlineAt: '',
|
||||
jdUpdatedAt: '',
|
||||
mainImageUrl: '',
|
||||
attrCount: null,
|
||||
imageCount: null,
|
||||
groupId: null,
|
||||
groupName: '',
|
||||
}
|
||||
const attrGroups = toAttrGroups(record.attrGroups ?? record.attr_groups)
|
||||
const attrJsonRaw = typeof record.attrJsonRaw === 'string'
|
||||
? record.attrJsonRaw
|
||||
: typeof record.attr_json_raw === 'string' ? record.attr_json_raw : ''
|
||||
return {
|
||||
item,
|
||||
attrGroups,
|
||||
images: toImages(record.images),
|
||||
skus: toSkus(record.skus),
|
||||
attrJsonRaw,
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime, orderedPair } from '@/utils/datetime'
|
||||
/** 外观专利无侵权数据 · 只读分页列表(v1.3,展示形式参照「去重数据库」页:自绘 table +
|
||||
* OldPagination,不做卡片宫格)。数据由出表成功点自动同步(后端 SyncService),本页零写操作:
|
||||
* 无编辑/导入,下载走既有结果直链/任务中心;导出(2026-11-11 客户需求)带当前过滤面 +
|
||||
* 公司 tab 走后端 /export 全量出 xlsx(含所属主管列)。分组下拉(主管=组长)选项与去重页
|
||||
* 共用 GET /shop-manages/groups,选中后以 group_id 走同一过滤面(列表与导出同源)。 */
|
||||
/** 外观专利数据库 · 明细分页表(2026-11-11 晚间按客户口径恢复「昨天那个格式」:
|
||||
* 「不是这种格式 你就按照昨天那个格式」——撤掉一主管一卡视图,恢复只读明细表;
|
||||
* 「添加个管理员 跟导出数据就可以」——表上加「管理员」列(后端读侧现算:主管/公司超管=自己,
|
||||
* 普通账户=创建人,读不到为空展示 -,不猜名),筛选行加「导出」(与「去重数据库」页同款:
|
||||
* 当前过滤面+公司 tab 全量出 xlsx,不传 supervisor_user_id——传了会走按主管分支并忽略任务号/ASIN);
|
||||
* 「任务号/ASIN 两个筛选框恢复」(后端能力一直在,之前产品决定下过架,客户要「一目了然」选数据);
|
||||
* 分组(主管)下拉保留「选中即查」。数据按 ASIN 累计:同 ASIN 只保留一条(V192 唯一键,
|
||||
* 重复检测更新那条),不同 ASIN 同品牌全保留——页面只管展示,累计语义在后端同步链。
|
||||
* 主管卡片视图与卡片级删除按钮从页面下架(客户下午反馈数据疑似被误删,删除入口先撤;
|
||||
* 后端 /supervisors 两接口保留不动)。 */
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import {
|
||||
exportAppearancePatentCleanList,
|
||||
@@ -81,7 +86,8 @@ async function load(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 导出与页签同一过滤面(含公司 tab 与分组),服务端全量出 xlsx;成功后浏览器落盘,失败弹可读文案。 */
|
||||
/** 导出与页签同一过滤面(含公司 tab 与分组),服务端全量出 xlsx;成功后浏览器落盘,失败弹可读文案。
|
||||
* 不传 supervisor_user_id:按主管分支会忽略任务号/ASIN 参数,「按当前筛选导出」必须走明细分支。 */
|
||||
async function exportAll(): Promise<void> {
|
||||
if (exporting.value) return
|
||||
exporting.value = true
|
||||
@@ -117,6 +123,13 @@ function apply(): void {
|
||||
void load()
|
||||
}
|
||||
|
||||
/** 重置(对齐店铺数据记录页样式):筛选面回出厂空态,回第一页重取。 */
|
||||
function reset(): void {
|
||||
Object.assign(filter, createAppearancePatentCleanFilterState())
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
function changePage(next: number): void {
|
||||
if (next < 1 || next > totalPages.value) return
|
||||
page.value = next
|
||||
@@ -164,7 +177,8 @@ onMounted(() => {
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>分组</label>
|
||||
<select v-model="filter.groupId">
|
||||
<!-- 分组(主管)选中即查:选完立刻按该主管过滤刷新(回第一页),不必再点查询。 -->
|
||||
<select v-model="filter.groupId" @change="apply">
|
||||
<option value="">全部分组</option>
|
||||
<option v-for="group in groupOptions" :key="group.id" :value="String(group.id)">{{ group.name }}</option>
|
||||
</select>
|
||||
@@ -182,16 +196,20 @@ onMounted(() => {
|
||||
<button class="btn btn-export" type="button" :disabled="exporting" @click="exportAll">
|
||||
{{ exporting ? '导出中...' : '导出' }}
|
||||
</button>
|
||||
<button class="btn btn-secondary" type="button" @click="reset">重置</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="clean-toolbar">
|
||||
<span class="clean-summary">共 {{ total }} 条无侵权数据</span>
|
||||
</div>
|
||||
<div class="table-scroll clean-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 90px">任务号</th>
|
||||
<th style="width: 110px">所属主管</th>
|
||||
<th style="width: 110px">管理员</th>
|
||||
<th>ASIN</th>
|
||||
<th style="width: 64px">国家</th>
|
||||
<th>SKU</th>
|
||||
@@ -199,7 +217,7 @@ onMounted(() => {
|
||||
<th style="width: 90px">价格</th>
|
||||
<th>标题</th>
|
||||
<th style="width: 130px">结论</th>
|
||||
<th style="width: 150px">同步时间</th>
|
||||
<th style="width: 170px">同步时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -233,7 +251,8 @@ onMounted(() => {
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 像素复刻参照「去重数据库」页(panel-box + 自绘表格 + 旧式分页),只读无操作列。 */
|
||||
/* 像素复刻参照「去重数据库」页(panel-box + 自绘表格 + 旧式分页),只读无操作列。
|
||||
2026-11-11 晚间恢复明细表形态(客户「按照昨天那个格式」),表头第二列=管理员。 */
|
||||
.clean-items-view {
|
||||
font-family: inherit;
|
||||
color: var(--c-text, #24384d);
|
||||
@@ -340,6 +359,26 @@ h3 {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #ffffff;
|
||||
color: #5b6f83;
|
||||
border-color: #c7d7e5;
|
||||
}
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
color: #2f5d8b;
|
||||
border-color: #95b1cb;
|
||||
background: #edf5fb;
|
||||
}
|
||||
.clean-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.clean-summary {
|
||||
color: #5b6f83;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
@@ -353,8 +392,12 @@ h3 {
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
/* 同步时间列=`YYYY-MM-DD HH:mm:ss` 固定 19 字符,13.5px 下实测约 133px;全局 `* { box-sizing: border-box }`
|
||||
把 24px 左右内边距算进列宽,旧的 150px 只剩 126px 内容宽 ⇒ 末尾被 ellipsis 吃掉(客户 2026-11-12
|
||||
反馈「日期显示不全」)。170px 与店铺管理/跳过价格等页的时间列同值(内容宽 146px,留 13px 余量);
|
||||
表 min-width 同步 +20px,其余列的可用宽度与改前一致。 */
|
||||
.clean-table-scroll > table {
|
||||
min-width: 1040px;
|
||||
min-width: 1060px;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
/** 外观专利无侵权数据列表查询适配(v1.3 AC-5):GET /api/admin/appearance-patent-clean-items。
|
||||
* 只读页+导出(2026-11-11 客户需求「数据得导出来」):公司 tab 的值由本发送口从原始入参自己下传
|
||||
* (白名单构造不认识 company_id),取值口形状由 company-tab-wiring 护栏钉住。 */
|
||||
* (白名单构造不认识 company_id),取值口形状由 company-tab-wiring 护栏钉住。
|
||||
* 2026-11-11 晚间恢复明细表:主管聚合(/supervisors)与按主管删除的前端发送口随卡片视图一并
|
||||
* 下架(客户「不是这种格式 按照昨天那个格式」+删除入口先撤);后端两接口保留,要恢复时
|
||||
* 从 git 历史(e1767faf)找回。 */
|
||||
import { http } from '@/api/http'
|
||||
import { errorTextOf } from '../../api/envelope.ts'
|
||||
import { errorTextOf, unwrap } from '../../api/envelope.ts'
|
||||
import {
|
||||
toAppearancePatentCleanExportParams,
|
||||
toAppearancePatentCleanListParams,
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* 原始入参自己下传——取值口由 company-tab-wiring 护栏的发送行钉看守。
|
||||
* 分组语义(2026-11-11 客户口径「主管就是组长,可以筛选组长来导出,就是分组」):下拉选项是
|
||||
* 分组管理里那一行(biz_shop_manage_group),group_id 下发后服务端解析「组长本人+名下子账户」
|
||||
* 整集 SQL 下推;行上「所属主管」列与它同源(组长行=自己,子账户行=创建人)。 */
|
||||
* 整集 SQL 下推;表上「管理员」列与它同源(组长行=自己,子账户行=创建人)。 */
|
||||
import { validIsoDateOrUndefined } from '../asin/asin-filter.ts'
|
||||
|
||||
/** 每页条数默认 10(蓝图 §3.2),上限 100。 */
|
||||
|
||||
@@ -7,7 +7,7 @@ export interface AppearancePatentCleanItem {
|
||||
resultId: number | null
|
||||
taskId: number | null
|
||||
userId: number | null
|
||||
/** 所属主管(后端读侧现算列:主管/公司超管=自己,普通账户=创建人;读不到为空 → 界面展示 -)。 */
|
||||
/** 管理员列(表头「管理员」,客户 2026-11-11 口径;后端读侧现算:主管/公司超管=自己,普通账户=创建人,读不到为空 → 界面展示 -)。 */
|
||||
supervisorName: string
|
||||
companyId: number | null
|
||||
rowNo: number | null
|
||||
@@ -41,6 +41,16 @@ export function emptyAppearancePatentCleanPage(): AppearancePatentCleanPageResul
|
||||
return { items: [], total: 0, page: 1, pageSize: APPEARANCE_PATENT_CLEAN_DEFAULT_SIZE }
|
||||
}
|
||||
|
||||
/** 结论列悬停提示=三因原文拼装(2026-11-11 随明细表恢复回归;3cfca462 曾随结论徽章一起退役)。 */
|
||||
export function cleanItemReasonTooltip(item: AppearancePatentCleanItem): string {
|
||||
const parts: string[] = []
|
||||
if (item.titleReason) parts.push(`标题:${item.titleReason}`)
|
||||
if (item.appearanceReason) parts.push(`外观:${item.appearanceReason}`)
|
||||
if (item.patentReason) parts.push(`专利:${item.patentReason}`)
|
||||
return parts.join('\n')
|
||||
}
|
||||
|
||||
|
||||
function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
@@ -97,12 +107,3 @@ export function parseAppearancePatentCleanPage(payload: unknown): AppearancePate
|
||||
if (typeof rawSize === 'number' && rawSize >= 1) out.pageSize = Math.floor(rawSize)
|
||||
return out
|
||||
}
|
||||
|
||||
/** 结论单元格的悬停全文:三因齐给,空因不下发(读侧不加工的展示面出口)。 */
|
||||
export function cleanItemReasonTooltip(item: AppearancePatentCleanItem): string {
|
||||
const parts: string[] = []
|
||||
if (item.titleReason) parts.push(`标题:${item.titleReason}`)
|
||||
if (item.appearanceReason) parts.push(`外观:${item.appearanceReason}`)
|
||||
if (item.patentReason) parts.push(`专利:${item.patentReason}`)
|
||||
return parts.join('\n')
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
@@ -1,7 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
/** 数富AI工作台客户端包管理页:上传 ZIP → 直传 MinIO → 服务端复算 sha256 落库;
|
||||
* 客户端从 /api/workbench-client/version/latest 自动检测并按最新上传升级。
|
||||
/** 数富AI工作台客户端包管理页:上传 ZIP → 直传 MinIO → 服务端复算 sha256 落库。
|
||||
* 列表默认按上传时间倒序,第一条即当前生效版本;删除最新包后自动回落到上一版。 */
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
@@ -177,7 +176,7 @@ onMounted(load)
|
||||
<button class="btn" type="button" @click="openUpload">上传客户端包</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="page-hint">客户端更新检查接口:<code>/api/workbench-client/version/latest</code>;最新上传的一条即当前生效版本。</p>
|
||||
<p class="page-hint">最新上传的一条即当前生效版本。</p>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll workbench-table-scroll">
|
||||
|
||||
@@ -20,9 +20,6 @@ export const WORKBENCH_CLIENT_CHUNK_ENDPOINT = `${WORKBENCH_CLIENT_PACKAGE_ENDPO
|
||||
export const WORKBENCH_CLIENT_UNCONFIRMED_OBJECT_ENDPOINT = `${WORKBENCH_CLIENT_PACKAGE_ENDPOINT}/object`
|
||||
export const FILES_CHUNK_ENDPOINT = '/api/files/chunk'
|
||||
|
||||
/** 客户端自动更新契约(后管页面不直接调用):GET 返回 {version,file_url,sha256,...}。 */
|
||||
export const WORKBENCH_CLIENT_PUBLIC_LATEST_ENDPOINT = '/api/workbench-client/version/latest'
|
||||
|
||||
/** MinIO 直传专用实例:不带 cookie、不挂 401 跳登录拦截器;大 zip 给足超时。 */
|
||||
const directPut = axios.create({ timeout: 600_000, withCredentials: false })
|
||||
|
||||
|
||||
@@ -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') },
|
||||
@@ -45,6 +44,11 @@ export const adminPages: AdminPageDef[] = [
|
||||
{ path: 'asin-center/categories', menuKey: 'admin_product_categories', title: '商品类目', companyScoped: false, load: () => import('@/pages/asin/ProductCategoryPage.vue') },
|
||||
{ path: 'asin-center/skip-price', menuKey: 'admin_skip_price_asin', title: '最低价ASIN', companyScoped: true, load: () => import('@/pages/asin/SkipPricePage.vue') },
|
||||
{ path: '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') },
|
||||
]
|
||||
|
||||
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
|
||||
},
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { PLATFORM_TABS } from '@/config/platform-scope'
|
||||
import type { PlatformTabId } from '@/config/platform-scope'
|
||||
|
||||
const STORAGE_KEY = 'admin-platform-tab'
|
||||
const DEFAULT_TAB: PlatformTabId = 'amazon'
|
||||
|
||||
function isKnownTab(id: unknown): id is PlatformTabId {
|
||||
return PLATFORM_TABS.some((tab) => tab.id === id)
|
||||
}
|
||||
|
||||
/** 读取持久化偏好;无存储/值非法/存储不可用一律回落亚马逊(隐私模式不阻断交互)。 */
|
||||
function readStoredTab(): PlatformTabId {
|
||||
try {
|
||||
const raw = typeof localStorage === 'undefined' ? null : localStorage.getItem(STORAGE_KEY)
|
||||
return isKnownTab(raw) ? raw : DEFAULT_TAB
|
||||
} catch {
|
||||
return DEFAULT_TAB
|
||||
}
|
||||
}
|
||||
|
||||
function writeStoredTab(id: PlatformTabId): void {
|
||||
try {
|
||||
if (typeof localStorage !== 'undefined') localStorage.setItem(STORAGE_KEY, id)
|
||||
} catch {
|
||||
// localStorage 不可用(隐私模式等)时忽略
|
||||
}
|
||||
}
|
||||
|
||||
/** 侧边栏平台 tab(亚马逊/京东)状态:纯显示分组不参与鉴权(2026-11-16 用户定案)。
|
||||
* 菜单可见性仍由 session.menuTree(后端按权限裁剪)决定,这里只记「当前看哪一侧」。 */
|
||||
export const usePlatformTabStore = defineStore('platform-tab', {
|
||||
state: () => ({
|
||||
active: readStoredTab(),
|
||||
}),
|
||||
actions: {
|
||||
setActive(id: PlatformTabId) {
|
||||
this.active = id
|
||||
writeStoredTab(id)
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -65,6 +65,22 @@ button, input, textarea, select { font: inherit; }
|
||||
.admin-brand-copy strong { color: var(--admin-text); font-size: 15px; font-weight: 600; letter-spacing: .5px; white-space: nowrap; }
|
||||
.admin-brand-copy span { color: #77899b; font-size: 11px; white-space: nowrap; }
|
||||
|
||||
/* 侧边栏顶部平台 tab(亚马逊/京东,2026-11-16「不混」定案):纯显示分组,只对当前用户
|
||||
* 已授权菜单分侧展示;单侧无可见菜单时整条隐藏(AdminLayout showPlatformTabs)。 */
|
||||
.admin-platform-tabs { display: flex; gap: 6px; padding: 10px 12px 0; }
|
||||
.admin-platform-tab {
|
||||
flex: 1; height: 34px; text-align: center; font-size: 13px; font-weight: 600;
|
||||
color: var(--admin-sidebar-text); background: transparent;
|
||||
border: 1px solid var(--admin-border); border-radius: 9px; cursor: pointer;
|
||||
}
|
||||
.admin-platform-tab:hover { color: #1e3b57; background: rgba(47, 93, 139, 0.16); }
|
||||
.admin-platform-tab.is-active {
|
||||
color: var(--admin-primary-strong);
|
||||
background: linear-gradient(180deg, #dce9f5, #edf4fa);
|
||||
border-color: #b6cbe0;
|
||||
box-shadow: inset 0 2px 0 #5f85ad;
|
||||
}
|
||||
|
||||
.admin-menu-scroll { flex: 1; padding: 12px 10px; }
|
||||
.admin-menu { border-right: 0; background: transparent; }
|
||||
.admin-menu .el-sub-menu__title,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -4,7 +4,7 @@ import { readSource } from './helpers.ts'
|
||||
import { adminPages } from '../src/router/routes.ts'
|
||||
import { OPERATION_GUIDES } from '../src/layout/operation-guides.ts'
|
||||
|
||||
/** 工作台客户端包管理页:独立渠道、上传直传、服务端 sha256、客户端自动更新契约。 */
|
||||
/** 工作台客户端包管理页:独立渠道、上传直传、服务端 sha256。 */
|
||||
|
||||
test('align_workbench_client_page_registered', () => {
|
||||
const page = adminPages.find((p) => p.path === 'records/workbench-client-package')
|
||||
@@ -28,7 +28,6 @@ test('align_workbench_client_page_wiring', () => {
|
||||
assert.match(page, /当前生效/, '最新上传的包标记当前生效')
|
||||
assert.match(page, /sha256/, '展示服务端复算的摘要')
|
||||
assert.match(page, /formatFileSize/, '展示包体大小')
|
||||
assert.match(page, /\/api\/workbench-client\/version\/latest/, '页面标明客户端更新检查接口')
|
||||
assert.match(page, /确认删除选中的/, '批量删除二次确认')
|
||||
assert.match(page, /暂无客户端包记录/, '空态文案')
|
||||
})
|
||||
@@ -43,7 +42,6 @@ test('align_workbench_client_api_contract', () => {
|
||||
assert.match(api, /params: \{ file_name: fileName, version \}/, '预签名回传文件名与版本号')
|
||||
assert.match(api, /params: \{ object_key: objectKey, file_name: fileName, version \}/, '确认回传对象 key、文件名与版本号')
|
||||
assert.match(api, /withCredentials: false/, '直传实例不挂会话拦截器')
|
||||
assert.match(api, /\/api\/workbench-client\/version\/latest/, '公开更新契约路径固定')
|
||||
})
|
||||
|
||||
test('align_workbench_client_model_parsers', () => {
|
||||
@@ -61,5 +59,4 @@ test('align_workbench_client_guide_registered', () => {
|
||||
const guide = OPERATION_GUIDES.admin_workbench_client_package
|
||||
assert.ok(guide, '每个菜单页都必须有操作提示')
|
||||
assert.match(guide.text, /sha256/, '提示说明服务端会复算摘要')
|
||||
assert.match(guide.text, /\/api\/workbench-client\/version\/latest/, '提示说明客户端更新检查接口')
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,12 @@ const BRAND_GATING_MIGRATION = join(process.cwd(), '..', 'backend-java', 'src',
|
||||
'V174__restore_admin_brand_gating_menu.sql')
|
||||
const KEYWORD_USAGE_MIGRATION = join(process.cwd(), '..', 'backend-java', 'src', 'main', 'resources', 'db',
|
||||
'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')
|
||||
/** 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
|
||||
@@ -95,3 +101,40 @@ test('V175 新增的关键词使用记录菜单 key 必须在路由注册表登
|
||||
assert.ok(sql.includes('SET col.`parent_id` = grp.`id`'), 'V175 必须把品牌Gating库迁到店铺管理组')
|
||||
assert.ok(sql.includes('col.`sort_order` = 85'), '品牌Gating库排序应为 85')
|
||||
})
|
||||
|
||||
test('V196 新增的京东数据库菜单 key 必须在路由注册表登记', () => {
|
||||
const sql = readFileSync(JD_DATABASE_MIGRATION, 'utf8')
|
||||
const menus = menusInsertedBy(sql)
|
||||
const insertCount = (sql.match(/INSERT INTO `columns`/g) || []).length
|
||||
assert.ok(menus.length > 0, 'V196 应当插入后台菜单,一条都没解析出来说明正则失效')
|
||||
assert.equal(menus.length, insertCount, `解析到 ${menus.length} 条,但迁移有 ${insertCount} 条 INSERT INTO columns`)
|
||||
|
||||
const menu = menus.find((item) => item.columnKey === 'admin_jd_database')
|
||||
assert.ok(menu, 'V196 必须插入 admin_jd_database 菜单')
|
||||
const page = adminPages.find((item) => item.menuKey === 'admin_jd_database')
|
||||
assert.ok(page, 'routes.ts 必须有 admin_jd_database 页面,否则菜单点进去 404')
|
||||
assert.equal(page.path, menu.routePath, '库里的 route_path 应与注册表路径一致')
|
||||
assert.equal(page.title, menu.name, '页面标题应与菜单名一致')
|
||||
// 2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」:数据全平台公共(行 company_id
|
||||
// 只剩同步来源标记),页面退出公司 tab 注册表、取数口不带 company_id ⇒ meta 必须 false
|
||||
// (true 会画出 tab 而取数不带参=点了没反应;同品牌数据库 admin_invalid_asin_data 的形状)。
|
||||
assert.equal(page.companyScoped, false, '京东数据库全平台公共,不画公司 tab(V196 当时的按公司隔离口径已被推翻)')
|
||||
|
||||
// 每公司一套树(公司 1 模板行 + 其余公司复制),挂数据管理组、排序 68(V190 外观专利占 67)。
|
||||
assert.ok(sql.includes("grp.`column_key` = 'admin_group_data'"), 'V196 必须把京东数据库挂到数据管理组')
|
||||
assert.ok(/'京东数据库', 'admin_jd_database', 'admin', 'jd-center\/database', 68/.test(sql), '京东数据库排序应为 68')
|
||||
assert.ok(!sql.includes('user_column_permission'), 'V196 不得预插授权行(默认仅超管可见)')
|
||||
})
|
||||
|
||||
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 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 路由必须下线')
|
||||
})
|
||||
|
||||
@@ -77,6 +77,7 @@ function escapeRegExp(text: string): string {
|
||||
* + 批次 6(控制方 2026-10-06 点名「菜单权限也加字段来区分」)3 处:菜单目录 / 新建菜单 / 用户管理里的授权树
|
||||
* + 批次 7(2026-11-10 v1.3 外观专利无侵权数据)2 处:只读列表 + 导出(2026-11-11 客户需求「数据得导出来」)。
|
||||
* 批次 2 原 12 处里的品牌库 1 处 + 商品类目 4 处,随 2026-10-06「这两页退回全平台共享」一并摘掉。
|
||||
* 批次 8 原 2 处(京东数据库列表/类目)随 2026-11-16「删除掉公司 tab,参考品牌数据库」一并摘掉。
|
||||
*
|
||||
* <p>`window` 的取法:本轮实扫的 own(到自己那行的距离)+ ≥150 余量,且当同文件还有下一个同名发送口时必须
|
||||
* `window < next`。own/next 不写死在这里——下面「窗口与真文件对平」那条用例逐处从真文件重算,
|
||||
@@ -125,11 +126,16 @@ const SEND_POINTS: ReadonlyArray<SendPoint> = [
|
||||
{ menuKey: 'admin_users', file: 'src/pages/account/user-menu-auth-api.ts', fn: 'fetchGrantableMenus', line: TASK_CENTER_SEND_LINE, window: 300, title: 'GET /permission-menus?grantableOnly 授权树:一家一套树后取错公司=已授权勾不上、提交必判无效' },
|
||||
// ↓ 批次 7(2026-11-10 v1.3 外观专利无侵权数据):出表成功自动同步的只读明细,归属物化在行
|
||||
// company_id 列(V189,同店铺密钥形状)⇒ 后端正门 readCompanyIdOrOwn;2026-11-11 客户需求
|
||||
// 「数据得导出来」补导出发送口(与列表共用同一过滤面与正门),这一页共两个发送口。
|
||||
// 窗口 500:两处 own 实测 416/395(groupId 行加入后),同文件两条塞键行的间距 1585 ⇒
|
||||
// 「数据得导出来」补导出发送口(与列表共用同一过滤面与正门)。这一页共两个发送口
|
||||
// (同日曾加的 /supervisors 取数与按主管删除两口,随当晚「恢复昨天那个明细表格式」一并
|
||||
// 下架——后端接口保留,前端发送口撤,重上时从 e1767faf 历史找回再登记)。
|
||||
// 窗口 500:own 实测 416(groupId 行加入后),同文件两条塞键行的间距 1585 ⇒
|
||||
// 500 够得着自己、够不到隔壁(对平用例逐处从真文件重算,注释过期即红)。
|
||||
{ menuKey: 'admin_appearance_patent_clean_items', file: 'src/pages/patent/appearance-patent-clean-api.ts', fn: 'fetchAppearancePatentCleanList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /appearance-patent-clean-items 无侵权只读列表' },
|
||||
{ menuKey: 'admin_appearance_patent_clean_items', file: 'src/pages/patent/appearance-patent-clean-api.ts', fn: 'exportAppearancePatentCleanList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /appearance-patent-clean-items/export 导出(2026-11-11 客户需求「数据得导出来」,与列表共用同一过滤面)' },
|
||||
// 批次 8(2026-11-14 v1.4 京东数据库)的两条发送口(列表/类目下拉)已于 2026-11-16 随
|
||||
// 「删除掉公司 tab,参考品牌数据库」整批摘下(后端读侧谓词同窗撤,重上时从 git 历史找回);
|
||||
// 「不得回流」由文件末尾「公司维度不得回流」清单看守(admin_jd_database 已入列)。
|
||||
]
|
||||
|
||||
/** 任务看板那 5 处(1b ④ 那条用例按文件筛它们,沿用旧名字不漂;表只有一份,不会漂出两个口径)。 */
|
||||
@@ -253,6 +259,8 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
|
||||
admin_columns: pinsFor('admin_columns'),
|
||||
// 批次 7(v1.3 无侵权只读页):同样由 SEND_POINTS 现算——只有一个发送口(列表)。
|
||||
admin_appearance_patent_clean_items: pinsFor('admin_appearance_patent_clean_items'),
|
||||
// 批次 8(v1.4 京东数据库)2026-11-16 随「删除掉公司 tab」整页摘除:登记表条目一并撤下,
|
||||
// 「不得回流」改由文件末尾「公司维度不得回流」清单看守(同品牌库/商品类目的先例形状)。
|
||||
}
|
||||
|
||||
/** 严格判据的分母由本轮实扫得出(修完不许恒绿也不许恒红):求值了几条 shape、其中几条通过。 */
|
||||
@@ -351,8 +359,13 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
|
||||
// ⚠ 分母是本轮实扫的表条数(批次 1 的 5 + 批次 2 的 7 + 批次 3 的 4 + 批次 4 的 1 + 批次 5 的 1 + 批次 6 的 3;
|
||||
// 批次 2 原 12 条里的品牌库 1 条 + 商品类目 4 条随 2026-10-06「这两页退回全平台共享」摘掉)。
|
||||
// 这条只防"整表被摘空/被改窄",逐处脱管由下面两条(对平闸门 + 窗口对平)负责。
|
||||
assert.ok(SEND_POINTS.length >= 21,
|
||||
`发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条 + 批次 7 v1.3 无侵权只读页与导出 2 条 = 25 条)⇒ 有人把钉从表里摘了,取值口看守成空`)
|
||||
// 2026-11-15 京东数据库公共化(用户定案「不区分公司、属于公共的」):批次 8 的详情/删除/
|
||||
// 分组列表/删分组/编辑 5 条 company_id 发送口随公司谓词整批撤下(后端写侧同窗摘),批次 8
|
||||
// 只剩列表/类目两条 ⇒ 32 → 27。
|
||||
// 2026-11-16 京东数据库摘公司 tab(用户定案「删除掉公司 tab,参考品牌数据库」):最后两条
|
||||
// 发送口(列表/类目下拉)与后端读侧谓词同窗摘掉,页面退出注册表 ⇒ 27 → 25。
|
||||
assert.ok(SEND_POINTS.length >= 25,
|
||||
`发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条 + 批次 7 v1.3 无侵权列表/导出 2 条 + 主管聚合 1 条 + 按主管删除 1 条 = 25 条;京东数据库两条 2026-11-16 随「删除掉公司 tab」摘、导出口 2026-11-15 随客户口径摘)⇒ 有人把钉从表里摘了,取值口看守成空`)
|
||||
for (const p of SEND_POINTS) {
|
||||
const shape = pointShape(p)
|
||||
const compliant = pointCompliant(p)
|
||||
@@ -385,7 +398,7 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
|
||||
else grouped.set(key, { file: p.file, line: p.line, pinned: 1 })
|
||||
}
|
||||
assert.equal(grouped.size, 19,
|
||||
`发送口表按 (文件, 整行) 应聚成 19 组(25 处发送口,批次 7 的列表与导出逐字同行走同一组),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`)
|
||||
`发送口表按 (文件, 整行) 应聚成 19 组(25 处发送口,批次 7 的列表/导出/主管聚合/按主管删除逐字同行各走同一组;京东数据库两组 2026-11-16 随「删除掉公司 tab」摘),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`)
|
||||
for (const g of grouped.values()) {
|
||||
const actual = occurrences(stripComments(read(g.file)), g.line)
|
||||
assert.equal(g.pinned, actual,
|
||||
@@ -741,6 +754,9 @@ const WATCH_BODY_PINS: ReadonlyArray<{
|
||||
{ file: 'src/pages/patent/appearance-patent-clean-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
|
||||
],
|
||||
},
|
||||
// 批次 8(2026-11-14 v1.4 京东数据库页)那条 watch 看守已于 2026-11-16 随「删除掉公司 tab,
|
||||
// 参考品牌数据库」一并摘下——页面不再 watch companyTab.activeId、不再消费公司 tab store,
|
||||
// 「不得回流」改由文件末尾「公司维度不得回流」清单看守。
|
||||
]
|
||||
|
||||
/** 取「`watch(() => companyTab.activeId, () => { … })`」这一条语句的原文;匹配不出返回 null(由调用方判探针失效)。 */
|
||||
@@ -750,8 +766,8 @@ function watchStatement(source: string): string | null {
|
||||
}
|
||||
|
||||
test('切公司的 watch 体:每对 (file, token) 都要在该页 watch 体内出现(批次 1 两页 + 批次 2 三页 + 批次 3 两页 + 批次 4 一页 + 批次 5 一页 + 批次 6 一页 + 批次 7 一页)', () => {
|
||||
assert.ok(WATCH_BODY_PINS.length >= 10,
|
||||
`watch 体看守只剩 ${WATCH_BODY_PINS.length} 对(批次 1 的店铺管理/任务看板 + 批次 2 的去重库/查询ASIN/最低价ASIN + 批次 3 的撞款监控/店铺数据记录 + 批次 4 的用户管理 + 批次 5 的店铺密钥 + 批次 6 的菜单管理 + 批次 7 v1.3 无侵权只读页共 11 对)`
|
||||
assert.ok(WATCH_BODY_PINS.length >= 11,
|
||||
`watch 体看守只剩 ${WATCH_BODY_PINS.length} 对(批次 1 的店铺管理/任务看板 + 批次 2 的去重库/查询ASIN/最低价ASIN + 批次 3 的撞款监控/店铺数据记录 + 批次 4 的用户管理 + 批次 5 的店铺密钥 + 批次 6 的菜单管理 + 批次 7 v1.3 无侵权只读页共 11 对;批次 8 京东数据库页那条 2026-11-16 随「删除掉公司 tab」摘下)`
|
||||
+ '⇒ 这一族又退回"只钉少数几页",被摘掉那一页的"切公司不清筛选项"再次没人看守')
|
||||
const pinnedFiles = new Set(WATCH_BODY_PINS.map((pin) => pin.file))
|
||||
for (const pin of WATCH_BODY_PINS) {
|
||||
@@ -953,26 +969,30 @@ test('渲染范围:tab 条只画在按公司取数的页上,公司管理那
|
||||
})
|
||||
|
||||
/**
|
||||
* 2026-10-06 控制方定案:品牌数据库、商品类目「做成所有公司共享的,不区分」。
|
||||
* 控制方/用户定案的「全平台共享、不区分公司」页清单:
|
||||
* - 品牌数据库、商品类目(2026-10-06 控制方定案「做成所有公司共享的,不区分」);
|
||||
* - 京东数据库(2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」)。
|
||||
*
|
||||
* <p>上面那几条正向判据全是从 {@code COMPANY_SCOPED_PAGES} 派生的,页一退出注册表就自动不再求值 ⇒
|
||||
* 「退出」这件事本身没有看守:谁把 {@code company_id} 重新塞回这三个取数口,全仓用例一支都不会红,
|
||||
* 而后端唯一键已经退回全局(V151),带公司参数的读会把共享库筛窄成「只看这一家」,
|
||||
* 「退出」这件事本身没有看守:谁把 {@code company_id} 重新塞回这些取数口,全仓用例一支都不会红,
|
||||
* 而后端唯一键已经退回全局(V151)/读侧谓词已摘(京东),带公司参数的读会把共享库筛窄成「只看这一家」,
|
||||
* 写侧则把一张全平台共享的表按家拆开——两边都是静默改口径,不是报错。所以这一支必须存在。</p>
|
||||
*
|
||||
* <p>判据只认「剥完注释的代码」:这三份文件现在各自留有一句说明共享口径的注释,
|
||||
* 注释里的 {@code company_id} 三个字面字符不是接线(全局约束 6)。正样本用摘掉之前那三行原文,
|
||||
* <p>判据只认「剥完注释的代码」:这些文件各自留有一句说明共享口径的注释,
|
||||
* 注释里的 {@code company_id} 三个字面字符不是接线(全局约束 6)。正样本用摘掉之前那些行原文,
|
||||
* 所以下面的 false 是测出来的,不是「正则本来就抓不到」。</p>
|
||||
*/
|
||||
const SHARED_PAGE_KEYS = ['admin_invalid_asin_data', 'admin_product_categories'] as const
|
||||
const SHARED_PAGE_KEYS = ['admin_invalid_asin_data', 'admin_product_categories', 'admin_jd_database'] as const
|
||||
const SHARED_API_FILES = [
|
||||
'src/pages/invalidasin/invalid-asin-api.ts',
|
||||
'src/pages/asin/product-category-api.ts',
|
||||
'src/pages/asin/product-category-export.ts',
|
||||
'src/pages/jd/jd-product-api.ts',
|
||||
] as const
|
||||
const SHARED_PAGE_FILES = [
|
||||
'src/pages/asin/AsinInvalidPage.vue',
|
||||
'src/pages/asin/ProductCategoryPage.vue',
|
||||
'src/pages/jd/JdDatabasePage.vue',
|
||||
] as const
|
||||
|
||||
/** 公司参数的两种写法:下传用的 snake、形参/字段用的 camel。 */
|
||||
@@ -985,7 +1005,7 @@ const FORMER_SEND_LINES = [
|
||||
'if (companyId != null) params.push(`company_id=${companyId}`)',
|
||||
]
|
||||
|
||||
test('公司维度不得回流:品牌库与商品类目已定案全平台共享,取数口与页面都不许再带公司参数', () => {
|
||||
test('公司维度不得回流:品牌库/商品类目/京东数据库已定案全平台共享,取数口与页面都不许再带公司参数', () => {
|
||||
// 判据自证(全局约束 15:反向钉不许独自成立)——改动前那三行必须抓得到,否则下面的 false 是空判据。
|
||||
for (const line of FORMER_SEND_LINES) {
|
||||
assert.ok(COMPANY_PARAM_TOKEN.test(line), `反向钉判据连原来的发送口「${line}」都匹配不出 ⇒ 这一族恒绿`)
|
||||
@@ -1000,7 +1020,7 @@ test('公司维度不得回流:品牌库与商品类目已定案全平台共
|
||||
|
||||
for (const key of SHARED_PAGE_KEYS) {
|
||||
assert.equal(COMPANY_SCOPED_PAGES.some((p) => p.menuKey === key), false,
|
||||
`${key} 又回到 COMPANY_SCOPED_PAGES:2026-10-06 已定案这两页全平台共享,不区分公司`)
|
||||
`${key} 又回到 COMPANY_SCOPED_PAGES:已定案全平台共享、不区分公司(品牌库/商品类目 2026-10-06、京东数据库 2026-11-16)`)
|
||||
const page = adminPages.find((p) => p.menuKey === key)
|
||||
assert.ok(page, `${key} 在路由注册表里找不到:菜单名改了,反向钉对不上页`)
|
||||
assert.equal(page.companyScoped, false,
|
||||
|
||||
@@ -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'/,
|
||||
|
||||
@@ -37,6 +37,9 @@ const EXEMPT = new Set([
|
||||
// 2026-11-10(v1.3):外观专利无侵权数据页与去重库同形状——出表成功自动同步的累计台账,
|
||||
// 默认当天会让首屏只剩今天同步的行,历史同步行整批"消失"。
|
||||
'src/pages/patent/AppearancePatentCleanItemsPage.vue',
|
||||
// 2026-11-14(v1.4 Phase 5):京东数据库页与外观专利页同形状——京东商品同步落库的累计台账,
|
||||
// 默认当天会让首屏只剩今天同步的行(页面注释与 filter 工厂同口径留空)。
|
||||
'src/pages/jd/JdDatabasePage.vue',
|
||||
// 2026-10-05(V146):两处是「到期时间」表单字段而非列表筛选——留空 = 永不过期,
|
||||
// 是有业务语义的默认值,绝不能默认当天(默认当天等于建号即过期)。
|
||||
'src/pages/account/CreateUserDialog.vue',
|
||||
|
||||
@@ -231,11 +231,11 @@ test('orderedPair 只在两端都有值且倒挂时交换', () => {
|
||||
})
|
||||
|
||||
test('分母硬钉:四面控件实例数与成对数(扫描失明即红)', () => {
|
||||
assert.equal(adminCtrls.length, 21, '后管实例数变了,先复算普查再改这里(v1.3 外观专利无侵权数据页再落一对起止=2 实例)')
|
||||
assert.equal(adminCtrls.length, 23, '后管实例数变了,先复算普查再改这里(v1.4 京东数据库页同步时间起止再落一对=2 实例)')
|
||||
assert.equal(userCtrls.length, 2, '用户端实例数变了')
|
||||
assert.equal(finCtrls.length, 30, '财务系统实例数变了')
|
||||
assert.equal(mxCtrls.length, 4, '麦象实例数变了')
|
||||
assert.equal(pairCount(adminCtrls), 9, '后管成对区间应为 9(v1.3 外观专利无侵权数据页再落一对)')
|
||||
assert.equal(pairCount(adminCtrls), 10, '后管成对区间应为 10(v1.4 京东数据库页同步时间起止再落一对)')
|
||||
assert.equal(pairCount(finCtrls), 11, '财务系统成对区间应为 11')
|
||||
assert.equal(pairCount(mxCtrls), 2, '麦象成对区间应为 2')
|
||||
assert.equal(pairCount(userCtrls), 0, '用户端出现成对区间说明新加了两个单只控件')
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { clampPanelLeftX } from '../src/pages/jd/jd-category-cascader-position.ts'
|
||||
|
||||
/** 类目面板水平钳制(2026-11-16 客户截图「超出视窗了」回归判据):面板锚 left:0 最宽
|
||||
* 4 栏 ×200px,触发框落在筛选行中部偏右时面板伸出视窗右缘。判据形状统一=「右缘装
|
||||
* 不下必须左移、左移过头贴左缘、装得下不动」三种写法一格定红;把组件改回无条件锚左
|
||||
* 即红(JdCategoryCascader.vue 的 reposition 必须经本函数算偏移)。 */
|
||||
|
||||
test('视口装得下=不偏移(默认锚左)', () => {
|
||||
// 宽视口:触发框在 x=300,4 栏 800px,右缘 1100 < 1920-8。
|
||||
assert.equal(clampPanelLeftX({ hostLeft: 300, panelWidth: 800, viewportWidth: 1920 }), 0)
|
||||
// 恰好贴齐:右缘正好压在 viewport-margin 上=零偏移(≤0 分支)。
|
||||
assert.equal(clampPanelLeftX({ hostLeft: 300, panelWidth: 800, viewportWidth: 1108 }), 0)
|
||||
})
|
||||
|
||||
test('右缘越界=整体左移到右缘贴齐(客户截图形状:末栏被窗缘裁掉)', () => {
|
||||
// 截图形状:触发框 x=250、3 栏 600px、窗宽 830 ⇒ 右缘 850 越界 28px ⇒ 左移 28。
|
||||
assert.equal(clampPanelLeftX({ hostLeft: 250, panelWidth: 600, viewportWidth: 830 }), -28)
|
||||
// 宽视口下钻到 4 栈仍越界(触发框靠右):1920 窗、触发框 x=1200、800px 面板。
|
||||
assert.equal(clampPanelLeftX({ hostLeft: 1200, panelWidth: 800, viewportWidth: 1920 }), -88)
|
||||
})
|
||||
|
||||
test('越界过头不得把面板推出左缘=钳在 margin', () => {
|
||||
// 窄窗:触发框 x=100、面板 800、窗宽 830 ⇒ 直移要 -78,但那样左缘到 22>8 可行;
|
||||
// 极端:触发框 x=4、面板 800、窗宽 500 ⇒ 直移 -312 ⇒ 左缘 -308 越左,钳到 margin=8。
|
||||
assert.equal(clampPanelLeftX({ hostLeft: 4, panelWidth: 800, viewportWidth: 500, margin: 8 }), 4)
|
||||
// 钳制后面板左缘=margin:偏移=margin-hostLeft。
|
||||
assert.equal(clampPanelLeftX({ hostLeft: 2, panelWidth: 600, viewportWidth: 400, margin: 8 }), 6)
|
||||
})
|
||||
|
||||
test('窄窗越界:直移后左缘仍够留白就正常左移;不够则钳在 margin(物理极限,不假装能塞下)', () => {
|
||||
// 窗宽 400、margin 8:面板 380 ⇒ 直移 -138 后左缘 12 ≥ 8 可行;
|
||||
// 面板 390 ⇒ 直移后左缘 2 < 8 ⇒ 钳到左缘 8(偏移 -142),右侧溢出是物理极限。
|
||||
assert.equal(clampPanelLeftX({ hostLeft: 150, panelWidth: 380, viewportWidth: 400, margin: 8 }), -138)
|
||||
assert.equal(clampPanelLeftX({ hostLeft: 150, panelWidth: 390, viewportWidth: 400, margin: 8 }), -142)
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
JD_CATEGORY_TREE,
|
||||
jdCategoryChildren,
|
||||
jdCategoryLeaves,
|
||||
jdCategoryRoots,
|
||||
jdCategorySearchLeaves,
|
||||
} from '../src/pages/jd/jd-category-tree.ts'
|
||||
|
||||
/** 京麦授权类目真树(2026-11-16 真机取证 getVenderLicenseCategory 快照;与用户端
|
||||
* frontend-vue 侧同数据两份正本,改树两边同轮同步)。判据钉的是取证读数:
|
||||
* 3 个一级 / 250 个末级 / 最深 4 级 / 4 组同名跨支——改树先对取证数据(京麦面板
|
||||
* 或 getVenderLicenseCategory 重抓),不得手改数字凑测试。 */
|
||||
test('树形状=京麦授权类目真机读数:3 个一级、250 个末级、最深 4 级', () => {
|
||||
const roots = jdCategoryRoots()
|
||||
assert.deepEqual(
|
||||
roots.map((node) => node.name),
|
||||
['服饰内衣', '母婴', '运动户外'],
|
||||
'一级就 3 个(京麦面板 2026-11-16 真机:该店铺授权经营类目,不得加回京东公开全量)',
|
||||
)
|
||||
assert.deepEqual(
|
||||
roots.map((node) => node.value),
|
||||
['1315', '1319', '1318'],
|
||||
'一级类目 id 与取证响应逐字同',
|
||||
)
|
||||
const leaves = jdCategoryLeaves()
|
||||
assert.equal(leaves.length, 250, '末级节点 250 个(取证读数)')
|
||||
const maxDepth = Math.max(...leaves.map((leaf) => leaf.path.length))
|
||||
assert.equal(maxDepth, 4, '树最深 4 级')
|
||||
})
|
||||
|
||||
test('服饰内衣二级与京麦面板逐字同源;逐级下钻到真机样本叶', () => {
|
||||
assert.deepEqual(
|
||||
jdCategoryChildren(['服饰内衣']).map((node) => node.name),
|
||||
['服饰配件', '内衣', '女装', '男装', '定制服装/工装'],
|
||||
'服饰内衣二级 5 个(京麦面板逐字)',
|
||||
)
|
||||
assert.deepEqual(
|
||||
jdCategoryChildren(['服饰内衣', '服饰配件']).map((node) => node.name),
|
||||
['腰带/腰链', '耳罩/耳包', '领带/领结/领带夹', '男士丝巾/围巾', '女士丝巾/围巾/披肩', '鸭舌帽',
|
||||
'礼帽', '手套', '围巾/手套/帽子套装', '毛线帽', '遮阳帽', '棒球帽', '渔夫帽'],
|
||||
'服饰配件三级 13 个(京麦面板 2026-11-16 截图逐字前 6 +取证快照全量)',
|
||||
)
|
||||
assert.deepEqual(
|
||||
jdCategoryChildren(['服饰内衣', '服饰配件', '腰带/腰链']),
|
||||
[],
|
||||
'三级叶子 children 空(末级,可选中)',
|
||||
)
|
||||
assert.deepEqual(
|
||||
jdCategoryChildren(['不存在的一级']),
|
||||
[],
|
||||
'未知路径回落空子级(面板该栏缺省)',
|
||||
)
|
||||
})
|
||||
|
||||
test('落库末级名真机样本都在树内(category_path 等值过滤成立的前提)', () => {
|
||||
const names = new Set(jdCategoryLeaves().map((leaf) => leaf.name))
|
||||
for (const sample of ['艺考形体服', '啦啦队服', '拉丁舞服']) {
|
||||
assert.ok(names.has(sample), `真机样本「${sample}」必须是树内末级(契约 E3 口径)`)
|
||||
}
|
||||
const yikao = jdCategoryLeaves().find((leaf) => leaf.name === '艺考形体服')
|
||||
assert.ok(yikao, '艺考形体服在树内')
|
||||
assert.equal(yikao!.path.length, 3, '艺考形体服是 level 3 节点(取证读数)')
|
||||
})
|
||||
|
||||
test('同名跨支叶子如实登记:4 组重名(同名行等值过滤一起命中,B112-05 口径)', () => {
|
||||
const counts = new Map<string, number>()
|
||||
for (const leaf of jdCategoryLeaves()) {
|
||||
counts.set(leaf.name, (counts.get(leaf.name) ?? 0) + 1)
|
||||
}
|
||||
const dups = [...counts.entries()].filter(([, count]) => count > 1)
|
||||
assert.deepEqual(
|
||||
dups.map(([name]) => name).sort(),
|
||||
['唐装', '吊带/背心', '短裤', '赠品'].sort(),
|
||||
'重名集与取证读数逐字同(改树后这里红=重名集变了,须复核登记)。注:「汉服」两处节点中'
|
||||
+ '一处带四级子级是非叶(点它会下钻),不构成末级重名。',
|
||||
)
|
||||
})
|
||||
|
||||
test('搜索:按名称或路径段命中末级;空词返回全量', () => {
|
||||
assert.equal(jdCategorySearchLeaves('').length, 250, '空词=全量末级')
|
||||
const byName = jdCategorySearchLeaves('艺考')
|
||||
assert.equal(byName.length, 1)
|
||||
assert.equal(byName[0]!.name, '艺考形体服')
|
||||
const byPath = jdCategorySearchLeaves('服饰配件')
|
||||
assert.ok(byPath.length >= 13, '按路径段命中服饰配件全部末级')
|
||||
assert.ok(byPath.every((leaf) => leaf.path.includes('服饰配件')))
|
||||
assert.deepEqual(jdCategorySearchLeaves('不存在词xyz'), [])
|
||||
})
|
||||
|
||||
test('树数据快照不可空、value 全非空(取证 id 留档完整)', () => {
|
||||
assert.ok(JD_CATEGORY_TREE.length > 0)
|
||||
for (const leaf of jdCategoryLeaves()) {
|
||||
assert.ok(leaf.value, `叶子 ${leaf.name} 必须带京麦类目 id`)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,119 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { adminPages } from '../src/router/routes.ts'
|
||||
import {
|
||||
jdPriceRange,
|
||||
jdSkuDimensions,
|
||||
jdSkuSummary,
|
||||
parseJdProductDetail,
|
||||
toJdProductItem,
|
||||
} from '../src/pages/jd/jd-product-model.ts'
|
||||
|
||||
/** v1.4「京东数据库」后管页契约(蓝图 docs/ITERATION_PLAN.md §3.4 / §4 Phase 5)。
|
||||
*
|
||||
* 只用 import 断言 routes 注册表——readSource 台账(source-pin-ratchet)钉住
|
||||
* tests/ 里 readFileSync/globSync 读取点逐文件只许减,新读源码文件会撞棘轮;
|
||||
* V196 迁移 / company-scope / operation-guides 的接线由既有护栏在 Phase 5 收口时
|
||||
* 自动覆盖(company-menu-route 把 V196 加进迁移清单、align-operation-guide、
|
||||
* company-tab-wiring),本文件不重复 fs 断言。
|
||||
* Pending 期整组 skip;Phase 5 落地后去掉 skip 跑绿。
|
||||
*/
|
||||
|
||||
const MENU_KEY = 'admin_jd_database'
|
||||
const ROUTE = 'jd-center/database'
|
||||
|
||||
test('routes 注册表出现京东数据库页面且退出公司 tab(2026-11-16 参考品牌数据库定案)', () => {
|
||||
const page = adminPages.find((item) => item.menuKey === MENU_KEY)
|
||||
assert.ok(page, `routes.ts 缺 menuKey=${MENU_KEY} 的注册行`)
|
||||
assert.equal(page.path, ROUTE, 'route_path 必须与 V196 菜单一侧一致')
|
||||
assert.equal(page.title, '京东数据库', '菜单标题以「京东数据库」为准')
|
||||
// 数据全平台公共(2026-11-15「不区分公司」→ 2026-11-16「删除掉公司 tab,参考品牌数据库」):
|
||||
// meta.companyScoped 必须 false——true 会画出公司 tab,而取数口已不带 company_id(点了没反应)。
|
||||
assert.equal(page.companyScoped, false, '京东数据库全平台公共,不画公司 tab(AC-6 已被 11-15/11-16 口径推翻)')
|
||||
})
|
||||
|
||||
/** 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 容错;坏行不炸整块。 */
|
||||
test('详情负载的 skus 归一化成矩阵行:skuId 为身份、销售属性维度按首次出现排序', () => {
|
||||
const detail = parseJdProductDetail({
|
||||
id: 1,
|
||||
productCode: '10036442942137',
|
||||
skus: [
|
||||
{ skuId: '10238877506570', skuName: '上衣 S', skuSeq: '1', price: 162.0, stock: 200, sortNo: 0,
|
||||
saleAttrs: [{ name: '颜色', value: '上衣' }, { name: '尺码', value: 'S' }] },
|
||||
{ skuId: '10238877506580', sku_name: '半裙 S', sku_seq: '3', price: '168.00', stock: 80, sort_no: 2,
|
||||
sale_attrs: [{ name: '颜色', value: '半裙' }, { name: '尺码', value: 'S' }] },
|
||||
],
|
||||
})
|
||||
|
||||
assert.equal(detail.skus.length, 2)
|
||||
assert.equal(detail.skus[0].skuId, '10238877506570')
|
||||
assert.equal(detail.skus[0].price, '162', 'BigDecimal 序列化成 number 也要能读')
|
||||
assert.equal(detail.skus[1].price, '168', '字符串价去尾零')
|
||||
assert.equal(detail.skus[1].sortNo, 2, 'snake 容错')
|
||||
assert.deepEqual(jdSkuDimensions(detail.skus), ['颜色', '尺码'], '维度名按首次出现顺序')
|
||||
assert.equal(jdSkuSummary(detail.skus), '2 个 SKU · ¥162 ~ ¥168 · 库存 280')
|
||||
})
|
||||
|
||||
test('缺 skuId 的行弃掉、空 skus 回空数组(旧数据不渲染空表)', () => {
|
||||
const detail = parseJdProductDetail({
|
||||
id: 2,
|
||||
skus: [{ skuName: '没有 skuId' }, { skuId: 'A1', price: 1, stock: 0 }],
|
||||
})
|
||||
assert.equal(detail.skus.length, 1)
|
||||
assert.equal(jdSkuSummary(detail.skus), '1 个 SKU · ¥1 · 库存 0')
|
||||
assert.equal(parseJdProductDetail({ id: 3 }).skus.length, 0)
|
||||
assert.equal(jdSkuSummary([]), '')
|
||||
})
|
||||
|
||||
/** 列表行价格(2026-11-16 修「采集到了却全显示 -」):后端 BigDecimal 序列化成 JSON number,
|
||||
* 解析层必须数值/字符串都收——text() 只认字符串=价格在解析层被丢成空串的生产实录
|
||||
* (生产库 273/273 行 price_min 全有值、界面价格列全「-」,用户报「价格没采集到」的真因)。 */
|
||||
test('列表行价格:BigDecimal 的 JSON number 形状与字符串形状都归一成展示文本', () => {
|
||||
const numeric = toJdProductItem({ id: 9, productCode: '10036368647085', priceMin: 107.64, priceMax: 109.26 })
|
||||
assert.ok(numeric, '只缺价格之外的字段不弃行')
|
||||
assert.equal(numeric.priceMin, '107.64', 'number 形状不许丢成空串')
|
||||
assert.equal(jdPriceRange(numeric), '107.64 ~ 109.26', 'number 形状价格列不许显示 -')
|
||||
|
||||
const single = toJdProductItem({ id: 10, priceMin: 64.8, priceMax: 64.8 })
|
||||
assert.ok(single)
|
||||
assert.equal(jdPriceRange(single), '64.8', '单值价(min==max)不拼区间')
|
||||
|
||||
const stringShape = toJdProductItem({ id: 11, priceMin: '12.90', priceMax: '' })
|
||||
assert.ok(stringShape)
|
||||
assert.equal(stringShape.priceMin, '12.9', '字符串形状仍收(去尾零,与详情 SKU 价同口径)')
|
||||
assert.equal(jdPriceRange(stringShape), '12.9')
|
||||
|
||||
const missing = toJdProductItem({ id: 12 })
|
||||
assert.ok(missing)
|
||||
assert.equal(jdPriceRange(missing), '', '两侧都空回空串(列表显示 -)')
|
||||
})
|
||||
|
||||
/** 类目筛选(2026-11-15):京麦末级类目等值过滤,空串不下发、非空透传 category。 */
|
||||
test('类目筛选参数序列化:空串不下发、非空下发 category(等值过滤)', async () => {
|
||||
const { createJdProductFilterState, toJdProductListParams, jdProductFilterActive } =
|
||||
await import('../src/pages/jd/jd-product-filter.ts')
|
||||
const empty = createJdProductFilterState()
|
||||
assert.equal('category' in toJdProductListParams(empty, 1, 20), false, '全部类目不下发 category')
|
||||
assert.equal(jdProductFilterActive(empty), false)
|
||||
|
||||
const filtered = { ...empty, category: ' 服饰内衣 ' }
|
||||
assert.equal(toJdProductListParams(filtered, 1, 20).category, '服饰内衣', '去空白透传(等值过滤)')
|
||||
assert.equal(jdProductFilterActive(filtered), true, '选中类目算激活筛选')
|
||||
})
|
||||
|
||||
test('自定义分类使用 group_id,不发送分类状态参数', async () => {
|
||||
const { createJdProductFilterState, toJdProductListParams } = await import('../src/pages/jd/jd-product-filter.ts')
|
||||
const query = toJdProductListParams({ ...createJdProductFilterState(), groupId: '7' }, 1, 20)
|
||||
assert.equal(query.group_id, 7)
|
||||
assert.equal('grouped' in query, false)
|
||||
assert.equal('ungrouped' in query, false)
|
||||
})
|
||||
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* 京东数据库页纯逻辑契约(v1.4 Phase 5)—— node --test 直跑(纯函数零依赖)。
|
||||
*
|
||||
* 不用 readFileSync/readSource/globSync 读点:source-pin-ratchet 对台账外新文件带读点即红,
|
||||
* 本文件只 import 被测纯函数。
|
||||
*
|
||||
* 覆盖:
|
||||
* 1. **snake 参数形状**:toJdProductListParams 产出 `page`/`page_size`(默认 20、上限 100)、
|
||||
* `product_code`/`title_keyword`/`group_id`/`owner_group_id`/`synced_from`/`synced_to`
|
||||
* (ISO yyyy-MM-dd;空白不下发;groupId 空串→不带、有值→snake group_id;ownerGroupId>0 才带、
|
||||
* 0/null/NaN 一律不带=后端按作用域默认分组取,V203);分页钳制(铁律 15)。
|
||||
* 商品状态筛选与导出参数口已随 2026-11-15 客户口径下线,不再出现在参数面;
|
||||
* 店铺筛选同日客户口径「店铺不需要」下线(shop_name 也不在参数面)。
|
||||
* 2. **详情解析**:parseJdProductDetail 解析 attrGroups/images(camel 为正 snake 容错、缺 url 弃行),
|
||||
* attrGroups 解析不出时 attrJsonRaw 原文兜底;列表行解析缺 id 弃行。
|
||||
*
|
||||
* 跑法:`node --test tests/jd-product-group.test.ts`
|
||||
*/
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import {
|
||||
JD_PRODUCT_MAX_PAGE,
|
||||
createJdProductFilterState,
|
||||
toJdProductListParams,
|
||||
} from '../src/pages/jd/jd-product-filter.ts'
|
||||
import {
|
||||
jdCategoryChildren,
|
||||
jdCategoryRoots,
|
||||
} from '../src/pages/jd/jd-category-tree.ts'
|
||||
import {
|
||||
jdPriceRange,
|
||||
parseJdProductDetail,
|
||||
parseJdProductPage,
|
||||
toJdProductItem,
|
||||
} from '../src/pages/jd/jd-product-model.ts'
|
||||
|
||||
test('类目级联静态导航树——服饰内衣二级与京麦面板样本逐字同源,一级集非空且无重名', () => {
|
||||
// 京麦面板真机样本(2026-11-16 客户截图):服饰内衣下就是这五个二级,改名即红。
|
||||
assert.deepEqual(jdCategoryChildren(['服饰内衣']).map(node => node.name), ['服饰配件', '内衣', '女装', '男装', '定制服装/工装'])
|
||||
assert.deepEqual(jdCategoryChildren(['不存在的类目']), [], '未知一级回落空子级(面板不出第二栏)')
|
||||
|
||||
const roots = jdCategoryRoots().map(node => node.name)
|
||||
assert.deepEqual(roots, ['服饰内衣', '母婴', '运动户外'], '一级导航与京麦授权类目一致')
|
||||
assert.equal(new Set(roots).size, roots.length, '一级类目名不得重复')
|
||||
for (const root of roots) {
|
||||
const children = jdCategoryChildren([root]).map(node => node.name)
|
||||
assert.equal(new Set(children).size, children.length, `${root} 的二级不得重复`)
|
||||
}
|
||||
})
|
||||
|
||||
test('京东列表参数——snake 形状:groupId 空→不带、有值→group_id,日期空白/非法不下发', () => {
|
||||
const full = toJdProductListParams(
|
||||
{
|
||||
productCode: ' JD-10086 ',
|
||||
titleKeyword: ' 保温杯 ',
|
||||
groupId: ' 7 ',
|
||||
syncedFrom: '2026-11-01',
|
||||
syncedTo: '2026-11-09',
|
||||
},
|
||||
2,
|
||||
20,
|
||||
// V203 第 4 参=当前数据权限分组(分类列/分类筛选的作用域,不是筛选条件)。
|
||||
11,
|
||||
)
|
||||
assert.deepEqual(full, {
|
||||
page: 2,
|
||||
page_size: 20,
|
||||
product_code: 'JD-10086',
|
||||
title_keyword: '保温杯',
|
||||
group_id: 7,
|
||||
owner_group_id: 11,
|
||||
synced_from: '2026-11-01',
|
||||
synced_to: '2026-11-09',
|
||||
})
|
||||
assert.equal('shop_name' in full, false, '店铺筛选已下线,参数面不再出现 shop_name')
|
||||
|
||||
// 全空态只有分页两项;脏值(非数字分组、非法日期)同罪不下发。
|
||||
const blank = toJdProductListParams(createJdProductFilterState(), 1, 20)
|
||||
assert.deepEqual(blank, { page: 1, page_size: 20 })
|
||||
assert.equal('group_id' in blank, false, 'groupId 空串不带 group_id')
|
||||
assert.equal('owner_group_id' in blank, false, '没传当前分组就不带 owner_group_id(后端按作用域默认组取)')
|
||||
const dirty = toJdProductListParams(
|
||||
{ productCode: '', titleKeyword: '', groupId: 'abc', syncedFrom: '2026/11/01', syncedTo: 'not-a-date' },
|
||||
1,
|
||||
20,
|
||||
)
|
||||
assert.deepEqual(dirty, { page: 1, page_size: 20 }, '脏值不下发')
|
||||
assert.equal('sale_status' in full, false, '商品状态筛选已下线,参数面不再出现 sale_status')
|
||||
// 当前分组非法值(0/NaN/null)一律不下发:0 是「不属于任何组」的哨兵,不能当组 id 发出去。
|
||||
for (const bad of [0, null, undefined, Number.NaN]) {
|
||||
assert.equal('owner_group_id' in toJdProductListParams(createJdProductFilterState(), 1, 20, bad), false,
|
||||
`ownerGroupId=${String(bad)} 不得下发 owner_group_id`)
|
||||
}
|
||||
})
|
||||
|
||||
test('京东列表参数——page 钳制防 (page-1)*page_size 溢出(铁律 15)', () => {
|
||||
const low = toJdProductListParams(createJdProductFilterState(), 0, 0)
|
||||
assert.equal(low.page, 1, 'page<1 归 1')
|
||||
assert.equal(low.page_size, 20, 'page_size 非法回默认 20')
|
||||
const big = toJdProductListParams(createJdProductFilterState(), 3, 500)
|
||||
assert.equal(big.page_size, 100, 'page_size 上限 100')
|
||||
|
||||
const extreme = toJdProductListParams(createJdProductFilterState(), Number.MAX_SAFE_INTEGER, 100)
|
||||
assert.equal(extreme.page, JD_PRODUCT_MAX_PAGE)
|
||||
const offset = (extreme.page - 1) * extreme.page_size
|
||||
assert.equal(Number.isSafeInteger(offset), true, `(page-1)*page_size=${offset} 必须留在安全整数域`)
|
||||
assert.equal(offset, 999_900)
|
||||
})
|
||||
|
||||
test('详情解析——attrGroups/images 结构化解析(snake 容错、缺 url 弃行)', () => {
|
||||
const detail = parseJdProductDetail({
|
||||
code: 0,
|
||||
message: 'ok',
|
||||
data: {
|
||||
id: 42,
|
||||
title: '304不锈钢保温杯',
|
||||
sale_status: '上架中',
|
||||
attrGroups: [
|
||||
{
|
||||
groupName: '规格',
|
||||
attrs: [
|
||||
{ key: 'capacity', label: '容量', value: '500ml' },
|
||||
{ key: 'material', label: '', value: '304不锈钢' },
|
||||
],
|
||||
},
|
||||
{ group_name: '其他', attrs: [{ key: 'color', label: '颜色', value: '白色' }] },
|
||||
],
|
||||
images: [
|
||||
{ imageType: 'MAIN', attrName: '', sortNo: 1, url: 'https://img.example/main.jpg', width: 800, height: 800 },
|
||||
{ image_type: 'ATTR', attrName: '白色', sortNo: 2, url: 'https://img.example/white.jpg' },
|
||||
{ imageType: 'ATTR', attrName: '', sortNo: 3, url: 'https://img.example/attr2.jpg' },
|
||||
{ imageType: 'DETAIL', sortNo: 4, url: '' }, // 缺 url 弃行
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
assert.equal(detail.item.id, 42)
|
||||
assert.equal(detail.item.title, '304不锈钢保温杯')
|
||||
assert.equal(detail.item.saleStatus, '上架中', 'snake 容错')
|
||||
assert.equal(detail.attrGroups.length, 2, '两个属性块')
|
||||
assert.equal(detail.attrGroups[0].groupName, '规格')
|
||||
assert.equal(detail.attrGroups[0].attrs[0].label, '容量')
|
||||
assert.equal(detail.attrGroups[1].groupName, '其他', 'group_name snake 容错')
|
||||
assert.equal(detail.images.length, 3, '缺 url 的 DETAIL 图弃行')
|
||||
assert.equal(detail.images[1].imageType, 'ATTR', 'image_type snake 容错')
|
||||
assert.equal(detail.images[1].attrName, '白色')
|
||||
assert.equal(detail.images[1].sortNo, 2)
|
||||
assert.equal(detail.images[2].attrName, '', 'attrName 缺省空串')
|
||||
assert.equal(detail.attrJsonRaw, '', '结构化解析成功时不需要原文兜底')
|
||||
})
|
||||
|
||||
test('详情解析——attrGroups 缺失时 attrJsonRaw 原文兜底;信封外裸负载同口径', () => {
|
||||
const raw = '{"规格":{"容量":"500ml"}}'
|
||||
const detail = parseJdProductDetail({ id: 7, attrJsonRaw: raw })
|
||||
assert.equal(detail.item.id, 7)
|
||||
assert.deepEqual(detail.attrGroups, [], 'attrGroups 解析不出为空')
|
||||
assert.equal(detail.attrJsonRaw, raw, '原文兜底字段原样透传(界面展示,不静默吞)')
|
||||
assert.deepEqual(detail.images, [])
|
||||
|
||||
// 非法负载不抛:整包垃圾回空详情(id 0),attrJsonRaw 留空。
|
||||
const junk = parseJdProductDetail('not-an-object')
|
||||
assert.equal(junk.item.id, 0)
|
||||
assert.equal(junk.attrJsonRaw, '')
|
||||
})
|
||||
|
||||
test('列表行解析——camel 为正 snake 容错、缺 id 弃行、价格区间拼装', () => {
|
||||
const page = parseJdProductPage({
|
||||
success: true,
|
||||
data: {
|
||||
items: [
|
||||
{
|
||||
id: 1,
|
||||
shopId: 3,
|
||||
shopName: '旗舰自营店',
|
||||
productCode: 'JD-10086',
|
||||
priceMin: '12.90',
|
||||
priceMax: '15.90',
|
||||
stockTotal: 500,
|
||||
saleStatus: '上架中',
|
||||
groupId: 7,
|
||||
groupName: '甲组',
|
||||
syncedAt: '2026-11-12 09:00:00',
|
||||
},
|
||||
{ id: 'not-a-number', title: '缺 id 弃行' },
|
||||
{ shop_name: 'snake 行也缺 id,弃' },
|
||||
],
|
||||
total: 1,
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
},
|
||||
})
|
||||
assert.equal(page.items.length, 1, '三条原始行里两条缺有效 id,只留 1 行')
|
||||
const row = page.items[0]
|
||||
assert.equal(row.shopName, '旗舰自营店')
|
||||
assert.equal(row.groupId, 7)
|
||||
assert.equal(row.groupName, '甲组')
|
||||
// 2026-11-16 价格改走 decimalText(数值/字符串都收)后同口径去尾零,与详情 SKU 价一致。
|
||||
assert.equal(jdPriceRange(row), '12.9 ~ 15.9', 'min/max 都有给区间(去尾零)')
|
||||
assert.equal(jdPriceRange({ priceMin: '12.90', priceMax: '' }), '12.9', '只空一侧给单值')
|
||||
assert.equal(jdPriceRange({ priceMin: '', priceMax: '' }), '', '全空为空串(界面展示 -)')
|
||||
|
||||
// snake 行同口径 + 缺省回默认。
|
||||
const snakePage = parseJdProductPage({ data: { items: [{ id: 9, shop_name: 'B店', main_image_url: 'https://img/x.jpg' }], total: 1, page: 2, page_size: 5 } })
|
||||
const snakeRow = toJdProductItem({ id: 9, shop_name: 'B店', main_image_url: 'https://img/x.jpg' })
|
||||
assert.equal(snakeRow?.mainImageUrl, 'https://img/x.jpg')
|
||||
assert.equal(snakePage.pageSize, 5)
|
||||
})
|
||||
@@ -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)
|
||||
})
|
||||
@@ -1,11 +1,13 @@
|
||||
/**
|
||||
* 外观专利无侵权数据页(v1.3 AC-5)的挂载契约 —— Phase 3 激活。
|
||||
* 外观专利数据库页(v1.3 AC-5,2026-11-11 晚间恢复明细表)的挂载契约。
|
||||
*
|
||||
* 用户拍板(2026-11-10):展示形式参照「去重数据库」页(DedupeRegistryPage 形态:自绘
|
||||
* `<table>` 行列表 + `OldPagination.vue` 分页,**不做卡片宫格**);`companyScoped: true`
|
||||
* 公司 Tab;任务号/ASIN/国家/起止时间筛选;`page`/`page_size` snake 参数,响应
|
||||
* `{items, total, page, pageSize}`。默认仅 super_admin 可见(菜单不预授权,判据在后端
|
||||
* AdminAppearancePatentCleanItemsControllerTest 的菜单迁移支,这里只管前端接线)。
|
||||
* 形态(客户当日口径「不是这种格式 你就按照昨天那个格式」):撤掉一主管一卡视图,
|
||||
* 恢复只读明细表(自绘 table + OldPagination,参照「去重数据库」页);表头第二列=「管理员」
|
||||
* (后端读侧现算 supervisorName,读不到展示 -);「添加个管理员 跟导出数据就可以」——
|
||||
* 筛选行有「导出」(当前过滤面+公司 tab 全量出 xlsx,与去重页同款);「任务号/ASIN 两个
|
||||
* 筛选框恢复」(客户要「一目了然」选数据);分组(主管)下拉保留选中即查。
|
||||
* 卡片级下载/删除入口随卡片视图一并下架(删除入口先撤,防误删;后端 /supervisors 接口保留)。
|
||||
* 数据按 ASIN 累计(同 ASIN 只保留一条,V192 唯一键),页面零写操作。
|
||||
*
|
||||
* 跑法:`npx vitest run tests/mount/appearance-patent-clean-page.test.ts`
|
||||
*/
|
||||
@@ -32,29 +34,29 @@ const cleanApi = vi.hoisted(() => ({
|
||||
|
||||
vi.mock('@/pages/patent/appearance-patent-clean-api.ts', () => cleanApi)
|
||||
|
||||
function row(id: number, over: Record<string, unknown> = {}) {
|
||||
function item(id: number, over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id,
|
||||
resultId: 900 + id,
|
||||
taskId: 33179,
|
||||
userId: 7,
|
||||
supervisorName: `主管${id}`,
|
||||
resultId: 36800 + id,
|
||||
taskId: 33874,
|
||||
userId: 9,
|
||||
supervisorName: '主管9',
|
||||
companyId: 1,
|
||||
rowNo: id,
|
||||
asin: `B0AB8CDEF${id}`,
|
||||
asin: `B0CLEAN00${id}`,
|
||||
country: 'DE',
|
||||
sku: `SKU-${id}`,
|
||||
brand: 'Anker',
|
||||
price: '29.99',
|
||||
title: `无侵权商品 ${id}`,
|
||||
sku: `SKU-00${id}`,
|
||||
brand: 'Nike',
|
||||
price: '12.99',
|
||||
title: 'Women Floral Dress Summer Casual',
|
||||
imageUrl: '',
|
||||
itemUrl: '',
|
||||
conclusion: '无侵权',
|
||||
titleReason: '',
|
||||
appearanceReason: '',
|
||||
patentReason: '',
|
||||
sourceFilename: 'list.xlsx',
|
||||
syncedAt: '2026-11-10T10:30:00',
|
||||
sourceFilename: 'appearance_patent_33874.xlsx',
|
||||
syncedAt: '2026-11-11T11:34:29',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
@@ -67,7 +69,6 @@ beforeEach(() => {
|
||||
setActivePinia(pinia)
|
||||
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
|
||||
useCompanyTabStore().setActiveId(1)
|
||||
// 分组(主管)选项默认空集:分组用例各自覆写
|
||||
cleanApi.fetchDedupeTotalGroups.mockResolvedValue([])
|
||||
})
|
||||
|
||||
@@ -79,13 +80,22 @@ async function mountWith(payload: unknown): Promise<VueWrapper<Element>> {
|
||||
return wrapper
|
||||
}
|
||||
|
||||
describe('AC-5 外观专利无侵权数据页(分页列表,参照去重数据库页)', () => {
|
||||
it('页面组件落位且是自绘 table + OldPagination 的分页列表', () => {
|
||||
// vitest 的 cwd = admin-frontend-vue 根(Phase 0 预置用 new URL 模板串,被 vite 静态分析成
|
||||
// undefined——skip 期间从未执行所以没暴露,激活时改走 cwd 解析)。
|
||||
describe('外观专利数据库页(明细表,2026-11-11 恢复「昨天那个格式」)', () => {
|
||||
it('页面组件落位:明细表 + 明细端点 + 导出,卡片视图与删除入口已下架', () => {
|
||||
const src = readFileSync(resolve(process.cwd(), PAGE_PATH), 'utf-8')
|
||||
expect(src).toContain('OldPagination')
|
||||
expect(src).toContain('<table')
|
||||
expect(src).toContain('<table', '恢复自绘明细表(客户「按照昨天那个格式」)')
|
||||
expect(src).toContain('管理员', '表头必须有「管理员」列(客户「添加个管理员」)')
|
||||
expect(src).toContain('fetchAppearancePatentCleanList', '必须走明细分页端点')
|
||||
expect(src).toContain('exportAll', '筛选行要有「导出」(客户「跟数据去重一样 能导出来就可以」)')
|
||||
expect(src).toContain('cleanItemReasonTooltip', '结论列带三因原因提示')
|
||||
expect(src).toContain('filter.taskId', '任务号筛选框恢复')
|
||||
expect(src).toContain('filter.asin', 'ASIN 筛选框恢复')
|
||||
// 卡片视图与删除入口下架:这些符号只该在后端/历史里,不该再出现在本页
|
||||
expect(src).not.toContain('clean-card-grid', '一主管一卡视图已撤')
|
||||
expect(src).not.toContain('fetchAppearancePatentCleanSupervisors', '主管聚合取数口已撤')
|
||||
expect(src).not.toContain('deleteAppearancePatentCleanSupervisor', '按主管删除的页面入口已撤')
|
||||
expect(src).not.toContain('openAdminConfirm', '本页零写操作,不该再有任何确认弹窗')
|
||||
expect(src).not.toContain('el-card')
|
||||
})
|
||||
|
||||
@@ -100,95 +110,178 @@ describe('AC-5 外观专利无侵权数据页(分页列表,参照去重数
|
||||
expect(scoped?.pageFiles).toContain(PAGE_PATH)
|
||||
})
|
||||
|
||||
it('挂载后按首屏 snake 分页参数取数并解包 {items,total,page,pageSize}', async () => {
|
||||
const wrapper = await mountWith({ items: [row(1), row(2)], total: 42, page: 1, pageSize: 10 })
|
||||
it('挂载后按首屏分页参数取明细列表,行数=本页明细条数', async () => {
|
||||
const wrapper = await mountWith({
|
||||
items: [item(1), item(2), item(3)],
|
||||
total: 42,
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
})
|
||||
|
||||
expect(cleanApi.fetchAppearancePatentCleanList).toHaveBeenCalledTimes(1)
|
||||
const firstCall = cleanApi.fetchAppearancePatentCleanList.mock.calls[0][0]
|
||||
expect(firstCall.page).toBe(1)
|
||||
expect(firstCall.pageSize).toBe(10)
|
||||
expect(firstCall.companyId).toBe(1)
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(2)
|
||||
expect(wrapper.text()).toContain('共 42 条')
|
||||
expect(wrapper.text()).toContain('B0AB8CDEF1')
|
||||
expect(wrapper.text()).toContain('无侵权')
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(3)
|
||||
expect(wrapper.find('.clean-summary').text()).toContain('共 42 条', '汇总按明细条数(不是主管数)')
|
||||
})
|
||||
|
||||
it('主管列(2026-11-11 客户需求):表头就位,行值展示 supervisorName,读不到展示 -', async () => {
|
||||
const wrapper = await mountWith({
|
||||
items: [row(1, { supervisorName: '主管甲' }), row(2, { supervisorName: '' })],
|
||||
total: 2,
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
})
|
||||
it('行内容=任务号/管理员/ASIN/国家/SKU/品牌/价格/标题/结论/同步时间', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 10 })
|
||||
const cells = wrapper.findAll('tbody tr')[0].findAll('td')
|
||||
expect(cells).toHaveLength(10)
|
||||
expect(cells[0].text()).toBe('33874', '任务号')
|
||||
expect(cells[1].text()).toBe('主管9', '管理员(supervisorName 读侧现算列)')
|
||||
expect(cells[2].text()).toBe('B0CLEAN001')
|
||||
expect(cells[3].text()).toBe('德国', '国家码翻中文')
|
||||
expect(cells[4].text()).toBe('SKU-001')
|
||||
expect(cells[5].text()).toBe('Nike')
|
||||
expect(cells[6].text()).toBe('12.99')
|
||||
expect(cells[7].text()).toContain('Women Floral Dress')
|
||||
expect(cells[8].text()).toBe('无侵权')
|
||||
expect(cells[9].text()).not.toBe('-', '同步时间格式化展示')
|
||||
const headers = wrapper.findAll('thead th').map((th) => th.text())
|
||||
expect(headers).toContain('所属主管')
|
||||
expect(headers.indexOf('所属主管')).toBe(headers.indexOf('任务号') + 1, '主管列紧跟任务号之后')
|
||||
const firstRowCells = wrapper.findAll('tbody tr')[0].findAll('td')
|
||||
expect(firstRowCells[headers.indexOf('所属主管')].text()).toBe('主管甲')
|
||||
const secondRowCells = wrapper.findAll('tbody tr')[1].findAll('td')
|
||||
expect(secondRowCells[headers.indexOf('所属主管')].text()).toBe('-', '读不到主管不猜名字,展示 -')
|
||||
expect(headers).toContain('管理员')
|
||||
expect(headers).not.toContain('所属主管', '列名按客户口径叫「管理员」')
|
||||
})
|
||||
|
||||
it('导出按钮带当前过滤面与公司 tab 调导出接口,成功触发 blob 落盘', async () => {
|
||||
/** 客户 2026-11-12 反馈「外观专利数据库的日期显示不全」:全局 `* { box-sizing: border-box }` 把左右 24px
|
||||
* 内边距算进列宽,旧的 150px 只剩 126px 内容宽,而 `YYYY-MM-DD HH:mm:ss` 十九字符在 13.5px 下实测约
|
||||
* 133px ⇒ 末尾被 ellipsis 吃掉(表格单元格是 nowrap + text-overflow: ellipsis)。判据钉列宽下限:
|
||||
* ≥160px 才有 ≥136px 内容宽放得下完整时间;回退到 150px 即红。 */
|
||||
it('同步时间列宽够放十九字符时间(列宽下限 160px,防 ellipsis 再截断)', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 10 })
|
||||
const headers = wrapper.findAll('thead th')
|
||||
const dateHeader = headers[headers.length - 1]
|
||||
expect(dateHeader.text()).toBe('同步时间')
|
||||
const declared = Number.parseFloat(dateHeader.element.style.width)
|
||||
expect(Number.isFinite(declared), '同步时间列必须显式声明宽度(table-layout: fixed 下靠它定列宽)').toBe(true)
|
||||
expect(declared).toBeGreaterThanOrEqual(160, '150px − 24px 内边距 = 126px < 133px,时间会被截断')
|
||||
})
|
||||
|
||||
it('读不到主管的那一行管理员列展示 -(不猜名字)', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1, { supervisorName: '' })], total: 1, page: 1, pageSize: 10 })
|
||||
expect(wrapper.findAll('tbody tr')[0].findAll('td')[1].text()).toBe('-')
|
||||
})
|
||||
|
||||
it('导出=当前过滤面全量(含任务号/ASIN 与公司 tab),不传按主管参数', async () => {
|
||||
const createObjectURL = vi.fn(() => 'blob:mock-url')
|
||||
const revokeObjectURL = vi.fn()
|
||||
const urlRecord = URL as unknown as Record<string, unknown>
|
||||
const origCreate = urlRecord.createObjectURL
|
||||
const origRevoke = urlRecord.revokeObjectURL
|
||||
Object.defineProperty(URL, 'createObjectURL', { value: createObjectURL, configurable: true, writable: true })
|
||||
Object.defineProperty(URL, 'revokeObjectURL', { value: revokeObjectURL, configurable: true, writable: true })
|
||||
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||||
cleanApi.exportAppearancePatentCleanList.mockImplementation(() =>
|
||||
Promise.resolve({ blob: new Blob(['xlsx'], { type: 'application/vnd.ms-excel' }), filename: '外观专利数据库-20261111103000.xlsx' }),
|
||||
Promise.resolve({ blob: new Blob(['xlsx']), filename: '外观专利数据库-20261111235900.xlsx' }),
|
||||
)
|
||||
|
||||
try {
|
||||
const wrapper = await mountWith({ items: [row(1)], total: 1, page: 1, pageSize: 10 })
|
||||
const textInputs = wrapper.findAll('input[type="text"]')
|
||||
await textInputs[0].setValue('33179')
|
||||
const exportBtn = wrapper.findAll('button').find((b) => b.text() === '导出')
|
||||
expect(exportBtn).toBeTruthy()
|
||||
await exportBtn!.trigger('click')
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 10 })
|
||||
const btn = wrapper.findAll('button').find((b) => b.text() === '导出')
|
||||
expect(btn, '筛选行必须有「导出」按钮').toBeTruthy()
|
||||
await btn!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(cleanApi.exportAppearancePatentCleanList).toHaveBeenCalledTimes(1)
|
||||
const call = cleanApi.exportAppearancePatentCleanList.mock.calls[0][0]
|
||||
expect(call).toMatchObject({
|
||||
taskId: '33179',
|
||||
asin: '',
|
||||
country: '',
|
||||
groupId: '',
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
companyId: 1,
|
||||
})
|
||||
expect(call).toMatchObject({ taskId: '', asin: '', country: '', groupId: '', companyId: 1 })
|
||||
expect(call.supervisorUserId).toBeUndefined()
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(1)
|
||||
expect(revokeObjectURL).toHaveBeenCalledWith('blob:mock-url')
|
||||
expect(clickSpy).toHaveBeenCalled()
|
||||
expect(document.body.textContent).toContain('已导出', '成功反馈点名落盘文件')
|
||||
} finally {
|
||||
Object.defineProperty(URL, 'createObjectURL', { value: origCreate, configurable: true })
|
||||
Object.defineProperty(URL, 'revokeObjectURL', { value: origRevoke, configurable: true })
|
||||
Object.defineProperty(URL, 'createObjectURL', { value: undefined, configurable: true, writable: true })
|
||||
Object.defineProperty(URL, 'revokeObjectURL', { value: undefined, configurable: true, writable: true })
|
||||
clickSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('导出失败把服务端业务文案弹出来,不许静默', async () => {
|
||||
it('导出失败把服务端业务文案弹出来,不许静默;在途标记复位', async () => {
|
||||
cleanApi.exportAppearancePatentCleanList.mockImplementation(() =>
|
||||
Promise.reject(new Error('无侵权数据共 90001 行,超过导出上限 50000 行,请缩小筛选范围后重试')))
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 10 })
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 10 })
|
||||
await wrapper.findAll('button').find((b) => b.text() === '导出')!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(document.body.textContent).toContain('超过导出上限', '失败反馈必须是服务端那句可读文案')
|
||||
// 失败后导出锁复位,按钮可再次点击
|
||||
expect(wrapper.findAll('button').find((b) => b.text() === '导出')!.text()).toBe('导出')
|
||||
expect(document.body.textContent).toContain('超过导出上限')
|
||||
const btn = wrapper.findAll('button').find((b) => b.text() === '导出')
|
||||
expect(btn!.text()).toBe('导出', '失败后在途标记必须复位')
|
||||
expect((btn!.element as HTMLButtonElement).disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('任务号/ASIN/国家/分组/起止时间筛选生效', async () => {
|
||||
cleanApi.fetchDedupeTotalGroups.mockResolvedValue([{ id: 7, name: '甲组', leaderUserId: 9 }])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 10 })
|
||||
|
||||
const textInputs = wrapper.findAll('.form-group input[type="text"]')
|
||||
expect(textInputs).toHaveLength(2, '任务号+ASIN 两个筛选框恢复(客户要一目了然)')
|
||||
await textInputs[0].setValue('33874')
|
||||
await textInputs[1].setValue('B0CLEAN')
|
||||
|
||||
const selects = wrapper.findAll('select')
|
||||
await selects[0].setValue('DE') // 国家排在前(模板顺序:任务号/ASIN/国家/分组)
|
||||
await selects[1].setValue('7') // 分组(主管=组长)
|
||||
const dateInputs = wrapper.findAll('input[type="date"]')
|
||||
await dateInputs[0].setValue('2026-11-01')
|
||||
await dateInputs[1].setValue('2026-11-09')
|
||||
await wrapper.findAll('button').find((b) => b.text() === '查询')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const last = cleanApi.fetchAppearancePatentCleanList.mock.calls.at(-1)![0]
|
||||
expect(last).toMatchObject({
|
||||
taskId: '33874',
|
||||
asin: 'B0CLEAN',
|
||||
country: 'DE',
|
||||
groupId: '7',
|
||||
startDate: '2026-11-01',
|
||||
endDate: '2026-11-09',
|
||||
page: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('分组下拉(主管=组长)选中即查', async () => {
|
||||
cleanApi.fetchDedupeTotalGroups.mockResolvedValue([
|
||||
{ id: 7, name: '甲组', leaderUserId: 9 },
|
||||
{ id: 8, name: '乙组', leaderUserId: 10 },
|
||||
])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 10 })
|
||||
expect(cleanApi.fetchDedupeTotalGroups).toHaveBeenCalledWith(1)
|
||||
|
||||
const groupSelect = wrapper.findAll('select')[1] // 模板顺序:国家在前、分组在后
|
||||
const optionTexts = groupSelect.findAll('option').map((o) => o.text())
|
||||
expect(optionTexts).toContain('全部分组')
|
||||
expect(optionTexts).toContain('甲组')
|
||||
|
||||
const callsBeforeSelect = cleanApi.fetchAppearancePatentCleanList.mock.calls.length
|
||||
await groupSelect.setValue('7')
|
||||
await flushPromises()
|
||||
expect(cleanApi.fetchAppearancePatentCleanList.mock.calls.length).toBe(callsBeforeSelect + 1,
|
||||
'选中分组必须立刻重查')
|
||||
expect(cleanApi.fetchAppearancePatentCleanList.mock.calls.at(-1)![0]).toMatchObject({
|
||||
groupId: '7',
|
||||
page: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('重置把筛选面回空并回第一页重取', async () => {
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 10 })
|
||||
const textInputs = wrapper.findAll('.form-group input[type="text"]')
|
||||
await textInputs[0].setValue('33874')
|
||||
await textInputs[1].setValue('B0CLEAN')
|
||||
const callsBefore = cleanApi.fetchAppearancePatentCleanList.mock.calls.length
|
||||
|
||||
await wrapper.findAll('button').find((b) => b.text() === '重置')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(cleanApi.fetchAppearancePatentCleanList.mock.calls.length).toBeGreaterThan(callsBefore)
|
||||
const last = cleanApi.fetchAppearancePatentCleanList.mock.calls.at(-1)![0]
|
||||
expect(last).toMatchObject({ taskId: '', asin: '', page: 1 }, '重置后筛选全空、回第一页')
|
||||
})
|
||||
|
||||
it('翻页与改每页条数都重发请求,改条数回第一页', async () => {
|
||||
const wrapper = await mountWith({ items: [row(11)], total: 42, page: 2, pageSize: 10 })
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 42, page: 2, pageSize: 10 })
|
||||
|
||||
await wrapper.findAll('button').find((b) => b.text() === '下一页')!.trigger('click')
|
||||
await flushPromises()
|
||||
@@ -203,60 +296,11 @@ describe('AC-5 外观专利无侵权数据页(分页列表,参照去重数
|
||||
expect(last.page).toBe(1, '改每页条数后回第一页')
|
||||
})
|
||||
|
||||
it('任务号/ASIN/国家/起止时间筛选生效', async () => {
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 10 })
|
||||
|
||||
const textInputs = wrapper.findAll('input[type="text"]')
|
||||
await textInputs[0].setValue('33179')
|
||||
await textInputs[1].setValue('B0AB8CDEF1')
|
||||
await wrapper.find('select').setValue('DE')
|
||||
const dateInputs = wrapper.findAll('input[type="date"]')
|
||||
await dateInputs[0].setValue('2026-11-01')
|
||||
await dateInputs[1].setValue('2026-11-09')
|
||||
await wrapper.findAll('button').find((b) => b.text() === '查询')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const last = cleanApi.fetchAppearancePatentCleanList.mock.calls.at(-1)![0]
|
||||
expect(last).toMatchObject({
|
||||
taskId: '33179',
|
||||
asin: 'B0AB8CDEF1',
|
||||
country: 'DE',
|
||||
groupId: '',
|
||||
startDate: '2026-11-01',
|
||||
endDate: '2026-11-09',
|
||||
page: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('分组下拉(主管=组长):选项与去重页同源,选中后 groupId 进列表请求', async () => {
|
||||
cleanApi.fetchDedupeTotalGroups.mockResolvedValue([
|
||||
{ id: 7, name: '甲组', leaderUserId: 9 },
|
||||
{ id: 8, name: '乙组', leaderUserId: 10 },
|
||||
])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 10 })
|
||||
|
||||
// 选项取数走的是公司隔离的同一分组集(GET /shop-manages/groups 的适配层)
|
||||
expect(cleanApi.fetchDedupeTotalGroups).toHaveBeenCalledWith(1)
|
||||
|
||||
const groupSelect = wrapper.findAll('select')[1]
|
||||
const optionTexts = groupSelect.findAll('option').map((o) => o.text())
|
||||
expect(optionTexts).toContain('全部分组')
|
||||
expect(optionTexts).toContain('甲组')
|
||||
expect(optionTexts).toContain('乙组')
|
||||
|
||||
await groupSelect.setValue('7')
|
||||
await wrapper.findAll('button').find((b) => b.text() === '查询')!.trigger('click')
|
||||
await flushPromises()
|
||||
const last = cleanApi.fetchAppearancePatentCleanList.mock.calls.at(-1)![0]
|
||||
expect(last.groupId).toBe('7', '选中的分组 id 以 groupId 进列表过滤面(服务端解析组长+名下整集)')
|
||||
})
|
||||
|
||||
it('空态与加载失败条(失败给重试,不把整页打死)', async () => {
|
||||
const empty = await mountWith({ items: [], total: 0, page: 1, pageSize: 10 })
|
||||
const thCount = empty.findAll('thead th').length
|
||||
const emptyRow = empty.find('tbody tr')
|
||||
expect(emptyRow.text()).toContain('暂无无侵权数据')
|
||||
expect(Number(emptyRow.find('td').attributes('colspan'))).toBe(thCount, '空态 colspan 跟着列数走')
|
||||
const tip = empty.find('.empty-tip')
|
||||
expect(tip.exists()).toBe(true)
|
||||
expect(tip.text()).toContain('暂无无侵权数据')
|
||||
empty.unmount()
|
||||
|
||||
cleanApi.fetchAppearancePatentCleanList.mockRejectedValue(new Error('上游 502'))
|
||||
@@ -269,25 +313,25 @@ describe('AC-5 外观专利无侵权数据页(分页列表,参照去重数
|
||||
|
||||
it('切公司 Tab 重取并清掉上一家的筛选(company-tab-wiring 同口径)', async () => {
|
||||
cleanApi.fetchDedupeTotalGroups.mockResolvedValue([{ id: 7, name: '甲组', leaderUserId: 9 }])
|
||||
const wrapper = await mountWith({ items: [row(1)], total: 1, page: 1, pageSize: 10 })
|
||||
const textInputs = wrapper.findAll('input[type="text"]')
|
||||
await textInputs[0].setValue('33179')
|
||||
// 选上上一家公司的分组:切走后必须连同 groupId 一起清(分组的成员集是公司隔离的)
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 10 })
|
||||
const textInputs = wrapper.findAll('.form-group input[type="text"]')
|
||||
await textInputs[0].setValue('33874')
|
||||
await textInputs[1].setValue('B0CLEAN')
|
||||
const groupSelect = wrapper.findAll('select')[1]
|
||||
await groupSelect.setValue('7')
|
||||
const callsAfterMount = cleanApi.fetchAppearancePatentCleanList.mock.calls.length
|
||||
const callsBefore = cleanApi.fetchAppearancePatentCleanList.mock.calls.length
|
||||
|
||||
useCompanyTabStore().setActiveId(2)
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(cleanApi.fetchAppearancePatentCleanList.mock.calls.length).toBeGreaterThan(callsAfterMount)
|
||||
expect(cleanApi.fetchAppearancePatentCleanList.mock.calls.length).toBeGreaterThan(callsBefore)
|
||||
const last = cleanApi.fetchAppearancePatentCleanList.mock.calls.at(-1)![0]
|
||||
expect(last.companyId).toBe(2)
|
||||
expect(last.taskId).toBe('', '切公司必须清掉上一家填的任务号')
|
||||
expect(last.taskId).toBe('', '切公司必须清掉上一家的任务号')
|
||||
expect(last.asin).toBe('', '切公司必须清掉上一家的 ASIN')
|
||||
expect(last.groupId).toBe('', '切公司必须清掉上一家选的分组')
|
||||
expect(last.page).toBe(1)
|
||||
// 分组选项按新公司重取(选项集公司隔离)
|
||||
expect(cleanApi.fetchDedupeTotalGroups).toHaveBeenLastCalledWith(2)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,902 @@
|
||||
/**
|
||||
* 京东数据库页(v1.4 Phase 5)的挂载契约。
|
||||
*
|
||||
* 形态:panel-box + 筛选行(商品编码/标题关键字/类目/分组/同步起止 date 对)+
|
||||
* 查询/重置 + 自绘明细表(点行开详情抽屉)+ OldPagination;
|
||||
* 分组下拉 2026-11-16 用户口径「做成分组」上移进筛选行=带标签的表单控件(不再是工具栏裸下拉);
|
||||
* 店铺分类弹窗 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 客户口径从前端下线(后端端点保留);
|
||||
* 店铺筛选与店铺列同日客户口径「店铺不需要」下线(后端 shop_name 参数同窗撤,店铺仍收详情抽屉)。
|
||||
* 不用 readFileSync(source-pin-ratchet 对台账外新文件带读点即红),全部走真实挂载断言。
|
||||
*
|
||||
* 跑法:`npx vitest run tests/mount/jd-database-page.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 JdDatabasePage from '@/pages/jd/JdDatabasePage.vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
|
||||
const jdApi = vi.hoisted(() => ({
|
||||
JD_PRODUCT_ENDPOINT: '/api/admin/jd-products',
|
||||
JD_PRODUCT_GROUP_ENDPOINT: '/api/admin/jd-product-groups',
|
||||
fetchJdProductList: vi.fn(),
|
||||
fetchJdProductDetail: vi.fn(),
|
||||
deleteJdProducts: vi.fn(),
|
||||
fetchJdProductGroups: vi.fn(),
|
||||
fetchJdCategoryScope: vi.fn(),
|
||||
fetchJdProductCategories: vi.fn(),
|
||||
createJdProductGroup: vi.fn(),
|
||||
updateJdProductGroup: vi.fn(),
|
||||
deleteJdProductGroup: vi.fn(),
|
||||
updateJdProduct: vi.fn(),
|
||||
batchAssignJdProductGroup: vi.fn(),
|
||||
}))
|
||||
|
||||
const confirmMock = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi)
|
||||
vi.mock('@/components/admin-confirm', () => ({ openAdminConfirm: confirmMock }))
|
||||
|
||||
function item(id: number, over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id,
|
||||
shopId: 3,
|
||||
shopName: '旗舰自营店',
|
||||
productCode: `JD-100${id}`,
|
||||
skuId: `SKU-${id}`,
|
||||
itemNum: `ITEM-${id}`,
|
||||
skuCount: 12,
|
||||
healthScore: 81,
|
||||
title: '304不锈钢保温杯大容量便携',
|
||||
brand: '锅宝',
|
||||
categoryPath: '家居 > 厨具 > 保温杯',
|
||||
// 价格用 number 形状(2026-11-16 实录:后端 BigDecimal 序列化成 JSON number,
|
||||
// 字符串夹具曾把「解析层丢数字形状」这个真红藏住=生产库有价、界面全「-」)。
|
||||
priceMin: 12.9,
|
||||
priceMax: 15.9,
|
||||
stockTotal: 500,
|
||||
saleStatus: '上架中',
|
||||
listTab: 'search',
|
||||
jdCreatedAt: '2026-11-07 18:49:47',
|
||||
jdOnlineAt: '2026-11-12 15:03:37',
|
||||
jdUpdatedAt: '2026-11-13 14:06:07',
|
||||
mainImageUrl: `https://img.example/main-${id}.jpg`,
|
||||
attrCount: 6,
|
||||
imageCount: 9,
|
||||
groupId: 7,
|
||||
groupName: '甲组',
|
||||
syncedAt: '2026-11-12 09:00:00',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
let pinia: Pinia
|
||||
|
||||
/** 分组 id 常量:默认作用域就这一个可见且可写的组(组长档形状),分类与行集都按它取。 */
|
||||
const GROUP_A = 11
|
||||
|
||||
/** 分类作用域夹具(GET /scope 的归一形状):单组默认场景。 */
|
||||
function singleGroupScope(editable = true) {
|
||||
return {
|
||||
platformSuperAdmin: false,
|
||||
defaultGroupId: GROUP_A,
|
||||
groups: [{ id: GROUP_A, name: '甲组', label: '甲组', editable }],
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
|
||||
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope())
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([])
|
||||
jdApi.fetchJdProductCategories.mockResolvedValue([])
|
||||
confirmMock.mockResolvedValue(true)
|
||||
})
|
||||
|
||||
async function mountWith(payload: unknown): Promise<VueWrapper<Element>> {
|
||||
jdApi.fetchJdProductList.mockImplementation(() => Promise.resolve(payload))
|
||||
const wrapper = mount(JdDatabasePage, { global: { plugins: [pinia] } })
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
/** 批量编辑分类(2026-11-17 用户口径「店铺分类弹窗删了,加个批量编辑分类」):
|
||||
* 勾选跨页累计记忆(翻页/重取不清)→ 对话框选目标分类归入或移出 → 按 (ids, groupId,
|
||||
* ownerGroupId) 提交;成功后清勾选并重取。旧弹窗的「勾选翻页即清」口径同日废止。 */
|
||||
describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代入口)', () => {
|
||||
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 }))
|
||||
const wrapper = mount(JdDatabasePage, { global: { plugins: [pinia] } })
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
const deleteBtn = () => wrapper.get('.jd-delete-btn')
|
||||
|
||||
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
|
||||
expect(deleteBtn().text()).toContain('删除勾选(1)')
|
||||
|
||||
// 翻页:勾选不清(2026-11-17 口径「支持勾选翻页也要记住」)。
|
||||
await wrapper.findAll('button').find((b) => b.text() === '下一页')!.trigger('click')
|
||||
await flushPromises()
|
||||
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(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 })
|
||||
await deleteBtn().trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(confirmMock.mock.calls.at(-1)![0].message).toContain('确定删除勾选的 2 个商品吗', '确认文案点名累计总数')
|
||||
// 跨页累计的 id 一起提交。
|
||||
expect(jdApi.deleteJdProducts).toHaveBeenLastCalledWith([1, 2])
|
||||
expect(deleteBtn().text()).toContain('删除勾选(0)', '批量删除成功后自动清勾选')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('批量归入:未勾选时入口置灰,勾选后打开对话框选目标分类,按 (ids, groupId, ownerGroupId) 提交并清勾选重取', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([
|
||||
{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 },
|
||||
{ id: 8, name: '乙组', sortOrder: 1, productCount: 1 },
|
||||
])
|
||||
jdApi.batchAssignJdProductGroup.mockResolvedValue(2)
|
||||
const wrapper = await mountWith({ items: [item(1), item(2)], total: 2, page: 1, pageSize: 20 })
|
||||
const editBtn = () => wrapper.findAll('button').find((b) => b.text() === '批量编辑分类')!
|
||||
|
||||
expect(editBtn().attributes('disabled')).toBeDefined('勾选 0 时置灰(与删除勾选同款常显口径)')
|
||||
const boxes = wrapper.findAll('tbody input[type="checkbox"]')
|
||||
await boxes[0].setValue(true)
|
||||
await boxes[1].setValue(true)
|
||||
expect(editBtn().attributes('disabled')).toBeUndefined()
|
||||
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
|
||||
await editBtn().trigger('click')
|
||||
await flushPromises()
|
||||
const modal = wrapper.get('.batch-modal')
|
||||
expect(modal.text()).toContain('批量编辑分类')
|
||||
expect(modal.text()).toContain('已勾选 2 个商品(翻页累计)', '对话框点名累计勾选数')
|
||||
expect(modal.text()).toContain('甲组', '标题/上下文带当前分组名')
|
||||
expect(modal.findAll('.option-row')).toHaveLength(3, '两个分类+一个移出选项')
|
||||
|
||||
await modal.findAll('.option-row')[0].trigger('click')
|
||||
const confirmBtn = modal.findAll('button').find((b) => b.text() === '归入「甲组」')
|
||||
expect(confirmBtn, '确认按钮文案带目标分类名').toBeTruthy()
|
||||
await confirmBtn!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1, 2], 7, GROUP_A)
|
||||
expect(document.body.textContent).toContain('已把 2 个商品归入「甲组」')
|
||||
expect(wrapper.find('.batch-modal').exists()).toBe(false, '成功后对话框自动关闭')
|
||||
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore, '成功后重取列表(groupName 变了)')
|
||||
expect(wrapper.get('.jd-delete-btn').text()).toContain('删除勾选(0)', '成功后清勾选')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('移出分类:选「移出分类」确认 → groupId 传 null(后端只解挂本组归属行)', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
|
||||
jdApi.batchAssignJdProductGroup.mockResolvedValue(1)
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
|
||||
await wrapper.findAll('button').find((b) => b.text() === '批量编辑分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
const modal = wrapper.get('.batch-modal')
|
||||
await modal.find('.option-detach').trigger('click')
|
||||
await modal.findAll('button').find((b) => b.text() === '移出分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], null, GROUP_A)
|
||||
expect(document.body.textContent).toContain('已把 1 个商品移出分类')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
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)
|
||||
await wrapper.findAll('button').find((b) => b.text() === '批量编辑分类')!.trigger('click')
|
||||
await flushPromises()
|
||||
const modal = wrapper.get('.batch-modal')
|
||||
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()
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('店铺分类弹窗已下线(反向钉):入口按钮与 .group-modal 都不再存在,分类筛选照常', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 1 }])
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.findAll('button').some((b) => b.text() === '店铺分类')).toBe(false, '「店铺分类」入口已删')
|
||||
expect(wrapper.find('.group-modal').exists()).toBe(false)
|
||||
expect(wrapper.get('[aria-label="筛选店铺分类"]').exists()).toBe(true, '分类筛选下拉是读面,保留')
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
|
||||
/** 分类管理入口(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 })
|
||||
expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(1)
|
||||
const firstCall = jdApi.fetchJdProductList.mock.calls[0][0]
|
||||
expect(firstCall.page).toBe(1)
|
||||
expect(firstCall.pageSize).toBe(20)
|
||||
// 公司维度 2026-11-16 整页摘除:入参层不再有 companyId 键(单参 toHaveProperty 才是「键不存在」的真判据)。
|
||||
expect(firstCall).not.toHaveProperty('companyId')
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(3)
|
||||
expect(wrapper.find('.jd-summary').text()).toContain('共 42 条京东商品')
|
||||
})
|
||||
|
||||
it('行列字段与顺序(2026-11-15 用户口径;状态列+创建/修改两列 2026-11-16 客户口径「不需要采集/不要」下线仍收详情抽屉;操作置末「操作放最后一列」):勾选/分组/商品信息(图+标题+编码+货号+品牌·类目+SKU/信息分)/总库存/价格/同步/操作(7 列;店铺列 2026-11-15 下线)', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
const cells = wrapper.findAll('tbody tr')[0].findAll('td')
|
||||
expect(cells).toHaveLength(7)
|
||||
expect(cells[0].find('input[type="checkbox"]').exists()).toBe(true, '第 1 列是勾选框')
|
||||
expect(cells[1].text()).toBe('甲组', '第 2 列=分组(admin 专属)')
|
||||
// 商品信息列=京麦同款合并布局:主图+信息分+标题+商品编码+货号+品牌·类目行+SKU 标签。
|
||||
const info = cells[2]
|
||||
expect(info.find('.jd-thumb').exists()).toBe(true, '商品信息列含主图')
|
||||
expect(info.text()).toContain('304不锈钢保温杯')
|
||||
expect(info.text()).toContain('JD-1001', '商品编码并入商品信息列')
|
||||
expect(info.text()).toContain('ITEM-1', '货号并入商品信息列')
|
||||
expect(info.text()).toContain('锅宝', '品牌并入商品信息列(京麦品牌·类目行)')
|
||||
expect(info.text()).toContain('家居 > 厨具 > 保温杯', '类目随品牌·类目行上列表(京麦同款)')
|
||||
expect(info.text()).toContain('12个SKU')
|
||||
expect(info.text()).toContain('信息分 81')
|
||||
expect(cells[3].text()).toBe('500', '第 3 数据列=总库存(京麦第 2 列)')
|
||||
expect(cells[4].text()).toBe('12.9 ~ 15.9', '第 4 数据列=价格(京麦第 3 列;number 形状价格不许显示 -)')
|
||||
expect(cells[5].text()).not.toBe('-', '第 5 数据列=同步时间(创建/修改两列 2026-11-16 下线,时间列只剩同步)')
|
||||
expect(cells[6].text()).toContain('编辑', '第 6 数据列=操作(编辑/删除;2026-11-16「操作放最后一列」置末)')
|
||||
expect(cells[6].text()).toContain('删除', '操作列含删除按钮')
|
||||
// 表头字段名与顺序与京麦一致;品牌/类目不再是独立列(收进商品信息);店铺/状态/创建/修改列已下线。
|
||||
const headerText = wrapper.find('thead').text()
|
||||
for (const gone of ['品牌', '类目', '店铺', '上架时间 / 商品状态', '创建时间', '修改时间']) {
|
||||
expect(headerText).not.toContain(gone, `${gone}不再是独立列(品牌/类目收进商品信息;店铺 2026-11-15 下线;状态列+创建/修改 2026-11-16 下线)`)
|
||||
}
|
||||
for (const head of ['商品信息', '总库存', '价格', '同步时间', '操作']) {
|
||||
expect(headerText).toContain(head, `表头必须有「${head}」(京麦字段名)`)
|
||||
}
|
||||
expect(wrapper.find('.jd-thumb').exists()).toBe(true, '商品信息列渲染缩略图')
|
||||
})
|
||||
|
||||
it('操作列删除按钮防冒泡且走确认弹窗:确认后调 deleteJdProducts,取消不动(2026-11-15 行级删除)', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
// beforeEach 默认 confirm=true;本例先翻回 false 验「取消不动」。
|
||||
confirmMock.mockResolvedValue(false)
|
||||
const opsCell = wrapper.findAll('tbody tr')[0].findAll('td')[6]
|
||||
await opsCell.findAll('button').find((b) => b.text() === '删除')!.trigger('click')
|
||||
await flushPromises()
|
||||
// 防冒泡:点删除不得顺手打开详情抽屉(抽屉的可视判据=.drawer 出现)。
|
||||
expect(wrapper.find('.drawer').exists()).toBe(false, '删除按钮 @click.stop,点它不开详情抽屉')
|
||||
expect(confirmMock).toHaveBeenCalledTimes(1, '删除必须过二次确认')
|
||||
expect(jdApi.deleteJdProducts).toHaveBeenCalledTimes(0, '确认弹窗取消时不发删除请求')
|
||||
// 确认后:deleteJdProducts 按 id 直删(公共库写侧无公司维度,2026-11-15 公共化)。
|
||||
confirmMock.mockResolvedValue(true)
|
||||
jdApi.deleteJdProducts.mockResolvedValueOnce({ deleted: 1, imagesDeleted: 0, objectsDeleted: 0, objectsKept: 0, objectsSkipped: 0 })
|
||||
await wrapper.findAll('tbody tr')[0].findAll('td')[6].findAll('button').find((b) => b.text() === '删除')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.deleteJdProducts).toHaveBeenCalledWith([1])
|
||||
})
|
||||
|
||||
it('操作列编辑按钮防冒泡且打开编辑抽屉(抽屉自取详情回填,2026-11-15 行级编辑)', async () => {
|
||||
// fetchJdProductDetail 的返回已由 parseJdProductDetail 归一成 {item, attrGroups, images, skus, attrJsonRaw}。
|
||||
jdApi.fetchJdProductDetail.mockResolvedValue({
|
||||
item: {
|
||||
id: 1,
|
||||
title: '304不锈钢保温杯大容量便携',
|
||||
brand: '锅宝',
|
||||
categoryPath: '家居 > 厨具 > 保温杯',
|
||||
itemNum: 'ITEM-1',
|
||||
priceMin: 12.9,
|
||||
priceMax: 15.9,
|
||||
stockTotal: 500,
|
||||
saleStatus: '上架中',
|
||||
groupId: 7,
|
||||
groupName: '甲组',
|
||||
productCode: 'JD-1001',
|
||||
shopName: '旗舰自营店',
|
||||
},
|
||||
attrGroups: [],
|
||||
images: [],
|
||||
skus: [],
|
||||
attrJsonRaw: '',
|
||||
})
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
const opsCell = wrapper.findAll('tbody tr')[0].findAll('td')[6]
|
||||
await opsCell.findAll('button').find((b) => b.text() === '编辑')!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(wrapper.find('.drawer').exists()).toBe(true, '编辑抽屉打开')
|
||||
expect(wrapper.text()).toContain('编辑商品', '抽屉标题点商品')
|
||||
// 抽屉按 id 自取详情回填(公共库详情无公司维度)。
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(1)
|
||||
// 编辑抽屉的保存提示文案点名人工编辑锁后果(用户保存前看得见「采集不再覆盖」)。
|
||||
expect(wrapper.text()).toContain('人工维护', '保存后果提示常驻(V199 人工编辑锁)')
|
||||
})
|
||||
|
||||
it('商品信息列:主图无 URL 显示「无图」占位、healthScore 为空不出信息分行、skuCount 为空不出 SKU 标签', async () => {
|
||||
const wrapper = await mountWith({
|
||||
items: [item(1), item(2, { mainImageUrl: '', healthScore: null, skuCount: null })],
|
||||
total: 2, page: 1, pageSize: 20,
|
||||
})
|
||||
const rowTexts = wrapper.findAll('tbody tr').map((tr) => tr.text())
|
||||
expect(wrapper.findAll('img.jd-thumb')).toHaveLength(1, '只有有自有桶 URL 的行出真图(无图占位是 span,不冒充 img)')
|
||||
expect(rowTexts[1]).toContain('无图')
|
||||
expect(rowTexts[1]).not.toContain('信息分')
|
||||
expect(rowTexts[1]).not.toContain('个SKU')
|
||||
})
|
||||
|
||||
it('商品编码旁复制按钮:写入剪贴板且不冒泡开抽屉', async () => {
|
||||
const writeText = vi.fn().mockResolvedValue(undefined)
|
||||
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.find('.drawer-mask').exists()).toBe(false, '复制前抽屉未开')
|
||||
await wrapper.findAll('.jd-copy-btn')[0].trigger('click')
|
||||
expect(writeText).toHaveBeenCalledWith('JD-1001')
|
||||
expect(wrapper.find('.drawer-mask').exists()).toBe(false, '点复制按钮不冒泡开抽屉')
|
||||
})
|
||||
|
||||
it('分类读不到的那行展示「未分类」(不猜名字;2026-11-15「分组管理」改「店铺分类」只换措辞)', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.findAll('tbody tr')[0].findAll('td')[1].text()).toBe('未分类')
|
||||
})
|
||||
|
||||
it('筛选生效:编码/关键字/分组/起止日期,查询回第一页重发(店铺筛选 2026-11-15 下线)', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
|
||||
const textInputs = wrapper.findAll('.form-group input[type="text"]')
|
||||
expect(textInputs).toHaveLength(2, '商品编码+标题关键字两个文本筛选框(店铺/商品状态已下线)')
|
||||
await textInputs[0].setValue('JD-1001')
|
||||
await textInputs[1].setValue('保温杯')
|
||||
await wrapper.get('[aria-label="筛选店铺分类"]').setValue('7')
|
||||
const dateInputs = wrapper.findAll('input[type="date"]')
|
||||
await dateInputs[0].setValue('2026-11-01')
|
||||
await dateInputs[1].setValue('2026-11-09')
|
||||
await wrapper.findAll('button').find((b) => b.text() === '查询')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
|
||||
expect(last).toMatchObject({
|
||||
productCode: 'JD-1001',
|
||||
titleKeyword: '保温杯',
|
||||
groupId: '7',
|
||||
syncedFrom: '2026-11-01',
|
||||
syncedTo: '2026-11-09',
|
||||
page: 1,
|
||||
})
|
||||
// 单参 toHaveProperty 才是「键不存在」的真判据(第二参会稀释成值断言):
|
||||
// 页面 load() 入参已不带这三个键(店铺/商品状态筛选下线、公司维度 2026-11-16 摘除)。
|
||||
expect(last).not.toHaveProperty('shopName')
|
||||
expect(last).not.toHaveProperty('saleStatus')
|
||||
expect(last).not.toHaveProperty('companyId')
|
||||
})
|
||||
|
||||
it('类目京麦同款级联面板(2026-11-16 真树重做):授权一级 3 个逐级下钻,点末级即查回第一页', async () => {
|
||||
jdApi.fetchJdProductCategories.mockResolvedValue([
|
||||
{ name: '艺考形体服', productCount: 120 },
|
||||
{ name: '啦啦队服', productCount: 8 },
|
||||
])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
expect(jdApi.fetchJdProductCategories).toHaveBeenCalledWith()
|
||||
|
||||
const trigger = wrapper.find('.cat-trigger')
|
||||
expect(trigger.text()).toContain('全部类目', '未选时触发框显示占位「全部类目」')
|
||||
expect(wrapper.find('.cat-panel').exists()).toBe(false, '面板初始不展开')
|
||||
|
||||
await trigger.trigger('click')
|
||||
expect(wrapper.find('.cat-panel').exists()).toBe(true)
|
||||
// 第一栏=京麦授权一级真树(2026-11-16 真机取证就 3 个:服饰内衣/母婴/运动户外)。
|
||||
const firstCol = wrapper.findAll('.cat-col')[0]
|
||||
expect(firstCol.text()).toContain('服饰内衣')
|
||||
expect(firstCol.text()).toContain('母婴')
|
||||
expect(firstCol.text()).toContain('运动户外')
|
||||
// 点一级展开第二栏(非末级行点击=下钻)。
|
||||
await firstCol.findAll('.cat-row').find((row) => row.text().includes('服饰内衣'))!.trigger('click')
|
||||
let cols = wrapper.findAll('.cat-col')
|
||||
expect(cols).toHaveLength(2, '点亮一级后第二栏出现(树内逐级下钻)')
|
||||
expect(cols[1].text()).toContain('服饰配件')
|
||||
expect(cols[1].text()).toContain('女装')
|
||||
// 点二级展开第三栏(京麦同款三级末级,取证快照:服饰配件 13 个)。
|
||||
await cols[1].findAll('.cat-row').find((row) => row.text().includes('服饰配件'))!.trigger('click')
|
||||
cols = wrapper.findAll('.cat-col')
|
||||
expect(cols).toHaveLength(3, '三级栏出现(末级行不再下钻)')
|
||||
expect(cols[2].text()).toContain('腰带/腰链')
|
||||
|
||||
// 点末级=选中即查(按 category_path 等值过滤口径不变)、面板收起、触发框显示已选名。
|
||||
await cols[2].findAll('.cat-row').find((row) => row.text().includes('腰带/腰链'))!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ category: '腰带/腰链', page: 1 })
|
||||
expect(wrapper.find('.cat-panel').exists()).toBe(false, '选中后面板收起')
|
||||
expect(wrapper.find('.cat-trigger').text()).toContain('腰带/腰链')
|
||||
})
|
||||
|
||||
it('类目级联搜索与清选(2026-11-16 真树重做):树内末级命中+树外兜底段;「全部类目」行/触发框 × 都能清选重查', async () => {
|
||||
jdApi.fetchJdProductCategories.mockResolvedValue([
|
||||
{ name: '艺考形体服', productCount: 120 },
|
||||
{ name: '已下架历史类目', productCount: 3 },
|
||||
])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
|
||||
await wrapper.find('.cat-trigger').trigger('click')
|
||||
// 搜索态:树内末级按名称/路径命中(艺考形体服在树内=女装支末级)。
|
||||
await wrapper.findAll('.cat-col')[0].find('.cat-search').setValue('艺考')
|
||||
const searchCol = wrapper.find('.cat-col-search')
|
||||
const visibleRows = searchCol.findAll('.cat-row')
|
||||
expect(visibleRows).toHaveLength(1, '搜索「艺考」只命中树内末级「艺考形体服」')
|
||||
expect(searchCol.text()).toContain('艺考形体服')
|
||||
expect(searchCol.text()).not.toContain('已下架历史类目', '不匹配项不出现')
|
||||
await visibleRows[0].trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ category: '艺考形体服', page: 1 })
|
||||
|
||||
// 树外兜底:已落库但京麦树里已没有的名字(历史行)从兜底段搜出可选。
|
||||
await wrapper.find('.cat-trigger').trigger('click')
|
||||
await wrapper.findAll('.cat-col')[0].find('.cat-search').setValue('已下架历史')
|
||||
const fallbackCol = wrapper.find('.cat-col-search')
|
||||
expect(fallbackCol.text()).toContain('已落库类目(树外历史)')
|
||||
expect(fallbackCol.text()).toContain('已下架历史类目')
|
||||
await fallbackCol.findAll('.cat-row').find((row) => row.text().includes('已下架历史类目'))!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ category: '已下架历史类目' })
|
||||
|
||||
// 点「全部类目」行=清选重查(category 入参回空串、query 层不下发,回第一页)。
|
||||
await wrapper.find('.cat-trigger').trigger('click')
|
||||
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
|
||||
await wrapper.find('.cat-row-all').trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.length).toBe(callsBefore + 1, '清选也要重查')
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0].category).toBe('')
|
||||
|
||||
// 触发框已选时出 × 清除按钮:点了同样清选。
|
||||
await wrapper.find('.cat-trigger').trigger('click')
|
||||
await wrapper.findAll('.cat-col')[0].find('.cat-search').setValue('艺考')
|
||||
await wrapper.find('.cat-col-search').findAll('.cat-row')[0].trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.find('.cat-trigger').text()).toContain('艺考形体服')
|
||||
const callsBeforeClear = jdApi.fetchJdProductList.mock.calls.length
|
||||
await wrapper.find('.cat-clear').trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.length).toBe(callsBeforeClear + 1, '× 清除同样触发重查')
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0].category).toBe('')
|
||||
})
|
||||
|
||||
it('不再显示独立分类与分类状态筛选;工具栏入口是「批量编辑分类」(弹窗 2026-11-17 下线)', async () => {
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
expect(wrapper.find('.jd-filter-row').text()).not.toContain('分类状态')
|
||||
expect(wrapper.find('.jd-filter-row select').exists()).toBe(false)
|
||||
expect(wrapper.findAll('button').some(button => button.text() === '批量编辑分类')).toBe(true)
|
||||
expect(wrapper.findAll('button').some(button => button.text() === '店铺分类')).toBe(false, '「店铺分类」入口已删')
|
||||
})
|
||||
|
||||
it('重置把筛选面回空并回第一页重取', async () => {
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 1 }])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
const select = wrapper.get('[aria-label="筛选店铺分类"]')
|
||||
expect(select.text()).toContain('全部分类')
|
||||
await select.setValue('7')
|
||||
await wrapper.get('.cat-trigger').trigger('click')
|
||||
await wrapper.get('.cat-search').setValue('艺考')
|
||||
await wrapper.get('.cat-col-search .cat-row').trigger('click')
|
||||
const textInputs = wrapper.findAll('.form-group input[type="text"]')
|
||||
await textInputs[0].setValue('JD-1001')
|
||||
await textInputs[1].setValue('保温杯')
|
||||
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
|
||||
|
||||
await wrapper.findAll('button').find((b) => b.text() === '重置')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore)
|
||||
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
|
||||
expect(last).toMatchObject({ productCode: '', titleKeyword: '', groupId: '', category: '', page: 1 }, '重置后筛选全空、回第一页')
|
||||
expect((select.element as HTMLSelectElement).value).toBe('')
|
||||
})
|
||||
|
||||
it('翻页与改每页条数都重发请求,改条数回第一页', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 42, page: 2, pageSize: 20 })
|
||||
|
||||
await wrapper.findAll('button').find((b) => b.text() === '下一页')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(2)
|
||||
expect(jdApi.fetchJdProductList.mock.calls[1][0].page).toBe(3)
|
||||
|
||||
const sizeSelect = wrapper.find('.page-size-select')
|
||||
await sizeSelect.setValue('50')
|
||||
await flushPromises()
|
||||
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
|
||||
expect(last.pageSize).toBe(50)
|
||||
expect(last.page).toBe(1, '改每页条数后回第一页')
|
||||
})
|
||||
|
||||
it('导出按钮已下线:筛选行不再出现「导出」(2026-11-15 客户口径「导出也不用」)', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
const btn = wrapper.findAll('button').find((b) => b.text() === '导出')
|
||||
expect(btn, '导出按钮必须已从前端移除').toBeUndefined()
|
||||
expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(1, '下线导出不影响列表首屏')
|
||||
})
|
||||
|
||||
it('点行打开详情抽屉:按 id 取详情(公共库无公司维度),attrGroups 分块渲染', async () => {
|
||||
jdApi.fetchJdProductDetail.mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
item: item(1),
|
||||
attrGroups: [{ groupName: '规格', attrs: [{ key: 'capacity', label: '容量', value: '500ml' }] }],
|
||||
images: [{ imageType: 'MAIN', attrName: '', sortNo: 1, url: 'https://img.example/main-1.jpg', byteSize: null, width: 800, height: 800 }],
|
||||
skus: [],
|
||||
attrJsonRaw: '',
|
||||
}),
|
||||
)
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.find('.drawer-mask').exists()).toBe(false, '初始不显示抽屉')
|
||||
|
||||
await wrapper.findAll('tbody tr')[0].trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('.drawer-mask').exists()).toBe(true)
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledTimes(1)
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(1)
|
||||
// 2026-11-16 客户口径「详情页的样式要和京麦商品详情一样」:顶部改「左图右信息」hero
|
||||
// 布局(左侧主图大图+缩略图,右侧关键信息),「基本信息」块标题随 hero 化下线。
|
||||
expect(wrapper.find('.detail-hero').exists()).toBe(true, '顶部左图右信息 hero 布局')
|
||||
expect(wrapper.find('.hero-main').exists()).toBe(true, '左侧主图大图')
|
||||
expect(wrapper.find('.hero-info').text()).toContain('价格区间')
|
||||
expect(wrapper.find('.hero-info').text()).toContain('12.9 ~ 15.9', '价格走 decimalText(number/字符串都收)')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('规格')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('容量')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('500ml')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('主图')
|
||||
const drawerText = wrapper.find('.drawer-mask').text()
|
||||
expect(drawerText).toContain('货号')
|
||||
expect(drawerText).toContain('ITEM-1')
|
||||
expect(drawerText).toContain('信息分')
|
||||
expect(drawerText).toContain('上架时间')
|
||||
// B104:详情里全量可见(店铺/分组 2026-11-15 起也上了列表,抽屉仍保留)。
|
||||
expect(drawerText).toContain('家居 > 厨具 > 保温杯')
|
||||
expect(drawerText).toContain('SKU 数')
|
||||
expect(drawerText).toContain('京东创建时间')
|
||||
expect(drawerText).toContain('京东修改时间')
|
||||
expect(drawerText).toContain('旗舰自营店')
|
||||
expect(drawerText).toContain('甲组')
|
||||
})
|
||||
|
||||
it('详情抽屉的销售属性=京麦那 12 行 SKU 矩阵:颜色/尺码两列维度 + 京东价 + 库存 + skuId', async () => {
|
||||
const skuRows = [
|
||||
{ skuId: '10238877506570', skuName: '花屿巷… 上衣 S', skuSeq: '1', price: 162, stock: 200, sortNo: 0,
|
||||
saleAttrs: [{ name: '颜色', value: '上衣' }, { name: '尺码', value: 'S' }] },
|
||||
{ skuId: '10238877506574', skuName: '花屿巷… 上衣 M', skuSeq: '2', price: 168, stock: 150, sortNo: 1,
|
||||
saleAttrs: [{ name: '颜色', value: '上衣' }, { name: '尺码', value: 'M' }] },
|
||||
{ skuId: '10238877506580', skuName: '花屿巷… 半裙 S', skuSeq: '3', price: 162, stock: 80, sortNo: 2,
|
||||
saleAttrs: [{ name: '颜色', value: '半裙' }, { name: '尺码', value: 'S' }] },
|
||||
]
|
||||
jdApi.fetchJdProductDetail.mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
item: item(1),
|
||||
attrGroups: [],
|
||||
images: [],
|
||||
skus: skuRows,
|
||||
attrJsonRaw: '',
|
||||
}),
|
||||
)
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
await wrapper.findAll('tbody tr')[0].trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('销售属性 / SKU 矩阵')
|
||||
const headers = wrapper.findAll('.sku-table thead th').map((th) => th.text())
|
||||
expect(headers).toEqual(['序号', '颜色', '尺码', '京东价', '库存', 'SKU ID', 'SKU 名称'],
|
||||
'维度列从各 SKU 的 saleAttrs 派生(京麦「颜色/尺码」两列)')
|
||||
|
||||
const rows = wrapper.findAll('.sku-table tbody tr')
|
||||
expect(rows).toHaveLength(3, '12 行矩阵按入库行数渲染')
|
||||
const first = rows[0].findAll('td').map((td) => td.text())
|
||||
expect(first).toEqual(['1', '上衣', 'S', '¥162', '200', '10238877506570', '花屿巷… 上衣 S'])
|
||||
expect(rows[1].findAll('td').map((td) => td.text())[3]).toBe('¥168', '每行自己的京东价')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('3 个 SKU')
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('库存 430', '汇总=各行库存之和')
|
||||
})
|
||||
|
||||
it('旧行没有 SKU 矩阵时给可解释的空态(不渲染空表、不静默吞)', async () => {
|
||||
jdApi.fetchJdProductDetail.mockImplementation(() =>
|
||||
Promise.resolve({ item: item(1), attrGroups: [], images: [], skus: [], attrJsonRaw: '' }),
|
||||
)
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
await wrapper.findAll('tbody tr')[0].trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('.sku-table').exists()).toBe(false)
|
||||
expect(wrapper.find('.drawer-mask').text()).toContain('暂无 SKU 矩阵')
|
||||
})
|
||||
|
||||
it('删除:勾选两行点删除 → 二次确认点名数量与桶清理 → 批量端点按 id 直删(公共库无公司维度),成功后刷新并清勾选', async () => {
|
||||
jdApi.deleteJdProducts.mockResolvedValue({ deleted: 2, imagesDeleted: 18, objectsDeleted: 16, objectsKept: 2, objectsSkipped: 0 })
|
||||
const wrapper = await mountWith({ items: [item(1), item(2)], total: 2, page: 1, pageSize: 20 })
|
||||
|
||||
// 批量删除常显(2026-11-16 客户口径「不要勾选后才显示」):未勾选时就在,只是置灰。
|
||||
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true, '工具栏「删除勾选」常显')
|
||||
expect(wrapper.find('.jd-delete-btn').attributes('disabled')).toBeDefined()
|
||||
const boxes = wrapper.findAll('tbody input[type="checkbox"]')
|
||||
await boxes[0].setValue(true)
|
||||
await boxes[1].setValue(true)
|
||||
expect(wrapper.find('.jd-delete-btn').attributes('disabled')).toBeUndefined('勾选后按钮可点')
|
||||
await wrapper.find('.jd-delete-btn').trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(confirmMock).toHaveBeenCalledTimes(1)
|
||||
const options = confirmMock.mock.calls[0][0]
|
||||
expect(options.title).toBe('删除京东商品')
|
||||
expect(options.message).toContain('确定删除勾选的 2 个商品吗')
|
||||
expect(options.message).toContain('jd-products 桶内图片文件一并删除', '确认弹窗必须点名「桶文件也会删」')
|
||||
expect(options.danger).toBe(true)
|
||||
|
||||
expect(jdApi.deleteJdProducts).toHaveBeenCalledTimes(1)
|
||||
expect(jdApi.deleteJdProducts).toHaveBeenCalledWith([1, 2])
|
||||
expect(document.body.textContent).toContain('已删除 2 个商品')
|
||||
expect(document.body.textContent).toContain('2 个共用图片保留', '共用对象计数要透出到反馈')
|
||||
// 成功后重取列表并清勾选:常显按钮回到置灰(不再消失)。
|
||||
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(1)
|
||||
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true)
|
||||
expect(wrapper.find('.jd-delete-btn').attributes('disabled')).toBeDefined()
|
||||
})
|
||||
|
||||
it('删除:确认弹窗点取消就不发请求(防误删的第一道闸)', async () => {
|
||||
confirmMock.mockResolvedValue(false)
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
|
||||
await wrapper.find('.jd-delete-btn').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(confirmMock).toHaveBeenCalledTimes(1)
|
||||
expect(jdApi.deleteJdProducts).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('删除失败把后端「本次未删除任何数据」文案弹出来(整批拒绝的语义必须到界面)', async () => {
|
||||
jdApi.deleteJdProducts.mockRejectedValue(new Error('桶内对象删除失败,本次未删除任何数据(jd-products/5/a.jpg):oss 5xx'))
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
|
||||
await wrapper.find('.jd-delete-btn').trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
|
||||
expect(document.body.textContent).toContain('本次未删除任何数据')
|
||||
// 失败后勾选保留,用户可重试。
|
||||
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('空态与加载失败条(失败给重试,不把整页打死)', async () => {
|
||||
const empty = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
const tip = empty.find('.empty-tip')
|
||||
expect(tip.exists()).toBe(true)
|
||||
expect(tip.text()).toContain('暂无京东商品数据')
|
||||
empty.unmount()
|
||||
|
||||
jdApi.fetchJdProductList.mockRejectedValue(new Error('上游 502'))
|
||||
const failed = mount(JdDatabasePage, { global: { plugins: [pinia] } })
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(failed.find('.load-failure-bar').exists()).toBe(true)
|
||||
expect(failed.find('.load-failure-bar').text()).toContain('京东商品列表加载失败')
|
||||
})
|
||||
})
|
||||
|
||||
/** 写权限分档(2026-11-16 用户口径收窄商品行写;2026-11-17 弹窗下线后更新):
|
||||
* 商品行写(编辑/删除/勾选批量删)只对平台超管渲染;分类写(批量编辑分类、分类管理)由
|
||||
* scope 的每组 editable 决定(本组管理员/公司超管/平台超管)——同组普通号在本页只读,
|
||||
* 分类维护入口=工具栏「分类管理」对话框(V204 独立页 2026-11-17 并入,只读可看)。
|
||||
* 勾选列 2026-11-17 起对本组可写分类管理员开放(服务批量归类),商品行按钮仍只归平台超管。 */
|
||||
describe('京东数据库写权限分档(商品行写=平台超管;分类写=本组 editable)', () => {
|
||||
it('非超管且本组不可写:无勾选列、无操作列、无删除勾选、无批量编辑分类;列表/筛选/详情照常', async () => {
|
||||
useAdminSessionStore().user = { id: 2, username: 'ops', role: 'admin' }
|
||||
// 同组普通号:可见但不可写(editable=false)。
|
||||
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope(false))
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 1 }])
|
||||
jdApi.fetchJdProductDetail.mockImplementation(() =>
|
||||
Promise.resolve({ item: item(1), attrGroups: [], images: [], skus: [], attrJsonRaw: '' }),
|
||||
)
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
|
||||
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.get('[aria-label="筛选店铺分类"]').exists()).toBe(true, '分类筛选是读面,保留')
|
||||
expect(wrapper.findAll('tbody tr')[0].findAll('td')).toHaveLength(5, '普通号列表 5 列:分类/商品信息/总库存/价格/同步时间')
|
||||
await wrapper.findAll('tbody tr')[0].trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(wrapper.find('.drawer-mask').exists()).toBe(true, '点行仍可开只读详情抽屉')
|
||||
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(1)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('超管保留全部写入口(勾选列+操作列+删除勾选+批量编辑分类),且不显示只读提示', async () => {
|
||||
// beforeEach 默认 super_admin;这里显式再钉一次,防默认值漂移把这条闸门变成恒绿。
|
||||
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
|
||||
expect(wrapper.findAll('tbody input[type="checkbox"]')).toHaveLength(1)
|
||||
expect(wrapper.findAll('tbody tr')[0].findAll('td')).toHaveLength(7)
|
||||
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true)
|
||||
expect(wrapper.findAll('button').some((b) => b.text() === '批量编辑分类')).toBe(true)
|
||||
expect(wrapper.text()).not.toContain('只读:')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('本组管理员(非平台超管):商品行按钮仍无,但勾选列随批量编辑分类放开(6 列形状)', async () => {
|
||||
useAdminSessionStore().user = { id: 3, username: 'leader', role: 'admin' }
|
||||
// 组长档形状:可见组可写 ⇒ editable=true;商品行写仍按 isSuperAdmin 判(不受 editable 影响)。
|
||||
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope(true))
|
||||
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 1 }])
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.findAll('tbody tr')[0].findAll('td')).toHaveLength(6, '管理员 6 列:勾选/分类/商品信息/总库存/价格/同步时间(无操作列)')
|
||||
expect(wrapper.find('.jd-delete-btn').exists()).toBe(false, '批量删除(商品行写)仍只归平台超管')
|
||||
expect(wrapper.find('thead').text()).not.toContain('操作')
|
||||
const editBtn = wrapper.findAll('button').find((b) => b.text() === '批量编辑分类')
|
||||
expect(editBtn, '本组管理员有批量编辑分类入口').toBeTruthy()
|
||||
|
||||
// 管理员可勾选并走一遍归类(2026-11-17 弹窗下线后唯一的归类路径)。
|
||||
jdApi.batchAssignJdProductGroup.mockResolvedValue(1)
|
||||
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
|
||||
expect(editBtn!.attributes('disabled')).toBeUndefined('勾选后可点')
|
||||
await editBtn!.trigger('click')
|
||||
await flushPromises()
|
||||
const modal = wrapper.get('.batch-modal')
|
||||
await modal.findAll('.option-row')[0].trigger('click')
|
||||
await modal.findAll('button').find((b) => b.text() === '归入「甲组」')!.trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], 7, GROUP_A)
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
|
||||
describe('京东数据库分类按数据权限分组隔离(V203)', () => {
|
||||
it('多组可见:筛选行出带标签的「分组」下拉,切换后分类下拉与列表一并用新组取', async () => {
|
||||
jdApi.fetchJdCategoryScope.mockResolvedValue({
|
||||
platformSuperAdmin: true,
|
||||
defaultGroupId: 11,
|
||||
groups: [
|
||||
{ id: 11, name: 'A组', label: '甲公司 / A组', editable: true },
|
||||
{ id: 12, name: 'B组', label: '甲公司 / B组', editable: true },
|
||||
],
|
||||
})
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
// 首屏就按默认组取(不是先不带 ownerGroupId 再补一次)。
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith(11)
|
||||
expect(jdApi.fetchJdProductList.mock.calls[0][0]).toMatchObject({ ownerGroupId: 11 })
|
||||
|
||||
const picker = wrapper.get('[aria-label="当前分组"]')
|
||||
// 2026-11-16 用户口径「做成分组」:分组在筛选行里是带标签的表单控件(与其他筛选同壳同圆角),
|
||||
// 不再是工具栏裸下拉——钉住形状,防止搬回工具栏或丢标签。
|
||||
const groupField = (picker.element as HTMLSelectElement).closest('.form-group')
|
||||
expect(groupField?.querySelector('label')?.textContent).toBe('分组')
|
||||
expect(picker.findAll('option').map((o) => o.text())).toEqual(['甲公司 / A组', '甲公司 / B组'],
|
||||
'跨公司组名由后端拼进 label,前端不解析公司字段')
|
||||
|
||||
await picker.setValue('12')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(12)
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ ownerGroupId: 12, page: 1 },
|
||||
'切组后列表按新组重取并回第一页')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('只有一组:不出下拉(锁定显示组名),分类与行集仍按该组取', async () => {
|
||||
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
|
||||
expect(wrapper.find('[aria-label="当前分组"]').exists()).toBe(false, '单组不渲染切换下拉')
|
||||
expect(wrapper.get('.jd-group-locked').text()).toBe('甲组', '锁定芯片只放组名,「分组」二字在上方标签里(2026-11-16 口径)')
|
||||
expect(jdApi.fetchJdProductList.mock.calls[0][0]).toMatchObject({ ownerGroupId: GROUP_A })
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('分组住进筛选行但仍是作用域不是筛选条件:重置只清筛选面,分组保持当前组', async () => {
|
||||
jdApi.fetchJdCategoryScope.mockResolvedValue({
|
||||
platformSuperAdmin: true,
|
||||
defaultGroupId: 11,
|
||||
groups: [
|
||||
{ id: 11, name: 'A组', label: '甲公司 / A组', editable: true },
|
||||
{ id: 12, name: 'B组', label: '甲公司 / B组', editable: true },
|
||||
],
|
||||
})
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
const picker = wrapper.get('[aria-label="当前分组"]')
|
||||
await picker.setValue('12')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ ownerGroupId: 12 })
|
||||
await wrapper.findAll('button').find((b) => b.text() === '重置')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect((picker.element as HTMLSelectElement).value).toBe('12', '重置不清当前分组(作用域语义,搬进筛选行也不变)')
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ ownerGroupId: 12 },
|
||||
'重置后的重取仍带当前分组')
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
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)
|
||||
expect(wrapper.find('.jd-group-locked').exists()).toBe(false, '没有分组就没有可锁定的组名')
|
||||
expect(wrapper.find('[aria-label="筛选店铺分类"]').text()).toContain('全部分类', '分类筛选只剩「全部分类」')
|
||||
expect(wrapper.findAll('tbody tr')[0].findAll('td')[1].text()).toBe('未分类')
|
||||
expect(wrapper.findAll('button').some((b) => b.text() === '批量编辑分类')).toBe(false, '没有分组就没有可写的分类面')
|
||||
expect(jdApi.batchAssignJdProductGroup).not.toHaveBeenCalled()
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* 京东商品编辑抽屉「图片区」子组件 JdProductImageManager(2026-11-16 客户口径
|
||||
* 「删除做成打叉的 icon 放图右上角,也要支持编辑替换本地的图」+替换+新增,B109-01
|
||||
* 落地;从 JdProductEditDrawer 拆出成件后本测试直接挂子组件)的挂载契约。
|
||||
*
|
||||
* 形态:× 右上角标删(保存时一并删除,遮罩可点撤销,标删集合经 update:deleteIds 上抛);
|
||||
* hover 替换条(multipart 立即生效,返回详情经 update:images 上抛);「+ 新增主图」入口
|
||||
* (imageType=MAIN)。objectKey 服务端内容寻址生成——前端只传文件。
|
||||
* 跑法:`npx vitest run tests/mount/jd-edit-drawer-images.mount.test.ts`
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||||
|
||||
import JdProductImageManager from '@/pages/jd/JdProductImageManager.vue'
|
||||
|
||||
const jdApi = vi.hoisted(() => ({
|
||||
uploadJdProductImage: vi.fn(),
|
||||
}))
|
||||
|
||||
const feedbackMock = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('@/pages/jd/jd-product-api.ts', () => ({
|
||||
uploadJdProductImage: jdApi.uploadJdProductImage,
|
||||
}))
|
||||
vi.mock('@/components/admin-feedback-ui', () => ({ showAdminFeedback: feedbackMock }))
|
||||
|
||||
function image(id: number, imageType: string, url: string) {
|
||||
return { id, imageType, attrName: null, sortNo: id, url, byteSize: 1024, width: null, height: null }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
async function mountWith(images: ReturnType<typeof image>[]): Promise<VueWrapper<Element>> {
|
||||
const wrapper = mount(JdProductImageManager, {
|
||||
props: { productId: 9, images, disabled: false },
|
||||
})
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
/** 把夹具文件塞进隐藏 file input 并触发 change。 */
|
||||
async function chooseFile(wrapper: VueWrapper<Element>, name = 'a.png'): Promise<File> {
|
||||
const input = wrapper.find('input[type="file"]')
|
||||
const file = new File(['x'], name, { type: 'image/png' })
|
||||
Object.defineProperty(input.element, 'files', { value: [file] })
|
||||
await input.trigger('change')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
return file
|
||||
}
|
||||
|
||||
describe('京东商品编辑抽屉图片区子组件(×右上角+替换+新增,B109-01)', () => {
|
||||
it('挂载回填图片区:每格右上角有 × 标记、hover 替换条存在、新增按钮存在(上传/替换暂未开放的旧文案下线)', async () => {
|
||||
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg'), image(12, 'DETAIL', 'https://img.example/b.jpg')])
|
||||
const cells = wrapper.findAll('.image-cell')
|
||||
expect(cells).toHaveLength(2)
|
||||
expect(cells[0].find('.image-x').exists()).toBe(true, '右上角 × 删除标记')
|
||||
expect(cells[0].find('.image-replace').exists()).toBe(true, 'hover 替换条')
|
||||
expect(cells[0].find('.image-marked-mask').exists()).toBe(false, '未标删时无遮罩')
|
||||
const addBtn = wrapper.find('.btn-add-image')
|
||||
expect(addBtn.exists()).toBe(true)
|
||||
expect(addBtn.text()).toContain('新增主图')
|
||||
expect(wrapper.find('h4').text()).not.toContain('暂未开放', '「上传/替换暂未开放」旧文案下线')
|
||||
})
|
||||
|
||||
it('点 × 标记删除(保存时一并删除):遮罩出现、update:deleteIds 上抛、计数文案更新;再点撤销恢复', async () => {
|
||||
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg'), image(12, 'MAIN', 'https://img.example/b.jpg')])
|
||||
await wrapper.find('.image-cell .image-x').trigger('click')
|
||||
let cell = wrapper.findAll('.image-cell')[0]
|
||||
expect(cell.classes()).toContain('marked')
|
||||
expect(cell.find('.image-marked-mask').exists()).toBe(true)
|
||||
expect(wrapper.find('.delete-count').text()).toContain('已标记删除 1 张')
|
||||
expect(wrapper.emitted('update:deleteIds')).toBeTruthy()
|
||||
expect(wrapper.emitted('update:deleteIds')![0]).toEqual([[11]])
|
||||
|
||||
await cell.find('.image-marked-mask').trigger('click')
|
||||
cell = wrapper.findAll('.image-cell')[0]
|
||||
expect(cell.classes()).not.toContain('marked')
|
||||
expect(wrapper.find('.delete-count').exists()).toBe(false)
|
||||
expect(jdApi.uploadJdProductImage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('hover 替换条选本地图:uploadJdProductImage 带 replaceImageId 调用,update:images 上抛新行集并置 saved', async () => {
|
||||
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg')])
|
||||
const clickSpy = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {})
|
||||
await wrapper.find('.image-cell .image-replace').trigger('click')
|
||||
expect(clickSpy).toHaveBeenCalled()
|
||||
|
||||
jdApi.uploadJdProductImage.mockResolvedValue({
|
||||
item: { id: 9 },
|
||||
attrGroups: [],
|
||||
images: [image(11, 'MAIN', 'https://img.example/replaced.jpg')],
|
||||
skus: [],
|
||||
attrJsonRaw: '',
|
||||
})
|
||||
const file = await chooseFile(wrapper, 'b.png')
|
||||
expect(jdApi.uploadJdProductImage).toHaveBeenCalledTimes(1)
|
||||
expect(jdApi.uploadJdProductImage.mock.calls[0][0]).toBe(9)
|
||||
expect(jdApi.uploadJdProductImage.mock.calls[0][1]).toBe(file)
|
||||
expect(jdApi.uploadJdProductImage.mock.calls[0][2]).toEqual({ replaceImageId: 11 })
|
||||
expect(wrapper.emitted('update:images')![0][0]).toEqual([image(11, 'MAIN', 'https://img.example/replaced.jpg')])
|
||||
expect(feedbackMock).toHaveBeenCalledWith(expect.stringContaining('已替换'), 'success')
|
||||
expect(wrapper.emitted('saved')).toBeTruthy()
|
||||
clickSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('「+ 新增主图」入口:uploadJdProductImage 带 imageType=MAIN(objectKey 由服务端生成,前端不自造)', async () => {
|
||||
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg')])
|
||||
const clickSpy = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {})
|
||||
await wrapper.find('.btn-add-image').trigger('click')
|
||||
expect(clickSpy).toHaveBeenCalled()
|
||||
|
||||
jdApi.uploadJdProductImage.mockResolvedValue({
|
||||
item: { id: 9 },
|
||||
attrGroups: [],
|
||||
images: [image(11, 'MAIN', 'https://img.example/a.jpg'), image(13, 'MAIN', 'https://img.example/new.jpg')],
|
||||
skus: [],
|
||||
attrJsonRaw: '',
|
||||
})
|
||||
await chooseFile(wrapper, 'c.png')
|
||||
expect(jdApi.uploadJdProductImage.mock.calls[0][2]).toEqual({ imageType: 'MAIN' })
|
||||
expect(wrapper.emitted('update:images')![0][0]).toHaveLength(2)
|
||||
expect(feedbackMock).toHaveBeenCalledWith(expect.stringContaining('已新增'), 'success')
|
||||
clickSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('上传失败:红条出现(requestErrorMessage 对非信封异常回通用文案)、不 update:images 不置 saved', async () => {
|
||||
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg')])
|
||||
vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {})
|
||||
await wrapper.find('.btn-add-image').trigger('click')
|
||||
jdApi.uploadJdProductImage.mockRejectedValue(new Error('单张图片不能超过 10MB'))
|
||||
await chooseFile(wrapper, 'big.png')
|
||||
expect(wrapper.find('.drawer-failure').exists()).toBe(true, '失败红条出现')
|
||||
expect(wrapper.emitted('update:images')).toBeFalsy()
|
||||
expect(wrapper.emitted('saved')).toBeFalsy()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('行集变化清掉已不存在的标删 id:父级保存删行回填后,残留标删不再进 update:deleteIds', async () => {
|
||||
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg'), image(12, 'MAIN', 'https://img.example/b.jpg')])
|
||||
await wrapper.find('.image-cell .image-x').trigger('click')
|
||||
expect(wrapper.emitted('update:deleteIds')!.at(-1)).toEqual([[11]])
|
||||
|
||||
// 父级保存成功回填:11 行已删、只剩 12 —— 标删集合里 11 被清掉
|
||||
await wrapper.setProps({ images: [image(12, 'MAIN', 'https://img.example/b.jpg')] })
|
||||
await flushPromises()
|
||||
expect(wrapper.emitted('update:deleteIds')!.at(-1)).toEqual([[]])
|
||||
expect(wrapper.find('.delete-count').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,6 +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)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'/, '编辑公司回填行值')
|
||||
})
|
||||
@@ -0,0 +1,134 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import type { AdminMenuNode } from '../src/types/admin.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,京东侧=截图圈定
|
||||
* 数据页(京东数据库/分类管理)。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 => {
|
||||
const out: AdminMenuNode = { key, name }
|
||||
if (route) out.route = route
|
||||
if (children) out.children = children
|
||||
return out
|
||||
}
|
||||
|
||||
/** 侧边栏实测形状的缩影:账号与权限(混编京东侧账号菜单与亚马逊侧配置/密钥菜单)+数据管理。 */
|
||||
const TREE: AdminMenuNode[] = [
|
||||
node('admin_group_account', '账号与权限', undefined, [
|
||||
node('admin_columns', '菜单权限配置', '/account/menus'),
|
||||
node('admin_users', '用户管理', '/account/users'),
|
||||
node('admin_group_manage', '分组管理', '/account/groups'),
|
||||
node('admin_user_secrets', '密钥管理', '/account/user-secrets'),
|
||||
node('admin_user_secret_usage', '密钥用量统计', '/account/user-secret-usage'),
|
||||
node('admin_companies', '公司管理', '/account/companies'),
|
||||
]),
|
||||
node('admin_group_data', '数据管理', undefined, [
|
||||
node('admin_dedupe_total_data', '去重数据汇总', '/asin-center/registry'),
|
||||
node('admin_invalid_asin_data', '品牌数据库', '/asin-center/invalid'),
|
||||
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_product_categories', '商品类目', '/asin-center/categories'),
|
||||
]),
|
||||
]
|
||||
|
||||
function groupChildKeys(filtered: AdminMenuNode[], groupKey: string): string[] {
|
||||
const group = filtered.find((item) => item.key === groupKey)
|
||||
return (group?.children || []).map((child) => child.key)
|
||||
}
|
||||
|
||||
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:账号与权限只余双侧三项,数据管理只余京东独占页(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 晚用户口径「京东分类管理并到京东数据库分类编辑里」:分类管理子菜单
|
||||
// (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, '京东数据库')
|
||||
})
|
||||
|
||||
test('亚马逊 tab:除京东独占页外全数保留(含 2026-11-17 回归的双侧账号域三页),分组结构不变', () => {
|
||||
const filtered = filterMenuTreeByPlatform(TREE, 'amazon')
|
||||
assert.deepEqual(groupChildKeys(filtered, 'admin_group_account'),
|
||||
['admin_columns', 'admin_users', 'admin_group_manage', 'admin_user_secrets',
|
||||
'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'])
|
||||
})
|
||||
|
||||
test('子项全归另一平台的分组整组隐藏(空分组不画);未知 key 默认归亚马逊侧', () => {
|
||||
const mixed: AdminMenuNode[] = [
|
||||
node('admin_group_shop', '店铺管理', undefined, [
|
||||
node('admin_shop_manage', '店铺管理', '/shop-center/shops'),
|
||||
node('admin_shop_keys', '店铺密钥管理', '/shop-center/keys'),
|
||||
]),
|
||||
node('admin_jd_database', '京东数据库', '/jd-center/database'),
|
||||
node('admin_history', '生成记录', '/records/history'),
|
||||
]
|
||||
const jd = filterMenuTreeByPlatform(mixed, 'jd')
|
||||
assert.deepEqual(jd.map((item) => item.key), ['admin_jd_database'],
|
||||
'店铺管理组子项全在亚马逊侧 ⇒ 京东 tab 整组剪掉;生成记录未知 key 默认亚马逊')
|
||||
const amazon = filterMenuTreeByPlatform(mixed, 'amazon')
|
||||
assert.deepEqual(amazon.map((item) => item.key), ['admin_group_shop', 'admin_history'])
|
||||
})
|
||||
|
||||
test('tab 显示依据:两侧都有可见页才画 tab 条,仅一侧授权时另一侧自动隐藏', () => {
|
||||
assert.deepEqual(visiblePlatformsFor(TREE), ['amazon', 'jd'], '顺序固定随 PLATFORM_TABS')
|
||||
const amazonOnly: AdminMenuNode[] = [
|
||||
node('admin_group_data', '数据管理', undefined, [
|
||||
node('admin_dedupe_total_data', '去重数据汇总', '/asin-center/registry'),
|
||||
]),
|
||||
]
|
||||
assert.deepEqual(visiblePlatformsFor(amazonOnly), ['amazon'],
|
||||
'只授权亚马逊侧(无京东数据库)的用户只看到亚马逊 tab')
|
||||
const jdOnly: AdminMenuNode[] = [
|
||||
node('admin_group_data', '数据管理', undefined, [node('admin_jd_database', '京东数据库', '/jd-center/database')]),
|
||||
]
|
||||
assert.deepEqual(visiblePlatformsFor(jdOnly), ['jd'])
|
||||
assert.deepEqual(visiblePlatformsFor([]), [])
|
||||
assert.deepEqual(visiblePlatformsFor(null), [])
|
||||
})
|
||||
|
||||
test('平台 tab 定义与两份菜单清单钉死(防清单漂移):京东独占仅数据库一页、双侧共用账号域三页', () => {
|
||||
assert.deepEqual(PLATFORM_TABS, [
|
||||
{ id: 'amazon', label: '亚马逊' },
|
||||
{ id: 'jd', label: '京东' },
|
||||
])
|
||||
// 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('两份清单的每一条都必须在路由注册表登记(同 company-menu-route 护栏形状:少登记=看得见点进去404)', () => {
|
||||
const registered = new Set(adminPages.map((page) => page.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/)
|
||||
})
|
||||
@@ -56,6 +56,15 @@ public final class PageDefaults {
|
||||
/** {@link #ADMIN_LIST_PAGE_SIZE} 的数字镜像。 */
|
||||
public static final int ADMIN_LIST_PAGE_SIZE_INT = 20;
|
||||
|
||||
/**
|
||||
* 京东数据库后管只读页默认容量 = 20(v1.4 Phase 5,蓝图 §3.2「page_size 默认 20、上限 100」;
|
||||
* 上限钳制在 {@code JdProductQueryService},不在注解上)。
|
||||
*/
|
||||
public static final String JD_PRODUCTS_PAGE_SIZE = "20";
|
||||
|
||||
/** {@link #JD_PRODUCTS_PAGE_SIZE} 的数字镜像。 */
|
||||
public static final int JD_PRODUCTS_PAGE_SIZE_INT = 20;
|
||||
|
||||
/** 上架/采集类任务历史列表默认容量 = 50。现存 2 处 {@code page_size}(collect-data、publish)。 */
|
||||
public static final String TASK_LIST_PAGE_SIZE = "50";
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -67,7 +67,13 @@ public final class TaskModuleRegistry {
|
||||
Optional.of(UserSecretModule.SIMILAR_ASIN)),
|
||||
new Module("COLLECT_DATA", "采集数据", true, true, false, true, Optional.empty()),
|
||||
new Module("SHOP_DATA_CRAWL", "店铺数据抓取", true, false, true, false, Optional.empty()),
|
||||
new Module("BRAND", "品牌检测", true, false, true, false, Optional.empty())
|
||||
new Module("BRAND", "品牌检测", true, false, true, false, Optional.empty()),
|
||||
// v1.4 京东店铺采集(蓝图 §4 Phase 1):resultFileJob=false——不出 Excel 结果文件,
|
||||
// 商品数据直接落 biz_jd_product(V193),导出由后管做;ageCleanup=true——任务行
|
||||
// 照常按天清理(商品行在 biz_jd_product 独立保留,不被清);Phase 2 判死登记定型:
|
||||
// JdStaleTaskService 自带 @Scheduled(60 分钟超时线,selfScheduledStaleCheck=true,
|
||||
// 同 publish/collect-data 先例),京麦登录态失效判死由回传侧经它落终态。
|
||||
new Module("JD_SHOP_COLLECT", "京东店铺采集", false, true, false, true, Optional.empty())
|
||||
);
|
||||
|
||||
private TaskModuleRegistry() {
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package com.nanri.aiimage.common.retry;
|
||||
|
||||
import com.nanri.aiimage.modules.brand.support.BrandCheckFailureNotice;
|
||||
import com.nanri.aiimage.modules.task.service.TaskRetryEligibility;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* 「凭据坏了、再跑多少次都是同一个结果」这一类失败的唯一判据,以及该给用户看的那句动作。
|
||||
*
|
||||
* <p>用户口径(2026-11-12,34061 取证后):任何特性只要用到 LLM 密钥或代理 IP,遇到<b>不可自愈</b>的
|
||||
* 凭据故障都必须三件事一起做——行落失败并写真实原因、任务立即中断为终态、用户端弹窗一次。
|
||||
* 判据只此一处:外观专利、货源查询、跟价、店铺采集、采集数据都从这里取,不各自抄一份字面量表
|
||||
* (抄了就会改一处静默失效,与 {@link TaskRetryEligibility} 的注释同一条理由)。
|
||||
*
|
||||
* <p>代理侧的分档<b>不另立词汇表</b>:{@link BrandCheckFailureNotice} 已经按"未配置 / 套餐耗尽 /
|
||||
* 冷却 / 出口被拒 / 技术性 / 上游"六档分过品牌检测的原始原因(2026-10-20 起就是那张表)。
|
||||
* 这里只认它的前两档为致命,后四档一律继续重试——冷却与出口被拒是短时现象、上游不可用会自己恢复,
|
||||
* 拿它们判死就是让用户整单给一次抖动陪葬(铁律 27(c))。
|
||||
*
|
||||
* <p>LLM 那半边走 {@link TaskRetryEligibility.Category#BALANCE}(欠费与密钥失效同族)。
|
||||
* LLM 专属字样<b>先于</b>品牌侧判:品牌侧的「余额不足」与 LLM 的「余额欠费」都落在同一批中文词上,
|
||||
* 顺序反了就会把"代理套餐没钱了"说成"上游 LLM 账户欠费"——2026-10-27 用户点名要避免的那种误导。
|
||||
*/
|
||||
public final class CredentialFatalClassifier {
|
||||
|
||||
/** 凭据故障的两种来源:给用户的那句动作不同。 */
|
||||
public enum Kind {
|
||||
/** 上游 LLM 账户欠费/额度耗尽,或 LLM 密钥本身失效。 */
|
||||
LLM_CREDENTIAL,
|
||||
/** 代理提取:套餐到期、余额不足、密钥/链接不可用,或根本没配置。 */
|
||||
PROXY_CREDENTIAL
|
||||
}
|
||||
|
||||
/**
|
||||
* LLM 侧「钱/密钥」硬字样:与 {@code LlmBalanceGuard} 的余额识别、{@code TaskRetryEligibility.KEY_MARKERS}
|
||||
* 同一套词,加 {@code 余额欠费}/{@code 额度不足} 这两个中文签。
|
||||
*
|
||||
* <p>刻意<b>不</b>收裸「llm」或裸「余额不足」:任何一条 LLM 报错都带 {@code LLM} 三个字母
|
||||
* ({@code LLM 网关无应答}、{@code LLM http 502}),拿它当凭据判据会把一次抖动判成终态;
|
||||
* 「余额不足」是品牌侧套餐与 LLM 侧欠费共用的词,得靠品牌词汇表先分档。
|
||||
*/
|
||||
private static final List<String> LLM_CREDENTIAL_MARKERS = List.of(
|
||||
"insufficient_user_quota", "insufficient_quota", "insufficient balance", "insufficient_funds",
|
||||
"wallet balance insufficient", "quota exceeded",
|
||||
"预扣费额度", "余额欠费", "额度不足",
|
||||
"密钥无效", "密钥失效", "无效的密钥", "密钥不可用",
|
||||
"invalid api key", "invalid_api_key", "api key 无效", "apikey 无效");
|
||||
|
||||
/**
|
||||
* 代理侧「凭据本身不可用」的硬字样:与品牌侧词汇表无关的那些提供商失败码。
|
||||
*
|
||||
* <p>必须先于 {@link BrandCheckFailureNotice} 判:青果的 {@code API_AUTH_DENY} 常和「提取失败」
|
||||
* 出现在同一句里,而品牌侧把「提取失败」归 TECHNICAL(补测轮会再来)——顺序反了,
|
||||
* 一条注定失败的鉴权错就被说成"技术性失败、等等再试"。
|
||||
*/
|
||||
private static final List<String> PROXY_HARD_CREDENTIAL_MARKERS = List.of(
|
||||
"未配置代理", "代理地址为空", "代理链接为空",
|
||||
"invalid_key", "unavailable_key", "key_block", "api_auth_deny", "access_deny");
|
||||
|
||||
/** 代理侧专名/字面:只用于把一句泛化的「余额不足」判给代理而不是 LLM。 */
|
||||
private static final List<String> PROXY_CREDENTIAL_MARKERS = List.of(
|
||||
"代理", "提取链接", "提取分钟数", "青果", "qg.net", "jikip", "极客", "套餐",
|
||||
"invalid_key", "unavailable_key", "key_block", "api_auth_deny", "access_deny");
|
||||
|
||||
/**
|
||||
* 明确「外部自己会恢复」的字样:命中一律不致命。
|
||||
*
|
||||
* <p>刻意<b>不</b>放裸数字(429/502/503/504):上游欠费原文里带着账户号({@code 用户[151502]}),
|
||||
* 裸 {@code contains("502")} 会把一条真欠费判成 5xx 抖动——放过这一单,用户就又回到"只见失败、不见原因"。
|
||||
*/
|
||||
private static final List<String> SELF_HEALING_MARKERS = List.of(
|
||||
"no_available_channel", "没有可用的空闲通道", "channel_busy", "通道被占", "通道已满",
|
||||
"冷却", "cooldown", "稍后重试",
|
||||
"timeout", "timed out", "超时",
|
||||
"too many requests", "rate limited", "限流",
|
||||
"bad gateway", "service unavailable", "gateway timeout",
|
||||
"connection refused", "连接被拒绝", "不可达", "unreachable",
|
||||
"页面无效", "风控墙", "人机验证");
|
||||
|
||||
/** 代理侧终态动作句(与 {@link LlmBalanceGuard#TASK_TERMINAL_GUIDANCE} 同形:谁的问题、做了什么、下一步)。 */
|
||||
public static final String PROXY_TERMINAL_GUIDANCE =
|
||||
"任务已终止:代理 IP 套餐已到期或余额不足、或提取链接不可用(未配置/密钥无效),"
|
||||
+ "不是你本次上传的数据问题;已停止后续采集与检测,以免继续空跑并消耗额度。"
|
||||
+ "请到账号的代理设置里充值、续期或更换提取链接后重新发起任务。";
|
||||
|
||||
private CredentialFatalClassifier() {
|
||||
}
|
||||
|
||||
/** @return null=可以继续重试;非 null=不可自愈,按该档处置 */
|
||||
public static Kind kind(String failureMessage) {
|
||||
if (failureMessage == null || failureMessage.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
// 本仓自己写下的两条终态句先认出来(原文比对,模板里有大写 LLM/IP):它们各自都提到
|
||||
// 「密钥/代理出口」,让下面的词汇表去猜,存量单重读时就会在 LLM 与代理之间来回翻。
|
||||
if (failureMessage.contains(LlmBalanceGuard.TASK_TERMINAL_GUIDANCE)) {
|
||||
return Kind.LLM_CREDENTIAL;
|
||||
}
|
||||
if (failureMessage.contains(PROXY_TERMINAL_GUIDANCE)) {
|
||||
return Kind.PROXY_CREDENTIAL;
|
||||
}
|
||||
String text = failureMessage.toLowerCase(Locale.ROOT);
|
||||
if (containsAny(text, SELF_HEALING_MARKERS)) {
|
||||
return null;
|
||||
}
|
||||
if (containsAny(text, LLM_CREDENTIAL_MARKERS)) {
|
||||
return Kind.LLM_CREDENTIAL;
|
||||
}
|
||||
if (containsAny(text, PROXY_HARD_CREDENTIAL_MARKERS)) {
|
||||
return Kind.PROXY_CREDENTIAL;
|
||||
}
|
||||
BrandCheckFailureNotice.Kind brand = BrandCheckFailureNotice.classify(failureMessage);
|
||||
if (brand == BrandCheckFailureNotice.Kind.PROXY_NOT_CONFIGURED
|
||||
|| brand == BrandCheckFailureNotice.Kind.PROXY_PACKAGE_EXHAUSTED) {
|
||||
return Kind.PROXY_CREDENTIAL;
|
||||
}
|
||||
// 品牌侧认得的技术性/冷却/出口被拒三类:补测轮会自己再来,不进终态。
|
||||
if (brand != BrandCheckFailureNotice.Kind.UPSTREAM) {
|
||||
return null;
|
||||
}
|
||||
// 兜底:还没被任何一张词汇表认出来的欠费/密钥形状,按走 BALANCE 判死,
|
||||
// 靠有没有代理专名决定给哪句动作。判不出 BALANCE 就是普通可重试失败。
|
||||
if (TaskRetryEligibility.forceMajeureCategory(failureMessage) != TaskRetryEligibility.Category.BALANCE) {
|
||||
return null;
|
||||
}
|
||||
return containsAny(text, PROXY_CREDENTIAL_MARKERS) ? Kind.PROXY_CREDENTIAL : Kind.LLM_CREDENTIAL;
|
||||
}
|
||||
|
||||
/** 只要"要不要判死"的那一问。 */
|
||||
public static boolean isFatal(String failureMessage) {
|
||||
return kind(failureMessage) != null;
|
||||
}
|
||||
|
||||
/** 给定档位的终态动作句;这是写进 {@code biz_file_task.error_message} 尾巴的那一段。 */
|
||||
public static String guidance(Kind kind) {
|
||||
return kind == Kind.PROXY_CREDENTIAL
|
||||
? PROXY_TERMINAL_GUIDANCE
|
||||
: LlmBalanceGuard.TASK_TERMINAL_GUIDANCE;
|
||||
}
|
||||
|
||||
private static boolean containsAny(String text, List<String> markers) {
|
||||
for (String marker : markers) {
|
||||
if (text.contains(marker)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,11 @@ public final class LlmBalanceGuard {
|
||||
"insufficient_user_quota",
|
||||
"insufficient_quota",
|
||||
"insufficient balance",
|
||||
// 2026-11-11 现网:钱包型欠费走 insufficient_funds + "wallet balance insufficient",
|
||||
// 与上面两条的拼写与词序都不同("balance insufficient" 里没有连续的 "insufficient balance"),
|
||||
// 漏掉这两个锚点,欠费就会一路落回"未完成检测/上游不可用",用户根本看不到"欠费"。
|
||||
"insufficient_funds",
|
||||
"wallet balance insufficient",
|
||||
"预扣费额度失败",
|
||||
"额度不足",
|
||||
"余额不足",
|
||||
|
||||
@@ -85,6 +85,24 @@ public final class DeviceSessionPolicy {
|
||||
return isSuper(resolveRole(role, isAdmin, createdById));
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否<b>公司超级管理员</b>(本公司最高账号,数据只看本公司)。
|
||||
*
|
||||
* <p>为什么收这一处:这条比较在 src/main 里已有 22 处手抄({@code AdminUserService} 14、
|
||||
* {@code PermissionMenuService} 4、去重/分组/到期停任务/看板各 1)。京东数据库分类按
|
||||
* 「公司 → 数据权限分组」两级隔离(V203)需要它,新写点再手抄一份就是第 23 处,故先在这里
|
||||
* 收一个出口;<b>不改既有调用方</b>——要把那 22 处收进来,得连「业务数据面同权、管理动作收窄」
|
||||
* 那条定案一起落(见本类 {@link #COMPANY_SUPER_ADMIN} 注释)。</p>
|
||||
*/
|
||||
public static boolean isCompanySuperAdmin(String resolvedRole) {
|
||||
return COMPANY_SUPER_ADMIN.equals(resolvedRole);
|
||||
}
|
||||
|
||||
/** {@link #isCompanySuperAdmin(String)} 的原始字段版本(自行 resolve 角色)。 */
|
||||
public static boolean isCompanySuperAdmin(String role, Integer isAdmin, Long createdById) {
|
||||
return isCompanySuperAdmin(resolveRole(role, isAdmin, createdById));
|
||||
}
|
||||
|
||||
/** 从 JWT claims 中提取签名的设备号;缺失返回空串。 */
|
||||
public static String claimDeviceId(Claims claims) {
|
||||
Object raw = claims == null ? null : claims.get("deviceId");
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,9 @@ import java.util.List;
|
||||
* @param fileJobExhausted 结果文件作业是否已重试耗尽(true 时责任不在客户端回传)
|
||||
* @param submissionComplete 客户端是否已交完全部结果(末分片 done=true/scope 已封口)。
|
||||
* true 时责任在出表侧:采集早就干完了,是结果文件没生成出来
|
||||
* @param resultFileDelivered 结果文件其实已经交付({@code biz_file_result.result_file_url} 非空)。
|
||||
* 与 {@code submissionComplete} 一起看:交完了<b>而且</b>表已挂,就不能再说「未能生成」
|
||||
* (BACKLOG B96-08:33879 的终态文案把已交付说成没交付,用户据此以为白跑了三代)
|
||||
* @param timeoutMinutes 判死阈值(分钟)
|
||||
*/
|
||||
public record StaleTaskDeathReason(long chunkCount,
|
||||
@@ -29,6 +32,7 @@ public record StaleTaskDeathReason(long chunkCount,
|
||||
String lastProgress,
|
||||
boolean fileJobExhausted,
|
||||
boolean submissionComplete,
|
||||
boolean resultFileDelivered,
|
||||
int timeoutMinutes) {
|
||||
|
||||
/**
|
||||
@@ -46,17 +50,37 @@ public record StaleTaskDeathReason(long chunkCount,
|
||||
String lastProgress,
|
||||
boolean fileJobExhausted,
|
||||
int timeoutMinutes) {
|
||||
this(chunkCount, lastChunkAt, lastHeartbeatAt, lastProgress, fileJobExhausted, false, timeoutMinutes);
|
||||
this(chunkCount, lastChunkAt, lastHeartbeatAt, lastProgress, fileJobExhausted, false, false, timeoutMinutes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 没有「结果文件是否已交付」信号的调用方用这一档:等价于 {@code resultFileDelivered=false},
|
||||
* 文案与加这个字段之前逐字相同。外观专利那条链已经接上真信号({@code AppearancePatentStaleTaskScanner}),
|
||||
* 相似ASIN尚未接(见上文 6 参数的同一理由)。
|
||||
*/
|
||||
public StaleTaskDeathReason(long chunkCount,
|
||||
LocalDateTime lastChunkAt,
|
||||
LocalDateTime lastHeartbeatAt,
|
||||
String lastProgress,
|
||||
boolean fileJobExhausted,
|
||||
boolean submissionComplete,
|
||||
int timeoutMinutes) {
|
||||
this(chunkCount, lastChunkAt, lastHeartbeatAt, lastProgress, fileJobExhausted, submissionComplete,
|
||||
false, timeoutMinutes);
|
||||
}
|
||||
|
||||
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("MM-dd HH:mm");
|
||||
|
||||
public String describe() {
|
||||
if (chunkCount > 0 && fileJobExhausted) {
|
||||
return "已收到 " + chunkCount + " 个结果分片,但结果文件生成多次失败,任务已自动结束";
|
||||
}
|
||||
String headline;
|
||||
if (submissionComplete) {
|
||||
if (submissionComplete && resultFileDelivered) {
|
||||
// BACKLOG B96-08:交完了<b>而且</b>直链已经挂上时,「结果文件未能生成」是句假话——
|
||||
// 现网 33879 的表在上一代就出好并交付过(重试触发的是「已交付代」,见
|
||||
// TaskInPlaceRetryService 的形状分档),文案却说没生成,排查方向被带偏一整轮。
|
||||
headline = "客户端已上传完全部结果,结果文件已生成(沿用已交付的那份)";
|
||||
} else if (chunkCount > 0 && fileJobExhausted) {
|
||||
return "已收到 " + chunkCount + " 个结果分片,但结果文件生成多次失败,任务已自动结束";
|
||||
} else if (submissionComplete) {
|
||||
// 2026-11-10 现网 33828/33758 的形状:采集侧末分片 done=true 已上传成功
|
||||
// (worker 日志「任务处理完成 99/99,抓取失败 0 行」),出表作业却停在上一代的 SUCCESS 上
|
||||
// 没被复位,于是永不出表、心跳停了 30 分钟被判死。此时说「客户端回传中断」与事实相反——
|
||||
|
||||
@@ -24,19 +24,13 @@ import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* /api/admin/**、/debug/** 兜底鉴权过滤器。
|
||||
* /api/admin/** 兜底鉴权过滤器。
|
||||
*
|
||||
* <p>SecurityConfig 全局 permitAll 且无路径级拦截,历史上有多个 /api/admin 控制器遗漏方法级
|
||||
* require*(公网 18080 直连可达即匿名裸奔)。本过滤器作为第二道网:凡进入受保护前缀的请求
|
||||
* 必须具备"有效身份"(Java JWT,或可信内部令牌 X-Internal-Token + operatorId,复用
|
||||
* AdminAuthSupport),否则直接返回与全局异常一致的 401 响应体(HTTP 200 + {success:false,code})。
|
||||
*
|
||||
* <p>/debug/** 于 2026-09-11 一并纳入:两个 debug 控制器都没有方法级鉴权,而主机A 18080 公网
|
||||
* 直连、主机B nginx 的 location / 全量反代 Java,实测三处均可匿名调通——
|
||||
* GET /debug/request-info(泄漏实例与转发头)与
|
||||
* POST /debug/task-recovery/run-stale-finalize(**写操作**,强制收尾指定 task)。
|
||||
* 应急调用方改用 X-Internal-Token 或管理员 JWT 即可通过,不再裸奔。
|
||||
*
|
||||
* <p>只保证"已认证",管理员/菜单级校验仍由各控制器 require* 负责,避免拦截普通登录用户本可
|
||||
* 访问的 /api/admin 接口(如权限菜单列表仅 requireUser)。
|
||||
*
|
||||
@@ -70,9 +64,6 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final String ADMIN_API_PREFIX = "/api/admin";
|
||||
|
||||
/** 调试端点前缀:无方法级鉴权的诊断/运维入口,同样纳入兜底(2026-09-11)。 */
|
||||
private static final String DEBUG_PREFIX = "/debug";
|
||||
|
||||
/**
|
||||
* 用户态工具接口前缀:controller 无方法级鉴权(归属由请求参数 user_id 判定),
|
||||
* 匿名可达即越权读写他人数据。**默认不纳入兜底**,由
|
||||
@@ -290,11 +281,6 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// /debug/** 是应急/诊断入口,调用频次极低但敏感,单独留一条审计日志便于事后追溯
|
||||
if (matchesPrefix(uri, DEBUG_PREFIX)) {
|
||||
log.warn("[debug-guard] {} {} 通过鉴权放行,remoteAddr={}",
|
||||
request.getMethod(), uri, request.getRemoteAddr());
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
@@ -332,9 +318,9 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
|| Integer.valueOf(DeviceSessionPolicy.CODE_KICKED).equals(code);
|
||||
}
|
||||
|
||||
/** 必须解析出身份才放行的前缀:/api/admin、/debug、自助接口,以及已纳入收紧清单的用户态前缀。 */
|
||||
/** 必须解析出身份才放行的前缀:/api/admin、自助接口,以及已纳入收紧清单的用户态前缀。 */
|
||||
private boolean requiresCredential(String uri) {
|
||||
if (matchesPrefix(uri, ADMIN_API_PREFIX) || matchesPrefix(uri, DEBUG_PREFIX)) {
|
||||
if (matchesPrefix(uri, ADMIN_API_PREFIX)) {
|
||||
return true;
|
||||
}
|
||||
if (isCredentialRequiredWriteEndpoint(uri)) {
|
||||
@@ -448,7 +434,6 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
public static java.util.List<String> guardedPrefixes() {
|
||||
java.util.List<String> all = new java.util.ArrayList<>();
|
||||
all.add(ADMIN_API_PREFIX);
|
||||
all.add(DEBUG_PREFIX);
|
||||
all.addAll(java.util.List.of(USER_TOOL_PREFIXES));
|
||||
all.addAll(java.util.List.of(SELF_SERVICE_PREFIXES));
|
||||
return all;
|
||||
|
||||
@@ -77,7 +77,6 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
|
||||
"/logout",
|
||||
"/api/version", // 客户端启动时拉最新版本号,必须先于登录
|
||||
"/api/tutorial", // 后台可维护的使用教程,公开内容
|
||||
"/api/workbench-client", // 数富AI工作台客户端更新检查:必须先于登录,公开只读版本元数据
|
||||
"/api/kd-flow/verify", // 开店流程访问密码校验:它自己就是那道门
|
||||
// 下面四条都是 AdminConsoleController 的 302 兜底(response.sendRedirect 完事,
|
||||
// 不读库、不回数据),旧书签打进这些地址只会被送到 /admin-vue/。
|
||||
@@ -102,12 +101,7 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
|
||||
* 往里塞一条没设防的路径会红。
|
||||
*/
|
||||
static final Set<String> METHOD_GUARDED_PATHS = Set.of(
|
||||
"/api/client/credentials",
|
||||
// 五国关键词共享(2026-10-23 keywordshare 模块):9 个端点全部在 handler 体内经
|
||||
// requireKeywordShareAccess → adminAuthSupport.requireUser + PermissionMenuService
|
||||
// .requireConsolePageAccess(operator, …, "keyword-share") 逐请求把门,且 company_id
|
||||
// 一律服务端取、不收请求参数——第二道门已到位,只欠进 USER_TOOL_PREFIXES 第一道门。
|
||||
"/api/keyword-share");
|
||||
"/api/client/credentials");
|
||||
|
||||
/**
|
||||
* 待收欠账:数据按 user_id 归属、却既不进守卫名单也没有 require* 的前缀。
|
||||
@@ -120,6 +114,10 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
|
||||
* <li>{@code /api/delete-brand} —— 删品牌任务单,与已在名单里的 /api/brand 同形状,等同一批客户端</li>
|
||||
* <li>{@code /api/module-templates} —— 模板列表按 user_id 取,匿名可读他人模板</li>
|
||||
* <li>{@code /api/split} —— 拆合单任务,随 /api/convert 那批一起收</li>
|
||||
* <li>{@code /api/jd-collect} —— v1.4 京东采集任务面(建单/chunk 回传/心跳):建单方法体已有
|
||||
* requireOwnershipUserId(fail-closed 401),chunk 与 heartbeat 和 collect-data/delete-brand
|
||||
* 同形状(本机桌面执行器不带凭据,行归属以任务 owner 投影);chunk 的 error 上报已接整单
|
||||
* 判死,其 owner 对撞收口随 v1.4 Phase 6.1 落,判死口凭据化后随统一批进名单</li>
|
||||
* </ul>
|
||||
*/
|
||||
static final Set<String> PENDING_CONVERGENCE = Set.of(
|
||||
@@ -128,7 +126,8 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
|
||||
"/api/dedupe",
|
||||
"/api/delete-brand",
|
||||
"/api/module-templates",
|
||||
"/api/split");
|
||||
"/api/split",
|
||||
"/api/jd-collect");
|
||||
|
||||
private final RequestMappingHandlerMapping handlerMapping;
|
||||
|
||||
|
||||
@@ -25,6 +25,9 @@ public class CollectRoutingProperties {
|
||||
/** 相似ASIN(货源查询)模块名。 */
|
||||
public static final String MODULE_SIMILAR_ASIN = "SIMILAR_ASIN";
|
||||
|
||||
/** 京东店铺采集模块名(v1.4;紫鸟只在本机 Windows,默认通道必须 LOCAL,铁律 19 同形)。 */
|
||||
public static final String MODULE_JD_SHOP_COLLECT = "JD_SHOP_COLLECT";
|
||||
|
||||
/** LOCAL 通道的任务在 PENDING 超过多少分钟后允许 Linux 兜底认领。 */
|
||||
private long linuxFallbackMinutes = 30L;
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.nanri.aiimage.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 五国关键词客户端同步({@code /api/keyword-share/sync/import})的服务端参数。
|
||||
*
|
||||
* <p>存在的主要理由:工作台按对接文档口径使用**共享专用 API 账号**,而 {@code keyword_usage.user_name}
|
||||
* 是「谁用了哪个词」的唯一出处。若一律取 token 账号名,多人使用会被记成同一个人,后台按使用者筛选
|
||||
* 就失去意义;若无条件信任客户端自报姓名,又会把「阿武(扶金凡)/阿武(吴棋龙)」这类同音异写
|
||||
* 直接灌进留痕表。名单校验是这两者之间的收口:命中名单才按自报姓名落库。</p>
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "aiimage.keyword-share-sync")
|
||||
public class KeywordShareSyncProperties {
|
||||
|
||||
/**
|
||||
* 可信操作人姓名名单(真人显示名,与 {@code keyword_usage.user_name} 同形)。
|
||||
* 比对时两侧都做 trim + 全角括号归一,所以名单里写「阿武(吴棋龙)」也能匹配半角写法。
|
||||
*/
|
||||
private List<String> usedUsers = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* 名单外姓名的处置。
|
||||
* <ul>
|
||||
* <li>{@code false}(默认):放行自报姓名,只在响应里计数回报——首次上线时名单还没填,
|
||||
* 直接回退会把全部记录静默改写成账号名,比现状更糟;</li>
|
||||
* <li>{@code true}:名单外一律回退为本次调用的账号名,并计入 {@code usedUserFallback}。</li>
|
||||
* </ul>
|
||||
*/
|
||||
private boolean strict = false;
|
||||
}
|
||||
@@ -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, KeywordShareSyncProperties.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));
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.client;
|
||||
|
||||
import com.nanri.aiimage.modules.brand.client.BrandCheckClient;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 整批品牌查询全失败时,标题列该写哪句人话。
|
||||
*
|
||||
* <p>2026-11-11 现网(BACKLOG B95-02):16890 侧 {@code 解密失败: Malformed UTF-8 data} 成片刷,
|
||||
* 交付表却一律写「品牌库上游整体不可用」——上游其实**有应答**,坏的是应答体解密,运维照着
|
||||
* 「上游挂了」去查永远查不到东西。真因不同,指向的动作不同,所以按批内 reason 分档。
|
||||
*
|
||||
* <p>三条文案都必须以「商标查询失败」开头:{@code AppearancePatentLlmClient#isBrandQueryFailed}
|
||||
* 与状态列都靠这个前缀判定失败,措辞可以变,前缀不能变。
|
||||
*
|
||||
* <p>单独成类而不是塞回客户端:{@code AppearancePatentLlmClient} 已在可读性棘轮的
|
||||
* 「超长文件点名」账上,只许减。
|
||||
*/
|
||||
final class AppearancePatentBrandFailureText {
|
||||
|
||||
/** 分不出真因时的通用文案(保底,不是默认)。 */
|
||||
static final String UPSTREAM_UNAVAILABLE =
|
||||
"商标查询失败:品牌库上游整体不可用(本批待查词无一返回结果,非本行数据问题)";
|
||||
|
||||
/** 批内真因统一是「拿回了包但解不开」。 */
|
||||
static final String DECRYPT_BROKEN =
|
||||
"商标查询失败:品牌库返回内容无法解密(服务侧解密链路故障,非本行数据问题)";
|
||||
|
||||
/** 批内真因统一是「连接根本没建立」。 */
|
||||
static final String SERVICE_UNREACHABLE =
|
||||
"商标查询失败:品牌检测服务不可达(连接未建立,非本行数据问题)";
|
||||
|
||||
/** 样例最多留几个字:够定位真因,又不把整段上游报错糊进交付列。 */
|
||||
static final int SAMPLE_KEEP = 80;
|
||||
|
||||
private AppearancePatentBrandFailureText() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 整批待查词是否无一返回可用结果;是则给出该批的行级文案,否则 null(逐行写「商标查询失败」)。
|
||||
*
|
||||
* <p>判据刻意保守:只要有任何一行拿到过侵权命中、或有任何一行查成功过,就返回 null。
|
||||
* 没发过查询的行(LLM 已判「无」、或标题为空)不参与判定,否则一批全是"无需查"的行
|
||||
* 会被误判成上游故障。
|
||||
*/
|
||||
static String aggregate(List<BrandCheckClient.BrandCheckBatchResult> brandChecks) {
|
||||
boolean anyChecked = false;
|
||||
List<String> reasons = new ArrayList<>();
|
||||
for (BrandCheckClient.BrandCheckBatchResult check : brandChecks) {
|
||||
if (check == null || check.brands() == null || check.brands().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
anyChecked = true;
|
||||
// 命中过侵权就说明上游至少在返回结果,那种行优先给真实结论,不升级成整批口径
|
||||
if (check.hasFailedData() || !check.hasQueryFailedData()) {
|
||||
return null;
|
||||
}
|
||||
reasons.add(normalize(check.reason()));
|
||||
}
|
||||
return anyChecked ? describe(classify(reasons), reasons) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分类文案 + 一句失败样例。
|
||||
*
|
||||
* <p>BK B95-02 的判据是「解密失败那条要能回读到是哪一步失败」:分类只说到「解密链路」,
|
||||
* 具体是 UTF-8 解不开、密钥不对还是压缩坏了,只有上游那句 reason 才知道。样例截断到
|
||||
* {@link #SAMPLE_KEEP} 字并对齐单行——它是给人看的一句话,不是堆栈搬运。
|
||||
*/
|
||||
static String describe(String base, List<String> reasons) {
|
||||
String sample = "";
|
||||
if (reasons != null) {
|
||||
for (String reason : reasons) {
|
||||
String text = normalize(reason).replace('\n', ' ').replace('\r', ' ');
|
||||
if (!text.isEmpty()) {
|
||||
sample = text.length() > SAMPLE_KEEP ? text.substring(0, SAMPLE_KEEP) + "…" : text;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return sample.isEmpty() ? base : base + ";样例=" + sample;
|
||||
}
|
||||
|
||||
/** 批内 reason 全同形才分档;空 reason 或混形一律落回通用文案(不猜)。 */
|
||||
static String classify(List<String> reasons) {
|
||||
if (reasons == null || reasons.isEmpty()) {
|
||||
return UPSTREAM_UNAVAILABLE;
|
||||
}
|
||||
boolean allDecrypt = true;
|
||||
boolean allUnreachable = true;
|
||||
for (String reason : reasons) {
|
||||
String text = normalize(reason);
|
||||
if (text.isEmpty()) {
|
||||
return UPSTREAM_UNAVAILABLE;
|
||||
}
|
||||
allDecrypt &= text.contains("解密");
|
||||
allUnreachable &= text.contains("不可达") || text.contains("连接未建立");
|
||||
}
|
||||
if (allDecrypt) {
|
||||
return DECRYPT_BROKEN;
|
||||
}
|
||||
return allUnreachable ? SERVICE_UNREACHABLE : UPSTREAM_UNAVAILABLE;
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
+87
-33
@@ -11,6 +11,7 @@ import com.nanri.aiimage.config.AppearancePatentProperties;
|
||||
import com.nanri.aiimage.config.HttpClientPool;
|
||||
import com.nanri.aiimage.metrics.ExternalCallMetricsRecorder;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentRowOutcome;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentSheetBuilder;
|
||||
import com.nanri.aiimage.modules.brand.client.BrandCheckClient;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserSecretUsageService;
|
||||
@@ -60,7 +61,8 @@ public class AppearancePatentLlmClient {
|
||||
private static final int MAX_LLM_RESPONSE_BYTES = 16 * 1024 * 1024;
|
||||
private static final String INFRINGEMENT = "侵权";
|
||||
private static final String NO_INFRINGEMENT = "无侵权";
|
||||
private static final String BRAND_QUERY_FAILED = "商标查询失败";
|
||||
/** 文案唯一定义在 {@link AppearancePatentRowOutcome}(出表侧要用同一串判"这格是不是判定")。 */
|
||||
private static final String BRAND_QUERY_FAILED = AppearancePatentRowOutcome.BRAND_QUERY_FAILED;
|
||||
/**
|
||||
* 整批待查词无一返回结果时的文案,与逐行的「商标查询失败」区分开。
|
||||
*
|
||||
@@ -83,7 +85,20 @@ public class AppearancePatentLlmClient {
|
||||
private static final int LLM_CONNECT_FAILURE_EVIDENCE = 2;
|
||||
/** 连接层判定不可达时交付给行级的原因文案:说清是运维故障,不是这行数据的问题。 */
|
||||
static final String REASON_LLM_UNREACHABLE = "LLM 服务不可达(连接未建立,非本行数据问题)";
|
||||
private static final String APPEARANCE_ANOMALY = "外观识别异常";
|
||||
private static final String APPEARANCE_ANOMALY = AppearancePatentRowOutcome.APPEARANCE_ANOMALY;
|
||||
/**
|
||||
* 我们<b>根本没发出图片请求</b>时的外观维标签(无图片/无标题,或商标维先失败跳过外观那一步)。
|
||||
* 与 {@link #APPEARANCE_ANOMALY}(发了请求、上游没给出可用结论)必须分开:
|
||||
* 2026-11-12 任务 34061 的交付件里 987 行外观维写着「外观识别异常」、而「外观原因」整格空白,
|
||||
* 用户只能把它读成图片识别没认出来,真实原因(LLM 上游欠费、外观那一步压根没跑)得运维去翻日志。
|
||||
*/
|
||||
static final String APPEARANCE_NOT_RUN = AppearancePatentRowOutcome.APPEARANCE_NOT_RUN;
|
||||
/** 商标维命中但外观维没跑时的结论后缀(结论列不许写成裸「侵权」,见 {@link #buildConclusion})。 */
|
||||
static final String APPEARANCE_NOT_RUN_SUFFIX = "外观维未执行";
|
||||
static final String APPEARANCE_SKIPPED_NO_DATA = "未执行外观检测:本行没有标题或图片链接,未发出图片识别请求";
|
||||
static final String PATENT_SKIPPED_REASON = "未执行专利检测:外观维未执行";
|
||||
/** 商标维先失败时跳过外观那一步的原因前缀,后面接商标维自己的原话。 */
|
||||
static final String APPEARANCE_SKIPPED_BY_TITLE = "未执行外观检测:商标维先失败,本行没有发出图片识别请求";
|
||||
private static final String MISSING_ROW_DATA = "爬虫数据缺失";
|
||||
|
||||
/** 商标关键词提取系统提示词(与原 LLM 工作流一致) */
|
||||
@@ -198,7 +213,8 @@ public class AppearancePatentLlmClient {
|
||||
String rawTitle = normalize(row.getTitle());
|
||||
if (rawTitle.isBlank() || normalize(row.getUrl()).isBlank()) {
|
||||
llmRows.add(row);
|
||||
llmResults.add(fallbackResult(row, rawTitle, firstNonBlank(rawTitle, MISSING_ROW_DATA), ""));
|
||||
llmResults.add(skippedAppearanceResult(row, rawTitle,
|
||||
firstNonBlank(rawTitle, MISSING_ROW_DATA), APPEARANCE_SKIPPED_NO_DATA));
|
||||
} else {
|
||||
pending.add(results.size() - 1);
|
||||
}
|
||||
@@ -220,9 +236,10 @@ public class AppearancePatentLlmClient {
|
||||
}
|
||||
// 标题识别失败时本行必走回退分支(外观结果会被丢弃),再发外观请求只会在劣化中的上游白等一轮重试
|
||||
log.warn("[appearance-patent] 标题识别失败,跳过外观识别(本行同样走回退)asin={}", rows.get(index).getAsin());
|
||||
String titleError = firstNonBlank(titleErrors.get(index), "商标识别失败");
|
||||
llmRows.add(results.get(index));
|
||||
llmResults.add(fallbackResult(results.get(index), normalize(rows.get(index).getTitle()),
|
||||
firstNonBlank(titleErrors.get(index), "商标识别失败"), ""));
|
||||
llmResults.add(skippedAppearanceResult(results.get(index), normalize(rows.get(index).getTitle()),
|
||||
titleError, skippedAppearanceReason(titleError)));
|
||||
}
|
||||
Map<Integer, AppearanceJudgement> judgements = new LinkedHashMap<>();
|
||||
Map<Integer, String> appearanceErrors = new LinkedHashMap<>();
|
||||
@@ -256,9 +273,9 @@ public class AppearancePatentLlmClient {
|
||||
*/
|
||||
private void applyLlmRowsInOneBatch(List<AppearancePatentResultRowDto> llmRows, List<LlmResult> llmResults) {
|
||||
List<BrandCheckClient.BrandCheckBatchResult> brandChecks = brandChecksFor(llmResults);
|
||||
boolean brandUpstreamUnavailable = brandUpstreamUnavailable(brandChecks);
|
||||
String aggregateFailure = brandAggregateFailure(brandChecks);
|
||||
for (int k = 0; k < llmRows.size(); k++) {
|
||||
applyResult(llmRows.get(k), llmResults.get(k), brandChecks.get(k), brandUpstreamUnavailable);
|
||||
applyResult(llmRows.get(k), llmResults.get(k), brandChecks.get(k), aggregateFailure);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,6 +485,36 @@ public class AppearancePatentLlmClient {
|
||||
"");
|
||||
}
|
||||
|
||||
/**
|
||||
* 外观那一步<b>没跑</b>的行(无图/无标题,或商标维先失败跳过):标签与原因都要说清"没跑"。
|
||||
* 三条列(外观/专利/标题原因)都不许空着交付,否则用户拿到的是"外观识别异常"四个字加一片空白。
|
||||
*/
|
||||
private LlmResult skippedAppearanceResult(AppearancePatentResultRowDto row,
|
||||
String title,
|
||||
String titleReason,
|
||||
String appearanceReason) {
|
||||
return new LlmResult(
|
||||
row.getGroupKey(),
|
||||
row.getId(),
|
||||
row.getAsin(),
|
||||
row.getCountry(),
|
||||
title,
|
||||
APPEARANCE_NOT_RUN,
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
titleReason,
|
||||
appearanceReason,
|
||||
PATENT_SKIPPED_REASON,
|
||||
"");
|
||||
}
|
||||
|
||||
/** 跳过外观那一步的原因文案:把「没跑」与「跑了没答上」分开,后者另有 appearanceErrors 的原话。 */
|
||||
private String skippedAppearanceReason(String titleError) {
|
||||
String detail = abbreviate(firstNonBlank(titleError, "商标识别失败"), 160);
|
||||
return APPEARANCE_SKIPPED_BY_TITLE + "(" + detail + ")";
|
||||
}
|
||||
|
||||
/** 一批行合并为一次文本请求;返回的行下标 → 关键词,仅包含通过字面校验的行。 */
|
||||
private Map<Integer, String> invokeTitleBatch(List<AppearancePatentResultRowDto> rows,
|
||||
List<Integer> chunk,
|
||||
@@ -753,7 +800,7 @@ public class AppearancePatentLlmClient {
|
||||
recordSecretUsage();
|
||||
Map<String, Object> body = buildChatBody(model, system, userText, images, responseFormat);
|
||||
String host = resolveHost();
|
||||
// 渠道模型映射:龙抬头那边统一叫 gm-3.5-flash-lite,直接发贞贞的模型名会 model_not_found
|
||||
// 渠道模型映射:龙抬头那边统一叫 gm-3.1-flash-lite,直接发贞贞的模型名会 model_not_found
|
||||
String requestModel = LlmChannel.modelForHost(host, model);
|
||||
body.put("model", requestModel);
|
||||
// 思考参数按渠道补:贞贞把 thinking 写在模型名里,龙抬头要显式传(复刻现网的 thinking-medium)
|
||||
@@ -1076,10 +1123,10 @@ public class AppearancePatentLlmClient {
|
||||
resolved.add(result);
|
||||
}
|
||||
List<BrandCheckClient.BrandCheckBatchResult> brandChecks = brandChecksFor(resolved);
|
||||
boolean brandUpstreamUnavailable = brandUpstreamUnavailable(brandChecks);
|
||||
String aggregateFailure = brandAggregateFailure(brandChecks);
|
||||
for (int i = 0; i < rows.size(); i++) {
|
||||
AppearancePatentResultRowDto row = copy(rows.get(i));
|
||||
applyResult(row, resolved.get(i), brandChecks.get(i), brandUpstreamUnavailable);
|
||||
applyResult(row, resolved.get(i), brandChecks.get(i), aggregateFailure);
|
||||
merged.add(row);
|
||||
}
|
||||
return merged;
|
||||
@@ -1134,37 +1181,24 @@ public class AppearancePatentLlmClient {
|
||||
}
|
||||
|
||||
/**
|
||||
* 整批待查词是否无一返回可用结果——用来把「上游整体挂了」和「这个词查不了」分开写。
|
||||
*
|
||||
* <p>判据刻意保守:只要有任何一行拿到过侵权命中、或有任何一行查成功过,就不算整体不可用,
|
||||
* 仍按逐行的「商标查询失败」写。没发过查询的行(LLM 已判「无」、或标题为空)不参与判定,
|
||||
* 否则一批全是"无需查"的行会被误判成上游故障。
|
||||
* 整批待查词是否无一返回可用结果——是则给出该批的行级文案,否则 null(逐行写「商标查询失败」)。
|
||||
* 分档与判据都在 {@link AppearancePatentBrandFailureText}(本文件只许减,见可读性棘轮)。
|
||||
*/
|
||||
private static boolean brandUpstreamUnavailable(
|
||||
private String brandAggregateFailure(
|
||||
List<BrandCheckClient.BrandCheckBatchResult> brandChecks) {
|
||||
boolean anyChecked = false;
|
||||
for (BrandCheckClient.BrandCheckBatchResult check : brandChecks) {
|
||||
if (check == null || check.brands() == null || check.brands().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
anyChecked = true;
|
||||
if (check.hasFailedData() || !check.hasQueryFailedData()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return anyChecked;
|
||||
return AppearancePatentBrandFailureText.aggregate(brandChecks);
|
||||
}
|
||||
|
||||
void applyResult(AppearancePatentResultRowDto row, LlmResult result,
|
||||
BrandCheckClient.BrandCheckBatchResult brandCheck,
|
||||
boolean brandUpstreamUnavailable) {
|
||||
String brandAggregateFailure) {
|
||||
if (row == null || result == null) {
|
||||
return;
|
||||
}
|
||||
if (isNoTitleRisk(result)) {
|
||||
row.setTitleRisk(NO_INFRINGEMENT);
|
||||
} else if (shouldCheckBrand(result)) {
|
||||
row.setTitleRisk(buildTitleRisk(result.title(), brandCheck, brandUpstreamUnavailable));
|
||||
row.setTitleRisk(buildTitleRisk(result.title(), brandCheck, brandAggregateFailure));
|
||||
} else {
|
||||
row.setTitleRisk("");
|
||||
}
|
||||
@@ -1196,11 +1230,15 @@ public class AppearancePatentLlmClient {
|
||||
}
|
||||
|
||||
String buildTitleRisk(String llmTitle, BrandCheckClient.BrandCheckBatchResult brandCheck) {
|
||||
return buildTitleRisk(llmTitle, brandCheck, false);
|
||||
return buildTitleRisk(llmTitle, brandCheck, (String) null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param brandAggregateFailure 整批全失败时的行级文案(见 {@link AppearancePatentBrandFailureText});
|
||||
* null=不是整批口径,逐行写「商标查询失败」
|
||||
*/
|
||||
String buildTitleRisk(String llmTitle, BrandCheckClient.BrandCheckBatchResult brandCheck,
|
||||
boolean brandUpstreamUnavailable) {
|
||||
String brandAggregateFailure) {
|
||||
List<String> brands = brandCheck == null ? List.of() : brandCheck.brands();
|
||||
if (brands == null || brands.isEmpty()) {
|
||||
return firstNonBlank(llmTitle, "");
|
||||
@@ -1210,15 +1248,23 @@ public class AppearancePatentLlmClient {
|
||||
}
|
||||
if (brandCheck.hasQueryFailedData()) {
|
||||
// 命中过侵权就说明上游至少在返回结果,那种行优先给真实结论,不升级成整批口径。
|
||||
return brandUpstreamUnavailable ? BRAND_UPSTREAM_UNAVAILABLE : BRAND_QUERY_FAILED;
|
||||
return brandAggregateFailure == null ? BRAND_QUERY_FAILED : brandAggregateFailure;
|
||||
}
|
||||
return NO_INFRINGEMENT;
|
||||
}
|
||||
|
||||
String buildConclusion(String titleRisk, String appearanceRisk, String fallbackConclusion) {
|
||||
if (isInfringement(titleRisk) || isInfringement(appearanceRisk)) {
|
||||
if (isInfringement(appearanceRisk)) {
|
||||
return INFRINGEMENT;
|
||||
}
|
||||
if (isInfringement(titleRisk)) {
|
||||
// 商标维命中是真的(品牌库确实回了词),但外观维压根没跑时不许把整行结论写成裸「侵权」:
|
||||
// 34061 里 158 行就是这么变成「成功」的——图片识别一次没做,结论列却只说侵权。
|
||||
// 写成「商标侵权·外观维未执行」既保住命中的信息,又让它读起来就是一次没跑完的检测。
|
||||
return hasAppearanceVerdict(appearanceRisk)
|
||||
? INFRINGEMENT
|
||||
: "商标" + INFRINGEMENT + APPEARANCE_NOT_RUN_SUFFIX;
|
||||
}
|
||||
if (isNoInfringement(titleRisk) && isNoInfringement(appearanceRisk)) {
|
||||
return NO_INFRINGEMENT;
|
||||
}
|
||||
@@ -1234,6 +1280,14 @@ public class AppearancePatentLlmClient {
|
||||
return firstNonBlank(fallbackConclusion, "");
|
||||
}
|
||||
|
||||
/** 外观维真的判过才配当"整行结论"的一半;判据与出表侧同一句话。 */
|
||||
private boolean hasAppearanceVerdict(String appearanceRisk) {
|
||||
String normalized = normalize(appearanceRisk);
|
||||
return !normalized.isBlank()
|
||||
&& !AppearancePatentSheetBuilder.isTechnicalLlmFailure(normalized)
|
||||
&& !AppearancePatentRowOutcome.isNoVerdictText(normalized);
|
||||
}
|
||||
|
||||
private static final Pattern NO_INFRINGEMENT_WORDING = Pattern.compile(
|
||||
"(?:无侵权|未侵权|不侵权|没有侵权|非侵权|(?:未发现|无明显|不存在|不构成|未构成|不涉及|未涉及)[^。;;]*侵权)"); // 否定措辞优先,裸 contains("侵权") 会反判
|
||||
private boolean isInfringement(String value) {
|
||||
|
||||
+72
-6
@@ -9,6 +9,7 @@ import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.common.support.DownloadHeaderUtil;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentCleanItemPageVo;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentSupervisorPageVo;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentCleanItemQueryService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -19,10 +20,12 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
@@ -33,10 +36,11 @@ import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* 后管「外观专利无侵权数据」只读页(v1.3 R2/R3)。数据由出表成功点自动同步落表
|
||||
* ({@code AppearancePatentCleanSyncService}),本页只读——无写/删接口,下载走既有结果直链/
|
||||
* 任务中心;另有 GET 导出端点(2026-11-11 客户需求「数据得导出来」):与分页查询同一过滤面
|
||||
* (含公司隔离正门),服务侧卡导出上限,主管列为读侧现算列,无写/删/导入;分组筛选同日落地
|
||||
* 后管「外观专利无侵权数据」页(v1.3 R2/R3)。数据由出表成功点自动同步落表
|
||||
* ({@code AppearancePatentCleanSyncService}),本页不出表、不改明细内容——下载走导出端点、
|
||||
* 删除走 {@code DELETE /supervisors}(2026-11-11 客户「也要加个删除按钮」,按主管删快照明细行,
|
||||
* 不碰结果文件与任务记录);另有 GET 导出端点(2026-11-11 客户需求「数据得导出来」):与分页查询
|
||||
* 同一过滤面(含公司隔离正门),服务侧卡导出上限,主管列为读侧现算列,无导入;分组筛选同日落地
|
||||
* (客户口径「主管就是组长,可以筛选组长来导出,就是分组」)——group_id 参数(biz_shop_manage_group.id)
|
||||
* 在分页与导出同面生效,服务侧按 selectUserIdsByGroupId 解析「组长本人+名下子账户」整集后
|
||||
* SQL 侧下推;下拉选项复用既有 GET /shop-manages/groups(与去重页/店铺管理同源),不下新端点。
|
||||
@@ -47,6 +51,7 @@ import java.time.format.DateTimeFormatter;
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
@RequestMapping("/api/admin/appearance-patent-clean-items")
|
||||
@Tag(name = "外观专利无侵权数据", description = "后管只读页:出表成功自动同步的「结论=无侵权」明细,按分公司隔离分页查询与导出。")
|
||||
public class AdminAppearancePatentCleanItemsController {
|
||||
@@ -93,6 +98,31 @@ public class AdminAppearancePatentCleanItemsController {
|
||||
startDate, endDate, groupId, scopedCompanyId));
|
||||
}
|
||||
|
||||
@GetMapping("/supervisors")
|
||||
@Operation(summary = "按主管聚合查询(一主管一卡)", description = "后管「外观专利数据库」页的卡片面"
|
||||
+ "(2026-11-11 客户口径「获取店铺那边是按店铺做成卡片 我们这边就是按主管划分」):按主管"
|
||||
+ "归组返回条数/任务数/最近同步时间/国家集,total 是主管数;过滤面与明细分页同一段 SQL 谓词"
|
||||
+ "(公司/国家/同步起止/分组用户集),公司隔离走同一 readCompanyIdOrOwn 正门。")
|
||||
public ApiResponse<AppearancePatentSupervisorPageVo> supervisors(
|
||||
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页数量(主管卡片数)")
|
||||
@RequestParam(name = "page_size", defaultValue = PageDefaults.CLEAN_ITEMS_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "国家代码(如 DE、UK)") @RequestParam(name = "country", required = false) String country,
|
||||
@Parameter(description = "同步开始日期(包含)")
|
||||
@RequestParam(name = "start_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "同步结束日期(包含)")
|
||||
@RequestParam(name = "end_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
|
||||
@Parameter(description = "分组 id:按该分组「组长本人+名下子账户」的用户集过滤(主管=组长)")
|
||||
@RequestParam(name = "group_id", required = false) Long groupId,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireCleanItemsAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
return ApiResponse.success(cleanItemQueryService.supervisorPage(page, pageSize, country,
|
||||
startDate, endDate, groupId, scopedCompanyId));
|
||||
}
|
||||
|
||||
@GetMapping("/export")
|
||||
@Operation(summary = "导出外观专利数据库 Excel", description = "与分页查询同一过滤面(任务号/ASIN/国家/同步起止日期/分组),"
|
||||
+ "公司隔离走同一正门:company_id 只对站点超管生效(显式传才收窄,不传全量),非超管强制本公司。"
|
||||
@@ -108,6 +138,9 @@ public class AdminAppearancePatentCleanItemsController {
|
||||
@RequestParam(name = "end_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
|
||||
@Parameter(description = "分组 id:按该分组「组长本人+名下子账户」的用户集过滤(主管=组长)")
|
||||
@RequestParam(name = "group_id", required = false) Long groupId,
|
||||
@Parameter(description = "主管用户 id:只导出该主管名下明细(卡片上的「下载」,"
|
||||
+ "归属口径与主管聚合卡片同一表达式)")
|
||||
@RequestParam(name = "supervisor_user_id", required = false) Long supervisorUserId,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireCleanItemsAccess(request);
|
||||
@@ -115,8 +148,11 @@ public class AdminAppearancePatentCleanItemsController {
|
||||
// 导出与分页共用 readCompanyIdOrOwn 正门(同 page 的口径注释):超管显式传才收窄、
|
||||
// 不传全量;非超管强制本公司(忽略请求传参),绝不让导出绕过页签的公司隔离。
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
byte[] bytes = cleanItemQueryService.export(taskId, asin, country, startDate, endDate, groupId,
|
||||
scopedCompanyId);
|
||||
byte[] bytes = supervisorUserId != null
|
||||
? cleanItemQueryService.exportBySupervisor(supervisorUserId, country, startDate, endDate, groupId,
|
||||
scopedCompanyId)
|
||||
: cleanItemQueryService.export(taskId, asin, country, startDate, endDate, groupId,
|
||||
scopedCompanyId);
|
||||
String filename = "外观专利数据库-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx";
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
|
||||
@@ -125,6 +161,36 @@ public class AdminAppearancePatentCleanItemsController {
|
||||
.body(bytes);
|
||||
}
|
||||
|
||||
@DeleteMapping("/supervisors")
|
||||
@Operation(summary = "删除某位主管名下的外观专利数据库明细", description = "卡片上的「删除」(2026-11-11 客户"
|
||||
+ "「也要加个删除按钮」):谓词与卡片「下载」逐字同源(同一过滤面+同一主管归属表达式),"
|
||||
+ "supervisor_user_id 必填——缺值不按主管收窄就等于删整个过滤面,直接按业务错误拒绝。"
|
||||
+ "只删快照明细行,不动结果文件与任务记录。返回实际删除行数。")
|
||||
public ApiResponse<Integer> deleteBySupervisor(
|
||||
@Parameter(description = "主管用户 id(必填,卡片归属口径)")
|
||||
@RequestParam(name = "supervisor_user_id") Long supervisorUserId,
|
||||
@Parameter(description = "国家代码(如 DE、UK)") @RequestParam(name = "country", required = false) String country,
|
||||
@Parameter(description = "同步开始日期(包含)")
|
||||
@RequestParam(name = "start_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "同步结束日期(包含)")
|
||||
@RequestParam(name = "end_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
|
||||
@Parameter(description = "分组 id:按该分组「组长本人+名下子账户」的用户集过滤(主管=组长)")
|
||||
@RequestParam(name = "group_id", required = false) Long groupId,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireCleanItemsAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
// 删除与查询/导出同一公司隔离正门:非超管只能删本公司的行(忽略请求传参)。
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
|
||||
int deleted = cleanItemQueryService.deleteBySupervisor(supervisorUserId, country, startDate, endDate,
|
||||
groupId, scopedCompanyId);
|
||||
// 管理端真删必须留痕(谁、删了哪位主管、什么过滤面、删了多少行):日志是唯一的取证面。
|
||||
log.info("[appearance-patent-clean] 按主管删除明细 operatorId={} supervisorUserId={} country={} "
|
||||
+ "start={} end={} groupId={} companyId={} deleted={}",
|
||||
operator.id(), supervisorUserId, country, startDate, endDate, groupId, scopedCompanyId, deleted);
|
||||
return ApiResponse.success(deleted);
|
||||
}
|
||||
|
||||
private RequestOperator requireCleanItemsAccess(HttpServletRequest request) {
|
||||
AdminUserEntity operator = resolveOperator(request);
|
||||
if (operator == null || operator.getId() == null || operator.getId() <= 0) {
|
||||
|
||||
+80
-11
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.appearancepatent.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.entity.CleanItemEntity;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentSupervisorSummaryVo;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
@@ -9,11 +10,12 @@ import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 外观专利无侵权数据(biz_appearance_patent_clean_item,V189)数据访问口。
|
||||
* 外观专利无侵权数据(biz_appearance_patent_clean_item,V189;V192 起 ASIN 累计唯一键)数据访问口。
|
||||
*
|
||||
* <p>出表成功点由 {@code AppearancePatentCleanSyncService}(Phase 2)按 result_id
|
||||
* 覆盖式落表({@link #deleteByResultId} + {@link #insertBatch});后管只读页
|
||||
* (Phase 3)走 {@link #countCleanItems}/{@link #selectCleanItemPage}。SQL 全部落
|
||||
* <p>出表成功点由 {@code AppearancePatentCleanSyncService} 按唯一键 upsert 累计落表
|
||||
* ({@link #upsertBatch},2026-11-11 客户拍板「同 ASIN 只保留一条」;旧的按 result_id
|
||||
* delete-then-insert 覆盖式重写已退役——重投递载荷读不准时它会抹掉存量,实抹 1902 行);
|
||||
* 后管只读页(Phase 3)走 {@link #countCleanItems}/{@link #selectCleanItemPage}。SQL 全部落
|
||||
* {@code mapper/appearancepatent/AppearancePatentCleanItemMapper.xml}(铁律 1)。</p>
|
||||
*
|
||||
* <p>{@code userIds}(2026-11-11 分组筛选,主管=组长):服务侧由 {@code ShopManageGroupMapper
|
||||
@@ -23,16 +25,16 @@ import java.util.List;
|
||||
@Mapper
|
||||
public interface AppearancePatentCleanItemMapper extends BaseMapper<CleanItemEntity> {
|
||||
|
||||
/** 删除某次结果文件已同步的全部明细行(覆盖式重写第一步,AC-2)。 */
|
||||
int deleteByResultId(@Param("resultId") Long resultId);
|
||||
|
||||
/**
|
||||
* 多值批量插入明细行(调用方按 ≤500 行/批分批,蓝图 §3.3)。
|
||||
* 多值批量 upsert 明细行(调用方按 ≤500 行/批分批),冲突键=
|
||||
* {@code uk_company_user_country_asin}:同 ASIN 重复检测更新那条(刷新
|
||||
* synced_at),不同 ASIN 全保留,跨任务累计,<b>永不删除</b>。
|
||||
*
|
||||
* <p>刻意不写 synced_at:该列有 DB 默认值 CURRENT_TIMESTAMP,显式传 null 会覆盖掉
|
||||
* 默认值(同 ShopDataCrawlItemMapper#insertBatch 的口径)。</p>
|
||||
* <p>INSERT 路径不写 synced_at(列有 DB 默认值 CURRENT_TIMESTAMP,显式传 null
|
||||
* 会覆盖掉默认值);UPDATE 路径在 XML 里显式刷 CURRENT_TIMESTAMP(两段口径分开,
|
||||
* 见 XML 注释)。</p>
|
||||
*/
|
||||
int insertBatch(@Param("rows") List<CleanItemEntity> rows);
|
||||
int upsertBatch(@Param("rows") List<CleanItemEntity> rows);
|
||||
|
||||
/** 只读页总数(与 {@link #selectCleanItemPage} 同一过滤面)。 */
|
||||
long countCleanItems(@Param("companyId") Long companyId,
|
||||
@@ -59,4 +61,71 @@ public interface AppearancePatentCleanItemMapper extends BaseMapper<CleanItemEnt
|
||||
@Param("userIds") List<Long> userIds,
|
||||
@Param("offset") long offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 主管聚合分组数(2026-11-11「按主管划分」):组键由 XML 的 {@code supervisorIdExpr} 现算,
|
||||
* 与读侧 {@code fillSupervisorNames} 同口径(主管本人取自己、普通账户取创建人、读不到归 NULL 组)。
|
||||
* 过滤面与 {@link #selectSupervisorSummaries} 完全同一段 {@code cleanItemConds}。
|
||||
*/
|
||||
long countSupervisors(@Param("companyId") Long companyId,
|
||||
@Param("taskId") Long taskId,
|
||||
@Param("asin") String asin,
|
||||
@Param("country") String country,
|
||||
@Param("startDate") LocalDate startDate,
|
||||
@Param("endDate") LocalDate endDate,
|
||||
@Param("userIds") List<Long> userIds);
|
||||
|
||||
/**
|
||||
* 主管聚合分页(一主管一行:条数/任务数/最近任务号/最近同步时间/国家集)。
|
||||
*
|
||||
* <p>{@code offset}/{@code limit} 同样只收服务侧钳制后的值(铁律 15)。国家列是
|
||||
* GROUP_CONCAT 出来的 csv,服务侧拆列表(读侧不加工明细值,只在这个聚合面上做一次收集)。</p>
|
||||
*/
|
||||
List<AppearancePatentSupervisorSummaryVo> selectSupervisorSummaries(@Param("companyId") Long companyId,
|
||||
@Param("taskId") Long taskId,
|
||||
@Param("asin") String asin,
|
||||
@Param("country") String country,
|
||||
@Param("startDate") LocalDate startDate,
|
||||
@Param("endDate") LocalDate endDate,
|
||||
@Param("userIds") List<Long> userIds,
|
||||
@Param("offset") long offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
/** 单个主管名下的明细行数(卡片「下载」的导出口,先卡上限再取数)。 */
|
||||
long countSupervisorItems(@Param("companyId") Long companyId,
|
||||
@Param("taskId") Long taskId,
|
||||
@Param("asin") String asin,
|
||||
@Param("country") String country,
|
||||
@Param("startDate") LocalDate startDate,
|
||||
@Param("endDate") LocalDate endDate,
|
||||
@Param("userIds") List<Long> userIds,
|
||||
@Param("supervisorUserId") Long supervisorUserId);
|
||||
|
||||
/** 单个主管名下的明细页(导出全量用 offset=0、limit=上限;与明细分页同一过滤面)。 */
|
||||
List<CleanItemEntity> selectSupervisorItems(@Param("companyId") Long companyId,
|
||||
@Param("taskId") Long taskId,
|
||||
@Param("asin") String asin,
|
||||
@Param("country") String country,
|
||||
@Param("startDate") LocalDate startDate,
|
||||
@Param("endDate") LocalDate endDate,
|
||||
@Param("userIds") List<Long> userIds,
|
||||
@Param("supervisorUserId") Long supervisorUserId,
|
||||
@Param("offset") long offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 删除单个主管名下明细(2026-11-11 卡片上的「删除」)。
|
||||
*
|
||||
* <p>谓词与 {@link #selectSupervisorItems} 逐字同源(共享 {@code cleanItemConds} +
|
||||
* {@code supervisorScopeConds}):所见即所删。{@code supervisorUserId} 为 null 时那条
|
||||
* {@code <if>} 不生效=退化成整表删除,所以调用方(Service)必须先挡空值。</p>
|
||||
*/
|
||||
int deleteSupervisorItems(@Param("companyId") Long companyId,
|
||||
@Param("taskId") Long taskId,
|
||||
@Param("asin") String asin,
|
||||
@Param("country") String country,
|
||||
@Param("startDate") LocalDate startDate,
|
||||
@Param("endDate") LocalDate endDate,
|
||||
@Param("userIds") List<Long> userIds,
|
||||
@Param("supervisorUserId") Long supervisorUserId);
|
||||
}
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 主管卡片分页信封(2026-11-11「按主管划分」):形状与明细页一致(items/total/page/pageSize),
|
||||
* total 是<b>主管数</b>而不是明细条数——前端分页条按主管翻页。
|
||||
*/
|
||||
@Data
|
||||
public class AppearancePatentSupervisorPageVo {
|
||||
|
||||
private List<AppearancePatentSupervisorVo> items;
|
||||
|
||||
private Long total;
|
||||
|
||||
private Long page;
|
||||
|
||||
private Long pageSize;
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 主管聚合的 mapper 行(2026-11-11「按主管划分」):SQL 侧 {@code GROUP BY supervisorIdExpr}
|
||||
* 的原始读数,只负责搬运,不在这一层加工国家 csv(拆列表在服务层,避免 mapper 里做字符串处理)。
|
||||
*/
|
||||
@Data
|
||||
public class AppearancePatentSupervisorSummaryVo {
|
||||
|
||||
/** 主管用户 id(读不到主管的行=null,聚合时归入同一个「未知主管」组)。 */
|
||||
private Long supervisorId;
|
||||
|
||||
/** 该主管名下「无侵权」明细条数。 */
|
||||
private Long itemCount;
|
||||
|
||||
/** 该主管名下涉及的任务数(COUNT(DISTINCT task_id))。 */
|
||||
private Long taskCount;
|
||||
|
||||
/** 该主管名下最近一次涉及的任务号(MAX(task_id),卡片的「任务」行用它)。 */
|
||||
private Long lastTaskId;
|
||||
|
||||
/** 该主管名下最近一次同步时间(MAX(synced_at),卡片的「最新」列与默认排序键)。 */
|
||||
private LocalDateTime lastSyncedAt;
|
||||
|
||||
/** 国家集 csv(GROUP_CONCAT,服务层拆成列表;原样搬运不做翻译)。 */
|
||||
private String countryCsv;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user