Compare commits
3 Commits
f1269f3117
...
eba16ea639
| Author | SHA1 | Date | |
|---|---|---|---|
| eba16ea639 | |||
| f20bca1af2 | |||
| 5b8cf59d30 |
@@ -58,7 +58,8 @@ export interface DeviceLogConfigData {
|
||||
|
||||
export interface DeviceLogQuery {
|
||||
source?: string
|
||||
keyword?: string
|
||||
/** 指定用户(users.id);不传=全部上报者,含 uid 为空的采集机与未登录客户端。 */
|
||||
uid?: number
|
||||
startDate?: string
|
||||
endDate?: string
|
||||
page: number
|
||||
@@ -69,7 +70,7 @@ export interface DeviceLogQuery {
|
||||
export async function fetchDeviceLogFiles(params: DeviceLogQuery): Promise<DeviceLogPage> {
|
||||
const query: Record<string, string | number> = { page: params.page, pageSize: params.pageSize }
|
||||
if (params.source) query.source = params.source
|
||||
if (params.keyword) query.keyword = params.keyword
|
||||
if (params.uid) query.uid = params.uid
|
||||
if (params.startDate) query.startDate = params.startDate
|
||||
if (params.endDate) query.endDate = params.endDate
|
||||
const { data } = await http.get('/api/admin/device-logs/files', { params: query })
|
||||
|
||||
@@ -145,6 +145,7 @@ import {
|
||||
readLastNotifiedId,
|
||||
writeLastNotifiedId,
|
||||
} from '@/layout/notification-bell-model'
|
||||
import { todayDateInput } from '@/utils/datetime'
|
||||
|
||||
const PAGE_SIZE = 10
|
||||
|
||||
@@ -162,13 +163,14 @@ const loading = ref(false)
|
||||
const markingAll = ref(false)
|
||||
const loadError = ref('')
|
||||
const keyword = ref('')
|
||||
const startDate = ref('')
|
||||
const endDate = ref('')
|
||||
const startDate = ref(todayDateInput())
|
||||
const endDate = ref(todayDateInput())
|
||||
|
||||
const badgeText = computed(() => formatUnreadBadge(unreadCount.value))
|
||||
const groupedItems = computed(() => groupNotificationsByDay(items.value))
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / PAGE_SIZE)))
|
||||
const hasFilter = computed(() => Boolean(keyword.value.trim() || startDate.value || endDate.value))
|
||||
/** 日期恒为「当天」是默认视图、不算主动筛选:若计入,下方「无筛选才记录已提醒 id」的分支会永久失效。 */
|
||||
const hasFilter = computed(() => Boolean(keyword.value.trim()))
|
||||
|
||||
/**
|
||||
* el-date-picker 的绑定桥:日期区间在内部仍用 startDate/endDate 两个 ref 表示
|
||||
@@ -279,8 +281,8 @@ function onKeywordInput() {
|
||||
|
||||
function resetFilters() {
|
||||
keyword.value = ''
|
||||
startDate.value = ''
|
||||
endDate.value = ''
|
||||
startDate.value = todayDateInput()
|
||||
endDate.value = todayDateInput()
|
||||
void loadPage(1)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { todayDateInput } from '@/utils/datetime'
|
||||
import {
|
||||
fetchUserSecretUsage,
|
||||
type AdminUserSecretUsageRow,
|
||||
@@ -19,8 +20,8 @@ const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(15)
|
||||
const keyword = ref('')
|
||||
const startDate = ref('')
|
||||
const endDate = ref('')
|
||||
const startDate = ref(todayDateInput())
|
||||
const endDate = ref(todayDateInput())
|
||||
const groupFilter = ref<number | null>(null)
|
||||
const groupOptions = ref<GroupOption[]>([])
|
||||
|
||||
@@ -68,8 +69,8 @@ function search() {
|
||||
|
||||
function reset() {
|
||||
keyword.value = ''
|
||||
startDate.value = ''
|
||||
endDate.value = ''
|
||||
startDate.value = todayDateInput()
|
||||
endDate.value = todayDateInput()
|
||||
groupFilter.value = null
|
||||
page.value = 1
|
||||
load()
|
||||
@@ -180,7 +181,7 @@ onMounted(load)
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td :colspan="isSuperAdmin ? 7 : 6" class="empty-tip">
|
||||
{{ keyword || startDate || endDate || groupFilter ? '暂无匹配记录' : '暂无用量记录' }}
|
||||
{{ keyword || groupFilter ? '暂无匹配记录' : '暂无用量记录' }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { formatDateTime, todayDateInput } from '@/utils/datetime'
|
||||
/** 数据去重总数据(registry) · 像素复刻旧版 admin.html panel-dedupe-total-data(自绘:分组摘要 + 双行筛选 + 旧式表格/分页 + 编辑/导入弹窗 + 导出等待遮罩)。
|
||||
* script 逻辑沿用现有 Vue 实现(查询/编辑/删除/导入轮询/导出秒表)。 */
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
@@ -35,7 +35,7 @@ const rows = ref<DedupeTotalItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const filter = reactive(createDedupeTotalFilterState())
|
||||
const filter = reactive({ ...createDedupeTotalFilterState(), startDate: todayDateInput(), endDate: todayDateInput() })
|
||||
const groups = ref<DedupeGroupOption[]>([])
|
||||
/** 非超管仅有一个可访问分组时,编辑/导入弹窗分组选择锁定为该组(保留展示、不可改)。 */
|
||||
const lockedGroupId = computed<number | null>(() => {
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
/** 日志管理页:桌面客户端 / 麦象采集机上报的日志浏览(仅超管)。
|
||||
* 支持来源/日期/关键字筛选,尾部内容查看(自动滚到底、可向前加载更早内容)、
|
||||
* 支持来源/用户/日期筛选,尾部内容查看(自动滚到底、可向前加载更早内容)、
|
||||
* 完整下载、删除;「采集配置」可调全量/精选模式(全局默认 + 终端覆盖)。 */
|
||||
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { formatDateTime, todayDateInput } from '@/utils/datetime'
|
||||
import { fetchHistoryUserOptions } from './history-api.ts'
|
||||
import type { HistoryUserOption } from './history-user-option.ts'
|
||||
import {
|
||||
deleteDeviceLogFile,
|
||||
deleteDeviceLogOverride,
|
||||
@@ -53,9 +55,11 @@ const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(15)
|
||||
const sourceFilter = ref('')
|
||||
const keyword = ref('')
|
||||
const startDate = ref('')
|
||||
const endDate = ref('')
|
||||
const uidFilter = ref('')
|
||||
const userOptions = ref<HistoryUserOption[]>([])
|
||||
const usersLoading = ref(false)
|
||||
const startDate = ref(todayDateInput())
|
||||
const endDate = ref(todayDateInput())
|
||||
const retentionDays = ref(7)
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
@@ -65,7 +69,7 @@ async function load() {
|
||||
try {
|
||||
const result = await fetchDeviceLogFiles({
|
||||
source: sourceFilter.value || undefined,
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
uid: uidFilter.value ? Number(uidFilter.value) : undefined,
|
||||
startDate: startDate.value || undefined,
|
||||
endDate: endDate.value || undefined,
|
||||
page: page.value,
|
||||
@@ -81,6 +85,17 @@ async function load() {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadUserOptions() {
|
||||
usersLoading.value = true
|
||||
try {
|
||||
userOptions.value = await fetchHistoryUserOptions()
|
||||
} catch {
|
||||
userOptions.value = []
|
||||
} finally {
|
||||
usersLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function search() {
|
||||
page.value = 1
|
||||
load()
|
||||
@@ -88,9 +103,9 @@ function search() {
|
||||
|
||||
function reset() {
|
||||
sourceFilter.value = ''
|
||||
keyword.value = ''
|
||||
startDate.value = ''
|
||||
endDate.value = ''
|
||||
uidFilter.value = ''
|
||||
startDate.value = todayDateInput()
|
||||
endDate.value = todayDateInput()
|
||||
page.value = 1
|
||||
load()
|
||||
}
|
||||
@@ -237,7 +252,10 @@ async function removeOverride(row: DeviceLogOverride) {
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
onMounted(() => {
|
||||
load()
|
||||
loadUserOptions()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -259,9 +277,12 @@ onMounted(load)
|
||||
<option v-for="option in SOURCE_OPTIONS" :key="option.value" :value="option.value">{{ option.label }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group" style="min-width: 220px">
|
||||
<label>设备 / 文件名</label>
|
||||
<input v-model="keyword" type="text" placeholder="模糊搜索设备名、设备ID、文件名" @keyup.enter="search" />
|
||||
<div class="form-group" style="min-width: 180px">
|
||||
<label>指定用户</label>
|
||||
<select v-model="uidFilter" :disabled="usersLoading">
|
||||
<option value="">全部用户</option>
|
||||
<option v-for="u in userOptions" :key="u.id" :value="String(u.id)">{{ u.username }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-group" style="min-width: 150px">
|
||||
<label>日志日期(起)</label>
|
||||
@@ -285,8 +306,7 @@ onMounted(load)
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 110px">来源</th>
|
||||
<th style="width: 230px">设备</th>
|
||||
<th style="width: 130px">用户</th>
|
||||
<th style="width: 200px">用户</th>
|
||||
<th style="width: 230px">文件名</th>
|
||||
<th style="width: 110px">日志日期</th>
|
||||
<th style="width: 100px">已收大小</th>
|
||||
@@ -303,10 +323,6 @@ onMounted(load)
|
||||
{{ sourceLabel(row.source) }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<span class="device-name" :title="row.deviceId">{{ row.deviceName || '—' }}</span>
|
||||
<span class="device-id" :title="row.deviceId">{{ row.deviceId }}</span>
|
||||
</td>
|
||||
<td>
|
||||
<span v-if="row.username" class="user-name">{{ row.username }}</span>
|
||||
<span v-else-if="row.uid" class="user-name">UID {{ row.uid }}</span>
|
||||
@@ -327,11 +343,11 @@ onMounted(load)
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="9" class="empty-tip">加载中...</td>
|
||||
<td colspan="8" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="9" class="empty-tip">
|
||||
{{ keyword || sourceFilter || startDate || endDate ? '暂无匹配日志' : '暂无日志上报(客户端/采集机上报后自动出现在这里)' }}
|
||||
<td colspan="8" class="empty-tip">
|
||||
{{ sourceFilter || uidFilter ? '暂无匹配日志' : '暂无日志上报(客户端/采集机上报后自动出现在这里)' }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
/** 生成记录页 · 像素复刻旧版 admin.html panel-history(自绘:form-box 筛选 + panel-box 表格 + 旧式分页 + thumb 缩略图)。
|
||||
* script 逻辑沿用现有 Vue 实现(查询/翻页/跳页/点击缩略图放大预览)。 */
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { formatDateTime, todayDateTimeRange } from '@/utils/datetime'
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { fetchHistoryList, fetchHistoryUserOptions } from './history-api.ts'
|
||||
import type { HistoryUserOption } from './history-user-option.ts'
|
||||
@@ -19,7 +19,8 @@ const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const userOptions = ref<HistoryUserOption[]>([])
|
||||
const errorText = ref('')
|
||||
const filter = reactive({ userId: '', timeStart: '', timeEnd: '' })
|
||||
const [todayStart, todayEnd] = todayDateTimeRange()
|
||||
const filter = reactive({ userId: '', timeStart: todayStart, timeEnd: todayEnd })
|
||||
|
||||
const previewVisible = ref(false)
|
||||
const previewItem = ref<HistoryRecordItem | null>(null)
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { formatDateTime, todayDateTimeRange } from '@/utils/datetime'
|
||||
import {
|
||||
fetchTaskCenterOverview,
|
||||
fetchTaskCenterShopOptions,
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
progressPercent,
|
||||
progressText,
|
||||
shopDisplayName,
|
||||
tabCount,
|
||||
taskStatusLabel,
|
||||
taskStatusType,
|
||||
variantAccountText,
|
||||
@@ -51,7 +52,12 @@ const activeTab = ref<BoardTab>('tasks')
|
||||
const overview = ref<TaskCenterOverview | null>(null)
|
||||
const shops = ref<TaskCenterShop[]>([])
|
||||
const shopOptions = ref<string[]>([])
|
||||
const filter = reactive<TaskCenterTaskFilter>(createTaskFilter())
|
||||
/** 首屏与「重置」都锁定当天;共享工厂 createTaskFilter 保持全空(它被单测与别处复用)。 */
|
||||
function todayTaskRange(): Pick<TaskCenterTaskFilter, 'startTime' | 'endTime'> {
|
||||
const [startTime, endTime] = todayDateTimeRange()
|
||||
return { startTime, endTime }
|
||||
}
|
||||
const filter = reactive<TaskCenterTaskFilter>({ ...createTaskFilter(), ...todayTaskRange() })
|
||||
const tasks = ref<TaskCenterTaskRow[]>([])
|
||||
const taskTotal = ref(0)
|
||||
const taskPage = ref(1)
|
||||
@@ -62,7 +68,8 @@ const tasksLoading = ref(false)
|
||||
|
||||
const variantFilter = reactive<TaskCenterVariantFilter>(createVariantFilter())
|
||||
const variantRows = ref<TaskCenterVariantTaskRow[]>([])
|
||||
const variantTotal = ref(0)
|
||||
/** 没查过就是 null(徽章画「—」):变体列表是外部依赖,停在页签一时不能替它说 0。 */
|
||||
const variantTotal = ref<number | null>(null)
|
||||
const variantPage = ref(1)
|
||||
const variantPageSize = ref(20)
|
||||
const variantLoading = ref(false)
|
||||
@@ -76,7 +83,11 @@ const detail = ref<TaskCenterTaskDetail | null>(null)
|
||||
const updatedAt = ref('')
|
||||
|
||||
const taskTotalPages = computed(() => Math.max(1, Math.ceil(taskTotal.value / taskPageSize.value)))
|
||||
const variantTotalPages = computed(() => Math.max(1, Math.ceil(variantTotal.value / variantPageSize.value)))
|
||||
const variantTotalPages = computed(() => Math.max(1, Math.ceil((variantTotal.value ?? 0) / variantPageSize.value)))
|
||||
|
||||
/** 页签一徽章 = 当前在跑任务数,与汇总卡「进行中任务」同源,不允许两处各算各的。
|
||||
* 列表 total(历史全量,且每天 00:00 的 7 天保留清理会往下掉)只用于分页,不上徽章。 */
|
||||
const runningBadge = computed(() => tabCount(overview.value?.runningTasks))
|
||||
|
||||
/** 下拉候选 = 店铺库 + 面板上出现的店铺名(后者可能已从店铺库删掉,下钻要筛得动)。 */
|
||||
const shopFilterOptions = computed(() => {
|
||||
@@ -136,8 +147,9 @@ async function loadVariants(silent = false) {
|
||||
buildVariantQuery(variantFilter, variantPage.value, variantPageSize.value),
|
||||
)
|
||||
variantRows.value = result?.items || []
|
||||
variantTotal.value = Number(result?.total || 0)
|
||||
variantTotal.value = tabCount(result?.total)
|
||||
} catch (error) {
|
||||
variantTotal.value = null
|
||||
ElMessage.error(errorText(error, '变体采集加载失败'))
|
||||
} finally {
|
||||
if (!silent) variantLoading.value = false
|
||||
@@ -155,6 +167,13 @@ async function refreshAll(silent = false) {
|
||||
updatedAt.value = formatDateTime(Date.now())
|
||||
}
|
||||
|
||||
/** 首屏把「另一个页签」也查一遍,徽章才有真数可画。
|
||||
* 只补这一次:变体列表代理麦象 console(外部依赖、8s 超时),不进 30s 轮询热路径。 */
|
||||
async function loadInactiveTabTotal() {
|
||||
if (activeTab.value === 'tasks') await loadVariants(true)
|
||||
else await loadTasks(true)
|
||||
}
|
||||
|
||||
function switchTab(tab: BoardTab) {
|
||||
if (activeTab.value === tab) return
|
||||
activeTab.value = tab
|
||||
@@ -171,7 +190,7 @@ function search() {
|
||||
}
|
||||
|
||||
function resetFilter() {
|
||||
Object.assign(filter, createTaskFilter())
|
||||
Object.assign(filter, createTaskFilter(), todayTaskRange())
|
||||
taskPage.value = 1
|
||||
void loadTasks()
|
||||
}
|
||||
@@ -259,6 +278,7 @@ function onVisibilityChange() {
|
||||
|
||||
onMounted(() => {
|
||||
void refreshAll()
|
||||
void loadInactiveTabTotal()
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
pollTimer = setInterval(() => {
|
||||
if (typeof document !== 'undefined' && document.visibilityState !== 'visible') return
|
||||
@@ -281,10 +301,10 @@ onUnmounted(() => {
|
||||
<div class="tc-head">
|
||||
<div class="tabs">
|
||||
<button class="tab" :class="{ active: activeTab === 'tasks' }" type="button" @click="switchTab('tasks')">
|
||||
客户端任务 <span class="t-count">{{ taskTotal }}</span>
|
||||
客户端任务 <span class="t-count" title="当前在跑任务数,与上方「进行中任务」同源">{{ runningBadge ?? '—' }}</span>
|
||||
</button>
|
||||
<button class="tab" :class="{ active: activeTab === 'variant' }" type="button" @click="switchTab('variant')">
|
||||
变体采集 <span class="t-count">{{ variantTotal }}</span>
|
||||
变体采集 <span class="t-count" title="麦象批量任务条数(全部状态),「—」= 还没查到">{{ variantTotal ?? '—' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="tc-head-tools">
|
||||
@@ -394,6 +414,7 @@ onUnmounted(() => {
|
||||
<label>店铺</label>
|
||||
<el-select
|
||||
v-model="filter.shop"
|
||||
class="admin-filter"
|
||||
filterable
|
||||
clearable
|
||||
placeholder="全部店铺"
|
||||
@@ -429,12 +450,11 @@ onUnmounted(() => {
|
||||
<th style="width: 160px">店铺</th>
|
||||
<th style="width: 120px">业务</th>
|
||||
<th style="width: 120px">状态</th>
|
||||
<th style="width: 170px">当前处理</th>
|
||||
<th style="width: 170px">任务ID</th>
|
||||
<th style="width: 165px">开始时间</th>
|
||||
<th style="width: 165px">最近上报</th>
|
||||
<th style="width: 165px">结束时间</th>
|
||||
<th style="width: 190px">进度</th>
|
||||
<th style="width: 90px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -442,7 +462,6 @@ onUnmounted(() => {
|
||||
<tr v-for="row in tasks" :key="row.taskNo">
|
||||
<td>
|
||||
<span class="strong">{{ accountOf(row) }}</span>
|
||||
<span class="sub">{{ row.taskNo }}</span>
|
||||
</td>
|
||||
<td>{{ shopDisplayName(row.shopName, row.shopCount) }}</td>
|
||||
<td>{{ row.moduleLabel || row.moduleType }}</td>
|
||||
@@ -451,7 +470,7 @@ onUnmounted(() => {
|
||||
<span v-if="row.stuck" class="badge warn">疑似卡住</span>
|
||||
</td>
|
||||
<td>
|
||||
<span class="scope" :title="currentScopeOf(row)">{{ currentScopeOf(row) }}</span>
|
||||
<button class="cell-link mono" type="button" @click="openDetail(row)">{{ row.id }}</button>
|
||||
</td>
|
||||
<td>{{ formatDateTime(row.createdAt) }}</td>
|
||||
<td>
|
||||
@@ -467,16 +486,13 @@ onUnmounted(() => {
|
||||
</div>
|
||||
<div class="p-track"><div class="p-fill" :style="{ width: progressPercent(row) + '%' }"></div></div>
|
||||
</td>
|
||||
<td>
|
||||
<button class="btn btn-ghost btn-sm" type="button" @click="openDetail(row)">查看</button>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="tasksLoading">
|
||||
<td colspan="10" class="empty-tip">加载中...</td>
|
||||
<td colspan="9" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="10" class="empty-tip">暂无符合条件的任务</td>
|
||||
<td colspan="9" class="empty-tip">暂无符合条件的任务</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -559,7 +575,7 @@ onUnmounted(() => {
|
||||
</table>
|
||||
</div>
|
||||
<OldPagination
|
||||
:total="variantTotal"
|
||||
:total="variantTotal ?? 0"
|
||||
:page="variantPage"
|
||||
:page-size="variantPageSize"
|
||||
@change="changeVariantPage"
|
||||
@@ -771,7 +787,12 @@ h3 {
|
||||
.shop-filter {
|
||||
position: relative;
|
||||
}
|
||||
/* 提示行必须退出列流:.form-row 是 align-items: flex-end,组内多一行会把「店铺」label 顶得比别的筛选项高。 */
|
||||
.filter-tip {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: calc(100% + 4px);
|
||||
white-space: nowrap;
|
||||
color: #93a4b5;
|
||||
font-size: 11.5px;
|
||||
}
|
||||
@@ -780,7 +801,7 @@ h3 {
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 14px 18px;
|
||||
margin-bottom: 16px;
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
@@ -850,12 +871,6 @@ h3 {
|
||||
border-color: #95b1cb;
|
||||
color: #2f5d8b;
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 32px;
|
||||
padding: 4px 12px;
|
||||
font-size: 12.5px;
|
||||
border-radius: 7px;
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
overflow-x: auto;
|
||||
@@ -895,6 +910,17 @@ td {
|
||||
font-size: 12px;
|
||||
word-break: break-all;
|
||||
}
|
||||
/* 任务 ID 单元格:「操作」列删除后,它是详情抽屉唯一的入口。 */
|
||||
.cell-link {
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: #2f5d8b;
|
||||
cursor: pointer;
|
||||
}
|
||||
.cell-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.scope {
|
||||
display: inline-block;
|
||||
max-width: 160px;
|
||||
|
||||
@@ -135,17 +135,37 @@ export function shopDisplayName(shopName: string | null | undefined, shopCount:
|
||||
return count > 1 ? `${name} 等${count}个` : name
|
||||
}
|
||||
|
||||
export function progressText(row: { progressSuccess: number; progressTotal: number }): string {
|
||||
const total = Number(row.progressTotal || 0)
|
||||
if (total <= 0) return '—'
|
||||
return `成功 ${Number(row.progressSuccess || 0)} / 总 ${total}`
|
||||
/** 页签徽章用的条数:只有接口真的回了非负数才算一个数,否则回 null 画「—」。
|
||||
* 麦象在结果表未注册时把 total 回成 -1 哨兵,`Number(x || 0)` 会把它读成 0 条。 */
|
||||
export function tabCount(total: unknown): number | null {
|
||||
if (total === null || total === undefined || total === '') return null
|
||||
const value = Number(total)
|
||||
return Number.isFinite(value) && value >= 0 ? value : null
|
||||
}
|
||||
|
||||
export function progressPercent(row: { progressSuccess: number; progressTotal: number }): number {
|
||||
/** 进度行:已完成数 = 成功 + 失败,与客户端一致(跑完一步就计入,不论成败)。
|
||||
* 见 frontend-vue `BrandBrandTab.vue`「完成数 = 已处理品牌行(成功或查询失败都计入)」;
|
||||
* 旧口径只数成功,会把「1 步全失败」的终态任务显示成 0 / 1。 */
|
||||
export interface TaskCenterProgress {
|
||||
progressSuccess: number
|
||||
progressFailed: number
|
||||
progressTotal: number
|
||||
}
|
||||
|
||||
function progressDone(row: TaskCenterProgress): number {
|
||||
return Math.max(0, Number(row.progressSuccess || 0)) + Math.max(0, Number(row.progressFailed || 0))
|
||||
}
|
||||
|
||||
export function progressText(row: TaskCenterProgress): string {
|
||||
const total = Number(row.progressTotal || 0)
|
||||
if (total <= 0) return '—'
|
||||
return `已完成 ${progressDone(row)} / 总 ${total}`
|
||||
}
|
||||
|
||||
export function progressPercent(row: TaskCenterProgress): number {
|
||||
const total = Number(row.progressTotal || 0)
|
||||
if (total <= 0) return 0
|
||||
const percent = Math.round((Number(row.progressSuccess || 0) / total) * 100)
|
||||
return Math.min(100, Math.max(0, percent))
|
||||
return Math.min(100, Math.max(0, Math.round((progressDone(row) / total) * 100)))
|
||||
}
|
||||
|
||||
/** datetime-local 原生值(YYYY-MM-DDTHH:mm) → 后端 LocalDateTime 兼容的秒级格式。 */
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { formatDateTime, todayDateTimeRange } from '@/utils/datetime'
|
||||
/** 视频任务记录页 · 像素复刻旧版 admin.html panel-image-video-tasks(自绘:form-box 筛选[用户名/提交起止+查询/重置] + panel-box toolbar[全选/批量下载/权限配置/汇总] + 任务卡片网格 + 旧式分页)。
|
||||
* script 逻辑沿用现有 Vue 实现(批量打包/明细抽屉/权限授权)。 */
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
@@ -29,7 +29,10 @@ const pageSize = ref(10)
|
||||
const jumpPage = ref('')
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(totalTasks.value / pageSize.value)))
|
||||
|
||||
const filter = reactive<ImageVideoFilter & { dateRange: string[] }>({ ...createImageVideoFilter(), dateRange: [] })
|
||||
const filter = reactive<ImageVideoFilter & { dateRange: string[] }>({
|
||||
...createImageVideoFilter(),
|
||||
dateRange: todayDateTimeRange(),
|
||||
})
|
||||
const selection = ref<Set<string>>(new Set())
|
||||
|
||||
const detailVisible = ref(false)
|
||||
@@ -128,7 +131,7 @@ function apply() {
|
||||
|
||||
function reset() {
|
||||
Object.assign(filter, createImageVideoFilter())
|
||||
filter.dateRange = []
|
||||
filter.dateRange = todayDateTimeRange()
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { formatDateTime, todayDateTimeRange } from '@/utils/datetime'
|
||||
/** 店铺数据记录页 · 像素复刻旧版 admin.html panel-shop-data-crawl-tasks(自绘:form-box 筛选[h4 筛选条件] + panel-box toolbar[全选/批量下载/权限配置/汇总] + 每店卡片网格 + 旧式分页(店铺级+卡片级 9/页))。
|
||||
* script 逻辑沿用现有 Vue 实现(批量打包/删除结果文件[保留]/权限授权)。 */
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
@@ -40,7 +40,10 @@ const cardPageSize = ref(10)
|
||||
const cardJump = ref('')
|
||||
const cardTotalPages = computed(() => Math.max(1, Math.ceil(allResultRows.value.length / cardPageSize.value)))
|
||||
|
||||
const filter = reactive<ShopDataFilter & { dateRange: string[] }>({ ...createShopDataFilter(), dateRange: [] })
|
||||
const filter = reactive<ShopDataFilter & { dateRange: string[] }>({
|
||||
...createShopDataFilter(),
|
||||
dateRange: todayDateTimeRange(),
|
||||
})
|
||||
const selection = ref<Set<string>>(new Set())
|
||||
|
||||
const permissionVisible = ref(false)
|
||||
@@ -134,7 +137,7 @@ function apply() {
|
||||
|
||||
function reset() {
|
||||
Object.assign(filter, createShopDataFilter())
|
||||
filter.dateRange = []
|
||||
filter.dateRange = todayDateTimeRange()
|
||||
page.value = 1
|
||||
void load()
|
||||
}
|
||||
|
||||
@@ -34,6 +34,17 @@ function pad(n: string | number): string {
|
||||
return String(n).padStart(2, '0')
|
||||
}
|
||||
|
||||
/** 后台日期筛选的统一默认值:进入页面即锁定「当天」。 */
|
||||
export function todayDateInput(now: Date = new Date()): string {
|
||||
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`
|
||||
}
|
||||
|
||||
/** 当天区间(原生 <input type="datetime-local"> 取值形态,止于 23:59 与手工选择口径一致)。 */
|
||||
export function todayDateTimeRange(now: Date = new Date()): [string, string] {
|
||||
const day = todayDateInput(now)
|
||||
return [`${day}T00:00`, `${day}T23:59`]
|
||||
}
|
||||
|
||||
function padDate(d: Date): string {
|
||||
const y = d.getFullYear()
|
||||
const mo = pad(d.getMonth() + 1)
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, statSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { readSource } from './helpers.ts'
|
||||
import { todayDateInput, todayDateTimeRange } from '../src/utils/datetime.ts'
|
||||
|
||||
// 后台日期筛选统一默认「当天」(2026-10-04 定口径)的护栏:
|
||||
// 凡渲染了日期筛选控件的页面/组件,首屏初值与「重置」目标都必须是当天;
|
||||
// 以后新增带日期筛选的页若没接入,会被本用例拦下而不是悄悄漏掉。
|
||||
|
||||
const DATE_CONTROL_RES = [/type="date"/, /type="datetime-local"/, /<el-date-picker/]
|
||||
|
||||
/** 有意排除:该页日期是 ASIN「上架时间」,默认当天会让首屏几乎为空(用户 2026-10-04 确认)。 */
|
||||
const EXEMPT = new Set(['src/pages/tasks/DuplicateCheckPage.vue'])
|
||||
|
||||
/** 把日期筛选清回空值的写法(初值或重置里都不许出现)。 */
|
||||
const DATE_CLEARED =
|
||||
/(?:startDate|endDate|timeStart|timeEnd|startTime|endTime|dateFrom|dateTo)(?:\.value)?\s*[:=]\s*''|dateRange\s*[:=]\s*\[\s*\]/
|
||||
|
||||
/** 去掉 import 行:`import { todayDateInput }` 这种"只引不用"不能算接入(变异实测会造恒绿)。 */
|
||||
function withoutImportLines(src: string): string {
|
||||
return src.split(/\r?\n/).filter((line) => !/^\s*import\b/.test(line)).join('\n')
|
||||
}
|
||||
|
||||
function hasDateControl(src: string): boolean {
|
||||
return DATE_CONTROL_RES.some((re) => re.test(src))
|
||||
}
|
||||
|
||||
function vueFiles(): string[] {
|
||||
const out: string[] = []
|
||||
const walk = (dir: string): void => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const abs = join(dir, name)
|
||||
if (statSync(abs).isDirectory()) walk(abs)
|
||||
else if (name.endsWith('.vue')) out.push(abs.split(/[\\/]+/).join('/'))
|
||||
}
|
||||
}
|
||||
walk('src')
|
||||
return out
|
||||
}
|
||||
|
||||
const managed = vueFiles().filter((rel) => !EXEMPT.has(rel) && hasDateControl(readSource(rel)))
|
||||
|
||||
test('test_default_today_normal_inventory_is_not_empty', () => {
|
||||
// 分母由扫描得出、不自挑:掉到 7 以下说明控件识别正则已失效(会造出恒绿)
|
||||
assert.ok(managed.length >= 7, `只扫到 ${managed.length} 个带日期筛选的文件,扫描规则可能已失效`)
|
||||
})
|
||||
|
||||
test('test_default_today_normal_every_date_filter_page_is_wired', () => {
|
||||
for (const rel of managed) {
|
||||
const src = readSource(rel)
|
||||
assert.match(
|
||||
withoutImportLines(src),
|
||||
/todayDateInput\(|todayDateTimeRange\(/,
|
||||
`${rel} 有日期筛选控件但未默认当天`,
|
||||
)
|
||||
assert.match(src, /from ['"]@\/utils\/datetime['"]/, `${rel} 的 today* 取值须来自 @/utils/datetime`)
|
||||
}
|
||||
})
|
||||
|
||||
test('test_default_today_normal_reset_keeps_today', () => {
|
||||
for (const rel of managed) {
|
||||
const hit = readSource(rel)
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => DATE_CLEARED.test(line))
|
||||
assert.deepEqual(hit, [], `${rel} 仍把日期筛选清成空值:\n${hit.join('\n')}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('test_default_today_boundary_exempt_still_intentional', () => {
|
||||
for (const rel of EXEMPT) {
|
||||
const src = readSource(rel)
|
||||
assert.ok(hasDateControl(src), `${rel} 已无日期筛选控件,应从豁免清单移除`)
|
||||
assert.equal(
|
||||
/todayDateInput\(|todayDateTimeRange\(/.test(withoutImportLines(src)),
|
||||
false,
|
||||
`${rel} 已被排除,不得接入默认当天`,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('test_default_today_boundary_values_match_backend_patterns', () => {
|
||||
const day = todayDateInput()
|
||||
assert.match(day, /^\d{4}-\d{2}-\d{2}$/, 'type="date" 与各页 ISO 日期校验')
|
||||
const [start, end] = todayDateTimeRange()
|
||||
const LOCAL_DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/
|
||||
assert.match(start, LOCAL_DATETIME, 'datetime-local 各页的秒级校验')
|
||||
assert.match(end, LOCAL_DATETIME)
|
||||
assert.equal(day, start.slice(0, 10), '日期与区间必须同一天,不能跨零点各算各的')
|
||||
assert.ok(start < end, '起须早于止,否则各页「开始日期不能晚于结束」校验会弹警告')
|
||||
})
|
||||
|
||||
test('test_default_today_invalid_input_pads_and_uses_local_time', () => {
|
||||
const fixed = new Date(2026, 0, 5, 8, 30, 0)
|
||||
assert.equal(todayDateInput(fixed), '2026-01-05', '月/日须补零')
|
||||
assert.deepEqual(todayDateTimeRange(fixed), ['2026-01-05T00:00', '2026-01-05T23:59'])
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readSource } from './helpers.ts'
|
||||
|
||||
// 日志管理列表改「用户维度」的护栏(2026-10-04 用户要求:去掉设备/文件名模糊搜索与设备列,加用户筛选)。
|
||||
// 后端查询侧已有 DeviceLogServiceTest 锁住 uid 精确过滤;这里补前端这一段——
|
||||
// 页面筛选控件、请求参数、表头列三处任意一处退回设备维度,本用例会红而不是悄悄生效。
|
||||
|
||||
const PAGE = 'src/pages/records/DeviceLogsPage.vue'
|
||||
const API = 'src/api/device-logs.ts'
|
||||
|
||||
/** 取第一张表 = 日志文件列表;采集配置弹窗里另有一张含「设备」的表,混着判会误报。 */
|
||||
function firstTable(src: string): string {
|
||||
const matched = /<table[\s\S]*?<\/table>/.exec(src)
|
||||
assert.ok(matched, '页面里没找到 <table>,取块规则已失效')
|
||||
return matched[0]
|
||||
}
|
||||
|
||||
function functionBody(src: string, from: string, to: string): string {
|
||||
const start = src.indexOf(from)
|
||||
const end = src.indexOf(to)
|
||||
assert.ok(start >= 0, `api 里找不到 ${from}`)
|
||||
assert.ok(end > start, `api 里 ${to} 缺失或在 ${from} 之前`)
|
||||
return src.slice(start, end)
|
||||
}
|
||||
|
||||
test('test_device_log_list_header_is_user_scoped_without_device_column', () => {
|
||||
const table = firstTable(readSource(PAGE))
|
||||
assert.match(table, /<th[^>]*>\s*用户\s*<\/th>/, '列表表头没有「用户」列')
|
||||
assert.doesNotMatch(table, /设备/, '列表表头又出现「设备」列')
|
||||
})
|
||||
|
||||
test('test_device_log_list_colspan_matches_header_column_count', () => {
|
||||
// 「删了列忘了改占位行 colspan」是这类改动最常留下的残行
|
||||
const table = firstTable(readSource(PAGE))
|
||||
const columns = (table.match(/<th[\s>]/g) ?? []).length
|
||||
assert.ok(columns >= 2, `表头只数到 ${columns} 列,取块规则已失效`)
|
||||
const spans = [...table.matchAll(/colspan="(\d+)"/g)].map((m) => Number(m[1]))
|
||||
assert.ok(spans.length >= 1, '列表 tbody 没有 colspan 占位行')
|
||||
for (const span of spans) {
|
||||
assert.equal(span, columns, `占位行 colspan=${span} 与表头列数 ${columns} 不符`)
|
||||
}
|
||||
})
|
||||
|
||||
test('test_device_log_page_wires_user_dropdown_to_uid_param', () => {
|
||||
const page = readSource(PAGE)
|
||||
assert.match(page, /指定用户[\s\S]{0,220}?v-model="uidFilter"/, '筛选条没有绑定 uidFilter 的下拉')
|
||||
assert.match(page, /uid:\s*uidFilter\.value\s*\?\s*Number\(uidFilter\.value\)/, '请求未把所选用户映射成 uid')
|
||||
})
|
||||
|
||||
test('test_device_log_list_query_carries_no_fuzzy_keyword', () => {
|
||||
const body = functionBody(readSource(API), 'export async function fetchDeviceLogFiles', 'export async function fetchDeviceLogContent')
|
||||
assert.match(body, /query\.uid = params\.uid/, '列表接口不再下发 uid')
|
||||
assert.doesNotMatch(body, /keyword/, '列表接口又带回 keyword 模糊匹配')
|
||||
// 页面整份都不该出现 keyword:设备/文件名模糊搜索的入口应彻底消失
|
||||
assert.doesNotMatch(readSource(PAGE), /\bkeyword\b/, '日志管理页仍存在模糊搜索入参')
|
||||
})
|
||||
|
||||
test('test_device_log_user_dropdown_is_filled_from_admin_users', () => {
|
||||
// 复用生成记录页那份用户下拉,避免两处各写一套解析
|
||||
const page = readSource(PAGE)
|
||||
assert.match(page, /import \{[^}]*fetchHistoryUserOptions[^}]*\} from/, '用户下拉没有走既有的 admin users 取数')
|
||||
// 断言锁定挂载时的**调用点**:只写 /loadUserOptions\(\)/ 会匹配到函数声明本身,恒绿
|
||||
assert.match(
|
||||
page,
|
||||
/onMounted\(\(\)\s*=>\s*\{[^}]*loadUserOptions\(\)/,
|
||||
'用户选项未在 onMounted 里加载(首屏下拉会是空的)',
|
||||
)
|
||||
})
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
progressPercent,
|
||||
progressText,
|
||||
shopDisplayName,
|
||||
tabCount,
|
||||
taskStatusLabel,
|
||||
taskStatusType,
|
||||
toApiTime,
|
||||
@@ -124,12 +125,25 @@ test('task_center_device_display_falls_back_to_truncated_id', () => {
|
||||
assert.equal(shopDisplayName('', 0), '—')
|
||||
})
|
||||
|
||||
test('task_center_progress_text_and_percent_boundaries', () => {
|
||||
assert.equal(progressText({ progressSuccess: 3, progressTotal: 10 }), '成功 3 / 总 10')
|
||||
assert.equal(progressText({ progressSuccess: 0, progressTotal: 0 }), '—')
|
||||
assert.equal(progressPercent({ progressSuccess: 3, progressTotal: 10 }), 30)
|
||||
assert.equal(progressPercent({ progressSuccess: 0, progressTotal: 0 }), 0)
|
||||
assert.equal(progressPercent({ progressSuccess: 15, progressTotal: 10 }), 100, '超出按 100 截断')
|
||||
/**
|
||||
* 进度口径与客户端一致:完成数 = 已处理(成功 + 失败都算跑完一步),
|
||||
* 见 frontend-vue `BrandBrandTab.vue`「完成数 = 已处理品牌行(成功或查询失败都计入)」。
|
||||
* 旧文案「成功 0 / 总 1」会把一个已跑完(失败 1)的任务读成 0% 进度。
|
||||
*/
|
||||
test('task_center_progress_counts_done_rows_like_the_client', () => {
|
||||
assert.equal(progressText({ progressSuccess: 3, progressFailed: 0, progressTotal: 10 }), '已完成 3 / 总 10')
|
||||
assert.equal(
|
||||
progressText({ progressSuccess: 0, progressFailed: 1, progressTotal: 1 }),
|
||||
'已完成 1 / 总 1',
|
||||
'失败的那一步同样是已完成的一步',
|
||||
)
|
||||
assert.equal(progressText({ progressSuccess: 0, progressFailed: 0, progressTotal: 0 }), '—')
|
||||
assert.equal(progressText({ progressSuccess: 0, progressFailed: 0, progressTotal: -1 }), '—', '哨兵总数不当进度')
|
||||
assert.equal(progressPercent({ progressSuccess: 3, progressFailed: 1, progressTotal: 10 }), 40)
|
||||
assert.equal(progressPercent({ progressSuccess: 0, progressFailed: 1, progressTotal: 1 }), 100)
|
||||
assert.equal(progressPercent({ progressSuccess: 0, progressFailed: 0, progressTotal: 0 }), 0)
|
||||
assert.equal(progressPercent({ progressSuccess: 15, progressFailed: 0, progressTotal: 10 }), 100, '超出按 100 截断')
|
||||
assert.equal(progressPercent({ progressSuccess: -5, progressFailed: 0, progressTotal: 10 }), 0, '脏负数不按负进度画')
|
||||
})
|
||||
|
||||
test('task_center_query_builder_omits_blanks_and_normalizes_time', () => {
|
||||
@@ -195,6 +209,40 @@ test('task_center_shop_panel_is_the_board_and_drills_down_by_exact_shop', () =>
|
||||
assert.equal(page.includes('device-strip'), false, '设备卡条已删除')
|
||||
})
|
||||
|
||||
/**
|
||||
* 任务列表列改造(2026-10-04 用户要求):
|
||||
* ① 「当前处理」列全是「—」(无快照模块没有 current_scope_key),换成任务 ID;
|
||||
* ID 单元格继承被删掉的「查看」按钮职责,否则详情抽屉没有入口。
|
||||
* ② 账号下方的 taskNo 副行删掉——ID 已经在独立列里,长任务号只把行撑高。
|
||||
* ③ 「操作」列整条删除,空态 colspan 跟着从 10 收到 9。
|
||||
* ④ 店铺那组比别的多一行提示文案,而 .form-row 是 align-items: flex-end,
|
||||
* 于是它的 label 被顶高一行——提示必须退出列流(绝对定位)而不是删掉。
|
||||
*/
|
||||
test('task_center_task_list_columns_are_trimmed_to_the_data_that_exists', () => {
|
||||
const page = readSource(PAGE)
|
||||
const style = page.slice(page.indexOf('<style scoped>'))
|
||||
|
||||
assert.match(page, /<th style="width: 170px">任务ID<\/th>/, '「当前处理」列改名任务ID')
|
||||
assert.equal(/<th[^>]*>当前处理<\/th>/.test(page), false, '列表不再有全「—」的当前处理列')
|
||||
assert.match(page, /<td>\s*<button class="cell-link mono" type="button" @click="openDetail\(row\)">\{\{ row\.id \}\}<\/button>/, 'ID 单元格点开详情')
|
||||
assert.match(page, /:key="row\.taskNo"/, ':key 仍是唯一任务号(biz 与 brand 两张表的自增 id 会撞)')
|
||||
|
||||
assert.equal(/<span class="sub">\{\{ row\.taskNo \}\}<\/span>/.test(page), false, '账号下方不再重复任务号')
|
||||
assert.equal(/<th[^>]*>操作<\/th>/.test(page), false, '操作列已删')
|
||||
assert.equal(page.includes('btn-sm'), false, '没有别的按钮后 btn-sm 样式一并撤掉')
|
||||
assert.equal(/colspan="10"/.test(page), false, '任务表空态不再是 10 列')
|
||||
assert.equal(page.match(/colspan="9"/g)?.length, 2, '加载中/空态两处收到 9 列')
|
||||
|
||||
assert.match(style, /\.shop-filter\s*\{[^}]*position: relative/, '店铺组是提示的定位父元素')
|
||||
assert.match(style, /\.filter-tip\s*\{[^}]*position: absolute/, '提示绝对定位,不再撑高该组把 label 顶上去')
|
||||
assert.match(style, /\.form-row\s*\{[^}]*align-items: flex-end[^}]*margin-bottom: 22px/, '底部留白容纳提示行')
|
||||
assert.match(
|
||||
page,
|
||||
/<el-select[\s\S]{0,220}class="admin-filter"[\s\S]{0,220}placeholder="全部店铺"/,
|
||||
'店铺下拉挂全局 admin-filter(控件 42px,与其它原生控件同高,flex-end 下 label 才齐线)',
|
||||
)
|
||||
})
|
||||
|
||||
test('task_center_page_wires_tabs_filters_and_polling', () => {
|
||||
const page = readSource(PAGE)
|
||||
assert.match(page, /客户端任务/, '页签一文案')
|
||||
@@ -213,3 +261,40 @@ test('task_center_page_wires_tabs_filters_and_polling', () => {
|
||||
assert.match(page, /resMes/, '变体表展示麦象 res_mes')
|
||||
assert.equal(/shopName/.test(readSource(PAGE)), true)
|
||||
})
|
||||
|
||||
/**
|
||||
* 页签徽章的两个口径缺陷:
|
||||
* ① 「客户端任务」曾绑列表 total(默认全部状态、全部时间 = 历史全量,线上 1135 条,
|
||||
* 且每天 00:00 的 7 天保留清理会把它往下掉),而这一页讲的是「当前在跑」——
|
||||
* 现在绑汇总卡的 runningTasks,两处不允许各算各的。
|
||||
* ② 「变体采集」曾恒显示 0:refreshAll 只加载当前页签的列表,停在页签一时该接口
|
||||
* 从未请求过(线上此刻返回 106 条)。没查过与"查了是 0"必须是两个读数。
|
||||
*/
|
||||
test('task_center_tab_badge_never_claims_an_unqueried_count', () => {
|
||||
assert.equal(tabCount(undefined), null, '接口没回 total 不能读成 0')
|
||||
assert.equal(tabCount(null), null)
|
||||
assert.equal(tabCount(''), null)
|
||||
assert.equal(tabCount(Number.NaN), null)
|
||||
assert.equal(tabCount(-1), null, '麦象未注册结果表时 total 是 -1 哨兵,不是条数')
|
||||
assert.equal(tabCount(0), 0, '接口真的返回 0 才算 0')
|
||||
assert.equal(tabCount('106'), 106)
|
||||
|
||||
const page = readSource(PAGE)
|
||||
// ① 页签一 = 在跑数,与汇总卡同源;历史全量只留给分页用
|
||||
assert.match(page, /const runningBadge = computed\(\(\) => tabCount\(overview\.value\?\.runningTasks\)\)/,
|
||||
'页签一徽章取 overview.runningTasks')
|
||||
assert.match(page, /\{\{\s*runningBadge\s*\?\?\s*'—'\s*\}\}/, '页签一画在跑数,没取到时画 —')
|
||||
assert.equal(/<span class="t-count">\{\{ taskTotal/.test(page), false, '页签一不再绑列表总数')
|
||||
// ② 页签二 = 真查过的条数,未查过/查失败都画 —
|
||||
assert.match(page, /const variantTotal = ref<number \| null>\(null\)/, '初始是「没查过」不是 0')
|
||||
assert.match(page, /\{\{\s*variantTotal\s*\?\?\s*'—'\s*\}\}/, '页签二未查过时徽章画 —')
|
||||
assert.match(page, /variantTotal\.value = tabCount\(/, '变体总数经 tabCount 归一')
|
||||
assert.match(page, /catch[\s\S]{0,160}variantTotal\.value = null/, '加载失败退回「没查过」,不留在 0')
|
||||
assert.match(page, /loadInactiveTabTotal/, '首屏补查另一个页签的条数')
|
||||
assert.match(page, /onMounted\(\(\) => \{[\s\S]{0,220}loadInactiveTabTotal/, '补查挂在首屏')
|
||||
assert.match(
|
||||
page,
|
||||
/activeTab\.value === 'tasks' \? loadTasks\(silent\) : loadVariants\(silent\)/,
|
||||
'30s 轮询仍只刷当前页签:麦象 console 是外部依赖,不进热路径',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -79,14 +79,11 @@ public class NotificationProperties {
|
||||
*/
|
||||
private int maixiangSilentMinutes = 10;
|
||||
|
||||
/** 已读通知保留天数(超期自动清理),默认 90 天。 */
|
||||
private int readRetentionDays = 90;
|
||||
|
||||
/**
|
||||
* 未读通知保留天数,默认 180 天(比已读长一倍)。
|
||||
* 通知保留天数:已读与未读同一条线,超期物理删除,默认 7 天。
|
||||
*
|
||||
* <p>未读通知此前永不清理:不看铃铛的用户会无限累积。保留期给得更宽,
|
||||
* 是因为未读意味着"用户可能还没看到",但也不能永远留着。
|
||||
* <p>此前是「已读 90 / 未读 180」两档。一张按天扇出的告警表留半年只服务于一件没人做的事
|
||||
* ——翻历史告警;2026-10-04 收成与设备日志一致的 7 天,删除动作见 NotificationRetentionService。
|
||||
*/
|
||||
private int unreadRetentionDays = 180;
|
||||
private int retentionDays = 7;
|
||||
}
|
||||
|
||||
+4
-3
@@ -51,11 +51,12 @@ public class AdminDeviceLogController {
|
||||
|
||||
@GetMapping("/files")
|
||||
@Operation(summary = "日志文件分页列表",
|
||||
description = "source=client/maixiang;keyword 模糊匹配设备名/设备ID/文件名;日期为闭区间(早于保留窗口自动收紧)。")
|
||||
description = "source=client/maixiang;uid 按上报用户精确过滤(未登录/采集机的行 uid 为空,不匹配任何 uid);"
|
||||
+ "日期为闭区间(早于保留窗口自动收紧)。")
|
||||
public ApiResponse<DeviceLogPageVo> files(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "来源") @RequestParam(required = false) String source,
|
||||
@Parameter(description = "关键字(设备/文件名)") @RequestParam(required = false) String keyword,
|
||||
@Parameter(description = "指定用户 uid") @RequestParam(required = false) Long uid,
|
||||
@Parameter(description = "起始日期(含)") @RequestParam(required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "结束日期(含)") @RequestParam(required = false)
|
||||
@@ -63,7 +64,7 @@ public class AdminDeviceLogController {
|
||||
@RequestParam(defaultValue = "1") Long page,
|
||||
@RequestParam(defaultValue = "20") Long pageSize) {
|
||||
requireSuperAdmin(request);
|
||||
return ApiResponse.success(deviceLogService.page(source, keyword, startDate, endDate, page, pageSize));
|
||||
return ApiResponse.success(deviceLogService.page(source, uid, startDate, endDate, page, pageSize));
|
||||
}
|
||||
|
||||
@GetMapping("/content")
|
||||
|
||||
+5
-8
@@ -159,7 +159,7 @@ public class DeviceLogService {
|
||||
|
||||
// ---------------------------------------------------------------- 查询
|
||||
|
||||
public DeviceLogPageVo page(String source, String keyword, LocalDate startDate, LocalDate endDate,
|
||||
public DeviceLogPageVo page(String source, Long uid, LocalDate startDate, LocalDate endDate,
|
||||
Long pageParam, Long pageSizeParam) {
|
||||
int retentionDays = properties.retentionDaysOrDefault();
|
||||
LocalDate minDate = LocalDate.now().minusDays(retentionDays - 1L);
|
||||
@@ -173,11 +173,8 @@ public class DeviceLogService {
|
||||
if (source != null && !source.isBlank()) {
|
||||
qw.eq(DeviceLogFileEntity::getSource, source.trim());
|
||||
}
|
||||
if (keyword != null && !keyword.isBlank()) {
|
||||
String kw = keyword.trim();
|
||||
qw.and(w -> w.like(DeviceLogFileEntity::getDeviceName, kw)
|
||||
.or().like(DeviceLogFileEntity::getDeviceId, kw)
|
||||
.or().like(DeviceLogFileEntity::getFileName, kw));
|
||||
if (uid != null) {
|
||||
qw.eq(DeviceLogFileEntity::getUid, uid);
|
||||
}
|
||||
qw.ge(DeviceLogFileEntity::getLogDate, from);
|
||||
if (endDate != null) {
|
||||
@@ -207,8 +204,8 @@ public class DeviceLogService {
|
||||
vo.setPage(safePage);
|
||||
vo.setPageSize(safeSize);
|
||||
vo.setRetentionDays(retentionDays);
|
||||
log.info("[device-log] 列表查询 source={} keyword={} 起={} 止={} page={} size={} 命中={}",
|
||||
source, keyword, from, endDate, safePage, safeSize, total);
|
||||
log.info("[device-log] 列表查询 source={} uid={} 起={} 止={} page={} size={} 命中={}",
|
||||
source, uid, from, endDate, safePage, safeSize, total);
|
||||
return vo;
|
||||
}
|
||||
|
||||
|
||||
+25
@@ -2,8 +2,33 @@ package com.nanri.aiimage.modules.notification.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.notification.model.entity.UserNotificationEntity;
|
||||
import org.apache.ibatis.annotations.Delete;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Mapper
|
||||
public interface UserNotificationMapper extends BaseMapper<UserNotificationEntity> {
|
||||
|
||||
/**
|
||||
* 分批删除保留期外的<b>已读</b>通知。
|
||||
*
|
||||
* <p>两条都按 {@code created_at < cutoff} 走建表即有的 {@code idx_created_at}:保留窗口外的行
|
||||
* 几乎全部命中删除条件,索引 range 扫前 N 行就能凑满一批,因此不必再为 read_at 补组合索引。
|
||||
*/
|
||||
@Delete("""
|
||||
DELETE FROM biz_user_notification
|
||||
WHERE read_at IS NOT NULL AND created_at < #{cutoff}
|
||||
LIMIT #{batchSize}
|
||||
""")
|
||||
int deleteReadBeforeBatch(@Param("cutoff") LocalDateTime cutoff, @Param("batchSize") int batchSize);
|
||||
|
||||
/** 分批删除保留期外的<b>未读</b>通知(与已读同一条时间线)。 */
|
||||
@Delete("""
|
||||
DELETE FROM biz_user_notification
|
||||
WHERE read_at IS NULL AND created_at < #{cutoff}
|
||||
LIMIT #{batchSize}
|
||||
""")
|
||||
int deleteUnreadBeforeBatch(@Param("cutoff") LocalDateTime cutoff, @Param("batchSize") int batchSize);
|
||||
}
|
||||
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.nanri.aiimage.modules.notification.service;
|
||||
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.config.NotificationProperties;
|
||||
import com.nanri.aiimage.modules.notification.mapper.UserNotificationMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 站内通知的保留期清理:超过 {@code aiimage.notification.retention-days}(默认 7 天)的行物理删除,
|
||||
* 已读与未读同一条时间线。
|
||||
*
|
||||
* <p>此前这条清理寄生在 5 分钟一轮的 {@link NotificationScanScheduler} 里,有两个问题:
|
||||
* 一是它跟着 {@code scan-enabled} 一起被关——生产为降噪关掉扫描,保留期就悄悄停摆、表无限增长;
|
||||
* 二是一条无 LIMIT 的大 DELETE,首次收紧保留期时要一次删完 90/180 天攒下的存量,
|
||||
* 而这张表每 60 秒就被铃铛轮询 {@code COUNT(*)} 一次,长事务会直接放大锁等待。
|
||||
*
|
||||
* <p>现在独立成凌晨任务并分批删除,与 {@code DeviceLogRetentionService} 等保留清理任务同一范式:
|
||||
* 双节点靠 job 锁单实例执行,单轮限制批次数以免长时间占锁,剩余量留给下一轮。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class NotificationRetentionService {
|
||||
|
||||
/** 单轮最多删除的批次数(已读、未读各自计数),剩余留给下一轮。 */
|
||||
static final int MAX_BATCHES_PER_RUN = 20;
|
||||
|
||||
private static final String LOCK_NAME = "notification:retention";
|
||||
|
||||
private final UserNotificationMapper userNotificationMapper;
|
||||
private final NotificationProperties properties;
|
||||
private final DistributedJobLockService distributedJobLockService;
|
||||
|
||||
@Value("${aiimage.notification.retention-batch-size:2000}")
|
||||
private int retentionBatchSize = 2000;
|
||||
|
||||
@Scheduled(cron = "${aiimage.notification.retention-cron:0 5 4 * * *}")
|
||||
public void purgeExpired() {
|
||||
int days = Math.max(1, properties.getRetentionDays());
|
||||
int batchSize = Math.max(100, retentionBatchSize);
|
||||
LocalDateTime cutoff = LocalDateTime.now().minusDays(days);
|
||||
|
||||
DistributedJobLockService.LockHandle lockHandle =
|
||||
distributedJobLockService.tryLock(LOCK_NAME, Duration.ofMinutes(15));
|
||||
if (lockHandle == null) {
|
||||
log.info("[notification] 保留期清理跳过:另一实例持锁");
|
||||
return;
|
||||
}
|
||||
try (lockHandle) {
|
||||
int readDeleted = deleteInBatches(true, cutoff, batchSize);
|
||||
int unreadDeleted = deleteInBatches(false, cutoff, batchSize);
|
||||
log.info("[notification] 保留期清理完成 cutoff={} retentionDays={} 已读删除={} 未读删除={}",
|
||||
cutoff, days, readDeleted, unreadDeleted);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[notification] 保留期清理失败 cutoff={} msg={}", cutoff, ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
private int deleteInBatches(boolean read, LocalDateTime cutoff, int batchSize) {
|
||||
int totalDeleted = 0;
|
||||
for (int batch = 0; batch < MAX_BATCHES_PER_RUN; batch++) {
|
||||
int deleted = read
|
||||
? userNotificationMapper.deleteReadBeforeBatch(cutoff, batchSize)
|
||||
: userNotificationMapper.deleteUnreadBeforeBatch(cutoff, batchSize);
|
||||
totalDeleted += deleted;
|
||||
if (deleted < batchSize) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return totalDeleted;
|
||||
}
|
||||
}
|
||||
-18
@@ -17,7 +17,6 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
@@ -72,9 +71,6 @@ public class NotificationScanScheduler {
|
||||
private final ProxyBalancePort proxyBalancePort;
|
||||
private final MaixiangAnomalyScanner maixiangAnomalyScanner;
|
||||
|
||||
/** 上次清理日期(每天最多清理一次;双节点由分布式锁保证只有一个实例执行)。 */
|
||||
private volatile LocalDate lastCleanupDate;
|
||||
|
||||
@Scheduled(fixedDelayString = "${aiimage.notification.scan-interval-ms:300000}",
|
||||
initialDelayString = "${aiimage.notification.scan-initial-delay-ms:120000}")
|
||||
public void scan() {
|
||||
@@ -96,7 +92,6 @@ public class NotificationScanScheduler {
|
||||
}
|
||||
// 麦象异常扫描(任务停滞/失败/队列积压);开关与凭据在扫描器内部判定
|
||||
maixiangAnomalyScanner.scan();
|
||||
cleanupExpiredIfNeeded();
|
||||
} catch (Exception ex) {
|
||||
log.warn("[notification-scan] 扫描异常终止 err={}", ex.getMessage(), ex);
|
||||
}
|
||||
@@ -271,19 +266,6 @@ public class NotificationScanScheduler {
|
||||
"service_down:" + serviceKey + ":" + dayOf(LocalDateTime.now()), null);
|
||||
}
|
||||
|
||||
/** 通知保留期清理:每天最多一次;已读与未读各按自己的保留天数。 */
|
||||
private void cleanupExpiredIfNeeded() {
|
||||
LocalDate today = LocalDate.now();
|
||||
if (today.equals(lastCleanupDate)) {
|
||||
return;
|
||||
}
|
||||
lastCleanupDate = today;
|
||||
LocalDateTime readCutoff = LocalDateTime.now().minusDays(Math.max(1, properties.getReadRetentionDays()));
|
||||
notificationService.cleanupReadBefore(readCutoff);
|
||||
LocalDateTime unreadCutoff = LocalDateTime.now().minusDays(Math.max(1, properties.getUnreadRetentionDays()));
|
||||
notificationService.cleanupUnreadBefore(unreadCutoff);
|
||||
}
|
||||
|
||||
private String dedupeKeyOf(BucketKey key) {
|
||||
return "task_failed:" + key.userId() + ":" + key.moduleType() + ":" + key.day();
|
||||
}
|
||||
|
||||
-22
@@ -251,28 +251,6 @@ public class NotificationService {
|
||||
return updated;
|
||||
}
|
||||
|
||||
/** 清理指定时间之前已读的通知(保留期由调用方决定)。 */
|
||||
public int cleanupReadBefore(LocalDateTime cutoff) {
|
||||
int deleted = userNotificationMapper.delete(new LambdaQueryWrapper<UserNotificationEntity>()
|
||||
.isNotNull(UserNotificationEntity::getReadAt)
|
||||
.lt(UserNotificationEntity::getCreatedAt, cutoff));
|
||||
if (deleted > 0) {
|
||||
log.info("[notification] 清理历史已读通知 cutoff={} 删除={} 条", cutoff, deleted);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/** 清理指定时间之前仍未读的通知(保留期由调用方决定,比已读给得更宽)。 */
|
||||
public int cleanupUnreadBefore(LocalDateTime cutoff) {
|
||||
int deleted = userNotificationMapper.delete(new LambdaQueryWrapper<UserNotificationEntity>()
|
||||
.isNull(UserNotificationEntity::getReadAt)
|
||||
.lt(UserNotificationEntity::getCreatedAt, cutoff));
|
||||
if (deleted > 0) {
|
||||
log.info("[notification] 清理历史未读通知 cutoff={} 删除={} 条", cutoff, deleted);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
private LambdaQueryWrapper<UserNotificationEntity> baseWrapper(Long userId, String audience, boolean onlyUnread,
|
||||
NotificationPageQuery query) {
|
||||
LambdaQueryWrapper<UserNotificationEntity> wrapper = new LambdaQueryWrapper<UserNotificationEntity>()
|
||||
|
||||
@@ -467,9 +467,10 @@ aiimage:
|
||||
maixiang-queue-processing-threshold: ${AIIMAGE_NOTIFICATION_MAIXIANG_QUEUE_PROCESSING_THRESHOLD:100}
|
||||
# 采集端 worker 静默阈值(分钟):超时无轮询 = 采集机掉线。唯一直接反映整机停摆的信号。
|
||||
maixiang-silent-minutes: ${AIIMAGE_NOTIFICATION_MAIXIANG_SILENT_MINUTES:10}
|
||||
read-retention-days: ${AIIMAGE_NOTIFICATION_READ_RETENTION_DAYS:90}
|
||||
# 未读通知也设保留期(此前永不清理,不看铃铛的用户会无限累积);给得比已读宽一倍
|
||||
unread-retention-days: ${AIIMAGE_NOTIFICATION_UNREAD_RETENTION_DAYS:180}
|
||||
# 通知最多留 7 天(已读/未读同一条线),超期由 NotificationRetentionService 凌晨分批物理删除
|
||||
retention-days: ${AIIMAGE_NOTIFICATION_RETENTION_DAYS:7}
|
||||
retention-cron: ${AIIMAGE_NOTIFICATION_RETENTION_CRON:0 5 4 * * *}
|
||||
retention-batch-size: ${AIIMAGE_NOTIFICATION_RETENTION_BATCH_SIZE:2000}
|
||||
security:
|
||||
shop-credential-key: ${AIIMAGE_SHOP_CREDENTIAL_KEY:change-me-shop-credential-key}
|
||||
# 轮换过渡期用:逗号分隔的旧密钥,解密按顺序回试,加密只用上面那个;迁完就清空
|
||||
|
||||
+35
@@ -1,6 +1,8 @@
|
||||
package com.nanri.aiimage.modules.devicelog.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
@@ -184,4 +186,37 @@ class DeviceLogServiceTest {
|
||||
assertThat(vo.getContent()).isEqualTo("AAAA\nBBBB\n");
|
||||
assertThat(vo.isTruncated()).isFalse();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 列表筛选
|
||||
|
||||
/** 捕获 page() 传给 selectCount 的查询条件(计数与列表走同一条 wrapper 构造)。 */
|
||||
@SuppressWarnings("rawtypes")
|
||||
private AbstractWrapper capturePageWrapper(String source, Long uid) {
|
||||
when(mapper.selectCount(any())).thenReturn(0L);
|
||||
service().page(source, uid, null, null, 1L, 15L);
|
||||
ArgumentCaptor<Wrapper> captor = ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(mapper).selectCount(captor.capture());
|
||||
return (AbstractWrapper) captor.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageFiltersByUidExactly() {
|
||||
AbstractWrapper wrapper = capturePageWrapper(null, 7L);
|
||||
assertThat(wrapper.getSqlSegment()).contains("uid =");
|
||||
assertThat(wrapper.getParamNameValuePairs().values()).contains(7L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageWithoutUidKeepsAnonymousReportersVisible() {
|
||||
// 未登录的桌面端与麦象采集机 uid 为空:不指定用户时它们必须仍在结果里
|
||||
assertThat(capturePageWrapper(null, null).getSqlSegment()).doesNotContain("uid");
|
||||
}
|
||||
|
||||
/** 契约:列表筛选已改为用户维度,设备名/设备ID/文件名的模糊匹配不再存在于查询路径。 */
|
||||
@Test
|
||||
void pageNoLongerMatchesDeviceOrFileNameFuzzily() {
|
||||
String sql = capturePageWrapper("client", 7L).getSqlSegment();
|
||||
assertThat(sql).contains("source =");
|
||||
assertThat(sql).doesNotContain("device_name", "device_id", "file_name");
|
||||
}
|
||||
}
|
||||
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
package com.nanri.aiimage.modules.notification.service;
|
||||
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.config.NotificationProperties;
|
||||
import com.nanri.aiimage.modules.notification.mapper.UserNotificationMapper;
|
||||
import org.apache.ibatis.annotations.Delete;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 站内通知保留期清理(biz_user_notification 最多留 7 天,超期物理删除)。
|
||||
*/
|
||||
class NotificationRetentionServiceTest {
|
||||
|
||||
private final UserNotificationMapper mapper = mock(UserNotificationMapper.class);
|
||||
private final DistributedJobLockService jobLockService = mock(DistributedJobLockService.class);
|
||||
private final NotificationProperties properties = new NotificationProperties();
|
||||
|
||||
private NotificationRetentionService service(int retentionDays) {
|
||||
properties.setRetentionDays(retentionDays);
|
||||
return new NotificationRetentionService(mapper, properties, jobLockService);
|
||||
}
|
||||
|
||||
private void lockAvailable() {
|
||||
when(jobLockService.tryLock(anyString(), any()))
|
||||
.thenReturn(mock(DistributedJobLockService.LockHandle.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletesInBatchesUntilBatchNotFull() {
|
||||
lockAvailable();
|
||||
when(mapper.deleteReadBeforeBatch(any(), anyInt())).thenReturn(2000, 2000, 120);
|
||||
when(mapper.deleteUnreadBeforeBatch(any(), anyInt())).thenReturn(500);
|
||||
|
||||
service(7).purgeExpired();
|
||||
|
||||
verify(mapper, times(3)).deleteReadBeforeBatch(any(LocalDateTime.class), eq(2000));
|
||||
verify(mapper, times(1)).deleteUnreadBeforeBatch(any(LocalDateTime.class), eq(2000));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopsAtBatchLimitPerRun() {
|
||||
lockAvailable();
|
||||
when(mapper.deleteReadBeforeBatch(any(), anyInt())).thenReturn(2000);
|
||||
when(mapper.deleteUnreadBeforeBatch(any(), anyInt())).thenReturn(2000);
|
||||
|
||||
service(7).purgeExpired();
|
||||
|
||||
// 断言写成字面量而非引用常量:引用常量会让「改常量」这种变异同时改掉期望值,恒绿。
|
||||
verify(mapper, times(20))
|
||||
.deleteReadBeforeBatch(any(LocalDateTime.class), anyInt());
|
||||
verify(mapper, times(20))
|
||||
.deleteUnreadBeforeBatch(any(LocalDateTime.class), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsWhenAnotherInstanceHoldsLock() {
|
||||
when(jobLockService.tryLock(anyString(), any())).thenReturn(null);
|
||||
|
||||
service(7).purgeExpired();
|
||||
|
||||
verify(mapper, never()).deleteReadBeforeBatch(any(), anyInt());
|
||||
verify(mapper, never()).deleteUnreadBeforeBatch(any(), anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFailureIsLoggedAndDoesNotThrow() {
|
||||
lockAvailable();
|
||||
when(mapper.deleteReadBeforeBatch(any(), anyInt())).thenThrow(new IllegalStateException("db down"));
|
||||
|
||||
service(7).purgeExpired();
|
||||
|
||||
verify(mapper).deleteReadBeforeBatch(any(LocalDateTime.class), anyInt());
|
||||
}
|
||||
|
||||
/** 契约:已读与未读共用一条保留线(此前是「已读 90 / 未读 180」两档,现收成 7 天)。 */
|
||||
@Test
|
||||
void readAndUnreadShareOneCutoffAtRetentionBoundary() {
|
||||
lockAvailable();
|
||||
when(mapper.deleteReadBeforeBatch(any(), anyInt())).thenReturn(0);
|
||||
when(mapper.deleteUnreadBeforeBatch(any(), anyInt())).thenReturn(0);
|
||||
|
||||
service(7).purgeExpired();
|
||||
|
||||
ArgumentCaptor<LocalDateTime> readCutoff = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||
ArgumentCaptor<LocalDateTime> unreadCutoff = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||
verify(mapper).deleteReadBeforeBatch(readCutoff.capture(), anyInt());
|
||||
verify(mapper).deleteUnreadBeforeBatch(unreadCutoff.capture(), anyInt());
|
||||
assertThat(Duration.between(readCutoff.getValue(), unreadCutoff.getValue()).abs().toMillis()).isZero();
|
||||
assertThat(Duration.between(readCutoff.getValue(), LocalDateTime.now()).toDays()).isEqualTo(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void retentionDaysDefaultsToSeven() {
|
||||
lockAvailable();
|
||||
when(mapper.deleteReadBeforeBatch(any(), anyInt())).thenReturn(0);
|
||||
when(mapper.deleteUnreadBeforeBatch(any(), anyInt())).thenReturn(0);
|
||||
|
||||
new NotificationRetentionService(mapper, new NotificationProperties(), jobLockService).purgeExpired();
|
||||
|
||||
ArgumentCaptor<LocalDateTime> cutoff = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||
verify(mapper).deleteReadBeforeBatch(cutoff.capture(), anyInt());
|
||||
assertThat(Duration.between(cutoff.getValue(), LocalDateTime.now()).toDays()).isEqualTo(7);
|
||||
}
|
||||
|
||||
/** 契约:保留清理不再寄生在 scan-enabled 之下——为降噪关掉扫描,不能连带把保留期停摆。 */
|
||||
@Test
|
||||
void retentionRunsEvenWhenScanIsDisabled() {
|
||||
lockAvailable();
|
||||
when(mapper.deleteReadBeforeBatch(any(), anyInt())).thenReturn(0);
|
||||
when(mapper.deleteUnreadBeforeBatch(any(), anyInt())).thenReturn(0);
|
||||
properties.setRetentionDays(7);
|
||||
properties.setScanEnabled(false);
|
||||
|
||||
new NotificationRetentionService(mapper, properties, jobLockService).purgeExpired();
|
||||
|
||||
verify(mapper).deleteReadBeforeBatch(any(LocalDateTime.class), anyInt());
|
||||
verify(mapper).deleteUnreadBeforeBatch(any(LocalDateTime.class), anyInt());
|
||||
}
|
||||
|
||||
/**
|
||||
* 契约:两条分批删除各自锁死自己的谓词。上面的用例把 mapper 整层 mock 掉了,
|
||||
* 「已读写成未读条件」在单测里完全不可见,但线上表现为某一侧永远删不掉(表继续无限增长)。
|
||||
*/
|
||||
@Test
|
||||
void batchDeleteSqlKeepsItsOwnPredicateAndLimit() {
|
||||
String readSql = deleteSqlOf("deleteReadBeforeBatch");
|
||||
String unreadSql = deleteSqlOf("deleteUnreadBeforeBatch");
|
||||
for (String sql : List.of(readSql, unreadSql)) {
|
||||
assertThat(sql).contains("DELETE FROM biz_user_notification");
|
||||
assertThat(sql).contains("created_at < #{cutoff}");
|
||||
assertThat(sql).contains("LIMIT #{batchSize}");
|
||||
}
|
||||
assertThat(readSql).contains("read_at IS NOT NULL").doesNotContain("read_at IS NULL");
|
||||
// 未读侧必须只写 IS NULL:IS NOT NULL 不含 IS NULL,两者可互相排他
|
||||
assertThat(unreadSql).contains("read_at IS NULL").doesNotContain("IS NOT NULL");
|
||||
}
|
||||
|
||||
private static String deleteSqlOf(String methodName) {
|
||||
try {
|
||||
Delete delete = UserNotificationMapper.class
|
||||
.getMethod(methodName, LocalDateTime.class, int.class)
|
||||
.getAnnotation(Delete.class);
|
||||
assertThat(delete).as("%s 上的 @Delete 注解", methodName).isNotNull();
|
||||
return String.join(" ", delete.value());
|
||||
} catch (NoSuchMethodException ex) {
|
||||
throw new AssertionError(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
-8
@@ -196,14 +196,6 @@ class NotificationServiceTest {
|
||||
assertThat(service.markAllRead(7L, NotificationService.AUDIENCE_ADMIN)).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupDeletesOnlyReadRowsBeforeCutoff() {
|
||||
when(mapper.delete(any())).thenReturn(2);
|
||||
int deleted = service.cleanupReadBefore(LocalDateTime.now().minusDays(90));
|
||||
assertThat(deleted).isEqualTo(2);
|
||||
verify(mapper).delete(any());
|
||||
}
|
||||
|
||||
/**
|
||||
* 可见范围回归:读取侧必须按「接收者 user_id + 端 audience」双条件裁剪。
|
||||
* 一旦有人漏掉 user_id,管理员/用户就会看到别人的通知;漏掉 audience 则两端通知串台。
|
||||
|
||||
@@ -20,7 +20,8 @@
|
||||
(`columns` + `user_column_permission`),**不新建权限机制**:无授权记录 = 管理员看不到。
|
||||
- 顶部汇总卡:总店铺 / 在跑店铺 / 进行中任务 / 今日完成 / 疑似卡住。
|
||||
- 全局在跑店铺面板:一行一个店铺,列在跑任务数、疑似卡住数、业务分布、最近上报;点行下钻到该店铺的任务。
|
||||
- 列表字段:账号名、店铺、业务名称、任务状态、当前处理、开始时间、最近上报、结束时间、执行进度,
|
||||
- 列表字段:账号名、店铺、业务名称、任务状态、任务ID、开始时间、最近上报、结束时间、执行进度
|
||||
(进度按「已完成数 / 总数」,已完成 = 成功 + 失败,与客户端任务面板同口径),
|
||||
并提供筛选(账号/业务/状态/店铺/时间范围)。
|
||||
- 「只要客户端任务在跑就上报」是面板的前提:进行中任务的 `updated_at` 由心跳(60s)与结果回传共同顶新,
|
||||
因此不再需要任何设备身份基线(曾用过的 code.txt 台账已放弃)。
|
||||
@@ -171,10 +172,12 @@ SQL 用 `@Select` 注解 mapper + 手写 LIMIT/OFFSET 分页(先例 `ImageVide
|
||||
在跑店铺看板 + 筛选栏(账号/业务/状态/店铺/时间范围);
|
||||
- 在跑店铺看板:表格一行一个店铺(店铺、在跑任务、疑似卡住、业务分布、最近上报),
|
||||
点真店铺行 = 按该店铺精确筛任务(再点一次取消),「不挂店铺」桶行不可点并带说明文案;
|
||||
- 店铺筛选:`el-select filterable clearable`,候选 = 店铺库 ∪ 面板出现的店铺名
|
||||
- 店铺筛选:`el-select class="admin-filter" filterable clearable`(`admin-filter` 把控件补到 42px,
|
||||
与同行原生控件同高,`align-items: flex-end` 的筛选行里 label 才不会被顶偏),
|
||||
候选 = 店铺库 ∪ 面板出现的店铺名
|
||||
(店铺已删、但任务还在的情形也筛得动);
|
||||
- 页签一「客户端任务」:表格(账号、店铺、业务、状态、当前处理、开始、最近上报、结束、进度条、操作)
|
||||
+ 详情 `el-drawer`(设备名与分组明细只在详情出现);
|
||||
- 页签一「客户端任务」:表格(账号、店铺、业务、状态、任务ID、开始、最近上报、结束、进度)
|
||||
+ 详情 `el-drawer`(设备名、当前处理与分组明细只在详情出现;「操作」列已删,任务ID 单元格是详情入口);
|
||||
- 页签二「变体采集」:状态筛选 + 表格(账号、任务号、状态、开始/更新时间、进度文字 res_mes);
|
||||
- 30s 轮询:`document.hidden` 暂停、卸载清理、手动刷新按钮。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user