feat(keywordusage): 新增关键词使用记录并归位店铺管理菜单
V175 把品牌Gating库从数据管理组迁到店铺管理组(排序85),并在其后新增 关键词使用记录独立菜单(排序86)。后端新增只读查询模块,按公司范围读取 keyword_usage/keyword_add_log/keyword_delete_log,前端提供使用/删除记录、 统计卡与筛选。
This commit is contained in:
@@ -41,6 +41,8 @@ export const COMPANY_SCOPED_PAGES: readonly CompanyScopedPage[] = [
|
||||
// 而是「本公司账号名下的店铺」:后端由 DataReadScope 把公司 → 成员账号 → biz_shop_manage.created_by_id 逐级推导,
|
||||
// 前端只负责把 activeId 当 company_id 送下去。
|
||||
{ menuKey: 'admin_shop_data_duplicate_check', apiFiles: ['src/pages/tasks/duplicate-console-api.ts'], pageFiles: ['src/pages/tasks/DuplicateCheckPage.vue'] },
|
||||
// 关键词使用记录(2026-10-25):只读留痕按行 company_id 收窄;超管切 tab 重取,非超管后端强制本公司。
|
||||
{ menuKey: 'admin_keyword_usage', apiFiles: ['src/pages/tasks/keyword-usage-api.ts'], pageFiles: ['src/pages/tasks/KeywordUsagePage.vue'] },
|
||||
{ menuKey: 'admin_shop_data_crawl_tasks', apiFiles: ['src/pages/tasks/shop-data-api.ts'], pageFiles: ['src/pages/tasks/ShopDataTasksPage.vue'] },
|
||||
// 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」)。
|
||||
// 这一页的后端早就认 company_id(AdminUserService 只在**站点超管**身上用它筛,公司超管恒锁本公司),
|
||||
|
||||
@@ -76,6 +76,10 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
|
||||
text: '维护不符合规则的品牌(品牌Gating / 类目Gating)。新增后可用下方筛选快速回查;云端 Gating 库与前端排查软件同步同一份数据,命中后会自动拦截。',
|
||||
steps: ['新增或批量导入', '筛选回查', '按需解除或删除'],
|
||||
},
|
||||
admin_keyword_usage: {
|
||||
text: '本页记录所有关键词操作,只读、不可删除、永久留痕可追溯;与桌面端互通:桌面复制、添加、删除关键词会自动写入本页,两端同源。',
|
||||
steps: ['选择公司与筛选条件', '切换使用/删除记录', '核对操作人与时间'],
|
||||
},
|
||||
// admin_shop_data_duplicate_check(店铺撞款监控)为例外页:不展示全局提示条,不参与对齐。
|
||||
admin_image_video_tasks: {
|
||||
text: '可先使用筛选缩小任务范围,再查看任务状态、结果和权限范围。',
|
||||
|
||||
@@ -0,0 +1,528 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 关键词使用记录(独立菜单 admin_keyword_usage):只读展示 keyword_usage / keyword_add_log /
|
||||
* keyword_delete_log,按公司 tab 取数。口径对齐独立小网页后台 v1.2.6g。
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
import {
|
||||
KEYWORD_USAGE_SCENES,
|
||||
createKeywordUsageFilter,
|
||||
keywordUsageCountsText,
|
||||
keywordUsageSceneLabel,
|
||||
type KeywordUsageCounts,
|
||||
type KeywordUsageFilter,
|
||||
type KeywordUsageOverview,
|
||||
type KeywordUsageRow,
|
||||
} from './keyword-usage-model.ts'
|
||||
import {
|
||||
fetchKeywordUsage,
|
||||
fetchKeywordUsageDeletes,
|
||||
fetchKeywordUsageOverview,
|
||||
} from './keyword-usage-api.ts'
|
||||
|
||||
const companyTab = useCompanyTabStore()
|
||||
const session = useAdminSessionStore()
|
||||
const me = computed(() => session.user?.username || '')
|
||||
|
||||
const filter = reactive<KeywordUsageFilter>(createKeywordUsageFilter())
|
||||
const activeTab = ref<'usage' | 'deletes'>('usage')
|
||||
const loadError = ref('')
|
||||
|
||||
const overview = ref<KeywordUsageOverview | null>(null)
|
||||
const overviewLoading = ref(false)
|
||||
|
||||
const usageRows = ref<KeywordUsageRow[]>([])
|
||||
const usageTotal = ref(0)
|
||||
const usagePage = ref(1)
|
||||
const usagePageSize = ref(15)
|
||||
const usageCounts = ref<KeywordUsageCounts>({ copy: 0, copyExisting: 0, copyDeleted: 0, add: 0 })
|
||||
const usageLoading = ref(false)
|
||||
|
||||
const deleteRows = ref<KeywordUsageRow[]>([])
|
||||
const deleteTotal = ref(0)
|
||||
const deletePage = ref(1)
|
||||
const deletePageSize = ref(15)
|
||||
const deleteLoading = ref(false)
|
||||
|
||||
const statsCards = computed(() => {
|
||||
const stats = overview.value?.stats
|
||||
return [
|
||||
{ label: '复制关键词', value: stats?.used ?? 0, tone: 'primary' },
|
||||
{ label: '现存词', value: stats?.exist ?? 0, tone: 'ok' },
|
||||
{ label: '已删除词留痕', value: stats?.deletedKw ?? 0, tone: 'danger' },
|
||||
{ label: '添加关键词', value: stats?.added ?? 0, tone: 'info' },
|
||||
{ label: '使用记录合计', value: stats?.totalUse ?? 0, tone: '' },
|
||||
{ label: '删除记录', value: stats?.deletes ?? 0, tone: 'violet' },
|
||||
]
|
||||
})
|
||||
const userOptions = computed(() => overview.value?.users ?? [])
|
||||
const countryOptions = computed(() => overview.value?.countries ?? [])
|
||||
const usageSummary = computed(() => keywordUsageCountsText(usageCounts.value, usageTotal.value))
|
||||
|
||||
function queryParams() {
|
||||
return {
|
||||
companyId: companyTab.requestCompanyId,
|
||||
user: filter.user,
|
||||
country: filter.country,
|
||||
keyword: filter.keyword.trim(),
|
||||
scene: filter.scene,
|
||||
}
|
||||
}
|
||||
|
||||
async function loadOverview(): Promise<void> {
|
||||
overviewLoading.value = true
|
||||
try {
|
||||
overview.value = await fetchKeywordUsageOverview({ companyId: companyTab.requestCompanyId })
|
||||
} catch (error) {
|
||||
loadError.value = actionableErrorText(error)
|
||||
} finally {
|
||||
overviewLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadUsage(page = usagePage.value): Promise<void> {
|
||||
usageLoading.value = true
|
||||
try {
|
||||
const result = await fetchKeywordUsage({ ...queryParams(), page, pageSize: usagePageSize.value })
|
||||
usageRows.value = result.rows
|
||||
usageTotal.value = result.total
|
||||
usageCounts.value = result.counts
|
||||
usagePage.value = page
|
||||
} catch (error) {
|
||||
loadError.value = actionableErrorText(error)
|
||||
} finally {
|
||||
usageLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDeletes(page = deletePage.value): Promise<void> {
|
||||
deleteLoading.value = true
|
||||
try {
|
||||
const result = await fetchKeywordUsageDeletes({ ...queryParams(), page, pageSize: deletePageSize.value })
|
||||
deleteRows.value = result.rows
|
||||
deleteTotal.value = result.total
|
||||
deletePage.value = page
|
||||
} catch (error) {
|
||||
loadError.value = actionableErrorText(error)
|
||||
} finally {
|
||||
deleteLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function reload(): Promise<void> {
|
||||
loadError.value = ''
|
||||
await Promise.all([loadOverview(), loadUsage(1), loadDeletes(1)])
|
||||
}
|
||||
|
||||
function query(): void {
|
||||
loadError.value = ''
|
||||
void Promise.all([loadUsage(1), loadDeletes(1)])
|
||||
}
|
||||
|
||||
function reset(): void {
|
||||
Object.assign(filter, createKeywordUsageFilter())
|
||||
query()
|
||||
}
|
||||
|
||||
function changeUsagePageSize(size: number): void {
|
||||
usagePageSize.value = size
|
||||
void loadUsage(1)
|
||||
}
|
||||
|
||||
function changeDeletePageSize(size: number): void {
|
||||
deletePageSize.value = size
|
||||
void loadDeletes(1)
|
||||
}
|
||||
|
||||
watch(() => companyTab.activeId, () => {
|
||||
filter.user = ''
|
||||
filter.country = ''
|
||||
usagePage.value = 1
|
||||
deletePage.value = 1
|
||||
void reload()
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
void reload()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="kw-page">
|
||||
<LoadFailureBar v-if="loadError" :message="loadError" @retry="reload" />
|
||||
|
||||
<section class="kw-cards" v-loading="overviewLoading">
|
||||
<div v-for="card in statsCards" :key="card.label" class="kw-card" :class="card.tone">
|
||||
<div class="kw-n">{{ card.value.toLocaleString() }}</div>
|
||||
<div class="kw-t">{{ card.label }}</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="kw-panel">
|
||||
<div class="kw-panel-head">筛选条件</div>
|
||||
<div class="kw-panel-body">
|
||||
<div class="kw-filters">
|
||||
<label class="kw-field">
|
||||
<span>使用者</span>
|
||||
<select v-model="filter.user">
|
||||
<option value="">全部使用者</option>
|
||||
<option v-for="user in userOptions" :key="user" :value="user">{{ user }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="kw-field">
|
||||
<span>国家</span>
|
||||
<select v-model="filter.country">
|
||||
<option value="">全部国家</option>
|
||||
<option v-for="country in countryOptions" :key="country" :value="country">{{ country }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="kw-field kw-field-wide">
|
||||
<span>关键词</span>
|
||||
<input v-model="filter.keyword" placeholder="搜索关键词" @keyup.enter="query" />
|
||||
</label>
|
||||
<label class="kw-field">
|
||||
<span>场景</span>
|
||||
<select v-model="filter.scene">
|
||||
<option value="">全部场景</option>
|
||||
<option v-for="scene in KEYWORD_USAGE_SCENES" :key="scene" :value="scene">{{ scene }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="kw-actions">
|
||||
<button class="kw-btn kw-btn-primary" type="button" @click="query">查询</button>
|
||||
<button class="kw-btn kw-btn-ghost" type="button" @click="reset">重置</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="kw-tabs">
|
||||
<button class="kw-tab" :class="{ active: activeTab === 'usage' }" type="button" @click="activeTab = 'usage'">使用记录</button>
|
||||
<button class="kw-tab" :class="{ active: activeTab === 'deletes' }" type="button" @click="activeTab = 'deletes'">删除记录</button>
|
||||
</div>
|
||||
|
||||
<section v-show="activeTab === 'usage'" class="kw-panel">
|
||||
<div class="kw-panel-head">
|
||||
使用记录
|
||||
<span class="kw-sub">复制关键词 + 添加关键词,按时间倒序;绿色为本人的记录</span>
|
||||
</div>
|
||||
<div class="kw-panel-body">
|
||||
<div class="kw-table-wrap" v-loading="usageLoading">
|
||||
<table v-if="usageRows.length" class="kw-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 130px">使用者</th>
|
||||
<th style="width: 90px">国家</th>
|
||||
<th>关键词</th>
|
||||
<th style="width: 140px">使用场景</th>
|
||||
<th style="width: 170px">使用时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(row, index) in usageRows" :key="`usage-${row.time}-${index}`" :class="{ mine: row.userName === me }">
|
||||
<td class="kw-user">{{ row.userName || '—' }}</td>
|
||||
<td>{{ row.country || '—' }}</td>
|
||||
<td class="kw-keyword">{{ row.keyword || '—' }}</td>
|
||||
<td>
|
||||
<span class="kw-tag" :class="row.scene === '添加关键词' ? 'add' : 'copy'">
|
||||
{{ keywordUsageSceneLabel(row.scene) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="kw-time">{{ formatDateTime(row.time) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-else-if="!usageLoading" class="kw-empty">暂无使用记录</div>
|
||||
</div>
|
||||
<div class="kw-footer">
|
||||
<span class="kw-summary">{{ usageSummary }}</span>
|
||||
<OldPagination
|
||||
v-if="usageTotal"
|
||||
:total="usageTotal"
|
||||
:page="usagePage"
|
||||
:page-size="usagePageSize"
|
||||
@change="loadUsage"
|
||||
@size-change="changeUsagePageSize"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-show="activeTab === 'deletes'" class="kw-panel">
|
||||
<div class="kw-panel-head">
|
||||
删除记录
|
||||
<span class="kw-sub">只读、不可删除、永久留痕可追溯;红色为本人的记录</span>
|
||||
</div>
|
||||
<div class="kw-panel-body">
|
||||
<div class="kw-table-wrap" v-loading="deleteLoading">
|
||||
<table v-if="deleteRows.length" class="kw-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 130px">删除者</th>
|
||||
<th style="width: 90px">国家</th>
|
||||
<th>关键词</th>
|
||||
<th style="width: 170px">删除时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(row, index) in deleteRows" :key="`delete-${row.time}-${index}`" :class="{ mine: row.userName === me }">
|
||||
<td class="kw-user">{{ row.userName || '—' }}</td>
|
||||
<td>{{ row.country || '—' }}</td>
|
||||
<td class="kw-keyword">{{ row.keyword || '—' }}</td>
|
||||
<td class="kw-time">{{ formatDateTime(row.time) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-else-if="!deleteLoading" class="kw-empty">暂无删除记录</div>
|
||||
</div>
|
||||
<div class="kw-footer">
|
||||
<span class="kw-summary">共 {{ deleteTotal }} 条删除记录 · 只读留痕</span>
|
||||
<OldPagination
|
||||
v-if="deleteTotal"
|
||||
:total="deleteTotal"
|
||||
:page="deletePage"
|
||||
:page-size="deletePageSize"
|
||||
@change="loadDeletes"
|
||||
@size-change="changeDeletePageSize"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.kw-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.kw-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.kw-card {
|
||||
background: #fff;
|
||||
border: 1px solid #e5e9f0;
|
||||
border-top: 3px solid #9ca3af;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 1px 2px rgba(20, 30, 60, 0.05), 0 4px 18px rgba(20, 30, 60, 0.06);
|
||||
padding: 12px 14px;
|
||||
}
|
||||
.kw-card.primary { border-top-color: #2e5be6; }
|
||||
.kw-card.ok { border-top-color: #1f9d62; }
|
||||
.kw-card.danger { border-top-color: #d63a4a; }
|
||||
.kw-card.info { border-top-color: #0d9488; }
|
||||
.kw-card.violet { border-top-color: #7c5cd6; }
|
||||
.kw-card .kw-n {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
color: #1c2230;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.kw-card .kw-t {
|
||||
margin-top: 3px;
|
||||
font-size: 11.5px;
|
||||
color: #98a1b1;
|
||||
}
|
||||
|
||||
.kw-panel {
|
||||
background: #fff;
|
||||
border: 1px solid #e5e9f0;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 1px 2px rgba(20, 30, 60, 0.05), 0 4px 18px rgba(20, 30, 60, 0.06);
|
||||
overflow: hidden;
|
||||
}
|
||||
.kw-panel-head {
|
||||
padding: 11px 15px;
|
||||
background: #fafbfd;
|
||||
border-bottom: 1px solid #e9edf3;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
color: #1c2230;
|
||||
}
|
||||
.kw-panel-head::before {
|
||||
content: "";
|
||||
display: inline-block;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 2px;
|
||||
background: #2dd4bf;
|
||||
margin-right: 8px;
|
||||
vertical-align: 1px;
|
||||
}
|
||||
.kw-sub {
|
||||
margin-left: 8px;
|
||||
font-size: 11.5px;
|
||||
font-weight: 400;
|
||||
color: #98a1b1;
|
||||
}
|
||||
.kw-panel-body {
|
||||
padding: 14px 15px;
|
||||
}
|
||||
|
||||
.kw-filters {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 10px 12px;
|
||||
}
|
||||
.kw-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
min-width: 150px;
|
||||
}
|
||||
.kw-field-wide {
|
||||
min-width: 220px;
|
||||
}
|
||||
.kw-field > span {
|
||||
font-size: 12px;
|
||||
color: #5a6474;
|
||||
}
|
||||
.kw-field input,
|
||||
.kw-field select {
|
||||
height: 34px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid #d7dce5;
|
||||
border-radius: 7px;
|
||||
background: #fbfcfe;
|
||||
color: #1c2230;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
outline: none;
|
||||
}
|
||||
.kw-field input:focus,
|
||||
.kw-field select:focus {
|
||||
border-color: #2e5be6;
|
||||
box-shadow: 0 0 0 3px rgba(46, 91, 230, 0.12);
|
||||
background: #fff;
|
||||
}
|
||||
.kw-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.kw-btn {
|
||||
height: 34px;
|
||||
padding: 0 15px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 7px;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
.kw-btn-primary {
|
||||
background: #2e5be6;
|
||||
border-color: #2e5be6;
|
||||
color: #fff;
|
||||
}
|
||||
.kw-btn-primary:hover { background: #1e4bd8; border-color: #1e4bd8; }
|
||||
.kw-btn-ghost {
|
||||
background: #fff;
|
||||
border-color: #d7dce5;
|
||||
color: #5a6474;
|
||||
}
|
||||
.kw-btn-ghost:hover { border-color: #2e5be6; color: #2e5be6; }
|
||||
|
||||
.kw-tabs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
background: #fff;
|
||||
border: 1px solid #e5e9f0;
|
||||
border-radius: 9px;
|
||||
padding: 4px;
|
||||
align-self: flex-start;
|
||||
}
|
||||
.kw-tab {
|
||||
padding: 7px 18px;
|
||||
border: none;
|
||||
border-radius: 7px;
|
||||
background: none;
|
||||
color: #5a6474;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
.kw-tab:hover { color: #2e5be6; }
|
||||
.kw-tab.active { background: #2e5be6; color: #fff; }
|
||||
|
||||
.kw-table-wrap {
|
||||
overflow-x: auto;
|
||||
border: 1px solid #e5e9f0;
|
||||
border-radius: 9px;
|
||||
min-height: 90px;
|
||||
}
|
||||
.kw-table {
|
||||
width: 100%;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.kw-table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
padding: 10px;
|
||||
background: #f7f9fc;
|
||||
border-bottom: 1px solid #e5e9f0;
|
||||
color: #5a6474;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.kw-table td {
|
||||
padding: 9px 10px;
|
||||
border-bottom: 1px solid #eff2f7;
|
||||
color: #1c2230;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.kw-table tbody tr:hover td { background: #f7faff; }
|
||||
.kw-table tbody tr:last-child td { border-bottom: none; }
|
||||
.kw-table tr.mine td { color: #0f9d58; font-weight: 600; }
|
||||
.kw-user { font-weight: 500; }
|
||||
.kw-keyword { max-width: 320px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.kw-time { color: #5a6474; font-size: 11.5px; }
|
||||
|
||||
.kw-tag {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.kw-tag.copy { background: #e8f7f4; color: #0d9488; }
|
||||
.kw-tag.add { background: #eff6ff; color: #2563eb; }
|
||||
|
||||
.kw-empty {
|
||||
padding: 42px 16px;
|
||||
text-align: center;
|
||||
color: #98a1b1;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.kw-footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.kw-summary {
|
||||
font-size: 11.5px;
|
||||
color: #98a1b1;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,39 @@
|
||||
/** 关键词使用记录接口适配:/api/admin/keyword-usage 的使用记录、删除记录与概览。 */
|
||||
import { http } from '@/api/http'
|
||||
import { unwrap } from '@/api/envelope'
|
||||
import {
|
||||
parseKeywordUsageOverview,
|
||||
parseKeywordUsagePage,
|
||||
type KeywordUsageOverview,
|
||||
type KeywordUsagePage,
|
||||
type KeywordUsageQuery,
|
||||
} from './keyword-usage-model.ts'
|
||||
|
||||
export const KEYWORD_USAGE_ENDPOINT = '/api/admin/keyword-usage'
|
||||
|
||||
function toQuery(params: KeywordUsageQuery): Record<string, unknown> {
|
||||
const query: Record<string, unknown> = {}
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
if (params.user) query.user = params.user
|
||||
if (params.country) query.country = params.country
|
||||
if (params.keyword) query.keyword = params.keyword
|
||||
if (params.scene) query.scene = params.scene
|
||||
if (params.page != null) query.page = params.page
|
||||
if (params.pageSize != null) query.page_size = params.pageSize
|
||||
return query
|
||||
}
|
||||
|
||||
export async function fetchKeywordUsage(params: KeywordUsageQuery): Promise<KeywordUsagePage> {
|
||||
const { data } = await http.get<unknown>(KEYWORD_USAGE_ENDPOINT, { params: toQuery(params) })
|
||||
return parseKeywordUsagePage(unwrap<unknown>(data))
|
||||
}
|
||||
|
||||
export async function fetchKeywordUsageDeletes(params: KeywordUsageQuery): Promise<KeywordUsagePage> {
|
||||
const { data } = await http.get<unknown>(`${KEYWORD_USAGE_ENDPOINT}/deletes`, { params: toQuery(params) })
|
||||
return parseKeywordUsagePage(unwrap<unknown>(data))
|
||||
}
|
||||
|
||||
export async function fetchKeywordUsageOverview(params: KeywordUsageQuery): Promise<KeywordUsageOverview> {
|
||||
const { data } = await http.get<unknown>(`${KEYWORD_USAGE_ENDPOINT}/overview`, { params: toQuery(params) })
|
||||
return parseKeywordUsageOverview(unwrap<unknown>(data))
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/** 关键词使用记录(独立菜单 admin_keyword_usage):与 /api/admin/keyword-usage 的 camel 契约对齐,纯逻辑。 */
|
||||
|
||||
export interface KeywordUsageQuery {
|
||||
companyId?: number | null
|
||||
user?: string
|
||||
country?: string
|
||||
keyword?: string
|
||||
scene?: string
|
||||
page?: number
|
||||
pageSize?: number
|
||||
}
|
||||
|
||||
export interface KeywordUsageFilter {
|
||||
user: string
|
||||
country: string
|
||||
keyword: string
|
||||
scene: string
|
||||
}
|
||||
|
||||
export interface KeywordUsageRow {
|
||||
userName: string
|
||||
country: string
|
||||
keyword: string
|
||||
scene: string
|
||||
time: string
|
||||
}
|
||||
|
||||
export interface KeywordUsageCounts {
|
||||
copy: number
|
||||
copyExisting: number
|
||||
copyDeleted: number
|
||||
add: number
|
||||
}
|
||||
|
||||
export interface KeywordUsagePage {
|
||||
total: number
|
||||
rows: KeywordUsageRow[]
|
||||
counts: KeywordUsageCounts
|
||||
}
|
||||
|
||||
export interface KeywordUsageStats {
|
||||
used: number
|
||||
exist: number
|
||||
deletedKw: number
|
||||
added: number
|
||||
totalUse: number
|
||||
deletes: number
|
||||
}
|
||||
|
||||
export interface KeywordUsageOverview {
|
||||
stats: KeywordUsageStats
|
||||
users: string[]
|
||||
countries: string[]
|
||||
}
|
||||
|
||||
export const KEYWORD_USAGE_SCENES = ['已使用', '添加关键词'] as const
|
||||
|
||||
export function createKeywordUsageFilter(): KeywordUsageFilter {
|
||||
return { user: '', country: '', keyword: '', scene: '' }
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null
|
||||
}
|
||||
|
||||
function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value : value == null ? '' : String(value)
|
||||
}
|
||||
|
||||
function count(value: unknown): number {
|
||||
const n = Number(value)
|
||||
return Number.isFinite(n) && n >= 0 ? n : 0
|
||||
}
|
||||
|
||||
function textList(value: unknown): string[] {
|
||||
return Array.isArray(value) ? value.map(text).filter((item) => item !== '') : []
|
||||
}
|
||||
|
||||
export function parseKeywordUsageRow(value: unknown): KeywordUsageRow | null {
|
||||
const row = asRecord(value)
|
||||
if (!row) return null
|
||||
return {
|
||||
userName: text(row.userName),
|
||||
country: text(row.country),
|
||||
keyword: text(row.keyword),
|
||||
scene: text(row.scene),
|
||||
time: text(row.time),
|
||||
}
|
||||
}
|
||||
|
||||
export function parseKeywordUsagePage(value: unknown): KeywordUsagePage {
|
||||
const page = asRecord(value)
|
||||
const counts = asRecord(page?.counts)
|
||||
const rows = Array.isArray(page?.rows)
|
||||
? page.rows.map(parseKeywordUsageRow).filter((row): row is KeywordUsageRow => row !== null)
|
||||
: []
|
||||
return {
|
||||
total: count(page?.total),
|
||||
rows,
|
||||
counts: {
|
||||
copy: count(counts?.copy),
|
||||
copyExisting: count(counts?.copyExisting),
|
||||
copyDeleted: count(counts?.copyDeleted),
|
||||
add: count(counts?.add),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function parseKeywordUsageOverview(value: unknown): KeywordUsageOverview {
|
||||
const overview = asRecord(value)
|
||||
const stats = asRecord(overview?.stats)
|
||||
return {
|
||||
stats: {
|
||||
used: count(stats?.used),
|
||||
exist: count(stats?.exist),
|
||||
deletedKw: count(stats?.deletedKw),
|
||||
added: count(stats?.added),
|
||||
totalUse: count(stats?.totalUse),
|
||||
deletes: count(stats?.deletes),
|
||||
},
|
||||
users: textList(overview?.users),
|
||||
countries: textList(overview?.countries),
|
||||
}
|
||||
}
|
||||
|
||||
export function keywordUsageSceneLabel(scene: string): string {
|
||||
if (scene === '复制关键词') return '已使用(复制)'
|
||||
if (scene === '添加关键词') return '添加关键词'
|
||||
if (scene === '删除关键词') return '删除关键词'
|
||||
return scene || '—'
|
||||
}
|
||||
|
||||
/** 使用记录口径:复制 = 现存词 + 已删除词留痕;添加单列。 */
|
||||
export function keywordUsageCountsText(counts: KeywordUsageCounts, total: number): string {
|
||||
return `复制关键词 ${counts.copy} = 现存词 ${counts.copyExisting} + 已删除词 ${counts.copyDeleted}`
|
||||
+ ` · 添加关键词 ${counts.add} · 合计 ${total} 条`
|
||||
}
|
||||
@@ -26,6 +26,7 @@ export const adminPages: AdminPageDef[] = [
|
||||
{ path: 'account/companies', menuKey: 'admin_companies', title: '公司管理', superAdminOnly: true, load: () => import('@/pages/account/CompaniesPage.vue') },
|
||||
{ path: 'shop-center/duplicate-check', menuKey: 'admin_shop_data_duplicate_check', title: '店铺撞款监控', companyScoped: true, load: () => import('@/pages/tasks/DuplicateCheckPage.vue') },
|
||||
{ path: 'shop-center/brand-gating', menuKey: 'admin_brand_gating', title: '品牌Gating库', companyScoped: false, load: () => import('@/pages/tasks/BrandGatingPanel.vue') },
|
||||
{ path: 'shop-center/keyword-usage', menuKey: 'admin_keyword_usage', title: '关键词使用记录', companyScoped: true, load: () => import('@/pages/tasks/KeywordUsagePage.vue') },
|
||||
{ path: 'shop-center/keys', menuKey: 'admin_shop_keys', title: '店铺密钥管理', companyScoped: true, load: () => import('@/pages/shop/ShopKeysPage.vue') },
|
||||
{ path: 'shop-center/shops', menuKey: 'admin_shop_manage', title: '店铺管理', companyScoped: true, load: () => import('@/pages/shop/ShopManagePage.vue') },
|
||||
{ path: 'records/history', menuKey: 'admin_history', title: '生成记录', companyScoped: true, load: () => import('@/pages/records/RecordsHistoryPage.vue') },
|
||||
|
||||
@@ -13,6 +13,8 @@ const MIGRATION = join(process.cwd(), '..', 'backend-java', 'src', 'main', 'reso
|
||||
'V143__company_and_users_company_id.sql')
|
||||
const BRAND_GATING_MIGRATION = join(process.cwd(), '..', 'backend-java', 'src', 'main', 'resources', 'db',
|
||||
'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')
|
||||
|
||||
interface MigrationMenu {
|
||||
name: string
|
||||
@@ -74,3 +76,22 @@ test('V174 恢复的「品牌Gating库」菜单 key 必须在路由注册表登
|
||||
assert.equal(page.title, gating.name, '页面标题应与菜单名一致')
|
||||
assert.equal(page.companyScoped, false, 'Gating 库全平台共享,不参与公司 tab')
|
||||
})
|
||||
|
||||
test('V175 新增的关键词使用记录菜单 key 必须在路由注册表登记', () => {
|
||||
const sql = readFileSync(KEYWORD_USAGE_MIGRATION, 'utf8')
|
||||
const menus = menusInsertedBy(sql)
|
||||
const insertCount = (sql.match(/INSERT INTO `columns`/g) || []).length
|
||||
assert.ok(menus.length > 0, 'V175 应当插入后台菜单,一条都没解析出来说明正则失效')
|
||||
assert.equal(menus.length, insertCount, `解析到 ${menus.length} 条,但迁移有 ${insertCount} 条 INSERT INTO columns`)
|
||||
|
||||
const menu = menus.find((item) => item.columnKey === 'admin_keyword_usage')
|
||||
assert.ok(menu, 'V175 必须插入 admin_keyword_usage 菜单')
|
||||
const page = adminPages.find((item) => item.menuKey === 'admin_keyword_usage')
|
||||
assert.ok(page, 'routes.ts 必须有 admin_keyword_usage 页面,否则菜单点进去 404')
|
||||
assert.equal(page.title, menu.name, '页面标题应与菜单名一致')
|
||||
assert.equal(page.companyScoped, true, '关键词记录按公司 tab 取数')
|
||||
|
||||
// 品牌Gating库由数据管理组迁到店铺管理组,排序 85;关键词记录 86,紧随其后。
|
||||
assert.ok(sql.includes('SET col.`parent_id` = grp.`id`'), 'V175 必须把品牌Gating库迁到店铺管理组')
|
||||
assert.ok(sql.includes('col.`sort_order` = 85'), '品牌Gating库排序应为 85')
|
||||
})
|
||||
|
||||
@@ -227,6 +227,14 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
|
||||
// 批次 3 的两页同样由 SEND_POINTS 现算(撞款控制台三处发送口 = 三条钉)。
|
||||
admin_shop_data_duplicate_check: pinsFor('admin_shop_data_duplicate_check'),
|
||||
admin_shop_data_crawl_tasks: pinsFor('admin_shop_data_crawl_tasks'),
|
||||
// 2026-10-25 关键词使用记录:三个 GET 共用 toQuery,company_id 只许取函数自己的 params.companyId。
|
||||
admin_keyword_usage: [
|
||||
{
|
||||
file: 'src/pages/tasks/keyword-usage-api.ts',
|
||||
shape: /company_id\s*=\s*params\.companyId\b/,
|
||||
note: 'toQuery 是白名单构造,公司值只能来自调用方传入的 params.companyId(页面从 companyTab.requestCompanyId 取)',
|
||||
},
|
||||
],
|
||||
admin_users: pinsFor('admin_users'),
|
||||
// 批次 5(店铺密钥)同样由 SEND_POINTS 现算:这一页只有一个发送口(列表),
|
||||
// 新增/编辑/删除/白名单检测四支都不带公司参数——归属由后端从操作者会话推导(writeCompanyId 闸门)。
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
createKeywordUsageFilter,
|
||||
keywordUsageCountsText,
|
||||
keywordUsageSceneLabel,
|
||||
parseKeywordUsageOverview,
|
||||
parseKeywordUsagePage,
|
||||
} from '../src/pages/tasks/keyword-usage-model.ts'
|
||||
|
||||
test('keyword_usage_filter_defaults_and_scene_labels', () => {
|
||||
assert.deepEqual(createKeywordUsageFilter(), { user: '', country: '', keyword: '', scene: '' })
|
||||
assert.equal(keywordUsageSceneLabel('复制关键词'), '已使用(复制)')
|
||||
assert.equal(keywordUsageSceneLabel('添加关键词'), '添加关键词')
|
||||
assert.equal(keywordUsageSceneLabel('删除关键词'), '删除关键词')
|
||||
assert.equal(keywordUsageSceneLabel(''), '—')
|
||||
})
|
||||
|
||||
test('keyword_usage_page_parses_counts_and_skips_invalid_rows', () => {
|
||||
const page = parseKeywordUsagePage({
|
||||
total: 7,
|
||||
rows: [
|
||||
{ userName: 'alice', country: '英国', keyword: 'dress', scene: '复制关键词', time: '2026-10-25T10:00:00' },
|
||||
null,
|
||||
{ userName: 'bob', keyword: 'shoes', scene: '添加关键词', time: '2026-10-25T11:00:00' },
|
||||
],
|
||||
counts: { copy: 5, copyExisting: 4, copyDeleted: 1, add: 2 },
|
||||
})
|
||||
assert.equal(page.total, 7)
|
||||
assert.equal(page.rows.length, 2)
|
||||
assert.equal(page.rows[1].country, '')
|
||||
assert.deepEqual(page.counts, { copy: 5, copyExisting: 4, copyDeleted: 1, add: 2 })
|
||||
})
|
||||
|
||||
test('keyword_usage_page_tolerates_missing_fields', () => {
|
||||
const page = parseKeywordUsagePage({})
|
||||
assert.equal(page.total, 0)
|
||||
assert.deepEqual(page.rows, [])
|
||||
assert.deepEqual(page.counts, { copy: 0, copyExisting: 0, copyDeleted: 0, add: 0 })
|
||||
})
|
||||
|
||||
test('keyword_usage_overview_parses_stats_and_options', () => {
|
||||
const overview = parseKeywordUsageOverview({
|
||||
stats: { used: 10, exist: 7, deletedKw: 3, added: 2, totalUse: 12, deletes: 1 },
|
||||
users: ['alice', '', 3],
|
||||
countries: ['英国', '德国'],
|
||||
})
|
||||
assert.equal(overview.stats.used, 10)
|
||||
assert.equal(overview.stats.totalUse, 12)
|
||||
assert.deepEqual(overview.users, ['alice', '3'])
|
||||
assert.deepEqual(overview.countries, ['英国', '德国'])
|
||||
})
|
||||
|
||||
test('keyword_usage_counts_text_matches_desktop_formula', () => {
|
||||
assert.equal(
|
||||
keywordUsageCountsText({ copy: 5, copyExisting: 4, copyDeleted: 1, add: 2 }, 7),
|
||||
'复制关键词 5 = 现存词 4 + 已删除词 1 · 添加关键词 2 · 合计 7 条',
|
||||
)
|
||||
})
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.nanri.aiimage.modules.keywordusage.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageOverviewVo;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsagePageVo;
|
||||
import com.nanri.aiimage.modules.keywordusage.service.KeywordUsageAdminService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 关键词使用记录(管理后台):只读展示 keyword_usage / keyword_add_log / keyword_delete_log。
|
||||
*
|
||||
* <p>独立菜单「关键词使用记录」{@code admin_keyword_usage}(V175),按公司 tab 取数:
|
||||
* 平台超管可收窄到请求里的 company_id,其余账号由 DataReadScope 强制本公司。
|
||||
* 留痕表由桌面端与 keywordshare 模块共用,本页不写、不删。</p>
|
||||
*/
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/admin/keyword-usage")
|
||||
@Tag(name = "关键词使用记录(后台)", description = "关键词复制/添加/删除留痕的只读分页与统计。")
|
||||
public class AdminKeywordUsageController {
|
||||
|
||||
private static final String PERMISSION_KEY = "admin_keyword_usage";
|
||||
private static final String DENIAL_MESSAGE = "无权访问关键词使用记录";
|
||||
|
||||
private final KeywordUsageAdminService keywordUsageAdminService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
private final PermissionMenuService permissionMenuService;
|
||||
private final DataReadScope dataReadScope;
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "使用记录分页", description = "复制关键词 + 添加关键词合并按时间倒序;scene=已使用/添加关键词可只看一支。")
|
||||
public ApiResponse<KeywordUsagePageVo> usage(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
@Parameter(description = "使用者") @RequestParam(name = "user", required = false) String user,
|
||||
@Parameter(description = "国家") @RequestParam(name = "country", required = false) String country,
|
||||
@Parameter(description = "关键词模糊搜索") @RequestParam(name = "keyword", required = false) String keyword,
|
||||
@Parameter(description = "场景:已使用 / 添加关键词") @RequestParam(name = "scene", required = false) String scene,
|
||||
@Parameter(description = "页码(1 起)") @RequestParam(name = "page", required = false) Long page,
|
||||
@Parameter(description = "每页数量(默认 15,上限 100)")
|
||||
@RequestParam(name = "page_size", required = false) Long pageSize) {
|
||||
AdminUserEntity operator = requireAccess(request);
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
|
||||
return ApiResponse.success(
|
||||
keywordUsageAdminService.usage(scopedCompanyId, user, country, keyword, scene, page, pageSize));
|
||||
}
|
||||
|
||||
@GetMapping("/deletes")
|
||||
@Operation(summary = "删除记录分页", description = "keyword_delete_log 按删除时间倒序;只读、不可删。")
|
||||
public ApiResponse<KeywordUsagePageVo> deletes(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
@Parameter(description = "删除者") @RequestParam(name = "user", required = false) String user,
|
||||
@Parameter(description = "国家") @RequestParam(name = "country", required = false) String country,
|
||||
@Parameter(description = "关键词模糊搜索") @RequestParam(name = "keyword", required = false) String keyword,
|
||||
@Parameter(description = "页码(1 起)") @RequestParam(name = "page", required = false) Long page,
|
||||
@Parameter(description = "每页数量(默认 15,上限 100)")
|
||||
@RequestParam(name = "page_size", required = false) Long pageSize) {
|
||||
AdminUserEntity operator = requireAccess(request);
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
|
||||
return ApiResponse.success(
|
||||
keywordUsageAdminService.deletes(scopedCompanyId, user, country, keyword, page, pageSize));
|
||||
}
|
||||
|
||||
@GetMapping("/overview")
|
||||
@Operation(summary = "统计卡与筛选候选", description = "统计卡 + 有操作记录的使用者/国家(五国在首位)。")
|
||||
public ApiResponse<KeywordUsageOverviewVo> overview(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = requireAccess(request);
|
||||
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
|
||||
return ApiResponse.success(keywordUsageAdminService.overview(scopedCompanyId));
|
||||
}
|
||||
|
||||
/** 逐端点把门:登录态 + 「关键词使用记录」后台菜单权限(admin_keyword_usage)。 */
|
||||
private AdminUserEntity requireAccess(HttpServletRequest request) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireUser(request);
|
||||
permissionMenuService.requireConsolePageAccess(operator, DENIAL_MESSAGE, PERMISSION_KEY);
|
||||
return operator;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.nanri.aiimage.modules.keywordusage.mapper;
|
||||
|
||||
import com.nanri.aiimage.modules.keywordusage.model.dto.KeywordUsageFilterQuery;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageRowVo;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageStatsVo;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 关键词使用记录(管理后台只读视图)数据访问。
|
||||
*
|
||||
* <p>表 {@code keyword_usage} / {@code keyword_add_log} / {@code keyword_delete_log} /
|
||||
* {@code keyword_share} 由桌面端与 keywordshare 模块共用,本 Mapper 只读不写;
|
||||
* SQL 全部收口在 {@code mapper/keywordusage/KeywordUsageAdminMapper.xml}。</p>
|
||||
*/
|
||||
@Mapper
|
||||
public interface KeywordUsageAdminMapper {
|
||||
|
||||
long countUsageRows(@Param("f") KeywordUsageFilterQuery filter);
|
||||
|
||||
List<KeywordUsageRowVo> selectUsageRows(@Param("f") KeywordUsageFilterQuery filter);
|
||||
|
||||
long countCopy(@Param("f") KeywordUsageFilterQuery filter);
|
||||
|
||||
long countCopyExisting(@Param("f") KeywordUsageFilterQuery filter);
|
||||
|
||||
long countAdd(@Param("f") KeywordUsageFilterQuery filter);
|
||||
|
||||
long countDeletes(@Param("f") KeywordUsageFilterQuery filter);
|
||||
|
||||
List<KeywordUsageRowVo> selectDeleteRows(@Param("f") KeywordUsageFilterQuery filter);
|
||||
|
||||
KeywordUsageStatsVo selectStats(@Param("companyId") Long companyId);
|
||||
|
||||
List<String> selectUsers(@Param("companyId") Long companyId);
|
||||
|
||||
List<String> selectCountries(@Param("companyId") Long companyId);
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.nanri.aiimage.modules.keywordusage.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 关键词留痕查询条件——Mapper XML 的唯一入参载体({@code @Param("f")})。
|
||||
* 筛选值一律走 {@code #{}} 占位符,不做字符串拼接。
|
||||
*/
|
||||
@Data
|
||||
public class KeywordUsageFilterQuery {
|
||||
|
||||
/** null = 平台超管未指定公司(跨公司全量);非 null = 收窄到该公司。 */
|
||||
private Long companyId;
|
||||
|
||||
private String user;
|
||||
private String country;
|
||||
private String keyword;
|
||||
|
||||
/** 使用记录合并视图:是否包含「复制关键词」/「添加关键词」两支。 */
|
||||
private boolean includeCopy;
|
||||
private boolean includeAdd;
|
||||
|
||||
private long offset;
|
||||
private long limit;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.nanri.aiimage.modules.keywordusage.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/** 使用记录口径计数:复制 = 现存词 + 已删除词留痕。 */
|
||||
@Data
|
||||
@Schema(description = "关键词使用记录计数")
|
||||
public class KeywordUsageCountsVo {
|
||||
|
||||
@Schema(description = "复制关键词(标记已使用)总数")
|
||||
private long copy;
|
||||
|
||||
@Schema(description = "复制关键词中仍存在于 keyword_share 的数量")
|
||||
private long copyExisting;
|
||||
|
||||
@Schema(description = "复制关键词中已从 keyword_share 删除的数量")
|
||||
private long copyDeleted;
|
||||
|
||||
@Schema(description = "添加关键词总数")
|
||||
private long add;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.nanri.aiimage.modules.keywordusage.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 关键词使用记录页首屏:统计卡 + 筛选下拉候选。 */
|
||||
@Data
|
||||
@Schema(description = "关键词使用记录概览")
|
||||
public class KeywordUsageOverviewVo {
|
||||
|
||||
@Schema(description = "统计卡")
|
||||
private KeywordUsageStatsVo stats = new KeywordUsageStatsVo();
|
||||
|
||||
@Schema(description = "有操作记录的使用者")
|
||||
private List<String> users = List.of();
|
||||
|
||||
@Schema(description = "有操作记录的国家(五国在首位)")
|
||||
private List<String> countries = List.of();
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.nanri.aiimage.modules.keywordusage.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 关键词留痕分页负载。 */
|
||||
@Data
|
||||
@Schema(description = "关键词使用/删除记录分页")
|
||||
public class KeywordUsagePageVo {
|
||||
|
||||
@Schema(description = "总条数")
|
||||
private long total;
|
||||
|
||||
@Schema(description = "当前页行")
|
||||
private List<KeywordUsageRowVo> rows = List.of();
|
||||
|
||||
@Schema(description = "使用记录口径计数(删除记录页为空对象)")
|
||||
private KeywordUsageCountsVo counts = new KeywordUsageCountsVo();
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.nanri.aiimage.modules.keywordusage.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 关键词使用/删除留痕单行。 */
|
||||
@Data
|
||||
@Schema(description = "关键词使用记录行")
|
||||
public class KeywordUsageRowVo {
|
||||
|
||||
@Schema(description = "操作人")
|
||||
private String userName;
|
||||
|
||||
@Schema(description = "国家")
|
||||
private String country;
|
||||
|
||||
@Schema(description = "关键词")
|
||||
private String keyword;
|
||||
|
||||
@Schema(description = "场景:复制关键词 / 添加关键词 / 删除关键词")
|
||||
private String scene;
|
||||
|
||||
@Schema(description = "操作时间")
|
||||
private LocalDateTime time;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.nanri.aiimage.modules.keywordusage.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
/** 关键词使用记录统计卡。 */
|
||||
@Data
|
||||
@Schema(description = "关键词使用记录统计")
|
||||
public class KeywordUsageStatsVo {
|
||||
|
||||
@Schema(description = "复制关键词(标记已使用)总数")
|
||||
private long used;
|
||||
|
||||
@Schema(description = "复制关键词中仍存在于 keyword_share 的数量")
|
||||
private long exist;
|
||||
|
||||
@Schema(description = "已删除词留痕 = used - exist")
|
||||
private long deletedKw;
|
||||
|
||||
@Schema(description = "添加关键词总数")
|
||||
private long added;
|
||||
|
||||
@Schema(description = "使用记录合计 = used + added")
|
||||
private long totalUse;
|
||||
|
||||
@Schema(description = "删除关键词记录总数")
|
||||
private long deletes;
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
package com.nanri.aiimage.modules.keywordusage.service;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.keywordusage.mapper.KeywordUsageAdminMapper;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.dto.KeywordUsageFilterQuery;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageCountsVo;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageOverviewVo;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsagePageVo;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageRowVo;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageStatsVo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 关键词使用记录(管理后台只读视图)。
|
||||
*
|
||||
* <p>口径对齐独立小网页后台 v1.2.6g:使用记录 = 复制关键词(keyword_usage)+ 添加关键词
|
||||
* (keyword_add_log)合并按时间倒序;删除记录单独一页;统计卡里的「已删除词留痕」
|
||||
* = 复制总数 - 仍存在于 keyword_share 的数量。公司范围由 Controller 经 DataReadScope 解析后传入,
|
||||
* 本层不再自行从请求参数取公司。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class KeywordUsageAdminService {
|
||||
|
||||
private static final long DEFAULT_PAGE_SIZE = 15;
|
||||
private static final long MAX_PAGE_SIZE = 100;
|
||||
private static final List<String> BASE_COUNTRIES = List.of("英国", "德国", "法国", "西班牙", "意大利");
|
||||
|
||||
private final KeywordUsageAdminMapper keywordUsageAdminMapper;
|
||||
|
||||
public KeywordUsagePageVo usage(Long companyId, String user, String country, String keyword,
|
||||
String scene, Long page, Long pageSize) {
|
||||
KeywordUsageFilterQuery filter = buildFilter(companyId, user, country, keyword, page, pageSize);
|
||||
applyScene(filter, scene);
|
||||
|
||||
KeywordUsagePageVo vo = new KeywordUsagePageVo();
|
||||
if (!filter.isIncludeCopy() && !filter.isIncludeAdd()) {
|
||||
vo.setTotal(0);
|
||||
vo.setRows(List.of());
|
||||
vo.setCounts(new KeywordUsageCountsVo());
|
||||
return vo;
|
||||
}
|
||||
|
||||
long total = keywordUsageAdminMapper.countUsageRows(filter);
|
||||
long copy = filter.isIncludeCopy() ? keywordUsageAdminMapper.countCopy(filter) : 0;
|
||||
long copyExisting = filter.isIncludeCopy() ? keywordUsageAdminMapper.countCopyExisting(filter) : 0;
|
||||
long add = filter.isIncludeAdd() ? keywordUsageAdminMapper.countAdd(filter) : 0;
|
||||
KeywordUsageCountsVo counts = new KeywordUsageCountsVo();
|
||||
counts.setCopy(copy);
|
||||
counts.setCopyExisting(copyExisting);
|
||||
counts.setCopyDeleted(Math.max(0, copy - copyExisting));
|
||||
counts.setAdd(add);
|
||||
|
||||
vo.setTotal(total);
|
||||
vo.setRows(keywordUsageAdminMapper.selectUsageRows(filter));
|
||||
vo.setCounts(counts);
|
||||
return vo;
|
||||
}
|
||||
|
||||
public KeywordUsagePageVo deletes(Long companyId, String user, String country, String keyword,
|
||||
Long page, Long pageSize) {
|
||||
KeywordUsageFilterQuery filter = buildFilter(companyId, user, country, keyword, page, pageSize);
|
||||
KeywordUsagePageVo vo = new KeywordUsagePageVo();
|
||||
vo.setTotal(keywordUsageAdminMapper.countDeletes(filter));
|
||||
vo.setRows(keywordUsageAdminMapper.selectDeleteRows(filter));
|
||||
vo.setCounts(new KeywordUsageCountsVo());
|
||||
return vo;
|
||||
}
|
||||
|
||||
public KeywordUsageOverviewVo overview(Long companyId) {
|
||||
KeywordUsageStatsVo stats = keywordUsageAdminMapper.selectStats(companyId);
|
||||
if (stats == null) {
|
||||
stats = new KeywordUsageStatsVo();
|
||||
}
|
||||
stats.setDeletedKw(Math.max(0, stats.getUsed() - stats.getExist()));
|
||||
stats.setTotalUse(stats.getUsed() + stats.getAdded());
|
||||
|
||||
List<String> countries = new ArrayList<>(BASE_COUNTRIES);
|
||||
for (String country : safeList(keywordUsageAdminMapper.selectCountries(companyId))) {
|
||||
if (!countries.contains(country)) {
|
||||
countries.add(country);
|
||||
}
|
||||
}
|
||||
|
||||
KeywordUsageOverviewVo vo = new KeywordUsageOverviewVo();
|
||||
vo.setStats(stats);
|
||||
vo.setUsers(safeList(keywordUsageAdminMapper.selectUsers(companyId)));
|
||||
vo.setCountries(countries);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private KeywordUsageFilterQuery buildFilter(Long companyId, String user, String country, String keyword,
|
||||
Long page, Long pageSize) {
|
||||
KeywordUsageFilterQuery filter = new KeywordUsageFilterQuery();
|
||||
filter.setCompanyId(companyId);
|
||||
filter.setUser(trimToNull(user));
|
||||
filter.setCountry(normalizeCountry(country));
|
||||
filter.setKeyword(trimToNull(keyword));
|
||||
long safePage = page == null || page < 1 ? 1 : page;
|
||||
long safeSize = pageSize == null ? DEFAULT_PAGE_SIZE : Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
|
||||
filter.setOffset((safePage - 1) * safeSize);
|
||||
filter.setLimit(safeSize);
|
||||
return filter;
|
||||
}
|
||||
|
||||
private void applyScene(KeywordUsageFilterQuery filter, String scene) {
|
||||
String value = trimToNull(scene);
|
||||
boolean copy = value == null || "已使用".equals(value) || "复制关键词".equals(value);
|
||||
boolean add = value == null || "添加关键词".equals(value);
|
||||
if (!copy && !add) {
|
||||
throw new BusinessException("scene 只支持 已使用 / 添加关键词");
|
||||
}
|
||||
filter.setIncludeCopy(copy);
|
||||
filter.setIncludeAdd(add);
|
||||
}
|
||||
|
||||
private String normalizeCountry(String country) {
|
||||
String value = trimToNull(country);
|
||||
return value == null || "全部".equals(value) ? null : value;
|
||||
}
|
||||
|
||||
private String trimToNull(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
return trimmed.isEmpty() ? null : trimmed;
|
||||
}
|
||||
|
||||
private List<String> safeList(List<String> values) {
|
||||
return values == null ? List.of() : values;
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -80,7 +80,6 @@ public class PermissionMenuSchemaInitializer {
|
||||
new DefaultAdminMenu("密钥用量统计", "admin_user_secret_usage", "account/user-secret-usage", 42, "admin_group_account"),
|
||||
new DefaultAdminMenu("去重数据汇总", "admin_dedupe_total_data", "dedupe-total-data", 30, "admin_group_data"),
|
||||
new DefaultAdminMenu("品牌数据库", "admin_invalid_asin_data", "invalid-asin-data", 35, "admin_group_data"),
|
||||
new DefaultAdminMenu("品牌Gating库", "admin_brand_gating", "brand-gating", 36, "admin_group_data"),
|
||||
new DefaultAdminMenu("查询ASIN", "admin_query_asin", "query-asin", 65, "admin_group_data"),
|
||||
new DefaultAdminMenu("商品类目", "admin_product_categories", "product-categories", 66, "admin_group_data"),
|
||||
new DefaultAdminMenu("店铺密钥管理", "admin_shop_keys", "shop-keys", 40, "admin_group_shop"),
|
||||
@@ -88,6 +87,8 @@ public class PermissionMenuSchemaInitializer {
|
||||
new DefaultAdminMenu("最低价ASIN设置", "admin_skip_price_asin", "skip-price-asin", 60, "admin_group_shop"),
|
||||
new DefaultAdminMenu("店铺数据记录", "admin_shop_data_crawl_tasks", "shop-data-crawl-tasks", 82, "admin_group_shop"),
|
||||
new DefaultAdminMenu("店铺数据重复检查", "admin_shop_data_duplicate_check", "shop-data-duplicate-check", 84, "admin_group_shop"),
|
||||
new DefaultAdminMenu("品牌Gating库", "admin_brand_gating", "brand-gating", 85, "admin_group_shop"),
|
||||
new DefaultAdminMenu("关键词使用记录", "admin_keyword_usage", "keyword-usage", 86, "admin_group_shop"),
|
||||
new DefaultAdminMenu("生成记录", "admin_history", "history", 70, "admin_group_record"),
|
||||
new DefaultAdminMenu("视频任务记录", "admin_image_video_tasks", "image-video-tasks", 75, "admin_group_record"),
|
||||
new DefaultAdminMenu("软件版本管理", "admin_version", "version", 80, "admin_group_record"),
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V175__move_gating_and_add_keyword_usage_menu
|
||||
--
|
||||
-- 1. 变更目的(2026-10-25 控制方截图定案):
|
||||
-- a) 「品牌Gating库」从数据管理组迁到店铺管理组 admin_group_shop,排序 85,
|
||||
-- 紧跟「店铺数据重复检查」(84);
|
||||
-- b) 新增「关键词使用记录」独立菜单 admin_keyword_usage,挂在店铺管理组,排序 86。
|
||||
--
|
||||
-- 2. 口径:
|
||||
-- - 两行都按每家公司一套菜单树维护:company_id=1 为模板行,其余公司(含停用公司)
|
||||
-- 逐家复制;子行 parent_id 必须认本公司 admin_group_shop 组行,严禁跨公司认父。
|
||||
-- - 品牌Gating库行由 V174 恢复,V175 只改 parent_id/sort_order,不重建、不删授权。
|
||||
-- - 关键词使用记录只读页面,默认不预授 user_column_permission;管理员角色链可直进,
|
||||
-- 普通账号由管理员在「菜单权限配置」里按公司分配。
|
||||
-- - 幂等守卫按 (company_id, column_key) 判存,同时防 (menu_type, route_path) 唯一键
|
||||
-- uk_company_menu_type_route_path 撞行。
|
||||
--
|
||||
-- 3. 影响表与数据量:columns 更新 N 行 + 新增 N 行(N = 公司数),字典小表,毫秒级。
|
||||
--
|
||||
-- 4. 【可重跑性】UPDATE 重复执行结果一致;两段 INSERT 都带 NOT EXISTS 守卫,重跑逐条 no-op。
|
||||
-- =============================================================
|
||||
|
||||
-- ---------- 1. 品牌Gating库归位:店铺管理组、排序 85 ----------
|
||||
UPDATE `columns` col
|
||||
JOIN `columns` grp
|
||||
ON grp.`company_id` = col.`company_id`
|
||||
AND grp.`column_key` = 'admin_group_shop'
|
||||
SET col.`parent_id` = grp.`id`,
|
||||
col.`sort_order` = 85
|
||||
WHERE col.`column_key` = 'admin_brand_gating';
|
||||
|
||||
-- ---------- 2. 公司 1 模板行:关键词使用记录 ----------
|
||||
INSERT INTO `columns` (`name`, `column_key`, `menu_type`, `route_path`, `sort_order`, `parent_id`, `company_id`)
|
||||
SELECT '关键词使用记录', 'admin_keyword_usage', 'admin', 'keyword-usage', 86, grp.`id`, 1
|
||||
FROM `columns` grp
|
||||
WHERE grp.`company_id` = 1 AND grp.`column_key` = 'admin_group_shop'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM `columns`
|
||||
WHERE `company_id` = 1
|
||||
AND (`column_key` = 'admin_keyword_usage'
|
||||
OR (`menu_type` = 'admin' AND `route_path` = 'keyword-usage'))
|
||||
);
|
||||
|
||||
-- ---------- 3. 复制到其余公司(含停用公司),各自认本公司店铺管理组行 ----------
|
||||
INSERT INTO `columns` (`name`, `column_key`, `menu_type`, `route_path`, `sort_order`, `parent_id`, `company_id`)
|
||||
SELECT '关键词使用记录', 'admin_keyword_usage', 'admin', 'keyword-usage', 86, grp.`id`, c.`id`
|
||||
FROM `company` c
|
||||
JOIN `columns` grp ON grp.`company_id` = c.`id` AND grp.`column_key` = 'admin_group_shop'
|
||||
WHERE c.`id` <> 1
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM `columns` col
|
||||
WHERE col.`company_id` = c.`id`
|
||||
AND (col.`column_key` = 'admin_keyword_usage'
|
||||
OR (col.`menu_type` = 'admin' AND col.`route_path` = 'keyword-usage'))
|
||||
);
|
||||
|
||||
-- ---------- 4. 自检闸门:不为 0 就抛 1048(列 must_be_zero NOT NULL) ----------
|
||||
CREATE TEMPORARY TABLE IF NOT EXISTS `_v175_gate` (`must_be_zero` INT NOT NULL);
|
||||
|
||||
-- 闸门 1:每家公司恰好一行品牌Gating库,且父必须是本公司店铺管理组、排序 85
|
||||
INSERT INTO `_v175_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM (
|
||||
SELECT c.`id`
|
||||
FROM `company` c
|
||||
LEFT JOIN `columns` col ON col.`company_id` = c.`id` AND col.`column_key` = 'admin_brand_gating'
|
||||
LEFT JOIN `columns` grp ON grp.`id` = col.`parent_id`
|
||||
AND grp.`company_id` = c.`id` AND grp.`column_key` = 'admin_group_shop'
|
||||
GROUP BY c.`id`
|
||||
HAVING COUNT(col.`id`) <> 1 OR COUNT(grp.`id`) <> 1 OR MAX(col.`sort_order`) <> 85
|
||||
) bad;
|
||||
|
||||
-- 闸门 2:每家公司恰好一行关键词使用记录,且父必须是本公司店铺管理组、排序 86
|
||||
INSERT INTO `_v175_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM (
|
||||
SELECT c.`id`
|
||||
FROM `company` c
|
||||
LEFT JOIN `columns` col ON col.`company_id` = c.`id` AND col.`column_key` = 'admin_keyword_usage'
|
||||
LEFT JOIN `columns` grp ON grp.`id` = col.`parent_id`
|
||||
AND grp.`company_id` = c.`id` AND grp.`column_key` = 'admin_group_shop'
|
||||
GROUP BY c.`id`
|
||||
HAVING COUNT(col.`id`) <> 1 OR COUNT(grp.`id`) <> 1 OR MAX(col.`sort_order`) <> 86
|
||||
) bad;
|
||||
|
||||
-- 闸门 3:两条路由不允许被别的 column_key 占行
|
||||
INSERT INTO `_v175_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM `columns` col
|
||||
WHERE col.`menu_type` = 'admin'
|
||||
AND col.`route_path` IN ('brand-gating', 'keyword-usage')
|
||||
AND col.`column_key` NOT IN ('admin_brand_gating', 'admin_keyword_usage');
|
||||
|
||||
-- 闸门 4:两个 key 的 route_path 必须各自保持原值(防止历史行被别的迁移改名)
|
||||
INSERT INTO `_v175_gate`
|
||||
SELECT IF(COUNT(*) = 0, 0, NULL)
|
||||
FROM `columns` col
|
||||
WHERE (col.`column_key` = 'admin_brand_gating' AND col.`route_path` <> 'brand-gating')
|
||||
OR (col.`column_key` = 'admin_keyword_usage' AND col.`route_path` <> 'keyword-usage');
|
||||
|
||||
DROP TEMPORARY TABLE `_v175_gate`;
|
||||
@@ -0,0 +1,158 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.nanri.aiimage.modules.keywordusage.mapper.KeywordUsageAdminMapper">
|
||||
<!-- 关键词使用记录(管理后台只读视图)。四张表由桌面端/keywordshare 模块维护,这里只查不写;
|
||||
筛选值一律 #{} 占位符,LIKE 由 CONCAT 拼通配符,不拼接用户输入。 -->
|
||||
|
||||
<sql id="usageConds">
|
||||
<if test="f.companyId != null">AND k.company_id = #{f.companyId}</if>
|
||||
<if test="f.user != null and f.user != ''">AND k.user_name = #{f.user}</if>
|
||||
<if test="f.country != null and f.country != ''">AND k.country = #{f.country}</if>
|
||||
<if test="f.keyword != null and f.keyword != ''">
|
||||
AND k.keyword LIKE CONCAT('%', #{f.keyword}, '%')
|
||||
</if>
|
||||
</sql>
|
||||
|
||||
<sql id="addConds">
|
||||
<if test="f.companyId != null">AND a.company_id = #{f.companyId}</if>
|
||||
<if test="f.user != null and f.user != ''">AND a.user_name = #{f.user}</if>
|
||||
<if test="f.country != null and f.country != ''">AND a.country = #{f.country}</if>
|
||||
<if test="f.keyword != null and f.keyword != ''">
|
||||
AND a.keyword LIKE CONCAT('%', #{f.keyword}, '%')
|
||||
</if>
|
||||
</sql>
|
||||
|
||||
<sql id="deleteConds">
|
||||
<if test="f.companyId != null">AND d.company_id = #{f.companyId}</if>
|
||||
<if test="f.user != null and f.user != ''">AND d.user_name = #{f.user}</if>
|
||||
<if test="f.country != null and f.country != ''">AND d.country = #{f.country}</if>
|
||||
<if test="f.keyword != null and f.keyword != ''">
|
||||
AND d.keyword LIKE CONCAT('%', #{f.keyword}, '%')
|
||||
</if>
|
||||
</sql>
|
||||
|
||||
<select id="countUsageRows" resultType="long">
|
||||
SELECT
|
||||
<choose>
|
||||
<when test="f.includeCopy and f.includeAdd">
|
||||
(SELECT COUNT(*) FROM keyword_usage k WHERE 1=1 <include refid="usageConds"/>)
|
||||
+ (SELECT COUNT(*) FROM keyword_add_log a WHERE 1=1 <include refid="addConds"/>)
|
||||
</when>
|
||||
<when test="f.includeCopy">
|
||||
(SELECT COUNT(*) FROM keyword_usage k WHERE 1=1 <include refid="usageConds"/>)
|
||||
</when>
|
||||
<when test="f.includeAdd">
|
||||
(SELECT COUNT(*) FROM keyword_add_log a WHERE 1=1 <include refid="addConds"/>)
|
||||
</when>
|
||||
<otherwise>0</otherwise>
|
||||
</choose>
|
||||
</select>
|
||||
|
||||
<select id="selectUsageRows" resultType="com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageRowVo">
|
||||
SELECT x.user_name AS userName,
|
||||
x.country AS country,
|
||||
x.keyword AS keyword,
|
||||
x.scene AS scene,
|
||||
x.op_time AS `time`
|
||||
FROM (
|
||||
<if test="f.includeCopy">
|
||||
SELECT k.user_name, k.country, k.keyword, '复制关键词' AS scene,
|
||||
k.used_time AS op_time, k.id AS sid
|
||||
FROM keyword_usage k
|
||||
WHERE 1=1 <include refid="usageConds"/>
|
||||
</if>
|
||||
<if test="f.includeCopy and f.includeAdd">UNION ALL</if>
|
||||
<if test="f.includeAdd">
|
||||
SELECT a.user_name, a.country, a.keyword, '添加关键词' AS scene,
|
||||
a.add_time AS op_time, a.id AS sid
|
||||
FROM keyword_add_log a
|
||||
WHERE 1=1 <include refid="addConds"/>
|
||||
</if>
|
||||
) x
|
||||
ORDER BY x.op_time DESC, x.sid DESC
|
||||
LIMIT #{f.offset}, #{f.limit}
|
||||
</select>
|
||||
|
||||
<select id="countCopy" resultType="long">
|
||||
SELECT COUNT(*) FROM keyword_usage k WHERE 1=1 <include refid="usageConds"/>
|
||||
</select>
|
||||
|
||||
<select id="countCopyExisting" resultType="long">
|
||||
SELECT COUNT(*)
|
||||
FROM keyword_usage k
|
||||
INNER JOIN keyword_share s
|
||||
ON s.company_id = k.company_id
|
||||
AND s.country = k.country
|
||||
AND s.keyword = k.keyword
|
||||
WHERE 1=1 <include refid="usageConds"/>
|
||||
</select>
|
||||
|
||||
<select id="countAdd" resultType="long">
|
||||
SELECT COUNT(*) FROM keyword_add_log a WHERE 1=1 <include refid="addConds"/>
|
||||
</select>
|
||||
|
||||
<select id="countDeletes" resultType="long">
|
||||
SELECT COUNT(*) FROM keyword_delete_log d WHERE 1=1 <include refid="deleteConds"/>
|
||||
</select>
|
||||
|
||||
<select id="selectDeleteRows" resultType="com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageRowVo">
|
||||
SELECT d.user_name AS userName,
|
||||
d.country AS country,
|
||||
d.keyword AS keyword,
|
||||
'删除关键词' AS scene,
|
||||
d.delete_time AS `time`
|
||||
FROM keyword_delete_log d
|
||||
WHERE 1=1 <include refid="deleteConds"/>
|
||||
ORDER BY d.delete_time DESC, d.id DESC
|
||||
LIMIT #{f.offset}, #{f.limit}
|
||||
</select>
|
||||
|
||||
<select id="selectStats" resultType="com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageStatsVo">
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM keyword_usage k
|
||||
WHERE 1=1
|
||||
<if test="companyId != null">AND k.company_id = #{companyId}</if>) AS used,
|
||||
(SELECT COUNT(*)
|
||||
FROM keyword_usage k
|
||||
INNER JOIN keyword_share s
|
||||
ON s.company_id = k.company_id
|
||||
AND s.country = k.country
|
||||
AND s.keyword = k.keyword
|
||||
WHERE 1=1
|
||||
<if test="companyId != null">AND k.company_id = #{companyId}</if>) AS exist,
|
||||
(SELECT COUNT(*) FROM keyword_add_log a
|
||||
WHERE 1=1
|
||||
<if test="companyId != null">AND a.company_id = #{companyId}</if>) AS added,
|
||||
(SELECT COUNT(*) FROM keyword_delete_log d
|
||||
WHERE 1=1
|
||||
<if test="companyId != null">AND d.company_id = #{companyId}</if>) AS deletes
|
||||
</select>
|
||||
|
||||
<select id="selectUsers" resultType="string">
|
||||
SELECT DISTINCT user_name
|
||||
FROM (
|
||||
SELECT user_name, company_id FROM keyword_usage
|
||||
UNION
|
||||
SELECT user_name, company_id FROM keyword_add_log
|
||||
UNION
|
||||
SELECT user_name, company_id FROM keyword_delete_log
|
||||
) t
|
||||
WHERE user_name IS NOT NULL AND user_name != ''
|
||||
<if test="companyId != null">AND company_id = #{companyId}</if>
|
||||
ORDER BY user_name
|
||||
</select>
|
||||
|
||||
<select id="selectCountries" resultType="string">
|
||||
SELECT DISTINCT country
|
||||
FROM (
|
||||
SELECT country, company_id FROM keyword_usage
|
||||
UNION
|
||||
SELECT country, company_id FROM keyword_add_log
|
||||
UNION
|
||||
SELECT country, company_id FROM keyword_delete_log
|
||||
) t
|
||||
WHERE country IS NOT NULL AND country != ''
|
||||
<if test="companyId != null">AND company_id = #{companyId}</if>
|
||||
ORDER BY country
|
||||
</select>
|
||||
</mapper>
|
||||
@@ -63,7 +63,9 @@ class MigratedSqlEquivalenceTest {
|
||||
// (SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 124 → 126)。
|
||||
// 88 → 89:B28 新增 TaskFileJobMapper#selectFileTaskStatus(按主键读父任务状态),逐条点入
|
||||
// (SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 128 → 129)。
|
||||
private static final int XML_SELECT_TOTAL = 89;
|
||||
// 89 → 99:关键词使用记录管理端(keywordusage 模块)新写 10 条只读 select,逐条点入
|
||||
// (SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 130 → 140)。
|
||||
private static final int XML_SELECT_TOTAL = 99;
|
||||
|
||||
/**
|
||||
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
|
||||
@@ -103,7 +105,18 @@ class MigratedSqlEquivalenceTest {
|
||||
// B28(2026-10-25)新写的 1 条主键点查:父任务是否已终态。
|
||||
"TaskFileJobMapper#selectFileTaskStatus",
|
||||
// CR-01(2026-10-25)新写的 1 条写侧语句:会话世代原子自增。
|
||||
"LoginUserMapper#incrementSessionEpoch");
|
||||
"LoginUserMapper#incrementSessionEpoch",
|
||||
// 关键词使用记录管理端(2026-10-25)新写的 10 条只读 select。
|
||||
"KeywordUsageAdminMapper#countUsageRows",
|
||||
"KeywordUsageAdminMapper#selectUsageRows",
|
||||
"KeywordUsageAdminMapper#countCopy",
|
||||
"KeywordUsageAdminMapper#countCopyExisting",
|
||||
"KeywordUsageAdminMapper#countAdd",
|
||||
"KeywordUsageAdminMapper#countDeletes",
|
||||
"KeywordUsageAdminMapper#selectDeleteRows",
|
||||
"KeywordUsageAdminMapper#selectStats",
|
||||
"KeywordUsageAdminMapper#selectUsers",
|
||||
"KeywordUsageAdminMapper#selectCountries");
|
||||
|
||||
/** 账本 5 列:接口 / 方法 / @Select 种类 / 是否含常量插值 / 注解原文(Java 反转义后那条串)。 */
|
||||
private static final int LEDGER_COLUMNS = 5;
|
||||
|
||||
@@ -82,7 +82,8 @@ class SqlLayeringConventionTest {
|
||||
// 新写语句按约定直接进 XML,同轮登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED(88 → 89)。
|
||||
// 129 → 130:CR-01 新增 {@code LoginUserMapper#incrementSessionEpoch}(会话世代原子自增),
|
||||
// 新写语句直接进 mapper/auth/LoginUserMapper.xml,同轮登记进 NOT_MIGRATED。
|
||||
private static final int XML_STATEMENT_TOTAL = 130;
|
||||
// 130 → 140:关键词使用记录管理端(keywordusage 模块,1 份 XML 10 条只读 select)新写语句。
|
||||
private static final int XML_STATEMENT_TOTAL = 140;
|
||||
|
||||
/**
|
||||
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
|
||||
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package com.nanri.aiimage.modules.keywordusage.service;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.keywordusage.mapper.KeywordUsageAdminMapper;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.dto.KeywordUsageFilterQuery;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageOverviewVo;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsagePageVo;
|
||||
import com.nanri.aiimage.modules.keywordusage.model.vo.KeywordUsageStatsVo;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeywordUsageAdminServiceTest {
|
||||
|
||||
@Mock
|
||||
private KeywordUsageAdminMapper keywordUsageAdminMapper;
|
||||
|
||||
@InjectMocks
|
||||
private KeywordUsageAdminService service;
|
||||
|
||||
@Test
|
||||
@DisplayName("概览:已删除词=复制-现存,合计=复制+添加,五国在筛选国家首位")
|
||||
void overviewComputesDerivedStatsAndCountryOrder() {
|
||||
KeywordUsageStatsVo stats = new KeywordUsageStatsVo();
|
||||
stats.setUsed(10);
|
||||
stats.setExist(7);
|
||||
stats.setAdded(3);
|
||||
stats.setDeletes(2);
|
||||
when(keywordUsageAdminMapper.selectStats(1L)).thenReturn(stats);
|
||||
when(keywordUsageAdminMapper.selectCountries(1L)).thenReturn(List.of("美国", "英国"));
|
||||
when(keywordUsageAdminMapper.selectUsers(1L)).thenReturn(List.of("alice"));
|
||||
|
||||
KeywordUsageOverviewVo vo = service.overview(1L);
|
||||
|
||||
assertThat(vo.getStats().getDeletedKw()).isEqualTo(3);
|
||||
assertThat(vo.getStats().getTotalUse()).isEqualTo(13);
|
||||
assertThat(vo.getCountries()).containsExactly("英国", "德国", "法国", "西班牙", "意大利", "美国");
|
||||
assertThat(vo.getUsers()).containsExactly("alice");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("使用记录 scene=已使用:只查复制支,添加支为零且不发起查询")
|
||||
void usageSceneCopyOnly() {
|
||||
when(keywordUsageAdminMapper.countUsageRows(any())).thenReturn(5L);
|
||||
when(keywordUsageAdminMapper.countCopy(any())).thenReturn(5L);
|
||||
when(keywordUsageAdminMapper.countCopyExisting(any())).thenReturn(4L);
|
||||
when(keywordUsageAdminMapper.selectUsageRows(any())).thenReturn(List.of());
|
||||
|
||||
KeywordUsagePageVo vo = service.usage(1L, "alice", null, null, "已使用", 1L, 15L);
|
||||
|
||||
assertThat(vo.getTotal()).isEqualTo(5);
|
||||
assertThat(vo.getCounts().getCopy()).isEqualTo(5);
|
||||
assertThat(vo.getCounts().getCopyDeleted()).isEqualTo(1);
|
||||
assertThat(vo.getCounts().getAdd()).isZero();
|
||||
verify(keywordUsageAdminMapper, never()).countAdd(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("未知场景直接拒绝,不落任何查询")
|
||||
void unknownSceneRejected() {
|
||||
assertThatThrownBy(() -> service.usage(1L, null, null, null, "未知场景", 1L, 15L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("scene");
|
||||
verify(keywordUsageAdminMapper, never()).countUsageRows(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("分页参数:page<1 归一为 1,page_size 上限 100")
|
||||
void pageParamsAreClamped() {
|
||||
when(keywordUsageAdminMapper.countUsageRows(any())).thenReturn(0L);
|
||||
when(keywordUsageAdminMapper.countCopy(any())).thenReturn(0L);
|
||||
when(keywordUsageAdminMapper.countCopyExisting(any())).thenReturn(0L);
|
||||
when(keywordUsageAdminMapper.countAdd(any())).thenReturn(0L);
|
||||
when(keywordUsageAdminMapper.selectUsageRows(any())).thenReturn(List.of());
|
||||
|
||||
service.usage(1L, null, null, null, null, 0L, 1000L);
|
||||
|
||||
ArgumentCaptor<KeywordUsageFilterQuery> captor = ArgumentCaptor.forClass(KeywordUsageFilterQuery.class);
|
||||
verify(keywordUsageAdminMapper).selectUsageRows(captor.capture());
|
||||
assertThat(captor.getValue().getOffset()).isZero();
|
||||
assertThat(captor.getValue().getLimit()).isEqualTo(100);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("控制器与 Mapper 契约:独立菜单权限键、逐端点走公司范围门、XML 只读四表")
|
||||
void controllerAndMapperContract() throws Exception {
|
||||
String controller = Files.readString(Path.of(
|
||||
"src/main/java/com/nanri/aiimage/modules/keywordusage/controller/AdminKeywordUsageController.java"),
|
||||
StandardCharsets.UTF_8);
|
||||
assertThat(controller).contains("PERMISSION_KEY = \"admin_keyword_usage\"");
|
||||
assertThat(count(controller, "readCompanyIdOrOwn(operator, companyId)")).isEqualTo(3);
|
||||
assertThat(count(controller, "@RequestParam(name = \"company_id\"")).isEqualTo(3);
|
||||
assertThat(controller).contains("adminAuthSupport.requireUser(request)");
|
||||
assertThat(controller).contains("requireConsolePageAccess(operator, DENIAL_MESSAGE, PERMISSION_KEY)");
|
||||
|
||||
String xml = Files.readString(Path.of(
|
||||
"src/main/resources/mapper/keywordusage/KeywordUsageAdminMapper.xml"), StandardCharsets.UTF_8);
|
||||
assertThat(xml).contains("keyword_usage")
|
||||
.contains("keyword_add_log")
|
||||
.contains("keyword_delete_log")
|
||||
.contains("keyword_share");
|
||||
assertThat(xml).doesNotContain("${");
|
||||
assertThat(count(xml, "<select ")).isEqualTo(10);
|
||||
}
|
||||
|
||||
private static int count(String text, String token) {
|
||||
int hits = 0;
|
||||
int at = 0;
|
||||
while ((at = text.indexOf(token, at)) >= 0) {
|
||||
hits++;
|
||||
at += token.length();
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user