From de4465730fee1ee21463452b3215ad81d3e45def Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com> Date: Fri, 23 Oct 2026 23:00:33 +0800 Subject: [PATCH] =?UTF-8?q?fix(common-tools):=20=E5=85=B3=E9=94=AE?= =?UTF-8?q?=E8=AF=8D=E5=85=B1=E4=BA=AB=E6=8C=89=E5=90=8E=E7=AB=AF=E7=9C=9F?= =?UTF-8?q?=E5=AE=9E=E8=BF=94=E5=9B=9E=E6=8E=A5=E7=BB=9F=E8=AE=A1=E5=9B=9B?= =?UTF-8?q?=E6=AE=B5=E4=B8=8E=E6=97=A5=E5=BF=97=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /stats-grouped 是四段各自 GROUP BY(对齐桌面版弹窗),前端原先按 「国家×一级类目」交叉表建模 ⇒ 弹窗恒为暂无数据;/logs 返回 userName/time 而表格读 operator/createdAt ⇒ 两列恒为占位符。改为 API 层映射 + 四段渲染, 日志去掉后端不产出的「说明」列。 --- .../src/pages/common/KeywordSharePage.vue | 374 +----------------- .../shared/api/types/modules/keyword-share.ts | 150 ++++--- frontend-vue/tests/keyword-share-api.test.ts | 73 ++++ .../mount/keyword-share-page.mount.test.ts | 2 +- 4 files changed, 193 insertions(+), 406 deletions(-) create mode 100644 frontend-vue/tests/keyword-share-api.test.ts diff --git a/frontend-vue/src/pages/common/KeywordSharePage.vue b/frontend-vue/src/pages/common/KeywordSharePage.vue index f3767f11b..e9d64e6a5 100644 --- a/frontend-vue/src/pages/common/KeywordSharePage.vue +++ b/frontend-vue/src/pages/common/KeywordSharePage.vue @@ -77,17 +77,15 @@ 跨国重复 {{ stats.dup }} - 词库统计 + 词库统计 - 添加 - - {{ randomLoading ? '抽词中...' : '随机抽词' }} - - 团队共享记录 + 添加 + 随机抽词 + 团队共享记录 @@ -134,119 +132,15 @@ - - - - - - - - - - 删除行 - - - - 再加一行 - - {{ addSubmitting ? '提交中...' : '批量添加' }} - - - {{ addResultText }} - - - - - 暂无统计数据 - - - - - - - - - - - 暂无可抽取的关键词 - - - - {{ row.chinese || '—' }} - - - - - {{ row.used ? '✓已使用' : '未使用' }} - - - - - - {{ randomMarking ? '标记中...' : `一键标记已使用(${randomMarkableRows.length})` }} - - - - - - - - {{ tab.label }} - - 暂无记录 - - - {{ row.createdAt || '—' }} - - - {{ formatLogType(row.type) }} - - - {{ row.country || '—' }} - - - {{ row.keyword || '—' }} - - - {{ row.operator || '—' }} - - - {{ row.detail || '—' }} - - - - + + + + @@ -256,25 +150,21 @@ import { computed, onBeforeUnmount, onMounted, ref } from 'vue' import { ElMessage, ElMessageBox } from 'element-plus' import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue' +import AddKeywordsDialog from '@/pages/common/keyword-share/AddKeywordsDialog.vue' +import KeywordStatsDialog from '@/pages/common/keyword-share/KeywordStatsDialog.vue' +import RandomKeywordsDialog from '@/pages/common/keyword-share/RandomKeywordsDialog.vue' +import ShareLogsDialog from '@/pages/common/keyword-share/ShareLogsDialog.vue' import { - addKeywordShareKeywords, deleteKeywordShareKeywords, fetchKeywordShareFilters, fetchKeywordShareKeywords, - fetchKeywordShareLogs, - fetchKeywordShareRandom, - fetchKeywordShareStatsGrouped, markKeywordShareUsage, - normalizeKeywordStatsGrouped, unmarkKeywordShareUsage, } from '@/shared/api/types/modules/keyword-share' import type { - KeywordShareAddItem, KeywordShareCategory, KeywordShareFiltersVo, KeywordShareListVo, - KeywordShareLogRow, - KeywordShareLogType, KeywordShareRow, KeywordShareStatusFilter, KeywordShareUsedDays, @@ -282,8 +172,6 @@ import type { /** 后端分页每页 200(契约固定) */ const PAGE_SIZE = 200 -const STATS_PAGE_SIZE = 50 -const LOG_PAGE_SIZE = 20 const SEARCH_DEBOUNCE_MS = 300 const USED_DAYS_OPTIONS: ReadonlyArray<{ label: string; value: KeywordShareUsedDays }> = [ @@ -296,12 +184,6 @@ const USED_DAYS_OPTIONS: ReadonlyArray<{ label: string; value: KeywordShareUsedD { label: '近360天', value: 360 }, ] -const LOG_TYPE_TABS: ReadonlyArray<{ label: string; value: KeywordShareLogType }> = [ - { label: '使用', value: 'usage' }, - { label: '添加', value: 'add' }, - { label: '删除', value: 'delete' }, -] - // ---- 筛选状态 ---- const filterCountry = ref('') const filterCategory = ref('') @@ -475,162 +357,11 @@ function removeKeyword(row: KeywordShareRow) { }) } -// ---- 添加弹窗 ---- +// ---- 弹窗开关(内容、请求与分页状态由各弹窗组件自持)---- const addDialogVisible = ref(false) -const addRows = ref([]) -const addSubmitting = ref(false) -const addResultText = ref('') - -function openAddDialog() { - addRows.value = [{ country: filterCountry.value, keyword: '', chinese: '' }] - addResultText.value = '' - addDialogVisible.value = true -} - -function addAddRow() { - addRows.value.push({ country: filterCountry.value, keyword: '', chinese: '' }) -} - -function removeAddRow(index: number) { - if (addRows.value.length <= 1) return - addRows.value.splice(index, 1) -} - -function submitAdd() { - const items = addRows.value - .map((row) => ({ - country: String(row.country ?? '').trim(), - keyword: String(row.keyword ?? '').trim(), - chinese: String(row.chinese ?? '').trim(), - })) - .filter((row) => row.country && row.keyword) - if (!items.length) { - ElMessage.warning('请至少填写一行完整的关键词(国家 + 关键词)') - return - } - addSubmitting.value = true - addKeywordShareKeywords(items) - .then((data) => { - addSubmitting.value = false - addResultText.value = `新增 ${data.added} 条,跳过(重复)${data.skipped} 条` - ElMessage.success(addResultText.value) - reloadFromFirstPage() - }) - .catch((error: unknown) => { - addSubmitting.value = false - ElMessage.error(error instanceof Error ? error.message : '添加失败') - }) -} - -// ---- 词库统计弹窗 ---- const statsDialogVisible = ref(false) -const statsGroupedRows = ref>([]) -const statsPage = ref(1) - -const pagedStatsGrouped = computed(() => - statsGroupedRows.value.slice((statsPage.value - 1) * STATS_PAGE_SIZE, statsPage.value * STATS_PAGE_SIZE), -) - -function openStatsDialog() { - statsDialogVisible.value = true - fetchKeywordShareStatsGrouped() - .then((data) => { - // /stats-grouped 的返回结构按后端实现演进,这里统一做兼容映射 - statsGroupedRows.value = normalizeKeywordStatsGrouped(data) - statsPage.value = 1 - }) - .catch((error: unknown) => { - statsGroupedRows.value = [] - ElMessage.error(error instanceof Error ? error.message : '词库统计加载失败') - }) -} - -// ---- 随机抽词弹窗 ---- const randomDialogVisible = ref(false) -const randomLoading = ref(false) -const randomRows = ref([]) -const randomMarking = ref(false) - -const randomMarkableRows = computed(() => randomRows.value.filter((row) => !row.used)) - -function openRandomDialog() { - randomLoading.value = true - fetchKeywordShareRandom(10) - .then((data) => { - randomLoading.value = false - randomRows.value = Array.isArray(data) ? data : [] - randomDialogVisible.value = true - }) - .catch((error: unknown) => { - randomLoading.value = false - ElMessage.error(error instanceof Error ? error.message : '随机抽词失败') - }) -} - -function markRandomRows() { - const items = randomMarkableRows.value.map((row) => ({ - country: String(row.country ?? ''), - keyword: String(row.keyword ?? ''), - })) - if (!items.length) return - randomMarking.value = true - markKeywordShareUsage(items) - .then((data) => { - randomMarking.value = false - ElMessage.success(`已标记 ${data.marked} 条为已使用`) - randomRows.value = randomRows.value.map((row) => ({ ...row, used: true })) - void loadList() - }) - .catch((error: unknown) => { - randomMarking.value = false - ElMessage.error(error instanceof Error ? error.message : '标记失败') - }) -} - -// ---- 团队共享记录弹窗 ---- const logsDialogVisible = ref(false) -const logType = ref('usage') -const logRows = ref([]) -const logTotal = ref(0) -const logPage = ref(1) - -function formatLogType(type: unknown): string { - if (type === 'usage') return '使用' - if (type === 'add') return '添加' - if (type === 'delete') return '删除' - return String(type ?? '—') -} - -function loadLogs() { - fetchKeywordShareLogs({ type: logType.value, page: logPage.value, size: LOG_PAGE_SIZE }) - .then((data) => { - logRows.value = Array.isArray(data?.rows) ? data.rows : [] - logTotal.value = Number(data?.total) || 0 - }) - .catch((error: unknown) => { - logRows.value = [] - logTotal.value = 0 - ElMessage.error(error instanceof Error ? error.message : '共享记录加载失败') - }) -} - -function openLogsDialog() { - logsDialogVisible.value = true - logType.value = 'usage' - logPage.value = 1 - void loadLogs() -} - -function switchLogType(type: KeywordShareLogType) { - logType.value = type - logPage.value = 1 - void loadLogs() -} - -function onLogPageChange(next: number) { - logPage.value = next - void loadLogs() -} onMounted(() => { loadFilters() @@ -830,75 +561,6 @@ onBeforeUnmount(() => { cursor: not-allowed; } -.add-rows { - display: flex; - flex-direction: column; - gap: 10px; - margin-bottom: 14px; -} - -.add-row { - display: flex; - align-items: center; - gap: 10px; -} - -.add-country { - width: 130px; - flex-shrink: 0; -} - -.add-keyword { - flex: 1; -} - -.add-chinese { - flex: 1; -} - -.dialog-btn-row { - display: flex; - justify-content: flex-end; - gap: 10px; -} - -.dialog-result { - margin: 10px 0 0; - color: #86efac; - font-size: 13px; -} - -.dialog-empty { - color: #a0acbe; - font-size: 13px; - padding: 20px 0; - text-align: center; -} - -.logs-tabs { - display: flex; - gap: 8px; - margin-bottom: 12px; -} - -.logs-tab { - padding: 7px 18px; - border: 1px solid #3e4a62; - border-radius: 6px; - background: #2b3447; - color: #c8d2e2; - font-size: 13px; - font-weight: 700; - font-family: inherit; - cursor: pointer; -} - -.logs-tab--active { - border-color: #22c55e; - background: #12301f; - color: #86efac; -} - @media (max-width: 1100px) { .filter-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); diff --git a/frontend-vue/src/shared/api/types/modules/keyword-share.ts b/frontend-vue/src/shared/api/types/modules/keyword-share.ts index d8273fd30..80d3c1d61 100644 --- a/frontend-vue/src/shared/api/types/modules/keyword-share.ts +++ b/frontend-vue/src/shared/api/types/modules/keyword-share.ts @@ -172,7 +172,7 @@ export function fetchKeywordShareFilters() { export function fetchKeywordShareStatsGrouped() { return unwrapJavaResponse( - get>(`${JAVA_API_PREFIX}/keyword-share/stats-grouped`), + get>(`${JAVA_API_PREFIX}/keyword-share/stats-grouped`), ) } @@ -219,7 +219,7 @@ export function unmarkKeywordShareUsage(items: KeywordShareUsageItem[]) { export function fetchKeywordShareLogs(query: KeywordShareLogsQuery) { return unwrapJavaResponse( - get>(`${JAVA_API_PREFIX}/keyword-share/logs`, { + get>(`${JAVA_API_PREFIX}/keyword-share/logs`, { params: { type: query.type, country: query.country || undefined, @@ -227,7 +227,7 @@ export function fetchKeywordShareLogs(query: KeywordShareLogsQuery) { size: query.size ?? 20, }, }), - ) + ).then((raw) => mapKeywordShareLogs(raw, query.type)) } export function fetchKeywordShareRandom(count = 10) { @@ -238,53 +238,105 @@ export function fetchKeywordShareRandom(count = 10) { ) } -export interface KeywordStatsGroupedRow { - country: string - category: string +/** 后端 /stats-grouped 的四段分布(对齐桌面版词库统计弹窗:国家 / 一级 / 二级 / 三级) */ +export interface KeywordShareStatsGroupedVo { + byCountry?: Array<{ name?: string | null; count?: number | string | null }> | null + byCategory?: Array<{ name?: string | null; count?: number | string | null }> | null + bySubCategory?: Array<{ category?: string | null; name?: string | null; count?: number | string | null }> | null + byCategoryL3?: Array<{ + category?: string | null + subCategory?: string | null + name?: string | null + count?: number | string | null + }> | null +} + +/** 弹窗一行:group 是所属上级(二级/三级段用),label 是本段名称 */ +export interface KeywordStatsItem { + group: string + label: string count: number } -/** - * 词库统计弹窗的兼容映射:/stats-grouped 的返回结构按后端实现演进, - * 这里把已知形状统一拍平成「国家 × 一级类目 → 计数」行: - * ① { rows: [{country, category, count}] }; - * ② [{country, category, count}] 数组; - * ③ { 国家: { 类目: 数值 } } 二层映射。 - * 其余形状返回空数组(弹窗显示「暂无数据」,不报错)。 - */ -export function normalizeKeywordStatsGrouped(raw: unknown): KeywordStatsGroupedRow[] { - const rows: KeywordStatsGroupedRow[] = [] - - const pushRow = (country: unknown, category: unknown, count: unknown) => { - const c = String(country ?? '').trim() - const cat = String(category ?? '').trim() - const n = Number(count) - if (!c || !cat || !Number.isFinite(n)) return - rows.push({ country: c, category: cat, count: n }) - } - - if (Array.isArray(raw)) { - for (const item of raw) { - if (item && typeof item === 'object') { - const record = item as Record - pushRow(record.country, record.category, record.count) - } - } - return rows - } - - if (raw && typeof raw === 'object') { - const record = raw as Record - if (Array.isArray(record.rows)) { - return normalizeKeywordStatsGrouped(record.rows) - } - for (const [country, value] of Object.entries(record)) { - if (!value || typeof value !== 'object' || Array.isArray(value)) continue - for (const [category, count] of Object.entries(value as Record)) { - pushRow(country, category, count) - } - } - } - - return rows +export interface KeywordStatsSections { + byCountry: KeywordStatsItem[] + byCategory: KeywordStatsItem[] + bySubCategory: KeywordStatsItem[] + byCategoryL3: KeywordStatsItem[] +} + +function statsCount(value: unknown): number | null { + // Number(null) 与 Number('') 都是 0——缺计数的脏行必须判无效丢弃,不能冒充「0 个词」 + if (value === null || value === undefined || value === '') return null + const n = Number(value) + return Number.isFinite(n) ? n : null +} + +/** + * /stats-grouped → 四段分布。后端返回的是四份各自 GROUP BY 的清单(不是国家×类目交叉表), + * 缺段/脏行按空处理,弹窗对应段显示「暂无数据」而不是整窗报错。 + */ +export function buildKeywordStatsSections(raw: unknown): KeywordStatsSections { + const source = (raw && typeof raw === 'object' ? raw : {}) as KeywordShareStatsGroupedVo + const flat = ( + rows: Array<{ name?: string | null; count?: number | string | null }> | null | undefined, + groupOf: (row: { name?: string | null; count?: number | string | null }) => string, + ): KeywordStatsItem[] => + (Array.isArray(rows) ? rows : []).flatMap((row) => { + const label = String(row?.name ?? '').trim() + const count = statsCount(row?.count) + if (!label || count === null) return [] + return [{ group: groupOf(row), label, count }] + }) + + return { + byCountry: flat(source.byCountry, () => ''), + byCategory: flat(source.byCategory, () => ''), + bySubCategory: flat(source.bySubCategory, (row) => String((row as { category?: string | null }).category ?? '').trim()), + byCategoryL3: flat(source.byCategoryL3, (row) => { + const item = row as { category?: string | null; subCategory?: string | null } + const category = String(item.category ?? '').trim() + const sub = String(item.subCategory ?? '').trim() + return [category, sub].filter(Boolean).join(' / ') + }), + } +} + +/** 后端日志行字段名与展示口径不同(userName/time),映射到表格用的 operator/createdAt */ +export interface KeywordShareLogRawRow { + id?: number | string + userName?: string | null + country?: string | null + keyword?: string | null + /** Jackson 默认 ISO-8601(2026-10-23T21:12:34),也可能带毫秒 */ + time?: string | null +} + +export interface KeywordShareLogRawVo { + total?: number | string + rows?: KeywordShareLogRawRow[] | null +} + +/** ISO 时间 → 'YYYY-MM-DD HH:mm:ss';非 ISO 形态原样透出,空值给空串 */ +export function formatLogTime(raw?: string | null): string { + const value = String(raw ?? '').trim() + if (!value) return '' + const matched = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2})/.exec(value) + return matched ? `${matched[1]} ${matched[2]}` : value +} + +export function mapKeywordShareLogs(raw: unknown, type?: KeywordShareLogType): KeywordShareLogsVo { + const source = (raw && typeof raw === 'object' ? raw : {}) as KeywordShareLogRawVo + const rows = Array.isArray(source.rows) ? source.rows : [] + return { + total: Number.isFinite(Number(source.total)) ? Number(source.total) : rows.length, + rows: rows.map((row) => ({ + id: row?.id, + type, + country: row?.country ?? null, + keyword: row?.keyword ?? null, + operator: row?.userName ?? null, + createdAt: formatLogTime(row?.time), + })), + } } diff --git a/frontend-vue/tests/keyword-share-api.test.ts b/frontend-vue/tests/keyword-share-api.test.ts new file mode 100644 index 000000000..661cac8c0 --- /dev/null +++ b/frontend-vue/tests/keyword-share-api.test.ts @@ -0,0 +1,73 @@ +import test from 'node:test' +import assert from 'node:assert/strict' + +import { + buildKeywordStatsSections, + formatLogTime, + mapKeywordShareLogs, +} from '../src/shared/api/types/modules/keyword-share.ts' + +test('buildKeywordStatsSections:后端四段各自成段,二级/三级带上级分组', () => { + const sections = buildKeywordStatsSections({ + byCountry: [{ name: '英国', count: 1200 }, { name: '德国', count: 800 }], + byCategory: [{ name: '3C', count: 900 }], + bySubCategory: [{ category: '3C', name: '充电器', count: 300 }], + byCategoryL3: [{ category: '3C', subCategory: '充电器', name: '无线充', count: 90 }], + }) + assert.deepEqual(sections.byCountry, [ + { group: '', label: '英国', count: 1200 }, + { group: '', label: '德国', count: 800 }, + ]) + assert.deepEqual(sections.byCategory, [{ group: '', label: '3C', count: 900 }]) + assert.deepEqual(sections.bySubCategory, [{ group: '3C', label: '充电器', count: 300 }]) + assert.deepEqual(sections.byCategoryL3, [{ group: '3C / 充电器', label: '无线充', count: 90 }]) +}) + +test('buildKeywordStatsSections:缺段/脏行按空处理,不抛错(弹窗显示暂无数据)', () => { + const sections = buildKeywordStatsSections({ + byCountry: [{ name: '', count: 5 }, { name: '法国', count: null }, { name: '西班牙', count: 7 }], + byCategory: null, + }) + assert.deepEqual(sections.byCountry, [{ group: '', label: '西班牙', count: 7 }]) + assert.deepEqual(sections.byCategory, []) + assert.deepEqual(sections.bySubCategory, []) + assert.deepEqual(sections.byCategoryL3, []) + assert.deepEqual(buildKeywordStatsSections(undefined).byCountry, []) +}) + +test('mapKeywordShareLogs:userName/time 映射到 operator/createdAt,ISO 时间转可读', () => { + const vo = mapKeywordShareLogs( + { + total: 2, + rows: [ + { id: 1, userName: '张三', country: '英国', keyword: 'wireless charger', time: '2026-10-23T21:12:34' }, + { id: 2, userName: '李四', country: '德国', keyword: 'usb c hub', time: '2026-10-22T09:00:01.000' }, + ], + }, + 'usage', + ) + assert.equal(vo.total, 2) + assert.deepEqual(vo.rows[0], { + id: 1, + type: 'usage', + country: '英国', + keyword: 'wireless charger', + operator: '张三', + createdAt: '2026-10-23 21:12:34', + }) + assert.equal(vo.rows[1]?.createdAt, '2026-10-22 09:00:01') +}) + +test('mapKeywordShareLogs:空返回与缺 total 时按行数兜底,不造出幽灵记录', () => { + assert.deepEqual(mapKeywordShareLogs(undefined), { total: 0, rows: [] }) + const vo = mapKeywordShareLogs({ rows: [{ userName: '王五' }] }) + assert.equal(vo.total, 1) + assert.equal(vo.rows[0]?.country, null) + assert.equal(vo.rows[0]?.createdAt, '') +}) + +test('formatLogTime:非 ISO 形态原样透出,空值给空串', () => { + assert.equal(formatLogTime('2026-10-23 21:12:34'), '2026-10-23 21:12:34') + assert.equal(formatLogTime('刚刚'), '刚刚') + assert.equal(formatLogTime(null), '') +}) diff --git a/frontend-vue/tests/mount/keyword-share-page.mount.test.ts b/frontend-vue/tests/mount/keyword-share-page.mount.test.ts index 63c2b0b24..8ba8fec49 100644 --- a/frontend-vue/tests/mount/keyword-share-page.mount.test.ts +++ b/frontend-vue/tests/mount/keyword-share-page.mount.test.ts @@ -15,7 +15,7 @@ import ElementPlus from 'element-plus' import KeywordSharePage from '@/pages/common/KeywordSharePage.vue' -// API 层整模块 mock:纯函数(normalizeKeywordStatsGrouped)保留真实现, +// API 层整模块 mock:纯函数(buildKeywordStatsSections / mapKeywordShareLogs)保留真实现, // 网络函数按用例给桩。页面经 shared/api/types/modules/keyword-share 调用。 const api = vi.hoisted(() => ({ fetchKeywordShareFilters: vi.fn(),
{{ addResultText }}