Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5bfc4d701b | |||
| eab58b4d2e | |||
| 0639675c23 | |||
| c563edfb39 | |||
| 1d2cae2af6 | |||
| 4de21aeb1b | |||
| 784b920edb | |||
| 82f064a97f | |||
| 0236328faa | |||
| ea5807e11b | |||
| 2fdacdbaab | |||
| deafe45847 | |||
| 472b7e8bc6 | |||
| 4d729733a4 | |||
| e865488d61 | |||
| f7e520b9d5 | |||
| 3c8cab160b | |||
| 395c99b001 |
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { copyFeedback, isCopySupported } from './copy-model'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
|
||||
const props = defineProps<{ text: string }>()
|
||||
|
||||
@@ -13,7 +14,7 @@ async function handleCopy(): Promise<void> {
|
||||
await navigator.clipboard.writeText(props.text)
|
||||
ElMessage.success(copyFeedback(props.text))
|
||||
} catch {
|
||||
ElMessage.error(copyFeedback(''))
|
||||
showAdminFeedback(copyFeedback(''), 'error')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<script setup lang="ts">
|
||||
/** 列表加载失败条(四面9分口径 · 后管「模板内失败态只有 4/24 页」)。
|
||||
* 两件事一起做:把失败原因留在页面上(不是一闪而过的 toast),并给出一个真能重跑的出口。
|
||||
* 重试动作由父页面传回自己的取数函数,本组件不自己发请求、也不放占位按钮。 */
|
||||
import { LOAD_FAILURE_RETRY_LABEL } from './load-failure-model'
|
||||
|
||||
defineProps<{ message: string }>()
|
||||
defineEmits<{ (event: 'retry'): void }>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="load-failure-bar" role="alert">
|
||||
<span class="load-failure-bar-text">{{ message }}</span>
|
||||
<button class="load-failure-bar-retry" type="button" @click="$emit('retry')">{{ LOAD_FAILURE_RETRY_LABEL }}</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/* 自带样式:各页的 .btn 是 scoped 的,套不到子组件内部的元素上。 */
|
||||
.load-failure-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin: 0 0 14px;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid #e0bfc4;
|
||||
border-radius: 10px;
|
||||
background: #fdf3f4;
|
||||
color: #8f4650;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.load-failure-bar-text {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.load-failure-bar-retry {
|
||||
flex: none;
|
||||
min-height: 32px;
|
||||
padding: 5px 14px;
|
||||
border: 1px solid #b35f6a;
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(135deg, #c06d77, #b35f6a);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.load-failure-bar-retry:hover {
|
||||
background: linear-gradient(135deg, #cb7c84, #b96570);
|
||||
}
|
||||
</style>
|
||||
@@ -341,7 +341,7 @@ async function readAll() {
|
||||
unreadCount.value = 0
|
||||
} catch (error) {
|
||||
console.warn('[admin-notification] 全部已读失败:', error)
|
||||
ElMessage.error(error instanceof Error ? error.message : '操作失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '操作失败', 'error')
|
||||
} finally {
|
||||
markingAll.value = false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 列表加载失败态模型(四面9分口径 · 后管「模板内失败态只有 4/24 页」):
|
||||
* 把「请求失败了」归一成一条可读中文,配 LoadFailureBar.vue 的那个真能重跑的按钮用。
|
||||
*
|
||||
* 纯逻辑、不依赖 Vue 也不依赖 Element,`node --test` 直接 import 跑行为断言。
|
||||
* 文案把关复用 api/user-notice:后端把底层异常原文拼进 message 时,界面只留中文主干。
|
||||
*/
|
||||
import { userNotice } from '../api/user-notice.ts'
|
||||
|
||||
/** 失败条上那个按钮的字样:必须是「重试」而不是一句「知道了」——撤入口同时得是出口。 */
|
||||
export const LOAD_FAILURE_RETRY_LABEL = '重试'
|
||||
|
||||
/** 从 axios 错误 / Error / 字符串里取后端给的原因;取不到、或原文不是中文时返回空串。 */
|
||||
export function failureDetail(error: unknown): string {
|
||||
const data = (error as { response?: { data?: unknown } } | undefined)?.response?.data
|
||||
if (data && typeof data === 'object') {
|
||||
const record = data as Record<string, unknown>
|
||||
for (const key of ['message', 'error', 'msg']) {
|
||||
const value = record[key]
|
||||
if (typeof value === 'string' && value.trim()) return userNotice(value, '')
|
||||
}
|
||||
}
|
||||
if (error instanceof Error && error.message.trim()) return userNotice(error.message, '')
|
||||
if (typeof error === 'string' && error.trim()) return userNotice(error, '')
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 后端按范围拒掉的句子(`无权操作该总数据`、`缺少归属公司…`)补一句人话:
|
||||
* 这类失败不是页面坏了,重试一百次也是同一个结果,得把出路说清楚。
|
||||
*/
|
||||
export const SCOPE_REFUSAL_NOTE = '这一行不在你当前可操作的分组/公司范围内,需要由平台超级管理员处理'
|
||||
const SCOPE_REFUSAL = /无权|缺少归属公司/
|
||||
|
||||
/** 命中范围拒绝时返回补充说明,否则空串。 */
|
||||
export function scopeRefusalNote(detail: string): string {
|
||||
return SCOPE_REFUSAL.test(detail || '') ? SCOPE_REFUSAL_NOTE : ''
|
||||
}
|
||||
|
||||
/** 「本页兜底文案:后端原因」;没有可读原因时只留兜底文案,不拼出「加载失败:」这种半截句。 */
|
||||
export function loadFailureMessage(error: unknown, fallback: string): string {
|
||||
const head = (fallback || '').trim()
|
||||
const detail = failureDetail(error)
|
||||
if (!detail) return head
|
||||
const note = scopeRefusalNote(detail)
|
||||
const reason = note ? `${detail}(${note})` : detail
|
||||
if (!head || head.includes(detail)) return head || reason
|
||||
return `${head}:${reason}`
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { joinAdminPath } from '@/config/app'
|
||||
import { pageTitleOf, topbarUserOf } from '@/layout/topbar-model'
|
||||
@@ -17,6 +17,7 @@ import ExpiryNotice from '@/components/ExpiryNotice.vue'
|
||||
import OperationGuide from '@/layout/OperationGuide.vue'
|
||||
import CompanyTabs from '@/layout/CompanyTabs.vue'
|
||||
import { crumbsForActiveRoute, resolveDocumentTitle, updateDocumentTitle } from '@/layout/title-breadcrumb'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import {
|
||||
LOGOUT_CONFIRM_CANCEL,
|
||||
LOGOUT_CONFIRM_MESSAGE,
|
||||
@@ -59,7 +60,7 @@ async function signOut() {
|
||||
signOut: () => session.signOut(),
|
||||
})
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '退出登录失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '退出登录失败', 'error')
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -3,16 +3,19 @@
|
||||
* 可见范围由后端收窄(超管全部、公司内 admin 只自己公司);写操作仅超管,这里隐藏入口只是配合,
|
||||
* 真正的把关在 CompanyController,页面不得当作权限边界。 */
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { fetchCompanies } from '@/api/companies'
|
||||
import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '@/api/companies-dto'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import CompanyEditorDialog from './CompanyEditorDialog.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<CompanyItem[]>([])
|
||||
const editorVisible = ref(false)
|
||||
const editingCompany = ref<CompanyItem | null>(null)
|
||||
@@ -33,10 +36,12 @@ function changeSize(size: number) { pageSize.value = size; page.value = 1 }
|
||||
|
||||
async function loadCompanies() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
rows.value = await fetchCompanies()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '公司列表加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '公司列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -70,6 +75,7 @@ onMounted(loadCompanies)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadCompanies" />
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -11,10 +11,13 @@ import { deleteShopGroup, fetchShopGroups } from './shop-group-api'
|
||||
import type { ShopGroupItem } from './shop-group-model'
|
||||
import GroupEditorDialog from './GroupEditorDialog.vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<ShopGroupItem[]>([])
|
||||
const editorVisible = ref(false)
|
||||
const editingGroup = ref<ShopGroupItem | null>(null)
|
||||
@@ -47,10 +50,12 @@ function canEditOf(group: ShopGroupItem): boolean {
|
||||
|
||||
async function loadGroups() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
rows.value = await fetchShopGroups(companyTab.requestCompanyId)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '数据权限分组加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '数据权限分组加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -78,7 +83,7 @@ async function removeGroup(group: ShopGroupItem) {
|
||||
ElMessage.success('删除成功')
|
||||
await loadGroups()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,6 +109,7 @@ onMounted(loadGroups)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadGroups" />
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -7,6 +7,9 @@ import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { createMenu, deleteMenu, loadMenuManageTree, reorderMenus, updateMenu } from './menu-manage-api'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
import {
|
||||
MENU_TYPE_OPTIONS,
|
||||
createMenuForm,
|
||||
@@ -31,6 +34,7 @@ interface MenuRow extends MenuManageNode {
|
||||
|
||||
const companyTab = useCompanyTabStore()
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<MenuManageNode[]>([])
|
||||
/** 筛选:菜单名称/类型(用户要求账户域子菜单补筛选条件)。 */
|
||||
const filterName = ref('')
|
||||
@@ -85,10 +89,12 @@ function parentNameOf(node: MenuManageNode): string {
|
||||
|
||||
async function loadMenus() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
rows.value = await loadMenuManageTree(companyTab.requestCompanyId)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '菜单列表加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '菜单列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -154,7 +160,7 @@ async function onDrop(event: DragEvent, target: MenuManageNode): Promise<void> {
|
||||
ElMessage.success('排序已保存')
|
||||
await loadMenus()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '排序保存失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '排序保存失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,7 +189,7 @@ async function saveMenu() {
|
||||
createVisible.value = false
|
||||
await loadMenus()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '保存失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '保存失败', 'error')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
@@ -196,13 +202,13 @@ async function removeMenu(node: MenuManageNode) {
|
||||
return
|
||||
}
|
||||
// 对齐旧版:原生 confirm。
|
||||
if (!window.confirm(`确定删除菜单“${node.name}”吗?`)) return
|
||||
if (!(await openAdminConfirm({ message: `确定删除菜单“${node.name}”吗?`, danger: true }))) return
|
||||
try {
|
||||
await deleteMenu(node.id)
|
||||
ElMessage.success('删除成功')
|
||||
await loadMenus()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,6 +244,7 @@ onMounted(loadMenus)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadMenus" />
|
||||
<div class="table-scroll columns-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { orderedPair, todayDateInput } from '@/utils/datetime'
|
||||
import {
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
import type { GroupOption } from '@/api/user-secrets'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
@@ -17,6 +19,7 @@ const companyTab = useCompanyTabStore()
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<AdminUserSecretUsageRow[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -46,6 +49,7 @@ function formatCount(value: number | undefined) {
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchUserSecretUsage({
|
||||
startDate: startDate.value || undefined,
|
||||
@@ -66,7 +70,8 @@ async function load() {
|
||||
proxyCalls: Number(result?.proxyCalls || 0),
|
||||
}
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -160,6 +165,7 @@ onMounted(load)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="usage-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -15,6 +15,9 @@ import {
|
||||
} from '@/api/user-secrets'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
@@ -22,6 +25,7 @@ const companyTab = useCompanyTabStore()
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<AdminUserSecretRow[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -111,6 +115,7 @@ function rowStatusTooltip(row: AdminUserSecretRow) {
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchUserSecretList({
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
@@ -124,7 +129,8 @@ async function load() {
|
||||
total.value = Number(result?.total || 0)
|
||||
groupOptions.value = result?.groupOptions || []
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -166,7 +172,7 @@ async function check(row: AdminUserSecretRow) {
|
||||
}
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '检测失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '检测失败', 'error')
|
||||
} finally {
|
||||
checkingId.value = null
|
||||
}
|
||||
@@ -174,13 +180,13 @@ async function check(row: AdminUserSecretRow) {
|
||||
|
||||
async function remove(row: AdminUserSecretRow) {
|
||||
const who = row.username || `UID ${row.userId}`
|
||||
if (!window.confirm(`确定清空「${who}」的全部密钥与代理配置吗?后台锁定的代理会一并清除并解锁,该用户需要重新配置。`)) return
|
||||
if (!(await openAdminConfirm({ message: `确定清空「${who}」的全部密钥与代理配置吗?后台锁定的代理会一并清除并解锁,该用户需要重新配置。`, danger: true }))) return
|
||||
try {
|
||||
await deleteUserSecret(row.userId)
|
||||
ElMessage.success('已清空')
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '清空失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '清空失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,7 +209,7 @@ async function fillProxy(row: AdminUserSecretRow) {
|
||||
ElMessage.success(row.proxy?.locked ? '已更新锁定代理' : '已代填并锁定代理')
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '代填失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '代填失败', 'error')
|
||||
} finally {
|
||||
proxyBusyId.value = null
|
||||
}
|
||||
@@ -212,14 +218,14 @@ async function fillProxy(row: AdminUserSecretRow) {
|
||||
/** 解锁代理:清空后台代填值,该用户恢复自行配置。 */
|
||||
async function unlockProxy(row: AdminUserSecretRow) {
|
||||
const who = row.username || `UID ${row.userId}`
|
||||
if (!window.confirm(`确定解除「${who}」的代理锁定吗?解锁后当前后台代理值会被清空,客户端恢复自行配置。`)) return
|
||||
if (!(await openAdminConfirm({ message: `确定解除「${who}」的代理锁定吗?解锁后当前后台代理值会被清空,客户端恢复自行配置。`, danger: true }))) return
|
||||
proxyBusyId.value = row.userId
|
||||
try {
|
||||
await clearUserSecretModule(row.userId, 'proxy')
|
||||
ElMessage.success('已解锁')
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '解锁失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '解锁失败', 'error')
|
||||
} finally {
|
||||
proxyBusyId.value = null
|
||||
}
|
||||
@@ -274,6 +280,7 @@ onMounted(load)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="secrets-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -20,6 +20,8 @@ import { formatExpiryCell } from './user-expiry'
|
||||
import CreateUserDialog from './CreateUserDialog.vue'
|
||||
import EditUserDialog from './EditUserDialog.vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
@@ -84,7 +86,7 @@ async function loadUsers() {
|
||||
}
|
||||
} catch (error) {
|
||||
loadError.value = error instanceof Error ? error.message : '用户列表加载失败'
|
||||
ElMessage.error(loadError.value)
|
||||
showAdminFeedback(loadError.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -108,13 +110,13 @@ async function removeUser(row: AdminUser) {
|
||||
return
|
||||
}
|
||||
// 对齐旧版:浏览器原生 confirm 确认后删除。
|
||||
if (!window.confirm(deleteConfirmMessage(row))) return
|
||||
if (!(await openAdminConfirm({ message: deleteConfirmMessage(row), danger: true }))) return
|
||||
try {
|
||||
await deleteUser(row.id)
|
||||
ElMessage.success('删除成功')
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,13 +128,13 @@ async function toggleDisable(row: AdminUser) {
|
||||
ElMessage.warning(reason)
|
||||
return
|
||||
}
|
||||
if (!window.confirm(disableConfirmMessage(row, wantDisable))) return
|
||||
if (!(await openAdminConfirm({ message: disableConfirmMessage(row, wantDisable), danger: false }))) return
|
||||
try {
|
||||
await setUserDisabled(row.id, wantDisable)
|
||||
ElMessage.success(wantDisable ? '已停用,该账号会被强制退出到登录页' : '已解除停用')
|
||||
await loadUsers()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '操作失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '操作失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,8 +11,12 @@ import { invalidAsinDeleteText, recordSourceLabel } from '../invalidasin/invalid
|
||||
import { createEmptyInvalidAsinForm, invalidAsinFormFromItem, validateInvalidAsinForm } from '../invalidasin/invalid-asin-form-model.ts'
|
||||
import type { ShopGroupOption } from '../shop/shop-dto.ts'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<InvalidAsinItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -40,6 +44,7 @@ async function loadGroups() {
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchInvalidAsinPage({
|
||||
page: page.value,
|
||||
@@ -52,7 +57,8 @@ async function load() {
|
||||
total.value = result.total
|
||||
page.value = result.page
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '数据加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '数据加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -118,7 +124,7 @@ async function submit() {
|
||||
dialogVisible.value = false
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '保存失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '保存失败', 'error')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
@@ -126,13 +132,13 @@ async function submit() {
|
||||
|
||||
async function remove(row: InvalidAsinItem) {
|
||||
// 对齐旧版:原生 confirm。
|
||||
if (!window.confirm(invalidAsinDeleteText(row))) return
|
||||
if (!(await openAdminConfirm({ message: invalidAsinDeleteText(row), danger: true }))) return
|
||||
try {
|
||||
await deleteInvalidAsin(row.id)
|
||||
ElMessage.success('已删除')
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,6 +174,7 @@ onMounted(() => {
|
||||
<button class="btn" type="button" @click="apply">查询</button>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll invalid-asin-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { formatDateTime, orderedPair } from '@/utils/datetime'
|
||||
/** 数据去重总数据(registry) · 像素复刻旧版 admin.html panel-dedupe-total-data(自绘:分组摘要 + 双行筛选 + 旧式表格/分页 + 编辑/导入弹窗 + 导出等待遮罩)。
|
||||
* script 逻辑沿用现有 Vue 实现(查询/编辑/删除/导入轮询/导出秒表)。 */
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import {
|
||||
fetchDedupeTotalList,
|
||||
@@ -26,6 +26,10 @@ import { toExportUrl } from './dedupe-total-export.ts'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { loadFailureMessage } from '@/components/load-failure-model'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
@@ -33,6 +37,7 @@ const companyTab = useCompanyTabStore()
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<DedupeTotalItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -79,6 +84,8 @@ const exporting = ref(false)
|
||||
const exportWaitVisible = ref(false)
|
||||
const exportWaitSeconds = ref(0)
|
||||
let exportWaitTimer: ReturnType<typeof setInterval> | null = null
|
||||
/** 页面已卸载:导入轮询的下一拍不再发请求(离开页面后不该再挂 5 分钟的节拍)。 */
|
||||
let pageDisposed = false
|
||||
|
||||
function startExportWait(): void {
|
||||
exportWaitSeconds.value = 0
|
||||
@@ -98,6 +105,7 @@ function stopExportWait(): void {
|
||||
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchDedupeTotalList(
|
||||
toDedupeListParams(filter, page.value, pageSize.value, pendingCursor, companyTab.requestCompanyId),
|
||||
@@ -109,7 +117,8 @@ async function load(): Promise<void> {
|
||||
pageCursor.value = result.nextLastId ?? null
|
||||
pendingCursor = null
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '去重数据加载失败')
|
||||
loadFailure.value = loadFailureMessage(error, '去重数据加载失败')
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -173,7 +182,7 @@ async function saveEdit(): Promise<void> {
|
||||
ElMessage.success('保存成功')
|
||||
await load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '保存失败')
|
||||
showAdminFeedback(loadFailureMessage(error, '保存失败'), 'error')
|
||||
} finally {
|
||||
editSaving.value = false
|
||||
}
|
||||
@@ -181,13 +190,13 @@ async function saveEdit(): Promise<void> {
|
||||
|
||||
async function removeRow(row: DedupeTotalItem): Promise<void> {
|
||||
// 对齐旧版:浏览器原生 confirm 确认后删除。
|
||||
if (!window.confirm(`确定删除总数据“${row.dataValue}”吗?`)) return
|
||||
if (!(await openAdminConfirm({ message: `确定删除总数据“${row.dataValue}”吗?`, danger: true }))) return
|
||||
try {
|
||||
await deleteDedupeTotal(row.id)
|
||||
ElMessage.success('删除成功')
|
||||
await load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(loadFailureMessage(error, '删除失败'), 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,6 +246,7 @@ function sleep(ms: number): Promise<void> {
|
||||
|
||||
async function pollImport(poll: () => Promise<DedupeImportProgress>): Promise<DedupeImportProgress> {
|
||||
for (let i = 0; i < 300; i += 1) {
|
||||
if (pageDisposed) throw new Error('页面已离开,导入进度停止跟踪')
|
||||
const progress = await poll()
|
||||
importProgress.value = importOutcomeText(progress)
|
||||
if (importTaskFinished(progress)) return progress
|
||||
@@ -250,7 +260,7 @@ async function submitImport(): Promise<void> {
|
||||
const file = importFile.value as File
|
||||
const groupId = importGroupId.value as number
|
||||
if (importMode.value === 'delete') {
|
||||
if (!window.confirm('确定按 Excel 中的 ASIN 批量删除匹配的总数据吗?')) return
|
||||
if (!(await openAdminConfirm({ message: '确定按 Excel 中的 ASIN 批量删除匹配的总数据吗?', danger: true }))) return
|
||||
}
|
||||
const mode = importMode.value
|
||||
importRunning.value = true
|
||||
@@ -268,10 +278,10 @@ async function submitImport(): Promise<void> {
|
||||
ElMessage.success(mode === 'add' ? '导入完成' : '删除导入完成')
|
||||
await load()
|
||||
} else {
|
||||
ElMessage.error(importOutcomeText(finished))
|
||||
showAdminFeedback(importOutcomeText(finished), 'error')
|
||||
}
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '导入失败')
|
||||
showAdminFeedback(loadFailureMessage(error, '导入失败'), 'error')
|
||||
} finally {
|
||||
importRunning.value = false
|
||||
}
|
||||
@@ -303,7 +313,7 @@ async function doExport(): Promise<void> {
|
||||
URL.revokeObjectURL(url)
|
||||
ElMessage.success('导出完成')
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '导出失败,请重试')
|
||||
showAdminFeedback(loadFailureMessage(error, '导出失败,请重试'), 'error')
|
||||
} finally {
|
||||
stopExportWait()
|
||||
exporting.value = false
|
||||
@@ -327,6 +337,12 @@ onMounted(() => {
|
||||
void load()
|
||||
void loadGroups()
|
||||
})
|
||||
|
||||
// 导出秒表是 setInterval:不随页面卸载收掉的话,离开本页后它仍在每秒改一个已经没人看的 ref。
|
||||
onUnmounted(() => {
|
||||
pageDisposed = true
|
||||
stopExportWait()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -383,6 +399,7 @@ onMounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll dedupe-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -17,8 +17,12 @@ import { categoryDraftError, createProductCategoryDraft, toCategorySaveRequest,
|
||||
import { buildProductCategoryExportUrl } from './product-category-export.ts'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const tree = ref<ProductCategoryNode[]>([])
|
||||
const keyword = ref('')
|
||||
const selected = ref<ProductCategoryNode | null>(null)
|
||||
@@ -67,6 +71,7 @@ const rootTotal = ref(0)
|
||||
/** 拉取根级当前页(对齐 admin.js loadProductCategoryChildren(null) 懒加载根)。 */
|
||||
async function loadTree(): Promise<void> {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchProductCategoryChildren(null, rootPage.value, rootPageSize.value)
|
||||
const state = { page: result.page, total: result.total, hasMore: result.hasMore, loading: false }
|
||||
@@ -75,7 +80,8 @@ async function loadTree(): Promise<void> {
|
||||
tree.value = result.items
|
||||
rootTotal.value = result.total
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '类目加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '类目加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -167,7 +173,7 @@ async function loadChildrenPage(parent: ProductCategoryNode | null, page: number
|
||||
const fallback = childrenState.get(key) ?? { page: 0, total: 0, hasMore: false, loading: false }
|
||||
fallback.loading = false
|
||||
childrenState.set(key, fallback)
|
||||
ElMessage.error(error instanceof Error ? error.message : '子类目加载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '子类目加载失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,7 +207,7 @@ async function runSearch(page: number): Promise<void> {
|
||||
searchPage.value = result.page
|
||||
searchHasMore.value = result.hasMore
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '类目搜索失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '类目搜索失败', 'error')
|
||||
} finally {
|
||||
searchLoading.value = false
|
||||
}
|
||||
@@ -257,7 +263,7 @@ async function removeCategory(node: ProductCategoryNode): Promise<void> {
|
||||
return
|
||||
}
|
||||
// 对齐旧版:原生 confirm。
|
||||
if (!window.confirm(`确定删除“${node.name}”?`)) return
|
||||
if (!(await openAdminConfirm({ message: `确定删除“${node.name}”?`, danger: true }))) return
|
||||
try {
|
||||
await deleteProductCategory(node.id)
|
||||
ElMessage.success('已删除')
|
||||
@@ -265,7 +271,7 @@ async function removeCategory(node: ProductCategoryNode): Promise<void> {
|
||||
if (searching.value) void runSearch(1)
|
||||
else void loadTree()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -289,7 +295,7 @@ async function submit(): Promise<void> {
|
||||
if (searching.value) void runSearch(1)
|
||||
else void loadTree()
|
||||
} catch (err) {
|
||||
ElMessage.error(err instanceof Error ? err.message : '保存失败')
|
||||
showAdminFeedback(err instanceof Error ? err.message : '保存失败', 'error')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
@@ -322,6 +328,7 @@ onMounted(loadTree)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadTree" />
|
||||
<div class="table-scroll category-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -19,6 +19,9 @@ import type { ShopGroupOption } from '../shop/shop-dto.ts'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
@@ -26,6 +29,7 @@ const companyTab = useCompanyTabStore()
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<QueryAsinItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -69,7 +73,7 @@ function normalizeAsinInput(country: string): void {
|
||||
|
||||
async function removeShopAsin(item: QueryAsinItem) {
|
||||
// 删除该店铺全部站点的 ASIN 配置(逐国调用现有端点)。
|
||||
if (!window.confirm(`确定删除店铺“${item.shopName}”的全部站点 ASIN 配置吗?`)) return
|
||||
if (!(await openAdminConfirm({ message: `确定删除店铺“${item.shopName}”的全部站点 ASIN 配置吗?`, danger: true }))) return
|
||||
try {
|
||||
for (const country of QUERY_ASIN_COUNTRIES) {
|
||||
if (asinOf(item, country)) await deleteQueryAsinCountryAsin(item.id, country)
|
||||
@@ -77,7 +81,7 @@ async function removeShopAsin(item: QueryAsinItem) {
|
||||
ElMessage.success('已删除')
|
||||
await load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,7 +106,7 @@ async function saveConfig(): Promise<void> {
|
||||
}
|
||||
}
|
||||
if (errors.length) {
|
||||
ElMessage.error(errors.join(';'))
|
||||
showAdminFeedback(errors.join(';'), 'error')
|
||||
} else {
|
||||
ElMessage.success('保存成功')
|
||||
drawerVisible.value = false
|
||||
@@ -151,7 +155,7 @@ async function onCreateGroupChange(): Promise<void> {
|
||||
shopNames.value = await fetchShopNamesByGroup(createGroupId.value, companyTab.requestCompanyId)
|
||||
} catch (error) {
|
||||
shopNames.value = []
|
||||
ElMessage.error(error instanceof Error ? error.message : '店铺列表加载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '店铺列表加载失败', 'error')
|
||||
} finally {
|
||||
shopNamesLoading.value = false
|
||||
}
|
||||
@@ -242,7 +246,7 @@ async function submitImport(): Promise<void> {
|
||||
return
|
||||
}
|
||||
if (importMode.value === 'delete') {
|
||||
if (!window.confirm('确定按 Excel 中的分组、店铺名和国家 ASIN 批量删除吗?')) return
|
||||
if (!(await openAdminConfirm({ message: '确定按 Excel 中的分组、店铺名和国家 ASIN 批量删除吗?', danger: true }))) return
|
||||
}
|
||||
const mode = importMode.value
|
||||
const groupId = importGroupId.value ?? undefined
|
||||
@@ -263,7 +267,7 @@ async function submitImport(): Promise<void> {
|
||||
if (progress.status === 'failed') {
|
||||
importVisible.value = false
|
||||
resetImport()
|
||||
ElMessage.error((progress as { errorMessage?: string }).errorMessage || (mode === 'add' ? '导入失败' : '删除导入失败'))
|
||||
showAdminFeedback((progress as { errorMessage?: string }).errorMessage || (mode === 'add' ? '导入失败' : '删除导入失败'), 'error')
|
||||
return
|
||||
}
|
||||
importProgress.value = progress.status === 'pending' ? '等待导入任务开始…' : '导入处理中…'
|
||||
@@ -271,7 +275,7 @@ async function submitImport(): Promise<void> {
|
||||
}
|
||||
throw new Error('查询导入进度超时,请稍后刷新列表确认结果')
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '导入失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '导入失败', 'error')
|
||||
} finally {
|
||||
importRunning.value = false
|
||||
}
|
||||
@@ -298,6 +302,7 @@ async function loadGroups() {
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchQueryAsinList({
|
||||
page: page.value,
|
||||
@@ -312,7 +317,8 @@ async function load() {
|
||||
total.value = result.total
|
||||
page.value = result.page
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '数据加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '数据加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -394,6 +400,7 @@ onMounted(() => {
|
||||
<button class="btn btn-secondary" type="button" @click="doExport">导出 XLSX</button>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll query-asin-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -19,6 +19,9 @@ import type { ShopGroupOption } from '../shop/shop-dto.ts'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
@@ -26,6 +29,7 @@ const companyTab = useCompanyTabStore()
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<SkipPriceItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -95,7 +99,7 @@ async function onCreateGroupChange(): Promise<void> {
|
||||
shopNames.value = await fetchShopNamesByGroup(createGroupId.value, companyTab.requestCompanyId)
|
||||
} catch (error) {
|
||||
shopNames.value = []
|
||||
ElMessage.error(error instanceof Error ? error.message : '店铺列表加载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '店铺列表加载失败', 'error')
|
||||
} finally {
|
||||
shopNamesLoading.value = false
|
||||
}
|
||||
@@ -208,7 +212,7 @@ async function saveConfig(): Promise<void> {
|
||||
}
|
||||
}
|
||||
if (errors.length) {
|
||||
ElMessage.error(errors.join(';'))
|
||||
showAdminFeedback(errors.join(';'), 'error')
|
||||
} else {
|
||||
ElMessage.success('保存成功')
|
||||
drawerVisible.value = false
|
||||
@@ -240,7 +244,7 @@ async function removeRow(item: SkipPriceItem): Promise<void> {
|
||||
}
|
||||
await load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,7 +300,7 @@ async function submitImport(): Promise<void> {
|
||||
return
|
||||
}
|
||||
if (importMode.value === 'delete') {
|
||||
if (!window.confirm('确定按 Excel 中的删除ASIN批量删除该店铺跳过跟价 ASIN 吗?')) return
|
||||
if (!(await openAdminConfirm({ message: '确定按 Excel 中的删除ASIN批量删除该店铺跳过跟价 ASIN 吗?', danger: true }))) return
|
||||
}
|
||||
const mode = importMode.value
|
||||
const groupId = importGroupId.value as number
|
||||
@@ -317,7 +321,7 @@ async function submitImport(): Promise<void> {
|
||||
if (progress.status === 'failed') {
|
||||
importVisible.value = false
|
||||
resetImport()
|
||||
ElMessage.error(progress.errorMessage || (mode === 'add' ? '导入失败' : '删除导入失败'))
|
||||
showAdminFeedback(progress.errorMessage || (mode === 'add' ? '导入失败' : '删除导入失败'), 'error')
|
||||
return
|
||||
}
|
||||
importProgress.value = progress.status === 'pending' ? '等待导入任务开始…' : '导入处理中…'
|
||||
@@ -325,7 +329,7 @@ async function submitImport(): Promise<void> {
|
||||
}
|
||||
throw new Error('查询导入进度超时,请稍后刷新列表确认结果')
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '导入失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '导入失败', 'error')
|
||||
} finally {
|
||||
importRunning.value = false
|
||||
}
|
||||
@@ -351,13 +355,15 @@ async function loadGroups() {
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchSkipPriceList(toSkipPriceParams(filter, page.value, pageSize.value, companyTab.requestCompanyId))
|
||||
rows.value = result.items
|
||||
total.value = result.total
|
||||
page.value = result.page
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '数据加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '数据加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -447,6 +453,7 @@ onMounted(() => {
|
||||
<button class="btn btn-secondary" type="button" @click="doExport">导出 XLSX</button>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll skip-price-asin-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -9,6 +9,9 @@ import { formatDateTime, orderedPair, todayDateInput } from '@/utils/datetime'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { fetchHistoryUserOptions } from './history-api.ts'
|
||||
import type { HistoryUserOption } from './history-user-option.ts'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
import {
|
||||
deleteDeviceLogFile,
|
||||
deleteDeviceLogOverride,
|
||||
@@ -53,6 +56,7 @@ function formatBytes(bytes: number | null | undefined): string {
|
||||
const companyTab = useCompanyTabStore()
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<DeviceLogFileRow[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -76,6 +80,7 @@ const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.v
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchDeviceLogFiles({
|
||||
source: sourceFilter.value || undefined,
|
||||
@@ -90,7 +95,8 @@ async function load() {
|
||||
total.value = Number(result?.total || 0)
|
||||
if (result?.retentionDays) retentionDays.value = result.retentionDays
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '日志列表加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '日志列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -167,7 +173,7 @@ async function loadContent(scrollToBottom: boolean) {
|
||||
if (viewerPre.value) viewerPre.value.scrollTop = viewerPre.value.scrollHeight
|
||||
}
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '日志内容加载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '日志内容加载失败', 'error')
|
||||
} finally {
|
||||
viewerLoading.value = false
|
||||
}
|
||||
@@ -179,13 +185,13 @@ function loadMore() {
|
||||
}
|
||||
|
||||
async function remove(row: DeviceLogFileRow) {
|
||||
if (!window.confirm(`确认删除「${row.fileName}」(${row.deviceName || row.deviceId})的云端日志?删除后不可恢复。`)) return
|
||||
if (!(await openAdminConfirm({ message: `确认删除「${row.fileName}」(${row.deviceName || row.deviceId})的云端日志?删除后不可恢复。`, danger: true }))) return
|
||||
try {
|
||||
await deleteDeviceLogFile(row.id)
|
||||
ElMessage.success('已删除')
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,7 +227,7 @@ async function loadConfig() {
|
||||
overrides.value = data.overrides || []
|
||||
devices.value = (await fetchDeviceLogDevices()) || []
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '采集配置加载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '采集配置加载失败', 'error')
|
||||
} finally {
|
||||
configLoading.value = false
|
||||
}
|
||||
@@ -234,7 +240,7 @@ async function saveGlobalMode(mode: string) {
|
||||
globalMode.value = mode
|
||||
ElMessage.success(`全局采集模式已切换为「${modeLabel(mode)}」`)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '保存失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '保存失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,19 +257,19 @@ async function addOverride() {
|
||||
newOverrideKey.value = ''
|
||||
await loadConfig()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '保存失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '保存失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
async function removeOverride(row: DeviceLogOverride) {
|
||||
const who = row.deviceName || row.deviceId
|
||||
if (!window.confirm(`确认删除终端「${who}」的采集覆盖(回落到全局默认)?`)) return
|
||||
if (!(await openAdminConfirm({ message: `确认删除终端「${who}」的采集覆盖(回落到全局默认)?`, danger: true }))) return
|
||||
try {
|
||||
await deleteDeviceLogOverride(row.id)
|
||||
ElMessage.success('已删除')
|
||||
await loadConfig()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -316,6 +322,7 @@ onMounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="logs-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -23,8 +23,12 @@ import { canReleaseDigitalHumanVersion, releaseDigitalHumanConfirmText } from '.
|
||||
import { canSetLatestDigitalHumanVersion, setLatestDigitalHumanConfirmText } from './digitalhuman-latest.ts'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { digitalHumanStatusDisplay } from './digitalhuman-status-display.ts'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const items = ref<DigitalHumanVersion[]>([])
|
||||
|
||||
/** 分页(对齐 admin.js:6311 pageSize=20 + 数字页码 + 跳转;Java 列表接口不分页,前端分页呈现)。 */
|
||||
@@ -54,11 +58,13 @@ const downloadingVersion = ref<string | null>(null)
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
items.value = (await fetchDigitalHumanVersions()).items
|
||||
// 页码越界回钳见下方 watch(items)。
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '版本列表加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '版本列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -116,7 +122,7 @@ async function submitUpload() {
|
||||
form.value = { version: '', file: null, changelog: '', minClientVersion: '' }
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '上传失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '上传失败', 'error')
|
||||
} finally {
|
||||
uploading.value = false
|
||||
}
|
||||
@@ -126,14 +132,14 @@ async function release(row: DigitalHumanVersion) {
|
||||
const text = releaseDigitalHumanConfirmText(row.version)
|
||||
if (!text) return
|
||||
// 对齐旧版:原生 confirm。
|
||||
if (!window.confirm(text)) return
|
||||
if (!(await openAdminConfirm({ message: text, danger: false }))) return
|
||||
confirming.value = row.version
|
||||
try {
|
||||
await releaseDigitalHumanVersion(row.version)
|
||||
ElMessage.success('已发布')
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '发布失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '发布失败', 'error')
|
||||
} finally {
|
||||
confirming.value = null
|
||||
}
|
||||
@@ -142,14 +148,14 @@ async function release(row: DigitalHumanVersion) {
|
||||
async function setLatest(row: DigitalHumanVersion) {
|
||||
const text = setLatestDigitalHumanConfirmText(row.version)
|
||||
if (!text) return
|
||||
if (!window.confirm(text)) return
|
||||
if (!(await openAdminConfirm({ message: text, danger: false }))) return
|
||||
confirming.value = row.version
|
||||
try {
|
||||
await setLatestDigitalHumanVersion(row.version)
|
||||
ElMessage.success('已设为最新')
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '操作失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '操作失败', 'error')
|
||||
} finally {
|
||||
confirming.value = null
|
||||
}
|
||||
@@ -170,7 +176,7 @@ async function download(row: DigitalHumanVersion) {
|
||||
anchor.click()
|
||||
document.body.removeChild(anchor)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '下载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '下载失败', 'error')
|
||||
} finally {
|
||||
downloadingVersion.value = null
|
||||
}
|
||||
@@ -179,14 +185,14 @@ async function download(row: DigitalHumanVersion) {
|
||||
async function remove(row: DigitalHumanVersion) {
|
||||
const text = digitalHumanDeleteConfirmText(row.version)
|
||||
if (!text) return
|
||||
if (!window.confirm(text)) return
|
||||
if (!(await openAdminConfirm({ message: text, danger: true }))) return
|
||||
confirming.value = row.version
|
||||
try {
|
||||
await deleteDigitalHumanVersion(row.version)
|
||||
ElMessage.success('删除成功')
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
} finally {
|
||||
confirming.value = null
|
||||
}
|
||||
@@ -214,6 +220,7 @@ onMounted(load)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll digital-human-version-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -8,8 +8,12 @@ import { ElMessage } from 'element-plus'
|
||||
import { fetchSoftwareVersions, uploadSoftwareVersion, deleteSoftwareVersions } from './version-api.ts'
|
||||
import type { SoftwareVersionItem } from './version-dto.ts'
|
||||
import { isNonEmptyVersion } from './version-dto.ts'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const items = ref<SoftwareVersionItem[]>([])
|
||||
/** 版本号搜索(客户端过滤)。 */
|
||||
const versionKeyword = ref('')
|
||||
@@ -51,25 +55,25 @@ async function removeSelected() {
|
||||
const rows = items.value.filter((row) => selectedIds.value.has(row.id))
|
||||
const sample = rows.slice(0, 3).map((row) => row.version).join('、')
|
||||
const summary = rows.length > 3 ? `${sample} 等 ${rows.length} 个` : sample
|
||||
if (!window.confirm(`确认删除选中的 ${rows.length} 个版本(${summary})?此操作不可恢复。`)) return
|
||||
if (!(await openAdminConfirm({ message: `确认删除选中的 ${rows.length} 个版本(${summary})?此操作不可恢复。`, danger: true }))) return
|
||||
try {
|
||||
await deleteSoftwareVersions(Array.from(selectedIds.value))
|
||||
ElMessage.success(`已删除 ${rows.length} 个版本`)
|
||||
selectedIds.value = new Set()
|
||||
await load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
async function removeOne(row: SoftwareVersionItem) {
|
||||
if (!window.confirm(`确认删除版本 ${row.version}?此操作不可恢复。`)) return
|
||||
if (!(await openAdminConfirm({ message: `确认删除版本 ${row.version}?此操作不可恢复。`, danger: true }))) return
|
||||
try {
|
||||
await deleteSoftwareVersions([row.id])
|
||||
ElMessage.success('删除成功')
|
||||
selectedIds.value = new Set([...selectedIds.value].filter((id) => id !== row.id))
|
||||
await load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,10 +88,12 @@ const uploadMsgOk = ref(false)
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
items.value = (await fetchSoftwareVersions()).items
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '版本列表加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '版本列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -161,6 +167,7 @@ onMounted(load)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll version-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -10,8 +10,12 @@ import { ElMessage } from 'element-plus'
|
||||
import { fetchTutorialPackages, uploadTutorialPackage, deleteTutorialPackages } from './tutorial-api.ts'
|
||||
import { formatFileSize } from './tutorial-model.ts'
|
||||
import type { TutorialPackageItem } from './tutorial-dto.ts'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const items = ref<TutorialPackageItem[]>([])
|
||||
/** 文件名搜索(客户端过滤)。 */
|
||||
const keyword = ref('')
|
||||
@@ -108,25 +112,25 @@ async function removeSelected() {
|
||||
const rows = items.value.filter((row) => selectedIds.value.has(row.id))
|
||||
const sample = rows.slice(0, 3).map((row) => row.fileName).join('、')
|
||||
const summary = rows.length > 3 ? `${sample} 等 ${rows.length} 个` : sample
|
||||
if (!window.confirm(`确认删除选中的 ${rows.length} 个教程包(${summary})?此操作不可恢复。`)) return
|
||||
if (!(await openAdminConfirm({ message: `确认删除选中的 ${rows.length} 个教程包(${summary})?此操作不可恢复。`, danger: true }))) return
|
||||
try {
|
||||
await deleteTutorialPackages(Array.from(selectedIds.value))
|
||||
ElMessage.success(`已删除 ${rows.length} 个教程包`)
|
||||
selectedIds.value = new Set()
|
||||
await load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
async function removeOne(row: TutorialPackageItem) {
|
||||
if (!window.confirm(`确认删除教程包 ${row.fileName}?此操作不可恢复。`)) return
|
||||
if (!(await openAdminConfirm({ message: `确认删除教程包 ${row.fileName}?此操作不可恢复。`, danger: true }))) return
|
||||
try {
|
||||
await deleteTutorialPackages([row.id])
|
||||
ElMessage.success('删除成功')
|
||||
selectedIds.value = new Set([...selectedIds.value].filter((id) => id !== row.id))
|
||||
await load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,10 +145,12 @@ const uploadMsgOk = ref(false)
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
items.value = (await fetchTutorialPackages()).items
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '教程包列表加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '教程包列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -213,6 +219,7 @@ onMounted(load)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll tutorial-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -10,9 +10,13 @@ import { emptyShopKeyForm, normalizeZiniaoToken, validateProxyUrl } from './shop
|
||||
import type { IpWhitelistStatus, ShopKeyItem } from './shop-dto.ts'
|
||||
import { whitelistStatusMeta, whitelistStatusOptions } from './shop-key-model.ts'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const companyTab = useCompanyTabStore()
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<ShopKeyItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -55,6 +59,7 @@ function whitelistTooltip(row: ShopKeyItem): string {
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchShopKeyList({
|
||||
page: page.value,
|
||||
@@ -68,7 +73,8 @@ async function load() {
|
||||
total.value = result.total
|
||||
page.value = result.page
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '密钥列表加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '密钥列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -98,13 +104,13 @@ async function checkWhitelist(row: ShopKeyItem) {
|
||||
if (updated.ipWhitelistStatus === 'ALLOWED') {
|
||||
ElMessage.success('白名单检测通过')
|
||||
} else if (updated.ipWhitelistStatus === 'BLOCKED') {
|
||||
ElMessage.error(`白名单未放行:${updated.ipWhitelistMessage || '请求被拒绝'}`)
|
||||
showAdminFeedback(`白名单未放行:${updated.ipWhitelistMessage || '请求被拒绝'}`, 'error')
|
||||
} else {
|
||||
ElMessage.warning(updated.ipWhitelistMessage || '检测未通过')
|
||||
}
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '检测失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '检测失败', 'error')
|
||||
} finally {
|
||||
checkingId.value = null
|
||||
}
|
||||
@@ -139,7 +145,7 @@ async function submit() {
|
||||
dialogVisible.value = false
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '保存失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '保存失败', 'error')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
@@ -147,13 +153,13 @@ async function submit() {
|
||||
|
||||
async function remove(row: ShopKeyItem) {
|
||||
// 对齐旧版:原生 confirm。
|
||||
if (!window.confirm(`确定删除店铺密钥“${row.ziniaoAccountName}”吗?`)) return
|
||||
if (!(await openAdminConfirm({ message: `确定删除店铺密钥“${row.ziniaoAccountName}”吗?`, danger: true }))) return
|
||||
try {
|
||||
await deleteShopKey(row.id)
|
||||
ElMessage.success('已删除')
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,6 +225,7 @@ onMounted(load)
|
||||
<button class="btn" type="button" @click="apply">查询</button>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="shop-key-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -17,12 +17,16 @@ import {
|
||||
import { emptyShopManageForm } from './shop-manage-form-model.ts'
|
||||
import type { ShopCredential, ShopGroupOption, ShopSummary } from './shop-dto.ts'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<ShopSummary[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -70,7 +74,7 @@ async function togglePassword(row: ShopSummary) {
|
||||
revealedPasswordCache.value[row.id] = cred.password
|
||||
} catch (error) {
|
||||
revealedRowId.value = null
|
||||
ElMessage.error(error instanceof Error ? error.message : '读取密码失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '读取密码失败', 'error')
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,12 +83,13 @@ async function loadGroups() {
|
||||
try {
|
||||
groups.value = await fetchShopManageGroups(companyTab.requestCompanyId)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '分组加载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '分组加载失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchShopManageList({
|
||||
page: page.value,
|
||||
@@ -97,7 +102,8 @@ async function load() {
|
||||
total.value = result.total
|
||||
page.value = result.page
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '店铺列表加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '店铺列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -178,7 +184,7 @@ async function submit() {
|
||||
dialogVisible.value = false
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '保存失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '保存失败', 'error')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
@@ -189,19 +195,19 @@ async function showCredential(row: ShopSummary) {
|
||||
credential.value = await fetchShopCredential(row.id, row.shopName)
|
||||
credentialVisible.value = true
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '读取凭证失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '读取凭证失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(row: ShopSummary) {
|
||||
// 对齐旧版:原生 confirm。
|
||||
if (!window.confirm(`确定删除店铺“${row.shopName}”吗?`)) return
|
||||
if (!(await openAdminConfirm({ message: `确定删除店铺“${row.shopName}”吗?`, danger: true }))) return
|
||||
try {
|
||||
await deleteShopManage(row.id)
|
||||
ElMessage.success('已删除')
|
||||
load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '删除失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,6 +248,7 @@ onMounted(() => {
|
||||
<button class="btn" type="button" @click="apply">查询</button>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll shop-manage-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -9,6 +9,8 @@ import { ElMessage } from 'element-plus'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { formatDateTime, orderedPair } from '@/utils/datetime'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
import {
|
||||
fetchTaskCenterOverview,
|
||||
fetchTaskCenterShopOptions,
|
||||
@@ -77,6 +79,7 @@ const taskTotal = ref(0)
|
||||
const taskPage = ref(1)
|
||||
const taskPageSize = ref(20)
|
||||
const tasksLoading = ref(false)
|
||||
const tasksFailure = ref('')
|
||||
|
||||
// ---------------------------------------------------------------- 变体采集
|
||||
|
||||
@@ -111,7 +114,7 @@ async function loadOverview() {
|
||||
try {
|
||||
overview.value = await fetchTaskCenterOverview(companyTab.requestCompanyId)
|
||||
} catch (error) {
|
||||
ElMessage.error(errorText(error, '汇总数据加载失败'))
|
||||
showAdminFeedback(errorText(error, '汇总数据加载失败'), 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,12 +123,13 @@ async function loadShopOptions() {
|
||||
try {
|
||||
shopOptions.value = (await fetchTaskCenterShopOptions(companyTab.requestCompanyId)) || []
|
||||
} catch (error) {
|
||||
ElMessage.error(errorText(error, '店铺候选加载失败'))
|
||||
showAdminFeedback(errorText(error, '店铺候选加载失败'), 'error')
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTasks(silent = false) {
|
||||
if (!silent) tasksLoading.value = true
|
||||
tasksFailure.value = ''
|
||||
try {
|
||||
const result = await fetchTaskCenterTasks(
|
||||
buildTaskQuery(filter, taskPage.value, taskPageSize.value, companyTab.requestCompanyId),
|
||||
@@ -133,7 +137,8 @@ async function loadTasks(silent = false) {
|
||||
tasks.value = result?.items || []
|
||||
taskTotal.value = Number(result?.total || 0)
|
||||
} catch (error) {
|
||||
ElMessage.error(errorText(error, '任务列表加载失败'))
|
||||
tasksFailure.value = errorText(error, '任务列表加载失败')
|
||||
showAdminFeedback(tasksFailure.value, 'error')
|
||||
} finally {
|
||||
if (!silent) tasksLoading.value = false
|
||||
}
|
||||
@@ -149,7 +154,7 @@ async function loadVariants(silent = false) {
|
||||
variantTotal.value = tabCount(result?.total)
|
||||
} catch (error) {
|
||||
variantTotal.value = null
|
||||
ElMessage.error(errorText(error, '变体采集加载失败'))
|
||||
showAdminFeedback(errorText(error, '变体采集加载失败'), 'error')
|
||||
} finally {
|
||||
if (!silent) variantLoading.value = false
|
||||
}
|
||||
@@ -254,7 +259,7 @@ async function openDetail(row: TaskCenterTaskRow) {
|
||||
detail.value = await fetchTaskCenterTaskDetail(row.taskNo, companyTab.requestCompanyId)
|
||||
if (!detail.value) ElMessage.warning('任务不存在或无权查看')
|
||||
} catch (error) {
|
||||
ElMessage.error(errorText(error, '任务详情加载失败'))
|
||||
showAdminFeedback(errorText(error, '任务详情加载失败'), 'error')
|
||||
detailVisible.value = false
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
@@ -407,6 +412,7 @@ onUnmounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<LoadFailureBar v-if="tasksFailure" :message="tasksFailure" @retry="loadTasks" />
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 数据源保持自家后端:/duplicate-check-console(指标/店铺/撞款全集/分组统计) + /duplicate-check-ledger(台账分页) + /duplicate-check-export(Excel)。
|
||||
* 分组归属来自「店铺管理」真实店铺分组,本页只读展示,仅用于分组撞款范围切换。
|
||||
*/
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import type { DuplicateItem, DuplicateOccurrence, DuplicateMetrics, DuplicateShop } from './duplicate-model.ts'
|
||||
@@ -414,6 +414,11 @@ function siteColor(code: string): string {
|
||||
// loadConsole 的重挑分支(groupStats 为空时不触发)里留着一个不属于本公司的 selectedGroup。
|
||||
watch(() => companyTab.activeId, () => { filter.shop = ''; filter.group = ''; selectedGroup.value = ''; scope.value = 'global'; void loadConsole(); void loadLedger(1) })
|
||||
|
||||
// 卸载时收掉 toast 的 2.4s 收尾定时器:否则离开本页后它还会去摸一个已经不存在的节点。
|
||||
onUnmounted(() => {
|
||||
window.clearTimeout(toastTimer)
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
loadConsole()
|
||||
// 台账 Tab 计数打开即显示:挂载时预取第一页拿 total(对齐 reference 渲染即见台账条数)。
|
||||
@@ -432,6 +437,7 @@ onMounted(() => {
|
||||
|
||||
<div v-if="loadError" class="load-banner">
|
||||
<span>{{ loadError }}</span>
|
||||
<button class="btn btn-ghost btn-sm" type="button" @click="loadConsole">重试</button>
|
||||
<button class="btn btn-ghost btn-sm" type="button" @click="loadError = ''">知道了</button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -21,10 +21,13 @@ import { imageVideoDownloadFilename, videoKeysOf } from './image-video-view.ts'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const tasks = ref<ImageVideoRow[]>([])
|
||||
const totalTasks = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -122,13 +125,15 @@ function toFilter(): ImageVideoFilter {
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchImageVideoTasks(toFilter(), page.value, pageSize.value, companyTab.requestCompanyId)
|
||||
tasks.value = result.items
|
||||
totalTasks.value = result.total
|
||||
page.value = result.page
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '视频任务加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '视频任务加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -201,7 +206,7 @@ async function openDetail(task: ImageVideoRow) {
|
||||
try {
|
||||
detail.value = await fetchImageVideoTaskDetail(task.taskId)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '详情加载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '详情加载失败', 'error')
|
||||
detailVisible.value = false
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
@@ -218,7 +223,7 @@ async function downloadVideo(task: ImageVideoRow, index: number, video: ImageVid
|
||||
} catch {
|
||||
// 打包失败降级:直接打开该视频地址以便下载。
|
||||
if (video.displayUrl) window.open(video.displayUrl, '_blank')
|
||||
else ElMessage.error('视频下载失败')
|
||||
else showAdminFeedback('视频下载失败', 'error')
|
||||
} finally {
|
||||
downloadingKey.value = ''
|
||||
}
|
||||
@@ -237,7 +242,7 @@ async function downloadBatch() {
|
||||
const note = errorCount ? `,${errorCount} 个失败` : ''
|
||||
ElMessage.success(`正在打包 ${fileCount ?? keys.length} 个视频${note}`)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '批量下载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '批量下载失败', 'error')
|
||||
} finally {
|
||||
downloading.value = false
|
||||
}
|
||||
@@ -269,7 +274,7 @@ async function openPermission() {
|
||||
permPage.value = 1
|
||||
permissionVisible.value = true
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '权限用户加载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '权限用户加载失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,7 +291,7 @@ async function savePermission() {
|
||||
ElMessage.success('保存成功')
|
||||
permissionVisible.value = false
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '保存失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '保存失败', 'error')
|
||||
} finally {
|
||||
permissionSaving.value = false
|
||||
}
|
||||
@@ -328,6 +333,7 @@ onMounted(load)
|
||||
</section>
|
||||
|
||||
<section class="panel-box iv-panel">
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="iv-toolbar">
|
||||
<div class="iv-toolbar-main">
|
||||
<button v-if="session.isSuperAdmin" class="btn btn-secondary" type="button" @click="openPermission">权限配置</button>
|
||||
|
||||
@@ -27,10 +27,14 @@ import {
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const groups = ref<ShopDataTaskGroup[]>([])
|
||||
const totalShops = ref(0)
|
||||
const page = ref(1)
|
||||
@@ -127,13 +131,15 @@ function toFilter(): ShopDataFilter {
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const result = await fetchShopDataTaskList(toFilter(), page.value, pageSize.value, companyTab.requestCompanyId)
|
||||
groups.value = result.items
|
||||
totalShops.value = result.total
|
||||
page.value = result.page
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '店铺数据记录加载失败')
|
||||
loadFailure.value = error instanceof Error ? error.message : '店铺数据记录加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -223,7 +229,7 @@ async function downloadRow(row: ShopDataResultRow) {
|
||||
downloadProgress.visible = false
|
||||
ElMessage.success('下载已开始')
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '下载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '下载失败', 'error')
|
||||
} finally {
|
||||
busyKey.value = ''
|
||||
}
|
||||
@@ -244,7 +250,7 @@ async function downloadBatch() {
|
||||
const note = zip.errorCount ? `,${zip.errorCount} 个失败(详见包内错误清单)` : ''
|
||||
ElMessage.success(`已下载 ${zip.fileCount ?? resultIds.length} 个文件${note}`)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '批量下载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '批量下载失败', 'error')
|
||||
} finally {
|
||||
busyKey.value = ''
|
||||
}
|
||||
@@ -252,14 +258,14 @@ async function downloadBatch() {
|
||||
|
||||
async function removeRowByRow(row: ShopDataResultRow) {
|
||||
// 管理端真删:删除该店这条店铺数据记录(累计档 + 文件 + 明细),前台任务记录仍保留但文件不可再下载
|
||||
if (!window.confirm(`确认删除店铺“${row.shopName}”这条店铺数据记录及其数据文件?此操作不可恢复。`)) return
|
||||
if (!(await openAdminConfirm({ message: `确认删除店铺“${row.shopName}”这条店铺数据记录及其数据文件?此操作不可恢复。`, danger: true }))) return
|
||||
deletingKey.value = row.resultId
|
||||
try {
|
||||
await deleteShopDataResultHistory(row.resultId)
|
||||
ElMessage.success('删除成功')
|
||||
await load()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : `删除店铺“${row.shopName}”的记录失败`)
|
||||
showAdminFeedback(error instanceof Error ? error.message : `删除店铺“${row.shopName}”的记录失败`, 'error')
|
||||
} finally {
|
||||
deletingKey.value = ''
|
||||
}
|
||||
@@ -280,7 +286,7 @@ async function openPermission() {
|
||||
permPage.value = 1
|
||||
permissionVisible.value = true
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '权限用户加载失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '权限用户加载失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,7 +302,7 @@ async function savePermission() {
|
||||
ElMessage.success('保存成功')
|
||||
permissionVisible.value = false
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '保存失败')
|
||||
showAdminFeedback(error instanceof Error ? error.message : '保存失败', 'error')
|
||||
} finally {
|
||||
permissionSaving.value = false
|
||||
}
|
||||
@@ -347,6 +353,7 @@ onMounted(load)
|
||||
</section>
|
||||
|
||||
<section class="panel-box">
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="sd-toolbar">
|
||||
<div class="sd-toolbar-main">
|
||||
<label class="sd-select-all">
|
||||
|
||||
@@ -15,7 +15,7 @@ test('align_users_row_buttons_old_btn', () => {
|
||||
assert.match(s, /class="btn btn-sm"[^>]*@click="openEdit\(row\)"/, '编辑用旧版 btn-sm 实心小按钮')
|
||||
assert.match(s, /class="btn btn-sm btn-danger"[^>]*@click="removeUser\(row\)"/, '删除用旧版 btn-sm btn-danger')
|
||||
assert.doesNotMatch(s, /el-button/, '用户页已自绘,无 EP 按钮')
|
||||
assert.match(s, /window\.confirm\(deleteConfirmMessage\(row\)\)/, '删除确认走原生 confirm 对齐旧版')
|
||||
assert.match(s, /openAdminConfirm\(\{ message: deleteConfirmMessage\(row\), danger: true \}\)/, '删除确认走统一确认出口,文案仍取旧版模型')
|
||||
})
|
||||
|
||||
test('align_groups_row_buttons_old_btn', () => {
|
||||
@@ -30,5 +30,5 @@ test('align_menus_row_buttons_old_btn', () => {
|
||||
assert.match(s, /class="btn btn-sm"[^>]*@click="openEdit\(row\)"/, '编辑用旧版 btn-sm 实心小按钮')
|
||||
assert.match(s, /class="btn btn-sm btn-danger"[^>]*@click="removeMenu\(row\)"/, '删除用旧版 btn-sm btn-danger')
|
||||
assert.doesNotMatch(s, /el-button[^>]*@click="openEdit/, '行内不再用 EP 按钮')
|
||||
assert.match(s, /window\.confirm\(`确定删除菜单/, '删除确认走原生 confirm 对齐旧版')
|
||||
assert.match(s, /openAdminConfirm\(\{ message: `确定删除菜单/, '删除确认走统一确认出口,文案对齐旧版')
|
||||
})
|
||||
|
||||
@@ -22,7 +22,7 @@ test('align_invalid_asin_row_buttons_old_btn', () => {
|
||||
const s = readSource('src/pages/asin/AsinInvalidPage.vue')
|
||||
assertOldRowButton(s, 'openEdit(row)', '不符合ASIN')
|
||||
assertOldRowButton(s, 'remove(row)', '不符合ASIN')
|
||||
assert.match(s, /window\.confirm\(invalidAsinDeleteText\(row\)\)/, '删除确认原生 confirm 对齐旧版')
|
||||
assert.match(s, /openAdminConfirm\(\{ message: invalidAsinDeleteText\(row\), danger: true \}\)/, '删除确认走统一确认出口,文案仍取旧版模型')
|
||||
})
|
||||
|
||||
test('align_query_asin_config_old_btn', () => {
|
||||
@@ -57,7 +57,7 @@ test('align_dedupe_registry_row_buttons_old_btn', () => {
|
||||
assert.match(s, /class="btn btn-sm"[^>]*@click="openEdit\(row\)"/, '编辑用旧版 btn-sm 实心小按钮')
|
||||
assert.match(s, /class="btn btn-sm btn-danger"[^>]*@click="removeRow\(row\)"/, '删除用旧版 btn-sm btn-danger')
|
||||
assert.doesNotMatch(s, /el-button/, '去重汇总已自绘,无 EP 按钮')
|
||||
assert.match(s, /window\.confirm\(`确定删除总数据/, '删除确认文案对齐旧版(原生 confirm)')
|
||||
assert.match(s, /openAdminConfirm\(\{ message: `确定删除总数据/, '删除确认文案对齐旧版,出口统一为 openAdminConfirm')
|
||||
})
|
||||
|
||||
test('align_asin_actions_cell_spacing', () => {
|
||||
|
||||
@@ -16,7 +16,7 @@ test('align_shop_manage_row_buttons_old_btn', () => {
|
||||
assert.match(s, /class="btn btn-sm btn-secondary"[^>]*@click="showCredential\(row\)"/, '凭证用旧版 btn-sm btn-secondary')
|
||||
assert.match(s, /class="btn btn-sm btn-danger"[^>]*@click="remove\(row\)"/, '删除用旧版 btn-sm btn-danger')
|
||||
assert.doesNotMatch(s, /el-button[^>]*@click="openEdit/, '行内不再用 EP 按钮')
|
||||
assert.match(s, /window\.confirm\(`确定删除店铺/, '删除确认原生 confirm 对齐旧版')
|
||||
assert.match(s, /openAdminConfirm\(\{ message: `确定删除店铺/, '删除确认走统一确认出口,文案对齐旧版')
|
||||
})
|
||||
|
||||
test('align_shop_keys_row_buttons_old_btn', () => {
|
||||
@@ -39,7 +39,7 @@ test('align_digital_human_row_buttons_old_btn', () => {
|
||||
assert.match(s, /class="btn btn-sm btn-secondary"[^>]*@click="download\(row\)"/, '下载用旧版 btn-sm btn-secondary')
|
||||
assert.match(s, /class="btn btn-sm btn-danger"[^>]*@click="remove\(row\)"/, '删除用旧版 btn-sm btn-danger')
|
||||
assert.doesNotMatch(s, /el-button[^>]*@click="release/, '行内不再用 EP 按钮')
|
||||
assert.match(s, /window\.confirm\(text\)/, '确认走原生 confirm 对齐旧版')
|
||||
assert.match(s, /openAdminConfirm\(\{ message: text, danger: /, '确认走统一确认出口,文案仍由模型给出')
|
||||
})
|
||||
|
||||
test('align_image_video_detail_and_download_old_btn', () => {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
|
||||
"totals": {
|
||||
"files": 238,
|
||||
"cases": 1707,
|
||||
"pins": 436,
|
||||
"reads": 621
|
||||
"files": 244,
|
||||
"cases": 1726,
|
||||
"pins": 448,
|
||||
"reads": 639
|
||||
},
|
||||
"files": {
|
||||
"admin-scaffold.test.ts": {
|
||||
@@ -213,9 +213,9 @@
|
||||
"reads": 0
|
||||
},
|
||||
"company-tab-wiring.test.ts": {
|
||||
"cases": 7,
|
||||
"pins": 3,
|
||||
"reads": 7
|
||||
"cases": 0,
|
||||
"pins": 0,
|
||||
"reads": 2
|
||||
},
|
||||
"company-user-create.test.ts": {
|
||||
"cases": 9,
|
||||
@@ -227,11 +227,21 @@
|
||||
"pins": 2,
|
||||
"reads": 9
|
||||
},
|
||||
"confirm-exit-ledger.test.ts": {
|
||||
"cases": 5,
|
||||
"pins": 3,
|
||||
"reads": 5
|
||||
},
|
||||
"date-filter-default-today.test.ts": {
|
||||
"cases": 3,
|
||||
"pins": 1,
|
||||
"reads": 2
|
||||
},
|
||||
"date-range-order.test.ts": {
|
||||
"cases": 0,
|
||||
"pins": 0,
|
||||
"reads": 0
|
||||
},
|
||||
"datetime-format.test.ts": {
|
||||
"cases": 8,
|
||||
"pins": 0,
|
||||
@@ -242,6 +252,11 @@
|
||||
"pins": 6,
|
||||
"reads": 6
|
||||
},
|
||||
"dedupe-write-forbidden-reason.test.ts": {
|
||||
"cases": 6,
|
||||
"pins": 4,
|
||||
"reads": 4
|
||||
},
|
||||
"device-logs-user-filter.test.ts": {
|
||||
"cases": 5,
|
||||
"pins": 5,
|
||||
@@ -252,6 +267,11 @@
|
||||
"pins": 0,
|
||||
"reads": 0
|
||||
},
|
||||
"error-feedback-exit-ledger.test.ts": {
|
||||
"cases": 4,
|
||||
"pins": 3,
|
||||
"reads": 4
|
||||
},
|
||||
"expiry-notice.test.ts": {
|
||||
"cases": 7,
|
||||
"pins": 2,
|
||||
@@ -262,6 +282,11 @@
|
||||
"pins": 1,
|
||||
"reads": 1
|
||||
},
|
||||
"load-failure-visibility.test.ts": {
|
||||
"cases": 6,
|
||||
"pins": 2,
|
||||
"reads": 5
|
||||
},
|
||||
"login-failure-must-show-reason.test.ts": {
|
||||
"cases": 7,
|
||||
"pins": 1,
|
||||
@@ -1187,6 +1212,11 @@
|
||||
"pins": 3,
|
||||
"reads": 5
|
||||
},
|
||||
"timer-cleanup-pairing.test.ts": {
|
||||
"cases": 5,
|
||||
"pins": 3,
|
||||
"reads": 5
|
||||
},
|
||||
"user-disable.test.ts": {
|
||||
"cases": 7,
|
||||
"pins": 2,
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* 二次确认出口的收口台账(四面9分口径 · 后管「流程 6.0 / 交互 6.0:三套确认并存」)。
|
||||
*
|
||||
* 评审实测:`window.confirm` **23 处/15 文件**,而封装好的 `openAdminConfirm` 只有 1 个消费者。
|
||||
* 三套确认并存的问题是"取消"在两个域里读法相反、危险操作的分量全靠各页自己领会。
|
||||
* 本批次把 24 处 `window.confirm` 全并到 `openAdminConfirm`(都在 `async function` 里,await 不断调用链)。
|
||||
*
|
||||
* 这条台账管两件事,缺一不可:
|
||||
* ① `window.confirm(` 全树归零,例外要登记、只许减;
|
||||
* ② **每一处 `openAdminConfirm(` 必须被 await**——它是 Promise,不 await 就是
|
||||
* "点了确认也不执行"的行为回归(评审特别点过这一条)。同步换异步不是免费的。
|
||||
* 外加一条口径审计:文案里出现「删除/清空」的确认必须是 danger 形态(红色、按钮「确认删除」),
|
||||
* 不许有危险操作混在「请确认操作」里。
|
||||
*/
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, statSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { occurrences, readSource } from './helpers.ts'
|
||||
|
||||
const CONFIRM_MODULE = 'src/components/admin-confirm.ts'
|
||||
/** 例外名单只许减:本批次结束时 native confirm 归零。 */
|
||||
const NATIVE_CONFIRM_LEDGER_CAP = 0
|
||||
/** 分母硬钉:2026-10-10 实测 openAdminConfirm 调用 25 处(24 处新收口 + GroupsPage 原有 1 处)。 */
|
||||
const CONFIRM_CALLS_FLOOR = 25
|
||||
|
||||
const NATIVE_CONFIRM_LEDGER: Array<{ file: string; reason: string }> = []
|
||||
|
||||
function sourceFiles(): string[] {
|
||||
const out: string[] = []
|
||||
const walk = (dir: string): void => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const abs = join(dir, name)
|
||||
if (name.endsWith('.d.ts')) continue
|
||||
if (statSync(abs).isDirectory()) walk(abs)
|
||||
else if (name.endsWith('.vue') || name.endsWith('.ts')) out.push(abs.split(/[\\/]+/).join('/'))
|
||||
}
|
||||
}
|
||||
walk('src')
|
||||
return out
|
||||
}
|
||||
|
||||
/** 去掉行注释:注释里提一句 window.confirm 不该被数成调用点。 */
|
||||
function withoutLineComments(src: string): string {
|
||||
return src.split('\n')
|
||||
.filter((line) => !/^\s*(\/\/|\*)/.test(line))
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
/** native confirm 调用点:`window.confirm(` 以及裸 `confirm(`(logout.ts 那种注入回调的形态要排除)。 */
|
||||
export function nativeConfirmSites(src: string): number {
|
||||
const code = withoutLineComments(src)
|
||||
return occurrences(code, 'window.confirm(')
|
||||
}
|
||||
|
||||
/** 返回未被 await 的 openAdminConfirm 调用(调用点前 30 字符内必须以 `await ` 收尾)。 */
|
||||
export function unawaitedConfirmCalls(src: string): string[] {
|
||||
const code = withoutLineComments(src)
|
||||
const bad: string[] = []
|
||||
let at = code.indexOf('openAdminConfirm(')
|
||||
while (at >= 0) {
|
||||
const before = code.slice(Math.max(0, at - 30), at)
|
||||
const isDefinition = /function\s+$/.test(before)
|
||||
if (!isDefinition && !/\bawait\s+$/.test(before)) bad.push(`${before.trim()}openAdminConfirm(`)
|
||||
at = code.indexOf('openAdminConfirm(', at + 1)
|
||||
}
|
||||
return bad
|
||||
}
|
||||
|
||||
/** 文案含「删除/清空」却没走 danger 形态的调用行。 */
|
||||
export function dangerMismatchLines(src: string): string[] {
|
||||
return withoutLineComments(src).split('\n')
|
||||
.filter((line) => line.includes('openAdminConfirm({'))
|
||||
.filter((line) => /删除|清空/.test(line) ? !line.includes('danger: true') : !line.includes('danger:'))
|
||||
}
|
||||
|
||||
const FILES = sourceFiles()
|
||||
const NATIVE_OFFENDERS = FILES
|
||||
.filter((rel) => rel !== CONFIRM_MODULE && nativeConfirmSites(readSource(rel)) > 0)
|
||||
const CONFIRM_CALL_LINES = FILES
|
||||
.filter((rel) => rel !== CONFIRM_MODULE)
|
||||
.flatMap((rel) => readSource(rel).split('\n').filter((l) => l.includes('openAdminConfirm(')))
|
||||
|
||||
test('分母硬钉:扫描覆盖整棵 src,且统一确认出口的调用点真的在', () => {
|
||||
assert.ok(FILES.length >= 180, `只扫到 ${FILES.length} 个源文件,扫描规则可能已失效`)
|
||||
assert.ok(CONFIRM_CALL_LINES.length >= CONFIRM_CALLS_FLOOR,
|
||||
`openAdminConfirm 调用只有 ${CONFIRM_CALL_LINES.length} 处:24 处收口没落地或扫漏了`)
|
||||
})
|
||||
|
||||
test('window.confirm 归零:名单外一律点名,名单只许减且每条必须仍然成立', () => {
|
||||
assert.ok(NATIVE_CONFIRM_LEDGER.length <= NATIVE_CONFIRM_LEDGER_CAP,
|
||||
`例外名单从 ${NATIVE_CONFIRM_LEDGER_CAP} 涨到 ${NATIVE_CONFIRM_LEDGER.length}:这条口径只许减`)
|
||||
assert.deepEqual(NATIVE_OFFENDERS.slice().sort(), NATIVE_CONFIRM_LEDGER.map((e) => e.file).sort(),
|
||||
`native confirm 与名单不等值:${NATIVE_OFFENDERS.join(', ')}`)
|
||||
for (const entry of NATIVE_CONFIRM_LEDGER) {
|
||||
assert.ok(nativeConfirmSites(readSource(entry.file)) > 0, `${entry.file} 已无 native confirm,登记该删`)
|
||||
}
|
||||
})
|
||||
|
||||
test('每一处 openAdminConfirm 都被 await:不等待就等于点了确认也不执行', () => {
|
||||
const offenders = FILES
|
||||
.filter((rel) => rel !== CONFIRM_MODULE)
|
||||
.flatMap((rel) => unawaitedConfirmCalls(readSource(rel)).map((s) => `${rel}: ${s}`))
|
||||
assert.deepEqual(offenders, [], `未等待的确认调用(同步分支被改成异步的那类回归):\n${offenders.join('\n')}`)
|
||||
})
|
||||
|
||||
test('危险确认必须是 danger 形态:删除/清空心须配「确认删除」', () => {
|
||||
const offenders = FILES
|
||||
.filter((rel) => rel !== CONFIRM_MODULE)
|
||||
.flatMap((rel) => dangerMismatchLines(readSource(rel)).map((l) => `${rel}: ${l.trim()}`))
|
||||
assert.deepEqual(offenders, [], `文案与确认形态不匹配(或漏了 danger 键):\n${offenders.join('\n')}`)
|
||||
})
|
||||
|
||||
test('非零对照:注入一处 native confirm、一处未 await、一处 danger 不匹配都要被红', () => {
|
||||
const injected = "async function f() {\n if (!window.confirm('确定删除该项吗?')) return\n}\n"
|
||||
assert.equal(nativeConfirmSites(injected), 1, '扫不出 native confirm ⇒ 归零断言恒绿')
|
||||
const notAwaited = "async function f() {\n if (!(openAdminConfirm({ message: 'x', danger: true }))) return\n}\n"
|
||||
assert.equal(unawaitedConfirmCalls(notAwaited).length, 1, '扫不出未 await ⇒ 第二条断言恒绿')
|
||||
const awaited = "async function f() {\n if (!(await openAdminConfirm({ message: 'x', danger: true }))) return\n}\n"
|
||||
assert.deepEqual(unawaitedConfirmCalls(awaited), [])
|
||||
const wrongDanger = "await openAdminConfirm({ message: '确定删除店铺吗?', danger: false })"
|
||||
assert.equal(dangerMismatchLines(wrongDanger).length, 1, '扫不出 danger 不匹配 ⇒ 第三条断言恒绿')
|
||||
assert.deepEqual(dangerMismatchLines(awaited), [])
|
||||
assert.equal(nativeConfirmSites("// 这里写着 window.confirm( 只是注释"), 0)
|
||||
})
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* 去重库「前端能点、后端按范围拒」这一处(四面9分口径 · 后管「交互 6.0:1 处能点但后端 403」)。
|
||||
*
|
||||
* 判据来自后端 `DedupeTotalDataService`,两条谓词不是同一个口径:
|
||||
* 读侧 `applyGroupScope`:`scope.wholeCompany()`(公司超管)走 **`company_id = 本公司`**,整家公司的行全给看;
|
||||
* 写侧 `ensureRecordAccess` / `resolveAccessibleGroup`:只认 **`scope.groupIds()`**(本公司成员当组长的分组)
|
||||
* 与 `group_id IS NULL && uploaderUserId ∈ scope.userIds()`。
|
||||
* 于是「代导入行」(平台超管在 A 公司 tab 里把行挂到 B 公司的分组上)与「上传账号已被硬删的行」这两族
|
||||
* 会**看得见、改不了**:点编辑/删除直接被 403 拒。
|
||||
*
|
||||
* 这一支钉三件事:
|
||||
* ① 403 的中文原因(`无权操作该总数据`)必须真的到达界面——此前写路径取的是
|
||||
* `error instanceof Error ? error.message`,而 HTTP-403 是 axios 抛的,那句 message 是
|
||||
* `Request failed with status code 403`(英文、且把响应体里后端写的原因整段丢掉);
|
||||
* ② 前后端文案不许各说各话:后端那两句拒绝理由改字,本用例红;
|
||||
* ③ 不许用「客户端猜一个条件把按钮禁用」来糊:客户端拿不到 companyGroupIds,
|
||||
* 按 `groups` 下拉收窄会误伤同事名下**真能改**的行(假阴性=静默删功能)。
|
||||
* 要把这个入口收窄,得先让后端把可写标志随列表下发(现成的先例:用户菜单授权树的 `grantable`)。
|
||||
*/
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { readSource } from './helpers.ts'
|
||||
import { failureDetail, loadFailureMessage, scopeRefusalNote } from '../src/components/load-failure-model.ts'
|
||||
|
||||
const PAGE = 'src/pages/asin/DedupeRegistryPage.vue'
|
||||
const BACKEND = '../backend-java/src/main/java/com/nanri/aiimage/modules/dedupe/service/DedupeTotalDataService.java'
|
||||
/** 后端按范围拒人时写进响应的原话(HTTP 403 + 响应体 message)。 */
|
||||
const BACKEND_REFUSALS = ['无权操作该总数据', '无权操作该分组数据']
|
||||
|
||||
function fnBody(src: string, name: string): string {
|
||||
const at = src.search(new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`))
|
||||
assert.ok(at >= 0, `${name} 不在了:入口被改名或删掉,本用例得重看`)
|
||||
const open = src.indexOf('{', at)
|
||||
let depth = 0
|
||||
for (let i = open; i < src.length; i++) {
|
||||
if (src[i] === '{') depth += 1
|
||||
else if (src[i] === '}') {
|
||||
depth -= 1
|
||||
if (depth === 0) return src.slice(open + 1, i)
|
||||
}
|
||||
}
|
||||
throw new Error(`${name} 括号不配对`)
|
||||
}
|
||||
|
||||
/** 模拟后端 GlobalExceptionHandler 对 ResponseStatusException 的产物:HTTP 403 + 中文 reason 在响应体里。 */
|
||||
function http403(reason: string): unknown {
|
||||
return Object.assign(new Error(`Request failed with status code 403`), {
|
||||
isAxiosError: true,
|
||||
response: { status: 403, data: { success: false, code: 403, message: reason } },
|
||||
})
|
||||
}
|
||||
|
||||
test('后端源码仍在(跨树判据的前提:文件不在了要红,不能静默跳过)', () => {
|
||||
assert.ok(existsSync(BACKEND), `找不到后端判据源文件 ${BACKEND}:整条跨树对账失去依据`)
|
||||
})
|
||||
|
||||
test('403 的中文原因必须到达界面,而不是 axios 那句英文', () => {
|
||||
const err = http403('无权操作该总数据')
|
||||
// 收口前各写路径的写法:英文原文上屏,后端原因整段丢失
|
||||
const before = err instanceof Error ? err.message : '删除失败'
|
||||
assert.equal(before, 'Request failed with status code 403')
|
||||
assert.equal(/[\u4e00-\u9fff]/.test(before), false, '对照本体必须是"界面上一个中文都没有"的那种')
|
||||
// 收口后:本页兜底 + 后端原因 + 出路
|
||||
const after = loadFailureMessage(err, '删除失败')
|
||||
assert.match(after, /删除失败:无权操作该总数据/)
|
||||
assert.match(after, /平台超级管理员/, '按范围拒人要把出路一起说清楚')
|
||||
assert.equal(failureDetail(err), '无权操作该总数据')
|
||||
})
|
||||
|
||||
test('去重页四条写路径都把错误交给 loadFailureMessage,不再直接取 error.message', () => {
|
||||
const src = readSource(PAGE)
|
||||
for (const name of ['saveEdit', 'removeRow', 'submitImport', 'doExport']) {
|
||||
const body = fnBody(src, name)
|
||||
assert.match(body, /loadFailureMessage\(error,/, `${name} 的失败提示没有带出后端原因`)
|
||||
assert.equal(/error instanceof Error \? error\.message/.test(body), false,
|
||||
`${name} 还留着 error.message 那套写法:HTTP 403 时会把英文原文弹给用户`)
|
||||
}
|
||||
assert.match(src, /import \{ loadFailureMessage \} from '@\/components\/load-failure-model'/)
|
||||
})
|
||||
|
||||
test('前后端拒绝文案对账:后端改字,这条要红', () => {
|
||||
const backend = readSource(BACKEND)
|
||||
for (const reason of BACKEND_REFUSALS) {
|
||||
assert.ok(backend.includes(`"${reason}"`), `后端已不再用「${reason}」这句话拒人:前端那句补充说明要跟着改`)
|
||||
assert.match(scopeRefusalNote(reason), /平台超级管理员/, `「${reason}」没被识别成范围拒绝`)
|
||||
}
|
||||
// 业务校验类的中文(本公司已存在该数据)不许被套上越权说明
|
||||
assert.equal(scopeRefusalNote('本公司已存在该数据'), '')
|
||||
})
|
||||
|
||||
test('读写两条谓词确实不同口径(不对称仍在=这条台账还没到可关闭的时候)', () => {
|
||||
const backend = readSource(BACKEND)
|
||||
// 取 4 参那一条真身:3 参重载只是 `applyGroupScope(query, scope, groupId, false)` 的转发壳,
|
||||
// 用懒匹配会停在壳上,把"整家公司都放行"那半边看漏。
|
||||
const readSide = /private void applyGroupScope\(LambdaQueryWrapper<DedupeTotalDataEntity> query,\s*\n?\s*AccessScope scope, Long groupId, boolean groupPrevalidated\)\s*\{[\s\S]*?\n \}/
|
||||
.exec(backend)
|
||||
assert.ok(readSide, 'applyGroupScope 不在了:读侧裁剪改写法了,本用例要重读')
|
||||
assert.match(readSide[0], /scope\.wholeCompany\(\)/, '读侧不再有 wholeCompany 分支:这条不对称可能已被收口')
|
||||
assert.match(readSide[0], /getCompanyId, scope\.companyId\(\)/,
|
||||
'读侧已不按 company_id 给整家公司放行:请重判前端入口是否还需要收窄')
|
||||
const writeSide = /private void ensureRecordAccess\([\s\S]*?\n \}/.exec(backend)
|
||||
assert.ok(writeSide, 'ensureRecordAccess 不在了:写侧改判据了,本用例要重读')
|
||||
assert.match(writeSide[0], /scope\.groupIds\(\)\.contains/, '写侧不再按 groupIds 拒人')
|
||||
assert.equal(/scope\.wholeCompany\(\)/.test(writeSide[0]), false,
|
||||
'写侧也开始认 wholeCompany:读写字面口径一致了,可以把"能点但拒"这条台账关掉')
|
||||
})
|
||||
|
||||
test('不许用客户端猜测禁用行内入口:那会误伤真能改的行', () => {
|
||||
const src = readSource(PAGE)
|
||||
const opsCell = /<td class="ops-cell">[\s\S]*?<\/td>/.exec(src)
|
||||
assert.ok(opsCell, '行内操作列结构变了:这条判据要重写')
|
||||
assert.equal(/:disabled=|v-if=/.test(opsCell[0]), false,
|
||||
'行内编辑/删除上加了客户端权限闸——但前端拿不到后端写侧的 companyGroupIds,'
|
||||
+ '按分组下拉收窄会把同事名下"看得见也改得动"的行一起禁掉(静默删功能)。'
|
||||
+ '要收窄请先让后端在列表响应里下发可写标志(先例:用户菜单授权树的 grantable)。')
|
||||
assert.match(opsCell[0], /@click="removeRow\(row\)"/, '删除入口本身不在了:本用例失效')
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* 统一提示出口的收口台账(四面9分口径 · 后管「复用 6.0」)。
|
||||
*
|
||||
* 评审实测:`showAdminFeedback` 只有 17 处调用,而裸 `ElMessage.error` **92 处**——同一件事
|
||||
* (把后端或本地的错误文本弹给用户)有两种写法,新页面跟着抄哪一种全看运气,文案与时长也无从统一。
|
||||
* 这一支把 92 处机械可换的全部换成 `showAdminFeedback(msg, 'error')`,然后把「还剩哪几处裸调用」
|
||||
* 落成一张显式名单:
|
||||
* ① 名单外的任何裸 `ElMessage.error(` 一律红(新增拦在提交前,而不是等下轮评审再数一遍);
|
||||
* ② 名单里每一条都必须在文件里仍然成立(防止台账烂成没人删的历史账);
|
||||
* ③ 名单本身只许减(BARE_SITE_LEDGER_CAP=0)。
|
||||
*
|
||||
* 判据不锚行号:锚的是「哪个文件里还有裸调用」与「出口调用行的形状」。
|
||||
*/
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, statSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { occurrences, readSource } from './helpers.ts'
|
||||
|
||||
const EXIT_MODULE = 'src/components/admin-feedback-ui.ts'
|
||||
/** 例外名单只许减:收口批次结束时是 0 处(出口实现自己那一处不算名单,另用例单独钉)。 */
|
||||
const BARE_SITE_LEDGER_CAP = 0
|
||||
/** 出口实现里那一处 `ElMessage.error(m)` 是这条出口的本体。 */
|
||||
const EXIT_MODULE_CALLS = 1
|
||||
/** 分母硬钉:2026-10-10 实测走统一出口的 error 行 ≥ 92(92 处收口 + 批次前已有的几处)。 */
|
||||
const EXIT_ERROR_LINES_FLOOR = 92
|
||||
|
||||
/** 名单:不机械替换的裸调用,逐条给理由。新增一条 = 本用例红(超上限),且必须仍能对上实际代码。 */
|
||||
const BARE_SITE_LEDGER: Array<{ file: string; reason: string }> = []
|
||||
|
||||
function blankComments(src: string): string {
|
||||
return src
|
||||
.replace(/\/\*[\s\S]*?\*\//g, (block) => block.replace(/[^\n]/g, ' '))
|
||||
.replace(/^[ \t]*\/\/[^\n]*/gm, (line) => ' '.repeat(line.length))
|
||||
}
|
||||
|
||||
/** 剥掉注释与字符串字面量的内容:字符串里的 "ElMessage.error(" 字样不能算调用点。 */
|
||||
function stripNonCode(src: string): string {
|
||||
const out: string[] = []
|
||||
let i = 0
|
||||
const n = src.length
|
||||
while (i < n) {
|
||||
const two = src.slice(i, i + 2)
|
||||
if (two === '/*') {
|
||||
const close = src.indexOf('*/', i + 2)
|
||||
const end = close < 0 ? n : close + 2
|
||||
for (let k = i; k < end; k++) out.push(src[k] === '\n' ? '\n' : ' ')
|
||||
i = end; continue
|
||||
}
|
||||
if (two === '//') {
|
||||
const nl = src.indexOf('\n', i + 2)
|
||||
const end = nl < 0 ? n : nl
|
||||
for (let k = i; k < end; k++) out.push(src[k] === '\n' ? '\n' : ' ')
|
||||
i = end; continue
|
||||
}
|
||||
const q = src[i]
|
||||
if (q === '"' || q === "'" || q === '`') {
|
||||
let k = i + 1
|
||||
out.push(' ')
|
||||
while (k < n) {
|
||||
if (src[k] === '\\') { out.push(' ', src[k + 1] === '\n' ? '\n' : ' '); k += 2; continue }
|
||||
if (src[k] === q) { out.push(' '); k++; break }
|
||||
out.push(src[k] === '\n' ? '\n' : ' ')
|
||||
k++
|
||||
}
|
||||
i = k; continue
|
||||
}
|
||||
out.push(src[i]); i++
|
||||
}
|
||||
return out.join('')
|
||||
}
|
||||
|
||||
/** 在一个源码文本里数裸 ElMessage.error(注释与字符串里的字样不算)。 */
|
||||
export function bareErrorCount(src: string): number {
|
||||
return occurrences(stripNonCode(src), 'ElMessage.error(')
|
||||
}
|
||||
|
||||
/**
|
||||
* 数「走统一出口的 error 行」:一行里同时出现 `showAdminFeedback(` 与 `, 'error')`。
|
||||
* 用整行而不是 `showAdminFeedback\([^)]*, 'error'\)`——参数里带函数调用(`errorText(error, '…')`)时
|
||||
* `[^)]*` 会在第一个右括号处收口,分母会凭空少一截,把"扫不到"读成"没有"。
|
||||
*/
|
||||
export function exitErrorLineCount(src: string): number {
|
||||
return blankComments(src).split('\n')
|
||||
.filter((line) => line.includes('showAdminFeedback(') && line.includes(", 'error')")).length
|
||||
}
|
||||
|
||||
function sourceFiles(): string[] {
|
||||
const out: string[] = []
|
||||
const walk = (dir: string): void => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const abs = join(dir, name)
|
||||
if (name.endsWith('.d.ts')) continue
|
||||
if (statSync(abs).isDirectory()) walk(abs)
|
||||
else if (name.endsWith('.vue') || name.endsWith('.ts')) out.push(abs.split(/[\\/]+/).join('/'))
|
||||
}
|
||||
}
|
||||
walk('src')
|
||||
return out
|
||||
}
|
||||
|
||||
const FILES = sourceFiles()
|
||||
/** 出口实现之外,全树仍然裸打 ElMessage.error 的文件。 */
|
||||
const offenders = FILES.filter((rel) => rel !== EXIT_MODULE && bareErrorCount(readSource(rel)) > 0)
|
||||
|
||||
test('分母硬钉:扫描真的覆盖整棵 src,统一出口的 error 也确实被数到', () => {
|
||||
// 2026-10-10 实测 src 下 212 个 .vue/.ts;掉一档说明 walk 或后缀判据坏了。
|
||||
assert.ok(FILES.length >= 180, `只扫到 ${FILES.length} 个源文件,扫描规则可能已失效`)
|
||||
const viaExit = FILES.reduce((sum, rel) => sum + exitErrorLineCount(readSource(rel)), 0)
|
||||
assert.ok(viaExit >= EXIT_ERROR_LINES_FLOOR,
|
||||
`走统一出口的 error 只有 ${viaExit} 处:92 处收口没落地,或被整体扫漏了("扫不到"不等于"没有")`)
|
||||
})
|
||||
|
||||
test('出口实现里那一处 ElMessage.error 是出口本体,恰好一处', () => {
|
||||
assert.equal(bareErrorCount(readSource(EXIT_MODULE)), EXIT_MODULE_CALLS,
|
||||
'admin-feedback-ui.ts 是唯一允许裸 ElMessage.error 的地方,且只能有出口那 1 处')
|
||||
})
|
||||
|
||||
test('名单外的裸 ElMessage.error 一律点名;名单只许减、每条必须仍然成立', () => {
|
||||
assert.ok(BARE_SITE_LEDGER.length <= BARE_SITE_LEDGER_CAP,
|
||||
`例外名单从 ${BARE_SITE_LEDGER_CAP} 涨到 ${BARE_SITE_LEDGER.length}:这条口径只许减`)
|
||||
assert.deepEqual(offenders.slice().sort(), BARE_SITE_LEDGER.map((e) => e.file).sort(),
|
||||
`裸调用文件与名单不等值。名单外新增=${offenders.filter((f) => !BARE_SITE_LEDGER.some((e) => e.file === f))},`
|
||||
+ `名单里已消失(该删掉这条登记)=${BARE_SITE_LEDGER.filter((e) => !offenders.includes(e.file)).map((e) => e.file)}`)
|
||||
// 登记的每一条都得真的还有裸调用:烂账(登记了但代码里已经没有了)同样算破口。
|
||||
for (const entry of BARE_SITE_LEDGER) {
|
||||
assert.ok(bareErrorCount(readSource(entry.file)) > 0, `${entry.file} 已无裸调用,这条登记该删`)
|
||||
assert.ok(entry.reason.trim().length >= 8, `${entry.file} 的例外理由没写清楚`)
|
||||
}
|
||||
})
|
||||
|
||||
test('非零对照:扫描会抓到裸调用,也不会把统一出口误报成裸调用', () => {
|
||||
const injected = "try { await x() } catch (e) { ElMessage.error('店铺列表加载失败') }\n"
|
||||
assert.equal(bareErrorCount(injected), 1, '扫不出注入的裸调用 ⇒ 上面那条"名单外点名"是恒绿的')
|
||||
assert.equal(exitErrorLineCount(injected), 0)
|
||||
const migrated = "try { await x() } catch (e) { showAdminFeedback('店铺列表加载失败', 'error') }\n"
|
||||
assert.equal(bareErrorCount(migrated), 0)
|
||||
assert.equal(exitErrorLineCount(migrated), 1, '统一出口的 error 支必须被分母数到')
|
||||
// 参数里再套一层函数调用时,分母仍然数得到(这条正是 `[^)]*` 写法会静默漏掉的那种)。
|
||||
assert.equal(exitErrorLineCount("showAdminFeedback(errorText(error, '任务列表加载失败'), 'error')"), 1)
|
||||
assert.equal(bareErrorCount('// ElMessage.error( 只是注释里的字样'), 0, '注释里的字样算进来会让本用例永远红')
|
||||
assert.equal(bareErrorCount("const doc = 'ElMessage.error( 出现在字符串里'"), 0)
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* 失败态可见 + 重试真能跑(四面9分口径 · 后管「交互 6.0:模板内失败态只有 4/24 页、重试按钮 2」)。
|
||||
*
|
||||
* 一条列表页的硬规矩(本仓界面铁律):**撤入口/重试入口必须同时是一条真能办成事的出口**。
|
||||
* 所以这里不数「有没有红色文案」,而是逐页判三件事:
|
||||
* ① 请求失败的 catch 真的把原因写进一个失败 ref(`<ref>.value =` 落在 catch 窗口里);
|
||||
* ② 那个 ref 被模板 `v-if` 出来(不是一闪而过的 toast);
|
||||
* ③ 页面上有一个重试入口,且它绑的函数在同一个文件里真的定义着(`@retry="load"` 指向不存在的
|
||||
* 函数、或者只有「知道了」这种清掉红条的假出口,都算没过)。
|
||||
*
|
||||
* 名单(只许减):确实不该有重试按钮的页登记理由——登录页的出口是「再按一次登录」。
|
||||
*/
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync } from 'node:fs'
|
||||
import { readSource } from './helpers.ts'
|
||||
import {
|
||||
LOAD_FAILURE_RETRY_LABEL,
|
||||
failureDetail,
|
||||
loadFailureMessage,
|
||||
scopeRefusalNote,
|
||||
} from '../src/components/load-failure-model.ts'
|
||||
|
||||
/** 分母硬钉:2026-10-10 实测「有 *Loading = ref(false) 且 onMounted 取数」的页面 23 个。 */
|
||||
const UNIVERSE_FLOOR = 20
|
||||
/** 例外名单只许减:本轮只有登录页不进这条口径。 */
|
||||
const LEDGER_CAP = 1
|
||||
|
||||
const LEDGER: Array<{ file: string; reason: string }> = [
|
||||
{
|
||||
file: 'src/pages/login/LoginPage.vue',
|
||||
reason: '登录不是取数页:失败原因已由 errorMessage 的 role="alert" 说出,'
|
||||
+ '重试入口就是那张表单上的「登录」按钮本身,再加一个重试按钮是重复入口',
|
||||
},
|
||||
]
|
||||
|
||||
function pageFiles(): string[] {
|
||||
const out: string[] = []
|
||||
for (const domain of readdirSync('src/pages')) {
|
||||
for (const name of readdirSync(`src/pages/${domain}`)) {
|
||||
if (name.endsWith('.vue')) out.push(`src/pages/${domain}/${name}`)
|
||||
}
|
||||
}
|
||||
return out.sort()
|
||||
}
|
||||
|
||||
function templateOf(src: string): string {
|
||||
const at = src.indexOf('<template>')
|
||||
return at < 0 ? '' : src.slice(at)
|
||||
}
|
||||
|
||||
/** 页面的失败态判定:返回缺了哪几条(空数组 = 过)。 */
|
||||
export function failureGaps(src: string): string[] {
|
||||
const tmpl = templateOf(src)
|
||||
const refs = [...src.matchAll(/const (\w*(?:[Ff]ailure|[Ee]rror)\w*) = ref\(/g)].map((m) => m[1])
|
||||
const missing: string[] = []
|
||||
const rendered = refs.filter((r) => new RegExp(`v-if="[^"]*\\b${r}\\b`).test(tmpl))
|
||||
const writtenInCatch = refs.filter((r) => new RegExp(`catch[\\s\\S]{0,320}?${r}\\.value\\s*=`).test(src))
|
||||
if (rendered.length === 0) missing.push(`失败原因没被模板 v-if 出来(refs=${refs.join('/')})`)
|
||||
if (writtenInCatch.length === 0) missing.push('catch 里没有把失败原因写进任何失败 ref')
|
||||
const candidates = [...tmpl.matchAll(/@retry="(\w+)"|@click="(\w+)"[^>]*>\s*重试/g)]
|
||||
.map((m) => m[1] || m[2])
|
||||
.filter((fn): fn is string => Boolean(fn))
|
||||
const real = candidates.filter((fn) => new RegExp(`(?:function|const)\\s+${fn}\\s*[(=]`).test(src))
|
||||
if (real.length === 0) missing.push(`没有真能重跑的入口(重试绑的函数须在页内定义;候选=${candidates.join('/')})`)
|
||||
return missing
|
||||
}
|
||||
|
||||
const UNIVERSE = pageFiles().filter((rel) => {
|
||||
const src = readSource(rel)
|
||||
return /\w*[Ll]oading = ref\(false\)/.test(src) && src.includes('onMounted(')
|
||||
})
|
||||
const ledgerHas = (rel: string) => LEDGER.some((e) => e.file === rel)
|
||||
const offenders = UNIVERSE.filter((rel) => !ledgerHas(rel) && failureGaps(readSource(rel)).length > 0)
|
||||
const staleLedger = LEDGER.filter((e) => !UNIVERSE.includes(e.file) || failureGaps(readSource(e.file)).length === 0)
|
||||
|
||||
test('分母硬钉:整棵 pages 都扫到,取数页数量不像被过滤掉', () => {
|
||||
assert.ok(pageFiles().length >= 24, `只扫到 ${pageFiles().length} 个页面文件,扫描规则可能已失效`)
|
||||
assert.ok(UNIVERSE.length >= UNIVERSE_FLOOR,
|
||||
`首屏取数的页面只认出 ${UNIVERSE.length} 个(阈值 ${UNIVERSE_FLOOR}):判据漏了,"没有缺口"就读成了"没有请求"`)
|
||||
})
|
||||
|
||||
test('每个取数页都要有可见失败态 + 真能重跑的入口(名单外点名,名单只许减)', () => {
|
||||
assert.ok(LEDGER.length <= LEDGER_CAP, `例外名单从 ${LEDGER_CAP} 涨到 ${LEDGER.length}:这条口径只许减`)
|
||||
assert.deepEqual(offenders, [], `失败态缺失的页面:\n${offenders
|
||||
.map((f) => `${f}\n - ${failureGaps(readSource(f)).join('\n - ')}`).join('\n')}`)
|
||||
assert.deepEqual(staleLedger.map((e) => e.file), [],
|
||||
'名单里的页面已经补齐失败态(或已不是取数页),这条登记该删掉')
|
||||
for (const entry of LEDGER) assert.ok(entry.reason.length >= 12, `${entry.file} 的例外理由没写清楚`)
|
||||
})
|
||||
|
||||
test('失败文案模型:后端的中文原因进得来,英文原文进不来,取不到就只留兜底句', () => {
|
||||
const forbidden403 = { response: { status: 403, data: { message: '无权操作该总数据' } } }
|
||||
assert.equal(failureDetail(forbidden403), '无权操作该总数据')
|
||||
assert.equal(loadFailureMessage(forbidden403, '删除失败'),
|
||||
`删除失败:无权操作该总数据(${scopeRefusalNote('无权操作该总数据')})`)
|
||||
// unwrap 抛出来的 Error(BusinessException 走 HTTP 200 + body)同样要能带出原因
|
||||
assert.equal(loadFailureMessage(new Error('本公司已存在该数据'), '保存失败'), '保存失败:本公司已存在该数据')
|
||||
// 后端把底层英文拼进 message:界面只留中文主干
|
||||
assert.equal(loadFailureMessage(new Error('Internal Server Error'), '导出失败,请重试'), '导出失败,请重试')
|
||||
assert.equal(loadFailureMessage(undefined, '数据加载失败'), '数据加载失败')
|
||||
assert.equal(loadFailureMessage('网关超时', '数据加载失败'), '数据加载失败:网关超时')
|
||||
// 兜底句里已经含原因时不重复拼一遍
|
||||
assert.equal(loadFailureMessage(new Error('去重数据加载失败'), '去重数据加载失败'), '去重数据加载失败')
|
||||
})
|
||||
|
||||
test('范围拒绝要给出路,不是只说"失败了"', () => {
|
||||
assert.match(scopeRefusalNote('无权操作该分组数据'), /平台超级管理员/)
|
||||
assert.match(scopeRefusalNote('缺少归属公司:请先在页面上方选择公司'), /平台超级管理员/)
|
||||
assert.equal(scopeRefusalNote('本公司已存在该数据'), '', '普通业务校验不该被加成越权文案')
|
||||
assert.equal(LOAD_FAILURE_RETRY_LABEL, '重试', '按钮字样必须是能办成事的「重试」,不是「知道了」')
|
||||
})
|
||||
|
||||
test('重试入口的失败态组件本身不是占位:它把点击回抛给页面', () => {
|
||||
const bar = readSource('src/components/LoadFailureBar.vue')
|
||||
assert.match(bar, /\$emit\('retry'\)/, '按钮必须把动作交回页面的取数函数')
|
||||
assert.match(bar, /defineEmits<\{\s*\(event: 'retry'\): void\s*\}>\(\)/)
|
||||
assert.match(bar, /role="alert"/, '失败要对读屏与低视力用户可见')
|
||||
})
|
||||
|
||||
test('非零对照:造一个"loading 结束但没有失败分支"的页面会被点名', () => {
|
||||
const placeholder = `<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
const loading = ref(false)
|
||||
const rows = ref([])
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try { rows.value = await fetchRows() } catch (e) { showAdminFeedback('加载失败', 'error') }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
onMounted(load)
|
||||
</script>
|
||||
<template>
|
||||
<div class="table-scroll"><table><tbody><tr><td>{{ rows.length }}</td></tr></tbody></table></div>
|
||||
</template>
|
||||
`
|
||||
const gaps = failureGaps(placeholder)
|
||||
assert.equal(gaps.length, 3, `缺口应当被逐条点名,实测=${JSON.stringify(gaps)}`)
|
||||
assert.match(gaps.join(' '), /v-if/)
|
||||
assert.match(gaps.join(' '), /重试/)
|
||||
|
||||
const dismissed = `<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
const loading = ref(false)
|
||||
const loadError = ref('')
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try { } catch (e) { loadError.value = '加载失败' } finally { loading.value = false }
|
||||
}
|
||||
function retry() { void load() }
|
||||
onMounted(load)
|
||||
</script>
|
||||
<template>
|
||||
<div v-if="loadError" class="msg err">
|
||||
<span>{{ loadError }}</span>
|
||||
<button type="button" @click="loadError = ''">知道了</button>
|
||||
</div>
|
||||
</template>
|
||||
`
|
||||
assert.equal(failureGaps(dismissed).length, 1, '只有「知道了」这种清条按钮 = 撤入口不是出口,必须被点名')
|
||||
assert.match(failureGaps(dismissed)[0], /重试/)
|
||||
|
||||
const wired = `<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
async function load() {
|
||||
loading.value = true
|
||||
try { } catch (e) { loadFailure.value = '加载失败' } finally { loading.value = false }
|
||||
}
|
||||
onMounted(load)
|
||||
</script>
|
||||
<template>
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
</template>
|
||||
`
|
||||
assert.deepEqual(failureGaps(wired), [], '补齐形态必须判成过,否则上面那条"名单外点名"没有区分力')
|
||||
})
|
||||
@@ -47,7 +47,9 @@ test('test_task_003_layout_contract_boundary_single_item', () => {
|
||||
test('test_task_003_layout_contract_boundary_limit_or_missing_field', () => {
|
||||
// 边界上限:Element Plus 交互能力按需命名导入,不整包拖入壳层。
|
||||
const layout = readSource(LAYOUT)
|
||||
assert.match(layout, /import\s*\{\s*ElMessage(?:,\s*\w+)*\s*\}\s*from\s*['"]element-plus['"]/)
|
||||
assert.match(layout, /import\s*\{\s*ElMessageBox(?:,\s*\w+)*\s*\}\s*from\s*['"]element-plus['"]/)
|
||||
assert.doesNotMatch(layout, /import\s*\{[^}]*\bElMessage\b[^}]*\}\s*from\s*['"]element-plus['"]/,
|
||||
'壳层提示走 showAdminFeedback 统一出口,不再直接命名导入 ElMessage')
|
||||
assert.equal(occurrences(layout, 'import ElementPlus'), 0, '壳层不得整包导入 ElementPlus')
|
||||
})
|
||||
|
||||
|
||||
@@ -281,7 +281,7 @@ test('task_center_page_handles_empty_and_error_states', () => {
|
||||
const page = readSource(PAGE)
|
||||
assert.match(page, /暂无符合条件的任务/, '任务空态')
|
||||
assert.match(page, /暂无变体采集任务/, '变体空态:四态口径下不再限定「在跑」')
|
||||
assert.match(page, /ElMessage\.error/, '接口失败提示')
|
||||
assert.match(page, /showAdminFeedback\([^\n]*, 'error'\)/, '接口失败提示走统一出口')
|
||||
assert.match(page, /resetFilter/, '筛选重置接线')
|
||||
assert.match(page, /@size-change="changeTaskSize"/, '分页每页条数切换')
|
||||
assert.match(page, /@size-change="changeVariantSize"/, '变体分页每页条数切换')
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* 定时器 / 事件监听的清理配对(四面9分口径 · 后管「稳定 7.0:定时器清理配对只有 2/4」)。
|
||||
*
|
||||
* 评审点名:`DedupeRegistryPage.vue`(导出秒表 setInterval + 导入轮询)与 `DuplicateCheckPage.vue`
|
||||
* (toast 收尾 setTimeout)**没有 `onUnmounted`**——离开页面后定时器还在跑,每秒改一个没人看的 ref,
|
||||
* 而导入轮询最多还会再打 300 拍。这一支把配对关系落成判据:
|
||||
* ① 有 `setInterval(` 的文件必须同时有 `clearInterval(` 和一个卸载钩子;
|
||||
* ② 有 `addEventListener(` 的文件必须同时有 `removeEventListener(` 和一个卸载钩子;
|
||||
* ③ 一次性 `setTimeout(` 也要有配对,除非落在下面这张例外名单里(名单只许减,锚构造名不锚行号)。
|
||||
* 光有 clearInterval 不算过:只在"用户点了取消"那条路径清理,页面被路由切走时照样漏。
|
||||
*/
|
||||
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'
|
||||
|
||||
/** 分母硬钉:2026-10-10 实测 setInterval 3 处、addEventListener 4 处、setTimeout 5 处。 */
|
||||
const REPEATING_SITE_FLOOR = 7
|
||||
/** 例外名单只许减:三条 sleep() 节拍原语。 */
|
||||
const LEDGER_CAP = 3
|
||||
|
||||
const LEDGER: Array<{ file: string; construct: string; token: string; reason: string }> = [
|
||||
{
|
||||
file: 'src/pages/asin/DedupeRegistryPage.vue',
|
||||
construct: 'function sleep(',
|
||||
token: 'setTimeout(',
|
||||
reason: 'sleep() 是导入进度轮询的一次性节拍原语,不重复自持;跨卸载的泄漏由本页 pageDisposed '
|
||||
+ '闸门收口(onUnmounted 里置位,pollImport 下一拍直接抛),所以这一处不需要 clearTimeout',
|
||||
},
|
||||
{
|
||||
file: 'src/pages/asin/QueryAsinPage.vue',
|
||||
construct: 'function sleep(',
|
||||
token: 'setTimeout(',
|
||||
reason: '同 DedupeRegistryPage 的轮询节拍原语;本页 importProgress 轮询用完后自行走完,'
|
||||
+ '未接卸载中断(本批次只登记不扩改),名单只许减',
|
||||
},
|
||||
{
|
||||
file: 'src/pages/asin/SkipPricePage.vue',
|
||||
construct: 'function sleep(',
|
||||
token: 'setTimeout(',
|
||||
reason: '同上:sleep() 节拍原语,卸载中断未接,登记在案等下一批收口',
|
||||
},
|
||||
]
|
||||
|
||||
const REPEATING: Array<{ token: string; mate: string; what: string }> = [
|
||||
{ token: 'setInterval(', mate: 'clearInterval(', what: '重复定时器' },
|
||||
{ token: 'addEventListener(', mate: 'removeEventListener(', what: '事件监听' },
|
||||
{ token: 'setTimeout(', mate: 'clearTimeout(', what: '一次性定时器' },
|
||||
]
|
||||
|
||||
function codeOf(src: string): string {
|
||||
return src.split('\n').filter((line) => !/^\s*(\/\/|\*|\/\*)/.test(line)).join('\n')
|
||||
}
|
||||
|
||||
function hasHook(code: string): boolean {
|
||||
return code.includes('onUnmounted(') || code.includes('onBeforeUnmount(')
|
||||
}
|
||||
|
||||
/** 一个文件里未配对的定时器/监听(返回缺哪几条,空 = 过)。 */
|
||||
export function cleanupGaps(code: string, ledgerTokens: string[] = []): string[] {
|
||||
const gaps: string[] = []
|
||||
for (const { token, mate, what } of REPEATING) {
|
||||
if (!code.includes(token)) continue
|
||||
if (ledgerTokens.includes(token)) continue
|
||||
if (!code.includes(mate)) gaps.push(`${what}:有 ${token} 却没有 ${mate}`)
|
||||
if (!hasHook(code)) gaps.push(`${what}:${token} 所在文件没有 onUnmounted/onBeforeUnmount`)
|
||||
}
|
||||
return gaps
|
||||
}
|
||||
|
||||
function sourceFiles(): string[] {
|
||||
const out: string[] = []
|
||||
const walk = (dir: string): void => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const abs = join(dir, name)
|
||||
if (name.endsWith('.d.ts')) continue
|
||||
if (statSync(abs).isDirectory()) walk(abs)
|
||||
else if (name.endsWith('.vue') || name.endsWith('.ts')) out.push(abs.split(/[\\/]+/).join('/'))
|
||||
}
|
||||
}
|
||||
walk('src')
|
||||
return out
|
||||
}
|
||||
|
||||
const FILES = sourceFiles()
|
||||
/** 例外只在「登记的那个构造确实还在文件里」时生效:删掉了 sleep 也等于删掉了这条豁免。 */
|
||||
const ledgerTokensFor = (rel: string, code: string): string[] =>
|
||||
LEDGER.filter((e) => e.file === rel && code.includes(e.construct)).map((e) => e.token)
|
||||
const offenders = FILES
|
||||
.map((rel) => {
|
||||
const code = codeOf(readSource(rel))
|
||||
return { rel, gaps: cleanupGaps(code, ledgerTokensFor(rel, code)) }
|
||||
})
|
||||
.filter((x) => x.gaps.length > 0)
|
||||
|
||||
test('分母硬钉:重复定时器/监听的数量像被真的数到了', () => {
|
||||
assert.ok(FILES.length >= 180, `只扫到 ${FILES.length} 个源文件`)
|
||||
const sites = FILES.reduce((sum, rel) => {
|
||||
const code = codeOf(readSource(rel))
|
||||
return sum + (code.match(/setInterval\(/g) || []).length + (code.match(/addEventListener\(/g) || []).length
|
||||
}, 0)
|
||||
assert.ok(sites >= REPEATING_SITE_FLOOR,
|
||||
`setInterval+addEventListener 只数到 ${sites} 处(阈值 ${REPEATING_SITE_FLOOR}):判据扫空了会把"漏清理"读成"没有定时器"`)
|
||||
})
|
||||
|
||||
test('每处定时器/监听都有配对的清理 + 卸载钩子(名单外点名,名单只许减)', () => {
|
||||
assert.ok(LEDGER.length <= LEDGER_CAP, `例外名单从 ${LEDGER_CAP} 涨到 ${LEDGER.length}:这条口径只许减`)
|
||||
assert.deepEqual(offenders.map((x) => `${x.rel} -> ${x.gaps.join(';')}`), [],
|
||||
`清理没配对的页面:\n${offenders.map((x) => `${x.rel}: ${x.gaps.join(';')}`).join('\n')}`)
|
||||
// 名单里的每一条都要仍然成立:构造还在、文件确实还有裸 setTimeout。
|
||||
for (const entry of LEDGER) {
|
||||
const code = codeOf(readSource(entry.file))
|
||||
assert.ok(code.includes(entry.construct), `${entry.file} 里已经找不到 ${entry.construct},这条登记该删`)
|
||||
assert.ok(code.includes('setTimeout('), `${entry.file} 已无 setTimeout,这条登记该删`)
|
||||
assert.ok(entry.reason.length >= 16, `${entry.file} 的例外理由没写清楚`)
|
||||
}
|
||||
})
|
||||
|
||||
/** 取 `onUnmounted(() => { ... })` 的钩子体(到配对的右括为止,最多 400 字符)。 */
|
||||
export function unmountHookBody(code: string): string {
|
||||
const at = code.search(/on(?:Before)?Unmounted\(\s*\(\s*\)\s*=>\s*\{/)
|
||||
if (at < 0) return ''
|
||||
const open = code.indexOf('{', at)
|
||||
let depth = 0
|
||||
for (let i = open; i < code.length && i - open < 400; i++) {
|
||||
if (code[i] === '{') depth += 1
|
||||
else if (code[i] === '}') {
|
||||
depth -= 1
|
||||
if (depth === 0) return code.slice(open + 1, i)
|
||||
}
|
||||
}
|
||||
return code.slice(open + 1, open + 400)
|
||||
}
|
||||
|
||||
/** 找到某个本地函数体的文本(够用到 clearInterval 那一层即可)。 */
|
||||
function localFnBody(code: string, name: string): string {
|
||||
const at = code.search(new RegExp(`function\\s+${name}\\s*\\(`))
|
||||
if (at < 0) return ''
|
||||
const open = code.indexOf('{', at)
|
||||
let depth = 0
|
||||
for (let i = open; i < code.length; i++) {
|
||||
if (code[i] === '{') depth += 1
|
||||
else if (code[i] === '}') {
|
||||
depth -= 1
|
||||
if (depth === 0) return code.slice(open + 1, i)
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 卸载钩子真的把定时器收掉了?直接 clear 或调一个内部会 clear 的本地函数都算。 */
|
||||
export function hookClearsTimer(code: string): boolean {
|
||||
const body = unmountHookBody(code)
|
||||
if (!body) return false
|
||||
if (/clear(Interval|Timeout)\(/.test(body)) return true
|
||||
return [...body.matchAll(/(\w+)\(\)/g)]
|
||||
.some((m) => /clear(Interval|Timeout)\(/.test(localFnBody(code, m[1])))
|
||||
}
|
||||
|
||||
test('评审点名的两个文件确实补上了卸载钩子', () => {
|
||||
for (const rel of ['src/pages/asin/DedupeRegistryPage.vue', 'src/pages/tasks/DuplicateCheckPage.vue']) {
|
||||
const code = codeOf(readSource(rel))
|
||||
assert.ok(hasHook(code), `${rel} 仍无 onUnmounted/onBeforeUnmount`)
|
||||
assert.ok(hookClearsTimer(code), `${rel} 的卸载钩子里没有真的清定时器(直接 clear 或调会 clear 的本地函数都算)`)
|
||||
}
|
||||
// 去重页另外半边:离开页面后导入轮询必须自己收口,不然还会再打 300 拍。
|
||||
const dedupe = codeOf(readSource('src/pages/asin/DedupeRegistryPage.vue'))
|
||||
assert.match(dedupe, /pageDisposed = true/)
|
||||
assert.match(dedupe, /if \(pageDisposed\) throw/)
|
||||
})
|
||||
|
||||
test('非零对照:钩子只置个标志位、没清定时器,会被判不过', () => {
|
||||
const fakeHook = `function stop() { /* 这里没清 */ }\n`
|
||||
+ `onUnmounted(() => { stop() })\n`
|
||||
assert.equal(hookClearsTimer(fakeHook), false, '钩子调了个不清定时器的方法也算过 ⇒ 这条判据是软的')
|
||||
const indirect = `function stop() { clearInterval(t) }\n`
|
||||
+ `onUnmounted(() => { stop() })\n`
|
||||
assert.equal(hookClearsTimer(indirect), true, '间接清理要认:不然 stopExportWait() 那种写法会被误判')
|
||||
})
|
||||
|
||||
test('非零对照:造一个只 setInterval 不清理的文件会被点名', () => {
|
||||
const leaked = `const t = setInterval(() => tick(), 1000)\n`
|
||||
assert.deepEqual(cleanupGaps(leaked), [
|
||||
'重复定时器:有 setInterval( 却没有 clearInterval(',
|
||||
'重复定时器:setInterval( 所在文件没有 onUnmounted/onBeforeUnmount',
|
||||
], '漏清理扫不出来 ⇒ 上面那条断言恒绿')
|
||||
|
||||
const hookless = `let t = null\nfunction go() { t = setInterval(() => tick(), 1000) }\nfunction stop() { clearInterval(t) }\n`
|
||||
assert.deepEqual(cleanupGaps(hookless), ['重复定时器:setInterval( 所在文件没有 onUnmounted/onBeforeUnmount'],
|
||||
'只在"点取消"那条路径清理、路由切走仍会漏,这种形态必须判不过')
|
||||
|
||||
const paired = `let t = null\nfunction go() { t = setInterval(() => tick(), 1000) }\n`
|
||||
+ `onUnmounted(() => { clearInterval(t) })\n`
|
||||
assert.deepEqual(cleanupGaps(paired), [])
|
||||
|
||||
const listenerLeak = `window.addEventListener('resize', onResize)\n`
|
||||
assert.equal(cleanupGaps(listenerLeak).length, 2, 'addEventListener 不配对同样要被抓到')
|
||||
})
|
||||
@@ -5,10 +5,10 @@
|
||||
|
||||
## 概览
|
||||
|
||||
- 版本化迁移文件数:**153**(`src/main/resources/db/V*.sql`,其中整数版本 152 个 + 小版本 V25_1)
|
||||
- 整数版本范围:**V1..V155**,其中 V132/V133/V148 为已退役空号(见下),其余连续
|
||||
- 版本化迁移文件数:**154**(`src/main/resources/db/V*.sql`,其中整数版本 153 个 + 小版本 V25_1)
|
||||
- 整数版本范围:**V1..V156**,其中 V132/V133/V148 为已退役空号(见下),其余连续
|
||||
- 历史遗留小版本:**V25_1__shop_manage_group_bind_user.sql**(Flyway 语义 25.1,紧跟在 V25 之后、V26 之前执行,属历史命名,保留)
|
||||
- 最新版本:**V155__users_disabled_at.sql**(上一版 **V154__biz_dedupe_total_data_company_id_drop_default.sql**,再上一版 **V153__shop_manage_group_company_id.sql**,其前 **V152__columns_shop_key_company_id_drop_default.sql**——概览往下推时旧文件名一个不许挤掉,`CompanyDefaultDropV152Test.inventoryDocTracksV152` 就是钉这件事的)
|
||||
- 最新版本:**V156__dedupe_total_data_pioneer_backfill.sql**(上一版 **V155__users_disabled_at.sql**,再上一版 **V154__biz_dedupe_total_data_company_id_drop_default.sql**,其前 **V153__shop_manage_group_company_id.sql**,再往前 **V152__columns_shop_key_company_id_drop_default.sql**——概览往下推时旧文件名一个不许挤掉,`CompanyDefaultDropV152Test.inventoryDocTracksV152` 就是钉这件事的)
|
||||
- 待下一次 jar 发版执行:**V154、V155**(V152、V153 已于 10-09 09:50 随 jar `69d2ebb0` 双台同版应用——启动日志实查 "Current version of schema `aiimage`: 153 / Schema `aiimage` is up to date. No migration necessary.";V149/V150/V151 已于 10-06 17:32 应用。V153 给分组表加 `company_id` 并把分组名从"全平台唯一"收窄成"同公司唯一",**写侧代码必须同批**,两个方向单独发都不行——见 V153 头注释第 6 段;V154 只摘一列的默认值,前提逐条取证见下面的 V154 条目;V155 只给 `users` 加一列可空 `disabled_at`,140 行全取 NULL、对旧 jar 零行为差异,但它必须与读这列的代码同版——只发迁移则停用无人执行,只发 jar 则启动期读列即 1054)
|
||||
- 已应用:V142(10-03 18:23)、V143(10-04 10:48)、**V144(10-04 13:22)**、`V145__brand_dedupe_company_scope.sql`(10-05 13:01)、`V146__users_expires_at_admin_expiry.sql`(10-05 13:01)、**`V147__product_category_company_scope.sql`(10-06 11:03)**、`V149__permission_menu_company_tree.sql` / `V150__shop_key_company_scope.sql` / `V151__rule_tables_shared_across_companies.sql`(三条均为 10-06 17:32)
|
||||
- 末段 `flyway_schema_history` 为 2026-10-07 主机A 只读实查(`success` 全 1,最大整数版本 151),不是从 jar 版本推的
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.nanri.aiimage.common.api;
|
||||
|
||||
/**
|
||||
* 分页与列表条数默认值的<b>具名出处</b>(2026-10-09 评审「可读 5.0 / 交互 5.5」项 5:
|
||||
* {@code defaultValue} 里 15/20/50/1000 四种并存,31 处魔法数)。
|
||||
*
|
||||
* <p><b>这里没有"全局统一默认页容量"这一说,而且是故意的。</b>
|
||||
* 实测 49 处数字型 {@code defaultValue}(21 处页码 + 28 处条数)分属不同的真实用途:
|
||||
* 用户端列表、超管台、任务历史、扫描上限、导出取全量——把它们拍成一个值是<b>改行为</b>,
|
||||
* 不是清理。本类只做一件事:让每个数字有一个说明它<i>为什么是这个数</i>的名字,
|
||||
* 并让"同一个用途冒出第二个默认值"变成判据红({@code PageDefaultsLedgerTest})。
|
||||
*
|
||||
* <p>注解里的 {@code defaultValue} 必须是编译期字符串常量,所以常量声明成 {@link String};
|
||||
* 每个都配一个 {@code *_INT} 镜像,业务代码里要用数字时不必再 {@code Integer.parseInt}。
|
||||
*
|
||||
* <p>命名口径:{@code <用途>_PAGE_SIZE} 是"一页几条",{@code <用途>_LIMIT} 是"本次最多返回几条"
|
||||
* (不是分页,是扫描/返回截断)。两者不许混用——把 limit 当 pageSize 用会把上限调到用户可见的错位。
|
||||
*/
|
||||
public final class PageDefaults {
|
||||
|
||||
private PageDefaults() {
|
||||
}
|
||||
|
||||
// ---- 页码:21 处全是 1,这一族本来就是单一口径 ----
|
||||
|
||||
/** 起始页码。全树 21 处分页入口一致取 1(不是 0);改这个数等于把所有列表第一页翻空。 */
|
||||
public static final String FIRST_PAGE = "1";
|
||||
|
||||
/** {@link #FIRST_PAGE} 的数字镜像。 */
|
||||
public static final int FIRST_PAGE_INT = 1;
|
||||
|
||||
// ---- 每页条数:现存 4 个不同的真实默认 ----
|
||||
|
||||
/**
|
||||
* 用户端/超管列表页默认容量 = 15。现存 10 处(admin 用户、去重库、图片历史、
|
||||
* 无效 ASIN、ASIN 查询、店铺凭据、店铺管理、跳价 ASIN……)。
|
||||
*/
|
||||
public static final String USER_LIST_PAGE_SIZE = "15";
|
||||
|
||||
/** {@link #USER_LIST_PAGE_SIZE} 的数字镜像。 */
|
||||
public static final int USER_LIST_PAGE_SIZE_INT = 15;
|
||||
|
||||
/** 超管台列表默认容量 = 20。现存 6 处(设备日志、图视任务、通知×2、商品分类×2)。 */
|
||||
public static final String ADMIN_LIST_PAGE_SIZE = "20";
|
||||
|
||||
/** {@link #ADMIN_LIST_PAGE_SIZE} 的数字镜像。 */
|
||||
public static final int ADMIN_LIST_PAGE_SIZE_INT = 20;
|
||||
|
||||
/** 上架/采集类任务历史列表默认容量 = 50。现存 2 处 {@code page_size}(collect-data、publish)。 */
|
||||
public static final String TASK_LIST_PAGE_SIZE = "50";
|
||||
|
||||
/** {@link #TASK_LIST_PAGE_SIZE} 的数字镜像。 */
|
||||
public static final int TASK_LIST_PAGE_SIZE_INT = 50;
|
||||
|
||||
/**
|
||||
* 一次性取全量的"页容量"= 1000。<b>现存 2 处,都是用户端列表接口</b>:
|
||||
* {@code PriceTrackController}(价格追踪)与 {@code ShopMatchController}(店铺匹配)的
|
||||
* {@code page_size}。
|
||||
*
|
||||
* <p>这一条是评审点名的<b>疑似笔误</b>:用户端下拉的默认页容量给到 1000,表现更像"根本没分页"
|
||||
* 而不是"一页 1000 条"。单独一个常量、不复用 {@link #TASK_LIST_PAGE_SIZE},是为了让它
|
||||
* 在判据里数得出来(2 处);<b>本轮没有改它,也不自行改成 50</b>——改成多少、是不是保留
|
||||
* 客户端传参上限,需要产品/运维拍板。
|
||||
*/
|
||||
public static final String FULL_EXPORT_PAGE_SIZE = "1000";
|
||||
|
||||
/** {@link #FULL_EXPORT_PAGE_SIZE} 的数字镜像。 */
|
||||
public static final int FULL_EXPORT_PAGE_SIZE_INT = 1000;
|
||||
|
||||
// ---- 返回条数上限(不是分页)----
|
||||
|
||||
/** 单接口一次最多返回多少条 = 50。现存 4 处 {@code limit}(外观专利、采集数据、上架任务、相似 ASIN)。 */
|
||||
public static final String DEFAULT_RESULT_LIMIT = "50";
|
||||
|
||||
/** {@link #DEFAULT_RESULT_LIMIT} 的数字镜像。 */
|
||||
public static final int DEFAULT_RESULT_LIMIT_INT = 50;
|
||||
|
||||
/** 超管扫描类接口的单次上限 = 100。现存 3 处 {@code limit}(店铺数据采集列表、结果作业列表×2)。 */
|
||||
public static final String ADMIN_SCAN_LIMIT = "100";
|
||||
|
||||
/** {@link #ADMIN_SCAN_LIMIT} 的数字镜像。 */
|
||||
public static final int ADMIN_SCAN_LIMIT_INT = 100;
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package com.nanri.aiimage.common.exception;
|
||||
|
||||
import io.micrometer.core.instrument.Gauge;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* 业务码 → 真 HTTP 状态码的<b>映射单点</b>(2026-10-09 评审「交互 5.5」项 4)。
|
||||
*
|
||||
* <p>现状实测:{@code GlobalExceptionHandler} 的 {@code BusinessException} 出口没有
|
||||
* {@code @ResponseStatus},于是 1,242 处业务失败全部以 <b>HTTP 200</b> 出。后果不是"不好看":
|
||||
* 业务失败在 HTTP 指标里彻底隐形(2026-09-18 那次滚动重启期间丢心跳就是这么被记成 200 的,
|
||||
* 见 {@code GlobalExceptionHandler} 里 503 那段注释),网关/监控/客户端拦截器都只能靠扒响应体猜。
|
||||
*
|
||||
* <p><b>但这一轮不翻面。</b>直接改状态码会让三个前端把"业务失败"当"网络挂了"处理——
|
||||
* 那是行为回归,不是修复。所以这里只做安全的一半:
|
||||
* <ol>
|
||||
* <li>映射表在这里,一处定完,判据钉死({@code BusinessErrorHttpStatusTest});</li>
|
||||
* <li>开关 {@code aiimage.api.business-error-http-status.enabled} <b>默认 false</b>;
|
||||
* 关闭时 {@link #render} 原样返回 {@code ApiResponse},序列化路径与今天逐字节一致;</li>
|
||||
* <li>"哪些 code 会变成非 200"是显式白名单:白名单外(含 {@code code == null})
|
||||
* <b>永远走 200</b>,所以翻开关不会把没预料到的码打成 4xx/5xx。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>开启动作要用户拍板:至少要先确认 {@code frontend-vue}、{@code admin-frontend-vue}
|
||||
* 与桌面端 {@code app_client} 三处拦截器都能吃非 200 + 同形响应体
|
||||
* (已实测 {@code admin-frontend-vue/src/api/envelope.ts} 对 401/403 同时读
|
||||
* {@code status}/{@code statusCode}/{@code code},这一族风险较低;其余两处本面无证据)。
|
||||
*
|
||||
* <p>白名单的取数口径来自实测码分布({@code src/main/java} 里 {@code BusinessException(code)} 的字面量统计):
|
||||
* 403×52、400×36、401×16、500×4、409×3、404×3、503×1,加 {@link BusinessCodes} 的 404xx/409xx 族、
|
||||
* {@code DeviceSessionPolicy.CODE_KICKED=4011}、{@code ClientVersionGuardFilter.CODE_TOO_OLD=4012}。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class BusinessErrorHttpStatus {
|
||||
|
||||
/** 开关的配置键(写在 application.yml 里,默认 false)。 */
|
||||
public static final String ENABLED_KEY = "aiimage.api.business-error-http-status.enabled";
|
||||
|
||||
/** 记账指标:开关打开后每次真的把业务失败写成非 200 时 +1,按 code 打标签。 */
|
||||
public static final String METRIC = "aiimage.api.business.error.http_status";
|
||||
|
||||
/** 日志锚点:翻真之后现网靠这一条定位"哪个 code 在改状态码"。 */
|
||||
public static final String ANCHOR = "[business-http-status]";
|
||||
|
||||
/**
|
||||
* 映射白名单。业务码 → 真 HTTP 状态。<b>表外一律 200</b>(见 {@link #statusFor})。
|
||||
*
|
||||
* <p>3 位码是"码里已经写着 HTTP 语义"的那一族,照它的字面意思映射;
|
||||
* 4 位 401x 与 5 位 404xx/409xx 是项目自造的族,按 {@link BusinessCodes} 注释里的语义映射。
|
||||
*
|
||||
* <p>注意 {@link BusinessCodes#TASK_ALREADY_FINISHED}(40901) <b>不在表里</b>:
|
||||
* {@code GlobalExceptionHandler} 对它是幂等忽略、返回 {@code success=true},
|
||||
* 那是成功响应,不该被写成 409。
|
||||
*/
|
||||
private static final Map<Integer, HttpStatus> MAPPINGS = buildMappings();
|
||||
|
||||
private static Map<Integer, HttpStatus> buildMappings() {
|
||||
Map<Integer, HttpStatus> map = new LinkedHashMap<>();
|
||||
// —— 3 位族:码本身就是 HTTP 状态语义
|
||||
map.put(400, HttpStatus.BAD_REQUEST);
|
||||
map.put(401, HttpStatus.UNAUTHORIZED);
|
||||
map.put(403, HttpStatus.FORBIDDEN);
|
||||
map.put(404, HttpStatus.NOT_FOUND);
|
||||
map.put(409, HttpStatus.CONFLICT);
|
||||
map.put(422, HttpStatus.UNPROCESSABLE_ENTITY);
|
||||
map.put(500, HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
map.put(503, HttpStatus.SERVICE_UNAVAILABLE);
|
||||
// —— 4 位 401x 族:鉴权/凭据
|
||||
map.put(4011, HttpStatus.UNAUTHORIZED); // DeviceSessionPolicy.CODE_KICKED:被顶下线
|
||||
map.put(4012, HttpStatus.BAD_REQUEST); // ClientVersionGuardFilter.CODE_TOO_OLD:客户端版本过低
|
||||
// —— 5 位 404xx/409xx 族:BusinessCodes
|
||||
map.put(BusinessCodes.TASK_NOT_FOUND, HttpStatus.NOT_FOUND); // 40401
|
||||
map.put(BusinessCodes.TASK_BUSY, HttpStatus.CONFLICT); // 40902
|
||||
map.put(BusinessCodes.TASK_OWNER_FORWARD, HttpStatus.CONFLICT); // 40903
|
||||
return Collections.unmodifiableMap(map);
|
||||
}
|
||||
|
||||
/** 可为 null:没配 Micrometer 注册表时只留日志与映射判定。 */
|
||||
private static volatile MeterRegistry registry;
|
||||
private static final AtomicInteger RENDER_COUNT = new AtomicInteger();
|
||||
|
||||
@Value("${" + ENABLED_KEY + ":false}")
|
||||
private boolean enabled;
|
||||
|
||||
/** 关掉时静态侧也必须是 false——判据与生产共用同一个开关值,不许两套默认。 */
|
||||
private static volatile boolean enabledFlag;
|
||||
|
||||
public BusinessErrorHttpStatus() {
|
||||
}
|
||||
|
||||
@Autowired
|
||||
public BusinessErrorHttpStatus(ObjectProvider<MeterRegistry> meterRegistryProvider,
|
||||
@Value("${" + ENABLED_KEY + ":false}") boolean enabled) {
|
||||
registry = meterRegistryProvider == null ? null : meterRegistryProvider.getIfAvailable();
|
||||
enabledFlag = enabled;
|
||||
log.info("{} 启动自检:{}={}({})映射白 {} 条,表外 code 恒走 200",
|
||||
ANCHOR, ENABLED_KEY, enabled,
|
||||
enabled ? "真改写 HTTP 状态" : "关闭:业务失败仍全部 HTTP 200,行为与改动前逐字节一致",
|
||||
MAPPINGS.size());
|
||||
if (enabled && registry != null) {
|
||||
Gauge.builder(METRIC + ".renders", RENDER_COUNT, AtomicInteger::get).register(registry);
|
||||
}
|
||||
}
|
||||
|
||||
/** 单测接线用:显式设置开关与注册表,不依赖容器。 */
|
||||
public static void bindForTests(boolean enabled, MeterRegistry meterRegistry) {
|
||||
enabledFlag = enabled;
|
||||
registry = meterRegistry;
|
||||
}
|
||||
|
||||
/** 当前是否启用了真状态码。 */
|
||||
public static boolean isEnabled() {
|
||||
return enabledFlag;
|
||||
}
|
||||
|
||||
/** 只改开关、不动映射(判据与回退用)。 */
|
||||
public void setEnabled(boolean value) {
|
||||
this.enabled = value;
|
||||
enabledFlag = value;
|
||||
}
|
||||
|
||||
public boolean isSwitchOn() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/** 映射表白名单的只读视图(判据③:"哪些 code 会被映射成非 200"就是这一份)。 */
|
||||
public static Map<Integer, HttpStatus> mappings() {
|
||||
return MAPPINGS;
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务码对应的 HTTP 状态。
|
||||
*
|
||||
* <p>三种落到 {@link HttpStatus#OK} 的情况,都是故意的:
|
||||
* {@code code == null}(历史上大量 {@code ApiResponse.fail(message)} 不带码)、
|
||||
* 表外码、成功响应。返回 OK 时 {@link #render} 不会构造 {@code ResponseEntity},
|
||||
* 也就是不会碰 HTTP 状态。
|
||||
*/
|
||||
public static HttpStatus statusFor(Integer code) {
|
||||
if (code == null) {
|
||||
return HttpStatus.OK;
|
||||
}
|
||||
return MAPPINGS.getOrDefault(code, HttpStatus.OK);
|
||||
}
|
||||
|
||||
/**
|
||||
* 出站点:开关关闭 → 原样返回 body(与改动前同一序列化成败路径);
|
||||
* 开关打开且 code 在白名单 → 包一层带状态码的 {@code ResponseEntity},响应体一个字节都不改。
|
||||
*/
|
||||
public static Object render(ApiResponse<?> body, Integer code) {
|
||||
if (!enabledFlag) {
|
||||
return body;
|
||||
}
|
||||
HttpStatus status = statusFor(code);
|
||||
if (status == HttpStatus.OK || body == null) {
|
||||
return body;
|
||||
}
|
||||
RENDER_COUNT.incrementAndGet();
|
||||
if (registry != null) {
|
||||
registry.counter(METRIC, "code", String.valueOf(code), "httpStatus",
|
||||
String.valueOf(status.value())).increment();
|
||||
}
|
||||
log.info("{} code={} -> HTTP {}(响应体不变,只改状态行)", ANCHOR, code, status.value());
|
||||
return ResponseEntity.status(status).body(body);
|
||||
}
|
||||
}
|
||||
+11
-6
@@ -78,8 +78,8 @@ public class GlobalExceptionHandler {
|
||||
}
|
||||
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ApiResponse<Void> handleBusinessException(BusinessException ex, HttpServletRequest request,
|
||||
jakarta.servlet.http.HttpServletResponse response) {
|
||||
public Object handleBusinessException(BusinessException ex, HttpServletRequest request,
|
||||
jakarta.servlet.http.HttpServletResponse response) {
|
||||
// 停用/删除的成因走响应头而非新业务码:code 必须保持 401,改成新码会同时打断
|
||||
// 两面前端拦截器与桌面端 app_client/main.py 里按 'code': 401 识别鉴权失败的判定
|
||||
if (ex instanceof AccountDisabledException) {
|
||||
@@ -103,13 +103,18 @@ public class GlobalExceptionHandler {
|
||||
}
|
||||
if (Integer.valueOf(BusinessCodes.TASK_BUSY).equals(ex.getCode())) {
|
||||
// 锁竞争:必须如实返回失败 + 可重试码,否则 worker 会把「未落库」当成功而停止重试
|
||||
return ApiResponse.fail(BusinessCodes.TASK_BUSY,
|
||||
UserMessages.orFallback(ex.getMessage(), "这个任务正在处理中,请稍后重试"));
|
||||
return BusinessErrorHttpStatus.render(
|
||||
ApiResponse.fail(BusinessCodes.TASK_BUSY,
|
||||
UserMessages.orFallback(ex.getMessage(), "这个任务正在处理中,请稍后重试")),
|
||||
BusinessCodes.TASK_BUSY);
|
||||
}
|
||||
String userMessage = UserMessages.orFallback(ex.getMessage(), chineseFallbackFor(ex.getCode()));
|
||||
// 状态码出口只在 BusinessErrorHttpStatus 的开关为 true 时才改 HTTP 行;开关关时 render 原样
|
||||
// 返回同一个 ApiResponse 实例,序列化路径与 2026-10-09 之前逐字节一致(评审「交互 5.5」项 4,
|
||||
// 翻真的开启动作要用户拍:三个前端的拦截器先要能吃非 200 + 同形响应体)。
|
||||
return ex.getCode() == null
|
||||
? ApiResponse.fail(userMessage)
|
||||
: ApiResponse.fail(ex.getCode(), userMessage);
|
||||
? BusinessErrorHttpStatus.render(ApiResponse.fail(userMessage), null)
|
||||
: BusinessErrorHttpStatus.render(ApiResponse.fail(ex.getCode(), userMessage), ex.getCode());
|
||||
}
|
||||
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
package com.nanri.aiimage.common.task;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 任务状态词表的<b>唯一定义点</b>(2026-10-09 评审「流程 6.0」项 2:状态字面量集合散落 33 处/17 文件、没有单一状态机)。
|
||||
*
|
||||
* <p>先普查再说收口。2026-10-10 自己数出来的实际词表是 <b>4 套自有 + 1 套外部 + 若干模块内小状态机</b>,
|
||||
* 不是一个"全局状态机"能覆盖的东西,所以这里按<b>表</b>分组,每组各留自己的口径:
|
||||
* <ol>
|
||||
* <li>{@link FileTask}:{@code biz_file_task.status},大写。12 个客户端模块共用这一张表;</li>
|
||||
* <li>{@link BrandTask}:{@code brand_crawl_tasks.status},<b>小写</b>(该表历史写法就是小写);</li>
|
||||
* <li>{@link Job}:{@code task_file_job.status},结果作业自己的四态;</li>
|
||||
* <li>{@link LoopRun}:{@code price_track_loop_run.status},比上面三套多一个 {@code STOPPED};</li>
|
||||
* <li>外部词表(Coze 工作流 {@code execute_status} 等,见
|
||||
* {@code ImageVideoAsyncTaskService}):<b>不在这里定义</b>——那是别人家的返回值,
|
||||
* 收进来等于假装我们能改上游。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p><b>三条不动的边界</b>(这是本类存在的约束,不是待办):
|
||||
* <ul>
|
||||
* <li>不改库里已存的值:{@code COMPLETED}、{@code CANCELED}、小写 {@code cancelled} 都还在库里躺着;</li>
|
||||
* <li>不改对外 API 的字符串契约:各模块接口原样回显 {@code FileTaskEntity#getStatus()},
|
||||
* 老行返回 {@code CANCELED} 就继续返回 {@code CANCELED};</li>
|
||||
* <li>不发明第三个词表:任务终态只有 {@code SUCCESS|COMPLETED|FAILED} 这一套口径,
|
||||
* 其中 {@code COMPLETED ≡ SUCCESS}(2026-10-04 状态三态收敛已定,见
|
||||
* {@code TaskCenterQueryMapper#SUCCESS_STATUSES_ORDERED}),别再往上添 {@code DONE}/{@code FINISHED}。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>判据在 {@code TaskStatusVocabularyRatchetTest}:新增内联状态集合字面量、新增写死的状态常量声明、
|
||||
* 词表成员被改动都会红;现存例外按文件台账化。
|
||||
*/
|
||||
public final class TaskStatuses {
|
||||
|
||||
private TaskStatuses() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 词表 1:{@code biz_file_task.status}(大写)。12 个客户端模块的公共状态面。
|
||||
*
|
||||
* <p>{@code ERROR} 与 {@code COMPLETED} 是历史值:{@code COMPLETED} 并入"成功"口径展示,
|
||||
* {@code ERROR} 并入"失败"口径展示({@code TaskCenterQueryMapper} 的展开口径),
|
||||
* 两者都不能从读侧集合里删——删了老行就在任务中心里凭空消失。
|
||||
*/
|
||||
public static final class FileTask {
|
||||
public static final String PENDING = "PENDING";
|
||||
public static final String RUNNING = "RUNNING";
|
||||
public static final String SCHEDULED = "SCHEDULED";
|
||||
public static final String SUCCESS = "SUCCESS";
|
||||
/** {@code SUCCESS} 的历史拼写;展示上已并入成功,读侧必须继续认。 */
|
||||
public static final String COMPLETED = "COMPLETED";
|
||||
public static final String FAILED = "FAILED";
|
||||
/** 失败口径的历史第二拼写(并入"失败"筛选项)。 */
|
||||
public static final String ERROR = "ERROR";
|
||||
public static final String CANCELLED = "CANCELLED";
|
||||
/**
|
||||
* {@code CANCELLED} 的历史脏值拼写。<b>当前 Java 代码从不写它</b>
|
||||
* (实测:全树没有一处把 {@code CANCELED} 写进库),它只可能来自早期 jar/Python 侧留下的行,
|
||||
* 所以只在读侧接受集合里出现,并由 SQL 的 {@code CASE WHEN} 归一后对外输出。
|
||||
*/
|
||||
public static final String CANCELED = "CANCELED";
|
||||
|
||||
/** 在跑口径(任务中心「执行中」筛选项与"卡住"判定的同一集合)。 */
|
||||
public static final Set<String> ACTIVE = Set.of(PENDING, RUNNING, SCHEDULED);
|
||||
/** {@link #ACTIVE} 的固定顺序版:展开成 SQL {@code IN} 列表时文本要可断言。 */
|
||||
public static final List<String> ACTIVE_ORDERED = List.of(PENDING, RUNNING, SCHEDULED);
|
||||
|
||||
/** 终态集合(历史脏拼写 {@link #CANCELED} 也在内,少一个就有一行永远收不了尾)。 */
|
||||
public static final Set<String> TERMINAL = Set.of(SUCCESS, FAILED, CANCELLED, CANCELED);
|
||||
|
||||
/** 「跑完了」的可数口径(各模块历史页 success/failed 计数用;不含 {@code CANCELED},是原口径,别顺手加宽)。 */
|
||||
public static final List<String> FINISHED_ORDERED = List.of(SUCCESS, FAILED);
|
||||
|
||||
/** 前端「成功」筛选项的展开口径:{@code COMPLETED ≡ SUCCESS}。 */
|
||||
public static final List<String> SUCCESS_VIEW_ORDERED = List.of(SUCCESS, COMPLETED);
|
||||
|
||||
/** 前端「失败」筛选项的展开口径:{@code ERROR} 与取消都按「没成功」并入失败。 */
|
||||
public static final List<String> FAILED_VIEW_ORDERED = List.of(FAILED, ERROR, CANCELLED);
|
||||
|
||||
private FileTask() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 词表 2:{@code brand_crawl_tasks.status}(小写)。这张表从建表起状态就是小写,
|
||||
* 与 {@link FileTask} 不是一个字符集,混用会让 brand 任务在 UNION 口径里整批消失。
|
||||
*/
|
||||
public static final class BrandTask {
|
||||
public static final String PENDING = "pending";
|
||||
public static final String RUNNING = "running";
|
||||
public static final String SUCCESS = "success";
|
||||
public static final String FAILED = "failed";
|
||||
/** brand 侧唯一的取消拼写就是这个小写;{@code canceled} 全树没有第二处写点。 */
|
||||
public static final String CANCELLED = "cancelled";
|
||||
|
||||
public static final Set<String> ACTIVE = Set.of(PENDING, RUNNING);
|
||||
public static final List<String> ACTIVE_ORDERED = List.of(PENDING, RUNNING);
|
||||
public static final Set<String> TERMINAL = Set.of(SUCCESS, FAILED, CANCELLED);
|
||||
public static final List<String> TERMINAL_ORDERED = List.of(CANCELLED, FAILED, SUCCESS);
|
||||
|
||||
private BrandTask() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 词表 3:{@code task_file_job.status}——结果作业四态,比任务少一个取消态。 */
|
||||
public static final class Job {
|
||||
public static final String PENDING = "PENDING";
|
||||
public static final String RUNNING = "RUNNING";
|
||||
public static final String SUCCESS = "SUCCESS";
|
||||
public static final String FAILED = "FAILED";
|
||||
|
||||
/** 在跑口径(作业还在等结果)。 */
|
||||
public static final List<String> ACTIVE_ORDERED = List.of(PENDING, RUNNING);
|
||||
/** 可重跑口径:待办 + 失败但没打满重试次数。全树有 6 处,都是这一对。 */
|
||||
public static final List<String> RETRYABLE_ORDERED = List.of(PENDING, FAILED);
|
||||
|
||||
private Job() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 词表 4:{@code price_track_loop_run.status}——轮次运行态,比 {@link FileTask} 多一个 {@code STOPPED}。 */
|
||||
public static final class LoopRun {
|
||||
public static final String RUNNING = "RUNNING";
|
||||
public static final String SUCCESS = "SUCCESS";
|
||||
public static final String FAILED = "FAILED";
|
||||
public static final String STOPPED = "STOPPED";
|
||||
|
||||
/** 轮次终态(巡检按这一组判"这一轮不会再自己动了")。 */
|
||||
public static final Set<String> TERMINAL = Set.of(SUCCESS, FAILED, STOPPED);
|
||||
|
||||
private LoopRun() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消拼写的归一映射——<b>只用来判断,不用来改写值</b>:不改库、不改对外字符串。
|
||||
* 键是"读到的原始值",值是"归一后的规范拼写"。
|
||||
*
|
||||
* <p>为什么只做取消这一对:实测全树只有 {@code CANCELED}/{@code CANCELLED} 存在同义双拼,
|
||||
* 其余(SUCCESS/COMPLETED、ERROR/FAILED)是<b>并入展示口径</b>而不是拼写错误,
|
||||
* 混进同一张归一表会把"历史值"洗成"错别字",后面就没人敢信库值了。
|
||||
*/
|
||||
public static final Map<String, String> CANCEL_SPELLINGS = Map.of(
|
||||
"CANCELED", FileTask.CANCELLED,
|
||||
"CANCELLED", FileTask.CANCELLED,
|
||||
"canceled", BrandTask.CANCELLED,
|
||||
"cancelled", BrandTask.CANCELLED);
|
||||
|
||||
/** 是不是"取消"这一族(两种拼写、大小写都认);用于判定,不用于改写。 */
|
||||
public static boolean isCancelSpelling(String status) {
|
||||
return status != null && CANCEL_SPELLINGS.containsKey(status);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一到规范拼写:两种取消拼写各归各家(大写值归 {@code CANCELLED}、小写值归 {@code cancelled}),
|
||||
* <b>其它状态原样返回</b>。
|
||||
*
|
||||
* <p>刻意不做大小写统一:{@link FileTask} 是大写表、{@link BrandTask} 是小写表,
|
||||
* 一刀切 upper/lower 会 cross 到对方词表里去。
|
||||
*/
|
||||
public static String canonicalizeCancel(String status) {
|
||||
String mapped = status == null ? null : CANCEL_SPELLINGS.get(status);
|
||||
return mapped == null ? status : mapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* 大写词表的全部<b>去重后</b>取值(判据用它核对"没有第五套")。
|
||||
*
|
||||
* <p>注意这里必须是去重集合:{@code Job.PENDING} 与 {@code FileTask.PENDING} 是同一个字符串,
|
||||
* 直接 {@code Set.of(全部常量)} 会在类初始化时抛 {@code duplicate element}——
|
||||
* 这条判据 2026-10-10 就是这么被抓红的,留着当例子。
|
||||
*/
|
||||
public static Set<String> allUppercaseStatuses() {
|
||||
return Set.copyOf(java.util.Arrays.asList(
|
||||
FileTask.PENDING, FileTask.RUNNING, FileTask.SCHEDULED, FileTask.SUCCESS,
|
||||
FileTask.COMPLETED, FileTask.FAILED, FileTask.ERROR, FileTask.CANCELLED,
|
||||
FileTask.CANCELED, LoopRun.STOPPED));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package com.nanri.aiimage.common.util;
|
||||
|
||||
import io.micrometer.core.instrument.Gauge;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/**
|
||||
* 分布式锁「没拿到就跳过」的可聚合出口(2026-10-09 评审「稳定 5.5」项)。
|
||||
*
|
||||
* <p>此前 {@code if (lockHandle == null) { continue; }} 在全树有 <b>28</b> 处(11 个文件),
|
||||
* 一处日志都不留。表现是:巡检任务每轮都跑、锁竞争越激烈被跳过的任务越多,而现网看不出任何痕迹
|
||||
* ——卡死任务没被收尾、结果作业没被续跑,日志里连一行都没有,只能靠人肉反推。跟
|
||||
* {@code TaskFileJobPublisher} 的 MQ 降级是同一个病:那条已经补了 {@code task.file.job.mq.degraded}
|
||||
* 计数出口,这批锁跳过出口是它的同类。
|
||||
*
|
||||
* <p>所以这里定的不是"把级别调大",而是<b>可聚合</b>:
|
||||
* <ul>
|
||||
* <li>锚点 {@value #ANCHOR}:一条 grep 得动的字面量,{@code point=}/{@code outcome=} 给聚合维度;</li>
|
||||
* <li>进程内台账 {@link #countOf}:按 point 累计,供判据与巡检直接读;</li>
|
||||
* <li>Micrometer 指标 {@value #METRIC}(可选,注册表缺席时只留日志与本地台账,判定一字不动,
|
||||
* 与 {@code TaskFileJobPublisher} 同一口径)。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>{@code point} 是<b>稳定字面量</b>(形如 {@code brand:stale-running-scan}),不锚行号:
|
||||
* 方法搬家、加几行注释都不该让一条已经在响的告警变成孤儿。新增调用点请同步
|
||||
* {@code LockSkipWitnessTest} 里的点位台账。
|
||||
*
|
||||
* <p>静态 API 是有意的:这 12 个 Service 清一色 {@code @RequiredArgsConstructor},
|
||||
* 塞一个实例字段等于改 12 个构造器签名、打断几十支 {@code new XxxService(...)} 的既有判据。
|
||||
* 注册表由 Spring 在启动时绑一次({@link #LockSkipWitness});没起 Spring 的单测照样能调
|
||||
* {@link #record},台账与日志都不依赖容器。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class LockSkipWitness {
|
||||
|
||||
/** 巡检/判据用的日志锚点。改这条字面量等于把现网告警规则删掉,动之前先对巡检。 */
|
||||
public static final String ANCHOR = "[lock-skip]";
|
||||
|
||||
/** 指标名:tag {@code point}/{@code outcome}/{@code moduleType}。 */
|
||||
public static final String METRIC = "aiimage.distributed.lock.skip";
|
||||
|
||||
/** outcome:循环里跳过这一项,后面还有别的(巡检批量扫描)。 */
|
||||
public static final String OUTCOME_SKIPPED = "skipped";
|
||||
|
||||
/** outcome:整次调用直接返回,本轮什么都没用做(含 try-with-resources 里锁没拿到)。 */
|
||||
public static final String OUTCOME_ABANDONED = "abandoned";
|
||||
|
||||
/** outcome:调用方没给结果类型——单独成桶,不折叠进上面两个真桶。 */
|
||||
public static final String OUTCOME_UNKNOWN = "unknown";
|
||||
|
||||
/** 台账键上限:point 是有限集合(调用点数),超上限后不再新增键,防无界增长。 */
|
||||
static final int LEDGER_KEYS_MAX = 256;
|
||||
|
||||
private static final ConcurrentMap<String, AtomicLong> LEDGER = new ConcurrentHashMap<>();
|
||||
private static final AtomicLong TOTAL = new AtomicLong();
|
||||
|
||||
/** 可为 null:没配 Micrometer 注册表时只留日志 + 本地台账。 */
|
||||
private static volatile MeterRegistry registry;
|
||||
|
||||
public LockSkipWitness() {
|
||||
}
|
||||
|
||||
/** 生产接线:注册表可选,缺席时不影响跳过语义与日志。 */
|
||||
@Autowired
|
||||
public LockSkipWitness(ObjectProvider<MeterRegistry> meterRegistryProvider) {
|
||||
bind(meterRegistryProvider == null ? null : meterRegistryProvider.getIfAvailable());
|
||||
}
|
||||
|
||||
/** 供 Spring 构造与单测显式接线;null 表示只用日志与本地台账。 */
|
||||
public static void bind(MeterRegistry meterRegistry) {
|
||||
registry = meterRegistry;
|
||||
if (meterRegistry != null) {
|
||||
// 计数器按 point 现建现取,注册一次总览 gauge,便于「一个 point 都没命中」也能看到 0。
|
||||
Gauge.builder(METRIC + ".total", TOTAL, AtomicLong::get).register(meterRegistry);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记一次「没拿到锁所以跳过/放弃」。
|
||||
*
|
||||
* @param point 稳定点位字面量(不要用行号/方法名+行号拼)
|
||||
* @param outcome {@link #OUTCOME_SKIPPED} 或 {@link #OUTCOME_ABANDONED}
|
||||
* @param moduleType 业务模块类型,可为 null(归一为 unknown)
|
||||
* @param taskId 任务 id,可为 null
|
||||
*/
|
||||
public static void record(String point, String outcome, String moduleType, Long taskId) {
|
||||
String key = point == null || point.isBlank() ? "unpointed" : point.trim();
|
||||
// outcome 缺失归一到 unknown 而不是猜一个真桶:折叠进 skipped/abandoned 会让聚合面说谎。
|
||||
String normalizedOutcome = outcome == null || outcome.isBlank() ? OUTCOME_UNKNOWN : outcome.trim();
|
||||
String normalizedModule = moduleType == null || moduleType.isBlank() ? "unknown" : moduleType.trim();
|
||||
long count = ledgerOf(key).incrementAndGet();
|
||||
long total = TOTAL.incrementAndGet();
|
||||
MeterRegistry current = registry;
|
||||
if (current != null) {
|
||||
current.counter(METRIC,
|
||||
"point", key,
|
||||
"outcome", normalizedOutcome,
|
||||
"moduleType", normalizedModule)
|
||||
.increment();
|
||||
}
|
||||
log.warn("{} point={} outcome={} moduleType={} taskId={} skippedSoFar={} total={} —— "
|
||||
+ "未拿到分布式锁,本轮跳过(锁被其它实例持有或锁名不可用)",
|
||||
ANCHOR, key, normalizedOutcome, normalizedModule, taskId, count, total);
|
||||
}
|
||||
|
||||
/** 最省事的写法:跳过(skipped)结果 + 不带模块上下文。 */
|
||||
public static void recordSkip(String point, String moduleType, Long taskId) {
|
||||
record(point, OUTCOME_SKIPPED, moduleType, taskId);
|
||||
}
|
||||
|
||||
/** 最省事的写法:整次放弃(abandoned)结果 + 不带模块上下文。 */
|
||||
public static void recordAbandoned(String point, String moduleType, Long taskId) {
|
||||
record(point, OUTCOME_ABANDONED, moduleType, taskId);
|
||||
}
|
||||
|
||||
/** 定时任务级作业锁没抢到:整轮直接返回,没有模块/任务上下文。 */
|
||||
public static void skipped(String point) {
|
||||
record(point, OUTCOME_SKIPPED, null, null);
|
||||
}
|
||||
|
||||
/** 定时任务级作业锁没抢到且方法直接返回:本轮什么都没做。 */
|
||||
public static void abandoned(String point) {
|
||||
record(point, OUTCOME_ABANDONED, null, null);
|
||||
}
|
||||
|
||||
private static AtomicLong ledgerOf(String key) {
|
||||
AtomicLong existing = LEDGER.get(key);
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
if (LEDGER.size() >= LEDGER_KEYS_MAX) {
|
||||
// 超出上限:仍计入总量与日志,只是不再为未知点位开新键。
|
||||
return LEDGER.computeIfAbsent("overflow", k -> new AtomicLong());
|
||||
}
|
||||
return LEDGER.computeIfAbsent(key, k -> new AtomicLong());
|
||||
}
|
||||
|
||||
/** 某个点位累计跳过次数;没记过就是 0。 */
|
||||
public static long countOf(String point) {
|
||||
AtomicLong value = LEDGER.get(point);
|
||||
return value == null ? 0L : value.get();
|
||||
}
|
||||
|
||||
/** 全部点位的累计台账快照(不可变副本,按点位名排序)。 */
|
||||
public static Map<String, Long> snapshot() {
|
||||
Map<String, Long> out = new LinkedHashMap<>();
|
||||
LEDGER.entrySet().stream()
|
||||
.sorted(Map.Entry.comparingByKey())
|
||||
.forEach(e -> out.put(e.getKey(), e.getValue().get()));
|
||||
return Collections.unmodifiableMap(out);
|
||||
}
|
||||
|
||||
/** 全部点位合计。 */
|
||||
public static long total() {
|
||||
return TOTAL.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试专用:清空台账,返回清理前的快照。
|
||||
*
|
||||
* <p>生产代码不要调——它会把巡检窗口里的计数抹平,看起来像"这段时间没人被锁挡"。
|
||||
* 之所以留着:判据要能钉住"走到这个分支留下了可查记录",而点位是全局静态计数,
|
||||
* 不清就测不出单次增量(用 delta 也能测,但 27 个点位共用一张表,清一次比 27 处读基线更好读)。
|
||||
*/
|
||||
public static Map<String, Long> resetLedgerForTests() {
|
||||
Map<String, Long> before = snapshot();
|
||||
LEDGER.clear();
|
||||
TOTAL.set(0L);
|
||||
return before;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
@@ -149,8 +150,42 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|
||||
private String exemptPrefixes;
|
||||
|
||||
/** 用户态接口的数据归属参数:收紧前它由客户端随意填。 */
|
||||
/** 巡检/发布记录用的 ASCII 锚点:三档开关的启动自述都带它(同 [client-version-floor] 口径)。 */
|
||||
static final String SWITCH_ANCHOR = "[api-guard-switch]";
|
||||
private static final String USER_ID_PARAM = "user_id";
|
||||
|
||||
/**
|
||||
* 启动自述:把「三档开关各在什么位置」打成一条 grep 得动的日志(ASCII 锚点 {@value #SWITCH_ANCHOR})。
|
||||
*
|
||||
* <p>动机与 {@code ClientVersionGuardFilter.reportFloorState()} 同一件:这四键过去只在代码里,
|
||||
* 「名单写了一堆但一条都不强制」在日志上和「这个过滤器不存在」完全同形。
|
||||
* 锚点用 ASCII 是现网口径——中文签名在容器日志换了编码后整条 grep 失效。
|
||||
*/
|
||||
@PostConstruct
|
||||
void reportGuardState() {
|
||||
if (!enabled) {
|
||||
log.warn("{} admin-guard-enabled=false ⇒ 本过滤器逐请求整体跳过(紧急回退态):"
|
||||
+ "{} 条用户态前缀与 /api/admin、/debug 以及无条件名单 {} 条都没有兜底鉴权,"
|
||||
+ "只剩 controller 里的 require*",
|
||||
SWITCH_ANCHOR, USER_TOOL_PREFIXES.length, SELF_SERVICE_PREFIXES.length);
|
||||
return;
|
||||
}
|
||||
if (!userToolGuardEnabled) {
|
||||
log.warn("{} aiimage.security.user-tool-guard-enabled=false ⇒ 名单里 {} 条用户态前缀"
|
||||
+ "不强制凭据(带 user_id 的匿名请求按参数定归属,只剩「身份能解析出来时参数必须对齐」那一半);"
|
||||
+ "仍无条件强制的是 /api/admin、/debug 与 {} 条自助前缀",
|
||||
SWITCH_ANCHOR, USER_TOOL_PREFIXES.length, SELF_SERVICE_PREFIXES.length);
|
||||
return;
|
||||
}
|
||||
Set<String> listed = splitToSet(userToolGuardPrefixes);
|
||||
log.info("{} aiimage.security.user-tool-guard-enabled=true scoped={}/{}({})exemptPrefixes={} ⇒"
|
||||
+ " 名单内前缀的匿名请求会被 401 挡住",
|
||||
SWITCH_ANCHOR,
|
||||
listed.isEmpty() ? USER_TOOL_PREFIXES.length : listed.size(), USER_TOOL_PREFIXES.length,
|
||||
listed.isEmpty() ? "全部" : String.join(",", listed),
|
||||
splitToSet(exemptPrefixes).size());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
if (!enabled) {
|
||||
|
||||
@@ -79,8 +79,11 @@ public class AppearancePatentProperties {
|
||||
* 组装结果文件时要求的 LLM 覆盖率下限(0~1,<=0 关闭)。
|
||||
* 低于该比例说明大批行根本没拿到结论(如 2026-09-20 任务 28805:904 行只检了 1 行却报成功),
|
||||
* 此时判任务失败并由失败通知告警,而不是交付一份看着完整、实际是复制结论的表。
|
||||
* 默认 0.5 只拦塌陷级异常;生产正常任务实测约 0.91(28798:723 行 658 行有结论),
|
||||
* 需要更严时调高,调到 1.0 即要求全行有结论。
|
||||
*
|
||||
* <p>2026-10-10 从 0.5 抬到 0.95:0.5 意味着半张表可以空着照样出文件。现网实测(10-06~10-09
|
||||
* 六份已交付 xlsx)空行比例 20.7%–51.3%,全部在 0.5 之上放行、且一条覆盖率告警都没打——
|
||||
* 因为旧分母按用户上传表的解析行数,用户表不带标题列时分母恒为 0。
|
||||
* 分母口径已改为「会写进结果文件的行集」,判据见 AppearancePatentRowOutcome。
|
||||
*/
|
||||
private double llmCoverageMinRatio = 0.5D;
|
||||
private double llmCoverageMinRatio = 0.95D;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import io.micrometer.core.instrument.Counter;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
@@ -116,6 +117,33 @@ public class ClientVersionGuardFilter extends OncePerRequestFilter {
|
||||
return minSupportedVersion != null && !minSupportedVersion.trim().isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动自述:把"地板到底在不在跑"打成一条看得见的日志。
|
||||
*
|
||||
* <p>此前这个类只有代码里的 {@code @Value} 默认值、任何 yml 里都没有这三键,于是"没配置"
|
||||
* 和"配置成惰性"都长得跟"这个功能不存在"一样——评审数出来就是"版本硬地板出厂即惰性"。
|
||||
* 三键现在写进 {@code application.yml} 了,这条自述补上另一半:万一被覆盖回空值
|
||||
* (或被紧急回退清空),启动日志里点名说清楚闸门没在跑,而不是安静地跳过每个请求。
|
||||
*/
|
||||
@PostConstruct
|
||||
void reportFloorState() {
|
||||
if (!isConfigured()) {
|
||||
log.warn("[client-version-floor] [版本地板] 启动自检:min-supported-version 未配置 ⇒ 闸门惰性,逐请求跳过,"
|
||||
+ "现网装机版本分布没有任何记账数据(enforce={} rejectUnreported={})",
|
||||
enforce, rejectUnreported);
|
||||
return;
|
||||
}
|
||||
if (parse(minSupportedVersion) == null) {
|
||||
log.warn("[client-version-floor] [版本地板] 启动自检:min-supported-version=\"{}\" 解析不出数字段 ⇒ 全部上报按 "
|
||||
+ "unparsable 记账、永不拒绝,请把配置改回点分数字版本", minSupportedVersion);
|
||||
return;
|
||||
}
|
||||
log.info("[client-version-floor] [版本地板] 启动自检:最低支持版本={} enforce={}({})rejectUnreported={}",
|
||||
minSupportedVersion.trim(), enforce,
|
||||
enforce ? "真拒绝:低于地板的装机会被挡在业务之前" : "记账模式:只计数与打日志,业务响应不变",
|
||||
rejectUnreported);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
return !isConfigured() || !isClientFacing(request.getRequestURI());
|
||||
@@ -135,7 +163,7 @@ public class ClientVersionGuardFilter extends OncePerRequestFilter {
|
||||
if (firstWitness(verdict, reported)) {
|
||||
// 一次配置变更会被每个在跑的客户端逐请求命中:这里按 (verdict, version) 去重,
|
||||
// 量交给指标,日志只留第一条(与 10-06 通知放大的处置同一口径)。
|
||||
log.warn("[版本地板] {} {} 自报版本={} 最低支持={} verdict={} enforce={} —— {}",
|
||||
log.warn("[client-version-floor] [版本地板] {} {} 自报版本={} 最低支持={} verdict={} enforce={} —— {}",
|
||||
request.getMethod(), uri, reported, minSupportedVersion.trim(), verdict, enforce,
|
||||
enforce ? "本次已拒绝" : "记账模式,暂不拒绝");
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.admin.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
|
||||
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
|
||||
import com.nanri.aiimage.modules.admin.model.vo.AdminUserListVo;
|
||||
@@ -33,8 +34,8 @@ public class AdminUserController {
|
||||
@GetMapping("/users")
|
||||
@Operation(summary = "分页查询用户列表")
|
||||
public ApiResponse<AdminUserListVo> listUsers(HttpServletRequest request,
|
||||
@RequestParam(required = false, defaultValue = "1") Integer page,
|
||||
@RequestParam(name = "page_size", required = false, defaultValue = "15") Integer pageSize,
|
||||
@RequestParam(required = false, defaultValue = PageDefaults.FIRST_PAGE) Integer page,
|
||||
@RequestParam(name = "page_size", required = false, defaultValue = PageDefaults.USER_LIST_PAGE_SIZE) Integer pageSize,
|
||||
@RequestParam(required = false) String username,
|
||||
@RequestParam(name = "search", required = false) String search,
|
||||
@RequestParam(name = "created_by_id", required = false) Long createdById,
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentParseRequest;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentSubmitResultRequest;
|
||||
@@ -72,7 +73,7 @@ public class AppearancePatentController {
|
||||
@Parameter(description = "当前用户 ID,用于查询该用户自己的历史记录。", required = true, example = "1")
|
||||
@RequestParam("user_id") Long userId,
|
||||
@Parameter(description = "历史记录条数,默认 50,最大 100", example = "50")
|
||||
@RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit,
|
||||
@RequestParam(value = "limit", required = false, defaultValue = PageDefaults.DEFAULT_RESULT_LIMIT) Integer limit,
|
||||
HttpServletRequest httpRequest) {
|
||||
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
|
||||
// 上限钳制(2026-09):文档写"最大 100"但此前无实际校验
|
||||
|
||||
+14
-2
@@ -58,7 +58,7 @@ public class AppearancePatentTaskCacheService extends AbstractPendingRowTaskCach
|
||||
return first == null || first;
|
||||
} catch (Exception ex) {
|
||||
log.warn("[appearance-patent-cache] begin row inspection degraded taskId={} rowKey={} msg={}", taskId, rowKey, ex.getMessage());
|
||||
// Redis 降级时放行,由持久化层的 hasResolvedLlmFields 判据兜底去重。
|
||||
// Redis 降级时放行,由持久化层的 AppearancePatentRowOutcome.isJudged 判据兜底去重。
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -102,9 +102,18 @@ public class AppearancePatentTaskCacheService extends AbstractPendingRowTaskCach
|
||||
|
||||
/**
|
||||
* 撤销处理中标记(本批没拿到可用结果时调用):让下一轮立刻能重新申领,不等 15 分钟 TTL。
|
||||
* TTL 只用来兜住「进程在批中被杀」。
|
||||
* TTL 只用来兜住「进程在批中被杀」。完成标记**不动**——动它会让已经落库的行重跑并重复计费。
|
||||
*/
|
||||
public void releaseRowInspection(Long taskId, List<String> rowKeys) {
|
||||
releaseRowInspection(taskId, rowKeys, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param alsoClearCompletionMark 交付缺口补检专用:结果落过库却又读不回来(分片被清、载荷过期)时,
|
||||
* 这行既没结论也再申领不到,等于扣了次数永久空着;只有这条出口
|
||||
* 允许连完成标记一起撤,代价(可能重发一次 LLM)由调用方点名承担。
|
||||
*/
|
||||
public void releaseRowInspection(Long taskId, List<String> rowKeys, boolean alsoClearCompletionMark) {
|
||||
if (taskId == null || taskId <= 0 || rowKeys == null || rowKeys.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -114,6 +123,9 @@ public class AppearancePatentTaskCacheService extends AbstractPendingRowTaskCach
|
||||
}
|
||||
try {
|
||||
stringRedisTemplate.delete(inFlightRowKey(taskId, rowKey));
|
||||
if (alsoClearCompletionMark) {
|
||||
stringRedisTemplate.delete(processedRowKey(taskId, rowKey));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.warn("[appearance-patent-cache] release row inspection degraded taskId={} rowKey={} msg={}",
|
||||
taskId, rowKey, ex.getMessage());
|
||||
|
||||
+170
-219
@@ -12,6 +12,7 @@ import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePate
|
||||
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.common.util.GroupResultPropagator;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import com.nanri.aiimage.common.util.FailedStatusRowFilter;
|
||||
import com.nanri.aiimage.common.util.StaleTaskDeathReason;
|
||||
import com.nanri.aiimage.config.AppearancePatentProperties;
|
||||
@@ -34,6 +35,7 @@ import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParse
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentTaskBatchVo;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentTaskDetailVo;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentTaskItemVo;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentRowOutcome;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentSheetBuilder;
|
||||
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
@@ -651,6 +653,7 @@ public class AppearancePatentTaskService {
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(task.getId(), 0L);
|
||||
if (lockHandle == null) {
|
||||
// 锁被 owner 实例/文件任务 worker 占用说明其仍活跃,静默跳过等下一轮
|
||||
LockSkipWitness.recordSkip("appearance-patent:running-stale-scan", MODULE_TYPE, task.getId());
|
||||
continue;
|
||||
}
|
||||
try (lockHandle) {
|
||||
@@ -666,6 +669,7 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId, 0L);
|
||||
if (lockHandle == null) {
|
||||
LockSkipWitness.recordAbandoned("appearance-patent:debug-finalize-stale", MODULE_TYPE, taskId);
|
||||
return;
|
||||
}
|
||||
try (lockHandle) {
|
||||
@@ -794,6 +798,8 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
TaskDistributedLockService.LockHandle neverReportedLock = acquireTaskLock(task.getId(), 0L);
|
||||
if (neverReportedLock == null) {
|
||||
LockSkipWitness.recordSkip("appearance-patent:never-reported-stale-scan",
|
||||
MODULE_TYPE, task.getId());
|
||||
continue;
|
||||
}
|
||||
try (neverReportedLock) {
|
||||
@@ -817,6 +823,7 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(task.getId(), 0L);
|
||||
if (lockHandle == null) {
|
||||
LockSkipWitness.recordSkip("appearance-patent:no-result-shard-stale-scan", MODULE_TYPE, task.getId());
|
||||
continue;
|
||||
}
|
||||
try (lockHandle) {
|
||||
@@ -938,8 +945,7 @@ public class AppearancePatentTaskService {
|
||||
private void submitLlmBatches(FileTaskEntity task,
|
||||
FileResultEntity result,
|
||||
TaskFileJobEntity job,
|
||||
List<TaskChunkEntity> chunks,
|
||||
Map<String, List<AppearancePatentParsedRowVo>> allRowsByBaseId) {
|
||||
List<TaskChunkEntity> chunks) {
|
||||
if (chunks == null || chunks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -948,7 +954,7 @@ public class AppearancePatentTaskService {
|
||||
int batchSize = Math.max(1, properties.getLlmBatchSize());
|
||||
ChunkRowKeyIndex rowKeyIndex = new ChunkRowKeyIndex();
|
||||
List<AppearancePatentResultRowDto> candidates = terminalizeRoundExhaustedRows(
|
||||
task, allRowsByBaseId, collectPendingLlmCandidates(chunks, rowKeyIndex), rowKeyIndex);
|
||||
task, collectPendingLlmCandidates(chunks, rowKeyIndex), rowKeyIndex);
|
||||
boolean flushRemainder = isResultSubmissionComplete(task.getId());
|
||||
if (!flushRemainder && !candidates.isEmpty()) {
|
||||
LocalDateTime jobUpdatedAt = job.getUpdatedAt();
|
||||
@@ -1001,7 +1007,7 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
List<String> keysToRetry = new ArrayList<>(batchRowKeys);
|
||||
try {
|
||||
Set<String> landedKeys = mergeLlmRowsIntoChunks(task, allRowsByBaseId, llmRows, batchRows, rowKeyIndex);
|
||||
Set<String> landedKeys = mergeLlmRowsIntoChunks(task, llmRows, batchRows, rowKeyIndex);
|
||||
// 完成标记只能打在真正落库的行上——这是「发版重启会不会丢行」的分界线
|
||||
if (batchAnswered) {
|
||||
List<String> landed = batchRowKeys.stream().filter(landedKeys::contains).toList();
|
||||
@@ -1040,7 +1046,6 @@ public class AppearancePatentTaskService {
|
||||
*/
|
||||
private List<AppearancePatentResultRowDto> terminalizeRoundExhaustedRows(
|
||||
FileTaskEntity task,
|
||||
Map<String, List<AppearancePatentParsedRowVo>> allRowsByBaseId,
|
||||
List<AppearancePatentResultRowDto> candidates,
|
||||
ChunkRowKeyIndex rowKeyIndex) {
|
||||
int maxRounds = properties.getLlmRowMaxRounds();
|
||||
@@ -1066,7 +1071,7 @@ public class AppearancePatentTaskService {
|
||||
List<String> exhaustedKeys = exhausted.stream().map(this::rowKey).filter(key -> !key.isBlank()).toList();
|
||||
boolean rowsTerminated = false;
|
||||
try {
|
||||
mergeLlmRowsIntoChunks(task, allRowsByBaseId, llmClient.markRowsFailed(exhausted, reason),
|
||||
mergeLlmRowsIntoChunks(task, llmClient.markRowsFailed(exhausted, reason),
|
||||
exhausted, rowKeyIndex);
|
||||
rowsTerminated = true;
|
||||
} finally {
|
||||
@@ -1081,7 +1086,6 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
|
||||
private Set<String> mergeLlmRowsIntoChunks(FileTaskEntity task,
|
||||
Map<String, List<AppearancePatentParsedRowVo>> allRowsByBaseId,
|
||||
List<AppearancePatentResultRowDto> llmRows,
|
||||
List<AppearancePatentResultRowDto> batchRows,
|
||||
ChunkRowKeyIndex rowKeyIndex) {
|
||||
@@ -1102,8 +1106,7 @@ public class AppearancePatentTaskService {
|
||||
deduped.put(key, row);
|
||||
}
|
||||
}
|
||||
return mergeLlmRowsIntoSubmittedChunks(task, new ArrayList<>(deduped.values()), allRowsByBaseId,
|
||||
null, null, rowKeyIndex);
|
||||
return mergeLlmRowsIntoSubmittedChunks(task, new ArrayList<>(deduped.values()), null, null, rowKeyIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1122,31 +1125,63 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 收集未检测的候选行:**逐行**申领——同一父号下的 {@code 2_1/2_2/2_3} 每行都各自进候选、各自送检。
|
||||
*
|
||||
* <p>历史上这里只挑「组代表行」,其余兄弟行指望 {@code expandRows} 在发起那一轮借用代表行的结论——
|
||||
* 那是把「同一个父号」当成「同一件东西」,而子序行各有各的 sku、标题和图片链接。
|
||||
* 口径(2026-10-10 用户定):这些行**都要检测**。折叠与借用一起撤掉,因为借用的后果不是省钱,
|
||||
* 而是成片空行随结果文件交付(10-08 任务 30426:1211 行里只有 960 行有结论、251 行整段空白,
|
||||
* 而任务报成功;10-09 任务 30455 的 281 行空行 100% 属于"同父号已有一行被判"这一形状)。
|
||||
*
|
||||
* <p>"这行算不算已经检过"用交付口径(标题维+外观维+结论三列齐,见
|
||||
* {@link AppearancePatentRowOutcome#isJudged})。旧代码用的是"四个字段里任一可用",于是
|
||||
* 只带着专利维度文本、或只带一个 error 的行会被判"已检测",从此退出候选,而表格里它那三列全是空的。
|
||||
*/
|
||||
private List<AppearancePatentResultRowDto> collectPendingLlmCandidates(List<TaskChunkEntity> chunks,
|
||||
ChunkRowKeyIndex rowKeyIndex) {
|
||||
if (chunks == null || chunks.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<AppearancePatentResultRowDto> candidates = new ArrayList<>();
|
||||
int claimBlocked = 0;
|
||||
int judgedSkipped = 0;
|
||||
int noDataSkipped = 0;
|
||||
int chunkRows = 0;
|
||||
for (TaskChunkEntity chunk : chunks) {
|
||||
Map<String, AppearancePatentResultRowDto> persistedRows = readChunkRows(chunk);
|
||||
if (persistedRows.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
// 这一遍已经把所有分片的载荷读进来了,顺手把「这片里有哪些行」记进索引:
|
||||
// 这一遍已经把这批分片的载荷读进来了,顺手把「这片里有哪些行」记进索引:
|
||||
// 下面每批落库前都要这份索引,不记的话就得每批把全部分片重读重解析一遍
|
||||
rememberChunkRowKeys(rowKeyIndex, chunk, persistedRows.keySet());
|
||||
for (AppearancePatentResultRowDto row : pickGroupRepresentativesForLlm(persistedRows.values())) {
|
||||
chunkRows += persistedRows.size();
|
||||
for (AppearancePatentResultRowDto row : persistedRows.values()) {
|
||||
String key = rowKey(row);
|
||||
if (key.isBlank() || hasResolvedLlmFields(row)) {
|
||||
if (key.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
if (AppearancePatentRowOutcome.isJudged(row)) {
|
||||
judgedSkipped++;
|
||||
continue;
|
||||
}
|
||||
if (!shouldInspectRow(row)) {
|
||||
// 连标题带图都没采到的行:送过去也只能回"外观识别异常",白扣一次
|
||||
noDataSkipped++;
|
||||
continue;
|
||||
}
|
||||
if (!taskCacheService.beginRowInspection(chunk.getTaskId(), key)) {
|
||||
// 被"处理中/已完成"标记挡住的行必须数得出来:历史上这里静默 continue,
|
||||
// 于是"扣了次数却永久没结论"和"这行本来就不该检"在日志里长得一模一样
|
||||
claimBlocked++;
|
||||
continue;
|
||||
}
|
||||
candidates.add(row);
|
||||
}
|
||||
}
|
||||
log.info("[appearance-patent] 候选收集逐行申领 taskId={} chunkRows={} judgedSkipped={} noDataSkipped={} claimBlocked={} candidates={}",
|
||||
chunks.get(0).getTaskId(), chunkRows, judgedSkipped, noDataSkipped, claimBlocked, candidates.size());
|
||||
return candidates;
|
||||
}
|
||||
|
||||
@@ -1161,8 +1196,8 @@ public class AppearancePatentTaskService {
|
||||
int total = 0;
|
||||
for (TaskChunkEntity chunk : chunks) {
|
||||
Map<String, AppearancePatentResultRowDto> persistedRows = readChunkRows(chunk);
|
||||
for (AppearancePatentResultRowDto row : pickGroupRepresentativesForLlm(persistedRows.values())) {
|
||||
if (!rowKey(row).isBlank() && !hasResolvedLlmFields(row)) {
|
||||
for (AppearancePatentResultRowDto row : persistedRows.values()) {
|
||||
if (!rowKey(row).isBlank() && !AppearancePatentRowOutcome.isJudged(row)) {
|
||||
total++;
|
||||
}
|
||||
}
|
||||
@@ -1180,7 +1215,8 @@ public class AppearancePatentTaskService {
|
||||
if (persistedRows.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
int unresolved = pickGroupRepresentativesForLlm(persistedRows.values()).size();
|
||||
int unresolved = (int) persistedRows.values().stream()
|
||||
.filter(row -> !rowKey(row).isBlank() && !AppearancePatentRowOutcome.isJudged(row)).count();
|
||||
if (unresolved > 0) {
|
||||
total += Math.max(1, (unresolved + batchSize - 1) / batchSize);
|
||||
}
|
||||
@@ -1220,8 +1256,7 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
log.info("[appearance-patent] stale recovery created assemble job taskId={} resultId={} jobId={} jobStatus={} chunkCount={}",
|
||||
task.getId(), result.getId(), job.getId(), job.getStatus(), chunks.size());
|
||||
Map<String, List<AppearancePatentParsedRowVo>> allRowsByBaseId = loadAllRowsByBaseId(task);
|
||||
submitLlmBatches(task, result, job, chunks, allRowsByBaseId);
|
||||
submitLlmBatches(task, result, job, chunks);
|
||||
if (isResultSubmissionComplete(task.getId())) {
|
||||
taskFileJobService.requeue(job.getId(), "检测结果已回流,正在组装 xlsx");
|
||||
} else {
|
||||
@@ -1529,104 +1564,6 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
}
|
||||
|
||||
private List<AppearancePatentResultRowDto> expandRows(List<AppearancePatentResultRowDto> representatives,
|
||||
Map<String, List<AppearancePatentParsedRowVo>> allRowsByBaseId) {
|
||||
if (representatives == null || representatives.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<AppearancePatentResultRowDto> result = new ArrayList<>();
|
||||
Set<String> emittedKeys = new LinkedHashSet<>();
|
||||
for (AppearancePatentResultRowDto representative : representatives) {
|
||||
List<AppearancePatentParsedRowVo> siblings = resolveSiblingRows(representative, allRowsByBaseId);
|
||||
if (siblings == null || siblings.isEmpty()) {
|
||||
result.add(representative);
|
||||
continue;
|
||||
}
|
||||
for (AppearancePatentParsedRowVo sibling : siblings) {
|
||||
String key = rowKey(sibling);
|
||||
if (!emittedKeys.add(key)) {
|
||||
continue;
|
||||
}
|
||||
result.add(copyResultToSibling(representative, sibling));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<AppearancePatentParsedRowVo> resolveSiblingRows(AppearancePatentResultRowDto representative,
|
||||
Map<String, List<AppearancePatentParsedRowVo>> groupedRows) {
|
||||
if (representative == null || groupedRows == null || groupedRows.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
String representativeGroupKey = normalize(representative.getGroupKey());
|
||||
if (!representativeGroupKey.isBlank()) {
|
||||
return groupedRows.getOrDefault(representativeGroupKey, List.of());
|
||||
}
|
||||
String representativeKey = rowKey(representative);
|
||||
String representativeLegacyKey = legacyRowKey(representative);
|
||||
for (List<AppearancePatentParsedRowVo> rows : groupedRows.values()) {
|
||||
for (AppearancePatentParsedRowVo row : rows) {
|
||||
if (Objects.equals(representativeKey, rowKey(row))
|
||||
|| Objects.equals(representativeLegacyKey, legacyRowKey(row))) {
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private Map<String, List<AppearancePatentParsedRowVo>> loadAllRowsByBaseId(FileTaskEntity task) {
|
||||
try {
|
||||
AppearancePatentParsedPayloadDto payload = readParsedPayload(task);
|
||||
List<AppearancePatentParsedRowVo> rows = payload.getAllItems();
|
||||
if (rows == null || rows.isEmpty()) {
|
||||
rows = payload.getItems();
|
||||
}
|
||||
if ((rows == null || rows.isEmpty()) && payload.getGroups() != null) {
|
||||
rows = payload.getGroups().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.flatMap(group -> group.getItems() == null ? java.util.stream.Stream.empty() : group.getItems().stream())
|
||||
.toList();
|
||||
}
|
||||
return groupRowsByBaseId(rows);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[appearance-patent] read all rows failed taskId={} err={}", task.getId(), ex.getMessage());
|
||||
return new LinkedHashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
private List<AppearancePatentResultRowDto> pickGroupRepresentativesForLlm(java.util.Collection<AppearancePatentResultRowDto> rows) {
|
||||
Map<String, List<AppearancePatentResultRowDto>> groupedRows = new LinkedHashMap<>();
|
||||
if (rows == null) {
|
||||
return List.of();
|
||||
}
|
||||
for (AppearancePatentResultRowDto row : rows) {
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
String key = firstNonBlank(normalize(row.getGroupKey()), rowKey(row));
|
||||
groupedRows.computeIfAbsent(key, ignored -> new ArrayList<>()).add(row);
|
||||
}
|
||||
List<AppearancePatentResultRowDto> representatives = new ArrayList<>();
|
||||
for (List<AppearancePatentResultRowDto> siblings : groupedRows.values()) {
|
||||
boolean alreadyResolved = siblings.stream().anyMatch(this::hasCompleteLlmResult);
|
||||
if (alreadyResolved) {
|
||||
continue;
|
||||
}
|
||||
AppearancePatentResultRowDto candidate = null;
|
||||
for (AppearancePatentResultRowDto sibling : siblings) {
|
||||
if (shouldInspectRow(sibling)) {
|
||||
candidate = sibling;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (candidate != null) {
|
||||
representatives.add(candidate);
|
||||
}
|
||||
}
|
||||
return representatives;
|
||||
}
|
||||
|
||||
private List<AppearancePatentParsedGroupVo> buildParsedGroups(List<AppearancePatentParsedRowVo> rows) {
|
||||
List<AppearancePatentParsedGroupVo> groups = new ArrayList<>();
|
||||
for (List<AppearancePatentParsedRowVo> siblings : groupRowsByBaseId(rows).values()) {
|
||||
@@ -1718,33 +1655,6 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
}
|
||||
|
||||
private AppearancePatentResultRowDto copyResultToSibling(AppearancePatentResultRowDto representative, AppearancePatentParsedRowVo sibling) {
|
||||
AppearancePatentResultRowDto row = new AppearancePatentResultRowDto();
|
||||
row.setSourceFileKey(sibling.getSourceFileKey());
|
||||
row.setSourceFilename(sibling.getSourceFilename());
|
||||
row.setRowToken(sibling.getRowToken());
|
||||
row.setGroupKey(sibling.getGroupKey());
|
||||
row.setId(sibling.getDisplayId());
|
||||
row.setAsin(sibling.getAsin());
|
||||
row.setCountry(sibling.getCountry());
|
||||
row.setSku(firstNonBlank(representative.getSku(), sibling.getSku()));
|
||||
row.setBrand(representative.getBrand());
|
||||
row.setUrl(firstNonBlank(representative.getUrl(), sibling.getUrl()));
|
||||
row.setTitle(firstNonBlank(representative.getTitle(), sibling.getTitle()));
|
||||
row.setError(representative.getError());
|
||||
row.setStatus(representative.getStatus());
|
||||
row.setTitleRisk(representative.getTitleRisk());
|
||||
row.setAppearanceRisk(representative.getAppearanceRisk());
|
||||
row.setPatentRisk(representative.getPatentRisk());
|
||||
row.setConclusion(representative.getConclusion());
|
||||
row.setTitleReason(representative.getTitleReason());
|
||||
row.setAppearanceReason(representative.getAppearanceReason());
|
||||
row.setPatentReason(representative.getPatentReason());
|
||||
row.setScore(representative.getScore());
|
||||
row.setDone(representative.getDone());
|
||||
return row;
|
||||
}
|
||||
|
||||
private String readAiPrompt(FileTaskEntity task) {
|
||||
try {
|
||||
return readParsedPayload(task).getAiPrompt();
|
||||
@@ -1775,6 +1685,7 @@ public class AppearancePatentTaskService {
|
||||
|
||||
private void finalizeTask(FileTaskEntity task, String error, int rowCount, boolean assembleWorkbook) {
|
||||
String finalError = error;
|
||||
AppearancePatentRowOutcome.Facts deliveryFacts = AppearancePatentRowOutcome.Facts.EMPTY;
|
||||
FileResultEntity result = null;
|
||||
boolean hasPersistedResultRows = hasPersistedResultRows(task.getId());
|
||||
List<FileResultEntity> rows = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
@@ -1790,7 +1701,7 @@ public class AppearancePatentTaskService {
|
||||
boolean shouldAssembleResult = assembleWorkbook && (finalError == null || finalError.isBlank() || hasPersistedResultRows);
|
||||
if (shouldAssembleResult && shouldAssembleSynchronously()) {
|
||||
try {
|
||||
assembleResultWorkbook(task, result);
|
||||
deliveryFacts = assembleResultWorkbook(task, result);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[appearance-patent] assemble result workbook failed taskId={} err={}", task.getId(), ex.getMessage());
|
||||
finalError = firstNonBlank(finalError, "Generate appearance patent result failed");
|
||||
@@ -1802,7 +1713,8 @@ public class AppearancePatentTaskService {
|
||||
task.setStatus(resolveTaskExecutionStatus(waitingForAssemble, failed));
|
||||
task.setSuccessFileCount(failed ? 0 : 1);
|
||||
task.setFailedFileCount(failed ? 1 : 0);
|
||||
task.setErrorMessage(finalError);
|
||||
// 缺口只写在消息里,不参与 failed 计算:95% 以上有结论的单仍是成功,但用户要看得见"N 行没检测完"
|
||||
task.setErrorMessage(appendDeliveryGapMessage(finalError, deliveryFacts));
|
||||
task.setUpdatedAt(LocalDateTime.now());
|
||||
task.setFinishedAt(waitingForAssemble ? null : LocalDateTime.now());
|
||||
fileTaskMapper.updateById(task);
|
||||
@@ -1915,25 +1827,58 @@ public class AppearancePatentTaskService {
|
||||
int plannedLlmUnits = Math.max(1, llmWorkUnits);
|
||||
int totalProgressUnits = Math.max(3, plannedLlmUnits + 3);
|
||||
saveFileBuildProgress(task, job, totalProgressUnits, 0, "正在提交检测");
|
||||
Map<String, List<AppearancePatentParsedRowVo>> allRowsByBaseId = loadAllRowsByBaseId(task);
|
||||
submitLlmBatches(task, result, job, chunks, allRowsByBaseId);
|
||||
submitLlmBatches(task, result, job, chunks);
|
||||
if (STATUS_RUNNING.equals(task.getStatus()) && !isResultSubmissionComplete(task.getId())) {
|
||||
taskFileJobService.touchRunning(job.getId());
|
||||
touchJavaSideTaskActivity(task.getId());
|
||||
saveFileBuildProgress(task, job, totalProgressUnits, Math.max(1, plannedLlmUnits), "等待 Python 继续回传数据");
|
||||
return false;
|
||||
}
|
||||
completeLlmFileJob(task, result, job, totalProgressUnits);
|
||||
return completeLlmFileJob(task, result, job, totalProgressUnits);
|
||||
}
|
||||
|
||||
/**
|
||||
* 有行没跑完就先别把半张表当成品发:撤销这些行的检测标记(完成态与处理中都要撤,
|
||||
* 否则 {@code beginRowInspection} 下一轮仍然申领不到它们),把作业排回队列补检一轮。
|
||||
*
|
||||
* <p>不会无限补检:作业重排受 {@code TaskFileJobService} 的 MAX_RETRY_COUNT 约束(requeue 返回
|
||||
* false 时这里就放行出文件),行级重发次数受 {@code llmRowMaxRounds} 约束(到顶的行会被判死并
|
||||
* 写上「重发轮次已达上限」的结论,从此不再是空行)。
|
||||
*/
|
||||
private boolean requestRecheckForMissingRows(FileTaskEntity task, TaskFileJobEntity job,
|
||||
AppearancePatentRowOutcome.Facts facts) {
|
||||
if (task == null || job == null || job.getId() == null || facts == null
|
||||
|| facts.missingRows() <= 0 || facts.missingKeys().isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
List<String> keys = facts.missingKeys();
|
||||
// 只有这条出口允许连完成标记一起撤:结果落过库却又读不回来的行,不撤就永远补不回来。
|
||||
// 代价(该行可能被重发一次 LLM、多扣一次次数)是这一档修法里用户点名要付的。
|
||||
taskCacheService.releaseRowInspection(task.getId(), keys, true);
|
||||
boolean requeued = taskFileJobService.requeue(job.getId(),
|
||||
"有 " + facts.missingRows() + " 行未完成检测,补检一轮后重新组装结果文件");
|
||||
if (!requeued) {
|
||||
log.warn("[appearance-patent] 交付缺口补检排不上队,按已有结果交付 taskId={} jobId={} missingRows={}",
|
||||
task.getId(), job.getId(), facts.missingRows());
|
||||
return false;
|
||||
}
|
||||
log.warn("[appearance-patent] 交付缺口触发补检轮 taskId={} jobId={} missingRows={} keys={} noDataRows={}",
|
||||
task.getId(), job.getId(), facts.missingRows(), keys.size(), facts.noDataRows());
|
||||
return true;
|
||||
}
|
||||
|
||||
private void completeLlmFileJob(FileTaskEntity task,
|
||||
private boolean completeLlmFileJob(FileTaskEntity task,
|
||||
FileResultEntity result,
|
||||
TaskFileJobEntity job,
|
||||
int totalProgressUnits) {
|
||||
int assembleProgress = Math.max(1, totalProgressUnits - 2);
|
||||
saveFileBuildProgress(task, job, totalProgressUnits, assembleProgress, "正在组装 xlsx");
|
||||
assembleResultWorkbook(task, result);
|
||||
AppearancePatentRowOutcome.Facts deliveryFacts = assembleResultWorkbook(task, result);
|
||||
if (requestRecheckForMissingRows(task, job, deliveryFacts)) {
|
||||
// 半张表先不发出去:撤销未完成行的检测标记、把作业排回队列补检一轮,
|
||||
// 上限由行级轮次闸(llmRowMaxRounds)与作业重试上限共同兜住。
|
||||
return false;
|
||||
}
|
||||
saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits - 1, "正在上传结果文件");
|
||||
fileResultMapper.updateById(result);
|
||||
boolean taskAlreadyFailed = STATUS_FAILED.equals(task.getStatus())
|
||||
@@ -1942,18 +1887,18 @@ public class AppearancePatentTaskService {
|
||||
task.setStatus(resolveTaskExecutionStatus(false, taskAlreadyFailed));
|
||||
task.setSuccessFileCount(taskAlreadyFailed ? 0 : 1);
|
||||
task.setFailedFileCount(taskAlreadyFailed ? 1 : 0);
|
||||
task.setErrorMessage(taskAlreadyFailed ? existingError : null);
|
||||
task.setErrorMessage(appendDeliveryGapMessage(taskAlreadyFailed ? existingError : null, deliveryFacts));
|
||||
task.setUpdatedAt(LocalDateTime.now());
|
||||
task.setFinishedAt(LocalDateTime.now());
|
||||
fileTaskMapper.updateById(task);
|
||||
taskCacheService.deleteTaskCache(task.getId());
|
||||
saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits, "结果文件已生成");
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 返回真正落库的行键;没匹配到分片行的键不会出现在里面,调用方据此决定要不要撤销已检测标记。 */
|
||||
private Set<String> mergeLlmRowsIntoSubmittedChunks(FileTaskEntity task,
|
||||
List<AppearancePatentResultRowDto> llmRows,
|
||||
Map<String, List<AppearancePatentParsedRowVo>> allRowsByBaseId,
|
||||
String fallbackScopeHash,
|
||||
Integer fallbackChunkIndex,
|
||||
ChunkRowKeyIndex rowKeyIndex) {
|
||||
@@ -1973,7 +1918,7 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
Map<String, Map<String, AppearancePatentResultRowDto>> mergeRowsByChunk = new LinkedHashMap<>();
|
||||
for (AppearancePatentResultRowDto resultRow : llmRows) {
|
||||
for (AppearancePatentResultRowDto expandedRow : expandRows(List.of(resultRow), allRowsByBaseId)) {
|
||||
for (AppearancePatentResultRowDto expandedRow : List.of(resultRow)) {
|
||||
String rowKey = rowKey(expandedRow);
|
||||
if (rowKey.isBlank()) {
|
||||
continue;
|
||||
@@ -2250,7 +2195,7 @@ public class AppearancePatentTaskService {
|
||||
.eq(TaskScopeStateEntity::getModuleType, MODULE_TYPE));
|
||||
}
|
||||
|
||||
private void assembleResultWorkbook(FileTaskEntity task, FileResultEntity result) {
|
||||
private AppearancePatentRowOutcome.Facts assembleResultWorkbook(FileTaskEntity task, FileResultEntity result) {
|
||||
AppearancePatentParsedPayloadDto parsed = readParsedPayload(task);
|
||||
List<AppearancePatentParsedRowVo> parsedRows = parsed.getAllItems() == null
|
||||
? List.of() : parsed.getAllItems();
|
||||
@@ -2262,6 +2207,7 @@ public class AppearancePatentTaskService {
|
||||
long resolvedRows = 0L;
|
||||
long reasonRows = 0L;
|
||||
int conclusionPropagated = 0;
|
||||
AppearancePatentRowOutcome.Facts deliveryFacts = AppearancePatentRowOutcome.Facts.EMPTY;
|
||||
File outputDir = new File(storageProperties.getLocalTempDir(), "appearance-patent-result");
|
||||
if (!outputDir.exists() && !outputDir.mkdirs()) {
|
||||
throw new BusinessException("创建结果目录失败");
|
||||
@@ -2274,7 +2220,8 @@ public class AppearancePatentTaskService {
|
||||
loadPersistedResultRowsForRowsWithRetry(task.getId(), item.rows());
|
||||
// 覆盖率先于「本文件无结果就跳过」判定:整源文件的 LLM 结果全丢(分片被跳过、
|
||||
// 结果清空)时覆盖率是 0%,必须在这里判掉,不能让 zip 少一个文件还报任务成功。
|
||||
validateCompleteLlmCoverage(task.getId(), item.rows(), resultMap);
|
||||
deliveryFacts = deliveryFacts.plus(
|
||||
validateCompleteLlmCoverage(task.getId(), item.rows(), resultMap));
|
||||
List<AppearancePatentParsedRowVo> receivedRows = filterReceivedParsedRows(item.rows(), resultMap);
|
||||
if (receivedRows.isEmpty()) {
|
||||
resultMap.clear();
|
||||
@@ -2345,6 +2292,7 @@ public class AppearancePatentTaskService {
|
||||
result.setResultFileSize(uploadFile.length());
|
||||
result.setResultContentType(contentType);
|
||||
result.setRowCount(receivedRowCount);
|
||||
return deliveryFacts;
|
||||
} finally {
|
||||
for (SourceResultWorkbook workbook : workbooks) {
|
||||
if (workbook.file().exists() && !workbook.file().delete()) {
|
||||
@@ -2468,68 +2416,90 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 覆盖率判定:分母必须是**解析出的全部行**(只滤掉不需要送检的行),不能是已经拿到结果的行。
|
||||
* 传已过滤的集合会让分母恒等于分子 —— 整片结果丢失(chunk payload 缺失被跳过、
|
||||
* 客户端漏回传)时覆盖率仍是 100%,阈值形同虚设。
|
||||
* 覆盖率判定:分母必须是**真正会写进结果文件的那批行**,且"该行有没有数据"要同时看
|
||||
* 用户上传表的解析行与客户端回传的结果行——只看解析行,用户表不带标题列时分母恒为 0,
|
||||
* 闸门对整份文件失明(现网 6 份已交付文件里 20%–51% 空行、零告警就是这么来的)。
|
||||
* 判据本身在 {@link AppearancePatentRowOutcome#summarize},与表格文案共用一套,不许两边各判。
|
||||
*/
|
||||
private void validateCompleteLlmCoverage(Long taskId,
|
||||
private AppearancePatentRowOutcome.Facts validateCompleteLlmCoverage(Long taskId,
|
||||
List<AppearancePatentParsedRowVo> parsedRows,
|
||||
Map<String, AppearancePatentResultRowDto> resultMap) {
|
||||
if (parsedRows == null || parsedRows.isEmpty()) {
|
||||
return;
|
||||
return AppearancePatentRowOutcome.Facts.EMPTY;
|
||||
}
|
||||
AppearancePatentRowOutcome.Facts facts =
|
||||
AppearancePatentRowOutcome.summarize(parsedRows, row -> findResultRow(row, resultMap));
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
if (task != null && STATUS_FAILED.equals(task.getStatus())) {
|
||||
return;
|
||||
boolean taskAlreadyFailed = task != null && STATUS_FAILED.equals(task.getStatus());
|
||||
if (facts.missingRows() > 0 || facts.noDataRows() > 0) {
|
||||
log.warn("[appearance-patent] 交付行账不完整 taskId={} expectedRows={} judgedRows={} missingRows={} noDataRows={} coverage={} taskFailed={} samples={}",
|
||||
taskId, facts.expectedRows(), facts.judgedRows(), facts.missingRows(), facts.noDataRows(),
|
||||
String.format("%.2f%%", facts.coverage() * 100), taskAlreadyFailed,
|
||||
sampleAsins(parsedRows, resultMap, facts));
|
||||
}
|
||||
double minCoverage = properties.getLlmCoverageMinRatio();
|
||||
// 已判失败的任务走的是"按已有分片出部分结果"这条既有口径,这里再抛会把成品彻底拿掉;
|
||||
// 但它不再静默:上面的行账锚点必打,缺口由调用方写进任务错误信息,用户看得到「N 行没检测」。
|
||||
if (!taskAlreadyFailed && minCoverage > 0 && facts.expectedRows() > 0
|
||||
&& facts.coverage() + 1e-9 < minCoverage) {
|
||||
throw new BusinessException("LLM 结果不完整:仅 " + facts.judgedRows() + "/" + facts.expectedRows()
|
||||
+ " 行拿到检测结论(低于 " + Math.round(minCoverage * 100) + "% 覆盖率下限)"
|
||||
+ noDataSuffix(facts) + ",请重新运行任务");
|
||||
}
|
||||
return facts;
|
||||
}
|
||||
|
||||
private List<String> sampleAsins(List<AppearancePatentParsedRowVo> parsedRows,
|
||||
Map<String, AppearancePatentResultRowDto> resultMap,
|
||||
AppearancePatentRowOutcome.Facts facts) {
|
||||
List<String> samples = new ArrayList<>(5);
|
||||
if (facts.missingRows() <= 0) {
|
||||
return samples;
|
||||
}
|
||||
int expectedRows = 0;
|
||||
int missingRows = 0;
|
||||
List<String> sampleAsins = new ArrayList<>();
|
||||
for (AppearancePatentParsedRowVo parsedRow : parsedRows) {
|
||||
if (!hasPromptFields(parsedRow)) {
|
||||
if (samples.size() >= 5) {
|
||||
break;
|
||||
}
|
||||
if (parsedRow == null) {
|
||||
continue;
|
||||
}
|
||||
expectedRows++;
|
||||
AppearancePatentResultRowDto resultRow = findResultRow(parsedRow, resultMap);
|
||||
if (resultRow == null || !hasDeliverableLlmResult(resultRow)) {
|
||||
missingRows++;
|
||||
if (sampleAsins.size() < 5) {
|
||||
sampleAsins.add(firstNonBlank(parsedRow.getAsin(), firstNonBlank(parsedRow.getDisplayId(), "")));
|
||||
}
|
||||
if (AppearancePatentRowOutcome.classify(parsedRow, findResultRow(parsedRow, resultMap))
|
||||
!= AppearancePatentRowOutcome.Kind.NOT_INSPECTED) {
|
||||
continue;
|
||||
}
|
||||
samples.add(firstNonBlank(parsedRow.getAsin(),
|
||||
firstNonBlank(parsedRow.getDisplayId(), "")));
|
||||
}
|
||||
if (expectedRows <= 0) {
|
||||
return;
|
||||
}
|
||||
int resolvedRows = expectedRows - missingRows;
|
||||
double coverage = (double) resolvedRows / expectedRows;
|
||||
double minCoverage = properties.getLlmCoverageMinRatio();
|
||||
if (missingRows > 0) {
|
||||
log.warn("[appearance-patent] incomplete llm coverage taskId={} expectedRows={} missingRows={} coverage={} samples={}",
|
||||
taskId, expectedRows, missingRows, String.format("%.2f%%", coverage * 100), sampleAsins);
|
||||
}
|
||||
if (minCoverage > 0 && coverage + 1e-9 < minCoverage) {
|
||||
throw new BusinessException("LLM 结果不完整:仅 " + resolvedRows + "/" + expectedRows
|
||||
+ " 行拿到检测结论(低于 " + Math.round(minCoverage * 100) + "% 覆盖率下限),请重新运行任务");
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
|
||||
/**
|
||||
* 交付口径的完整性判定:结论依赖标题维度、外观维度和最终结论三列。
|
||||
* 与 {@link #hasCompleteLlmResult} 的区别是不看 patentRisk —— 现网正常返回里 patent
|
||||
* 恒为空串(见 AppearancePatentLlmClient 的 LlmResult 构造),拿它当必要条件会把每个任务都判成不完整。
|
||||
*/
|
||||
private boolean hasDeliverableLlmResult(AppearancePatentResultRowDto row) {
|
||||
return hasUsableLlmField(row.getTitleRisk())
|
||||
&& hasUsableLlmField(row.getAppearanceRisk())
|
||||
&& hasUsableLlmField(row.getConclusion());
|
||||
private String noDataSuffix(AppearancePatentRowOutcome.Facts facts) {
|
||||
return facts.noDataRows() > 0
|
||||
? ";另有 " + facts.noDataRows() + " 行未采集到数据、无法检测"
|
||||
: "";
|
||||
}
|
||||
|
||||
private boolean hasCompleteLlmResult(AppearancePatentResultRowDto row) {
|
||||
return hasUsableLlmField(row.getTitleRisk())
|
||||
&& hasUsableLlmField(row.getAppearanceRisk())
|
||||
&& hasUsableLlmField(row.getPatentRisk())
|
||||
&& hasUsableLlmField(row.getConclusion());
|
||||
/** 交付缺口写进任务错误信息:让后台列表与用户端都能看到「N 行没检测完」,而不是只有一张半空表。 */
|
||||
private String appendDeliveryGapMessage(String existingError, AppearancePatentRowOutcome.Facts facts) {
|
||||
if (facts == null || (facts.missingRows() <= 0 && facts.noDataRows() <= 0)) {
|
||||
return existingError;
|
||||
}
|
||||
StringBuilder gap = new StringBuilder();
|
||||
if (facts.missingRows() > 0) {
|
||||
gap.append("有 ").append(facts.missingRows()).append(" 行未完成检测");
|
||||
}
|
||||
if (facts.noDataRows() > 0) {
|
||||
if (gap.length() > 0) {
|
||||
gap.append("、");
|
||||
}
|
||||
gap.append("有 ").append(facts.noDataRows()).append(" 行未采集到数据");
|
||||
}
|
||||
gap.append("(结果文件中这些行已单独标注)");
|
||||
String existing = firstNonBlank(existingError, "");
|
||||
if (existing.contains("未完成检测") || existing.contains("未采集到数据")) {
|
||||
return existing;
|
||||
}
|
||||
return existing.isBlank() ? gap.toString() : existing + ";" + gap;
|
||||
}
|
||||
|
||||
private boolean hasPersistedResultRows(Long taskId) {
|
||||
@@ -2847,29 +2817,10 @@ public class AppearancePatentTaskService {
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean hasPromptFields(AppearancePatentParsedRowVo row) {
|
||||
return row != null && (!normalize(row.getTitle()).isBlank() || !normalize(row.getUrl()).isBlank());
|
||||
}
|
||||
|
||||
private boolean shouldInspectRow(AppearancePatentResultRowDto row) {
|
||||
return row != null && (!normalize(row.getTitle()).isBlank() || !normalize(row.getUrl()).isBlank());
|
||||
}
|
||||
|
||||
private boolean hasResolvedLlmFields(AppearancePatentResultRowDto row) {
|
||||
if (row == null) {
|
||||
return false;
|
||||
}
|
||||
return hasUsableLlmField(row.getTitleRisk())
|
||||
|| hasUsableLlmField(row.getAppearanceRisk())
|
||||
|| hasUsableLlmField(row.getPatentRisk())
|
||||
|| hasUsableLlmField(row.getConclusion());
|
||||
}
|
||||
|
||||
private boolean hasUsableLlmField(String value) {
|
||||
String normalized = normalize(value);
|
||||
return !normalized.isBlank() && !AppearancePatentSheetBuilder.isTechnicalLlmFailure(normalized);
|
||||
}
|
||||
|
||||
private Map<String, Integer> buildHeaderMap(Row header, DataFormatter formatter) {
|
||||
Map<String, Integer> map = new LinkedHashMap<>();
|
||||
for (int i = 0; i < header.getLastCellNum(); i++) {
|
||||
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service.support;
|
||||
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedRowVo;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* 一行「没出结论」到底是哪一种原因的唯一点径:交付表格的文案与覆盖率闸门的分母共用这里。
|
||||
*
|
||||
* <p>历史上两边各判各的:闸门按**用户上传表的解析行**有没有标题/图片决定这行算不算
|
||||
* 「该被检测」,而表格按**客户端回传的结果行**有没有标题/图片决定这行有没有结论。
|
||||
* 现网(2026-10-06~10-09 实测 6 份已交付文件)用户表常只给 id/ASIN/国家,标题与图片链接
|
||||
* 全靠采集回传 ⇒ 解析行两列恒空 ⇒ 闸门分母为 0、整段不判,表里 20%–51% 的行写着
|
||||
* 「未取得检测结果」而日志里一条覆盖率告警都没有。
|
||||
*/
|
||||
public final class AppearancePatentRowOutcome {
|
||||
|
||||
public enum Kind {
|
||||
/** 三维结论齐了,正常交付。 */
|
||||
JUDGED,
|
||||
/** 该行有数据、本该检出,但没有可用结论:检测没跑到或结果丢了。 */
|
||||
NOT_INSPECTED,
|
||||
/** 连标题和图片都没采集到,无从检测。 */
|
||||
NO_DATA
|
||||
}
|
||||
|
||||
/**
|
||||
* 「有数据却没检」的专用文案。它和 {@link AppearancePatentSheetBuilder#NO_RESULT_TEXT}
|
||||
* 必须分开:后者意味着"检了但没答上",前者意味着"根本没跑到这一行",
|
||||
* 用户拿到的处置动作完全不同(等补检 / 重新发起)。
|
||||
*/
|
||||
public static final String NOT_INSPECTED_TEXT = "该行未完成检测(任务提前结束),重新运行可补检";
|
||||
|
||||
public static final String NO_DATA_TEXT = "该行未采集到数据(标题与图片都没有),无法检测";
|
||||
|
||||
private AppearancePatentRowOutcome() {
|
||||
}
|
||||
|
||||
public static Kind classify(AppearancePatentParsedRowVo parsedRow,
|
||||
AppearancePatentResultRowDto resultRow) {
|
||||
if (isJudged(resultRow)) {
|
||||
return Kind.JUDGED;
|
||||
}
|
||||
return hasCheckableData(parsedRow, resultRow) ? Kind.NOT_INSPECTED : Kind.NO_DATA;
|
||||
}
|
||||
|
||||
/** 交付口径的"这行有结论":标题维、外观维、结论三列都得有可用文本(结论依赖前两者)。 */
|
||||
public static boolean isJudged(AppearancePatentResultRowDto resultRow) {
|
||||
return resultRow != null
|
||||
&& isUsableField(resultRow.getTitleRisk())
|
||||
&& isUsableField(resultRow.getAppearanceRisk())
|
||||
&& isUsableField(resultRow.getConclusion());
|
||||
}
|
||||
|
||||
public static boolean isUsableField(String value) {
|
||||
String normalized = AppearancePatentSheetBuilder.normalize(value);
|
||||
return !normalized.isBlank() && !AppearancePatentSheetBuilder.isTechnicalLlmFailure(normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* 行上有没有任何能展示给用户的东西(三个维度、结论、错误原文)。
|
||||
* 全空才由行级文案({@link #NOT_INSPECTED_TEXT} / {@link #NO_DATA_TEXT})接管;
|
||||
* 只要带着错误原文,就让它照原样进格子——把「LLM http 503 模型过载」盖成泛化文案,
|
||||
* 用户和运维都失去归因线索。
|
||||
*/
|
||||
public static boolean carriesNothingToShow(AppearancePatentResultRowDto resultRow) {
|
||||
return resultRow == null
|
||||
|| (isBlank(resultRow.getTitleRisk()) && isBlank(resultRow.getAppearanceRisk())
|
||||
&& isBlank(resultRow.getConclusion()) && isBlank(resultRow.getError()));
|
||||
}
|
||||
|
||||
private static boolean isBlank(String value) {
|
||||
return AppearancePatentSheetBuilder.normalize(value).isBlank();
|
||||
}
|
||||
|
||||
/**
|
||||
* 这行到底有没有东西可检——解析行与回传行**任一处**有标题或图片链接就算有。
|
||||
* 只看解析行是历史缺陷:数据在回传行上,闸门因此对整份文件失明。
|
||||
*/
|
||||
public static boolean hasCheckableData(AppearancePatentParsedRowVo parsedRow,
|
||||
AppearancePatentResultRowDto resultRow) {
|
||||
return !titleOf(parsedRow, resultRow).isBlank() || !urlOf(parsedRow, resultRow).isBlank();
|
||||
}
|
||||
|
||||
public static String titleOf(AppearancePatentParsedRowVo parsedRow,
|
||||
AppearancePatentResultRowDto resultRow) {
|
||||
String fromResult = resultRow == null ? "" : AppearancePatentSheetBuilder.normalize(resultRow.getTitle());
|
||||
String fromParsed = parsedRow == null ? "" : AppearancePatentSheetBuilder.normalize(parsedRow.getTitle());
|
||||
return fromResult.isBlank() ? fromParsed : fromResult;
|
||||
}
|
||||
|
||||
public static String urlOf(AppearancePatentParsedRowVo parsedRow,
|
||||
AppearancePatentResultRowDto resultRow) {
|
||||
String fromResult = resultRow == null ? "" : AppearancePatentSheetBuilder.normalize(resultRow.getUrl());
|
||||
String fromParsed = parsedRow == null ? "" : AppearancePatentSheetBuilder.normalize(parsedRow.getUrl());
|
||||
return fromResult.isBlank() ? fromParsed : fromResult;
|
||||
}
|
||||
|
||||
/** 未完成检测的行在格子里写什么;已判定的行不走这里。 */
|
||||
public static String missingText(Kind kind) {
|
||||
return switch (kind) {
|
||||
case NO_DATA -> NO_DATA_TEXT;
|
||||
case NOT_INSPECTED -> NOT_INSPECTED_TEXT;
|
||||
case JUDGED -> "";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按交付口径数一遍行账。
|
||||
*
|
||||
* @param rows 真正会写进结果文件的行集(与出表同一集合,不许自挑)
|
||||
* @param finder 与出表同一个取结果函数,保证"闸门看到的行"="表格里的行"
|
||||
*/
|
||||
public static Facts summarize(List<AppearancePatentParsedRowVo> rows,
|
||||
Function<AppearancePatentParsedRowVo, AppearancePatentResultRowDto> finder) {
|
||||
int expected = 0;
|
||||
int judged = 0;
|
||||
int noData = 0;
|
||||
Set<String> missingKeys = new LinkedHashSet<>();
|
||||
List<AppearancePatentParsedRowVo> rowsToRead = rows == null ? List.of() : rows;
|
||||
for (AppearancePatentParsedRowVo parsedRow : rowsToRead) {
|
||||
if (parsedRow == null) {
|
||||
continue;
|
||||
}
|
||||
AppearancePatentResultRowDto resultRow = finder == null ? null : finder.apply(parsedRow);
|
||||
Kind kind = classify(parsedRow, resultRow);
|
||||
if (kind == Kind.NO_DATA) {
|
||||
noData++;
|
||||
continue;
|
||||
}
|
||||
expected++;
|
||||
if (kind == Kind.JUDGED) {
|
||||
judged++;
|
||||
continue;
|
||||
}
|
||||
addIfPresent(missingKeys, AppearancePatentSheetBuilder.rowKey(parsedRow));
|
||||
if (resultRow != null) {
|
||||
addIfPresent(missingKeys, AppearancePatentSheetBuilder.rowKey(resultRow));
|
||||
}
|
||||
}
|
||||
return new Facts(expected, judged, noData, List.copyOf(missingKeys));
|
||||
}
|
||||
|
||||
private static void addIfPresent(Set<String> target, String value) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
target.add(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param expectedRows 该被检测的行数(分母,交付口径)
|
||||
* @param judgedRows 其中拿到完整结论的行数(分子)
|
||||
* @param noDataRows 连数据都没采集到、无从检测的行数(进文案,不进分母)
|
||||
* @param missingKeys 未完成检测行的行键,供补检轮撤销标记重新申领
|
||||
*/
|
||||
public record Facts(int expectedRows, int judgedRows, int noDataRows, List<String> missingKeys) {
|
||||
|
||||
public static final Facts EMPTY = new Facts(0, 0, 0, List.of());
|
||||
|
||||
public int missingRows() {
|
||||
return Math.max(0, expectedRows - judgedRows);
|
||||
}
|
||||
|
||||
/** 分母为 0 时按 1 计:一个该检的行都没有,不存在"覆盖率不足"。 */
|
||||
public double coverage() {
|
||||
return expectedRows <= 0 ? 1D : (double) judgedRows / expectedRows;
|
||||
}
|
||||
|
||||
public Facts plus(Facts other) {
|
||||
if (other == null) {
|
||||
return this;
|
||||
}
|
||||
List<String> keys = new ArrayList<>(missingKeys);
|
||||
keys.addAll(other.missingKeys());
|
||||
return new Facts(expectedRows + other.expectedRows(), judgedRows + other.judgedRows(),
|
||||
noDataRows + other.noDataRows(), List.copyOf(new LinkedHashSet<>(keys)));
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
-17
@@ -43,9 +43,10 @@ public final class AppearancePatentSheetBuilder {
|
||||
}
|
||||
|
||||
/**
|
||||
* 没拿到判定的行写进格子里的显式文案。
|
||||
* 「检到了这一行、但这一列没给出文本」时写进格子的文案。
|
||||
*
|
||||
* <p>交付只要求 LLM 覆盖率过半({@code llm-coverage-min-ratio}),所以少数缺失行照样出文件。
|
||||
* <p>整行压根没检出结论的,走 {@link AppearancePatentRowOutcome#NOT_INSPECTED_TEXT} 与
|
||||
* {@link AppearancePatentRowOutcome#NO_DATA_TEXT}——三种原因对应的处置动作不同,不能挤进同一句。
|
||||
* 历史上这些格子留空,而"空白"和"没风险"在表格里长得一模一样——用户把漏检当成了安全,
|
||||
* 这正是最贵的那种静默失败。
|
||||
*/
|
||||
@@ -58,7 +59,11 @@ public final class AppearancePatentSheetBuilder {
|
||||
*/
|
||||
public static final String PENDING_REVIEW_SUFFIX = "·商标待复核";
|
||||
|
||||
private static final String NO_RESULT_REASON = NO_RESULT_TEXT + ":该行没有返回判定,重新运行任务可补检";
|
||||
private static final String NOT_INSPECTED_REASON = AppearancePatentRowOutcome.NOT_INSPECTED_TEXT
|
||||
+ ":该行没拿到判定,重新运行任务可补检";
|
||||
|
||||
private static final String NO_DATA_REASON = AppearancePatentRowOutcome.NO_DATA_TEXT
|
||||
+ ":请先在采集侧补齐该行数据";
|
||||
|
||||
public static void buildResultSheet(Workbook workbook, List<AppearancePatentParsedRowVo> rows,
|
||||
Map<String, AppearancePatentResultRowDto> resultMap) {
|
||||
@@ -94,6 +99,8 @@ public final class AppearancePatentSheetBuilder {
|
||||
continue;
|
||||
}
|
||||
AppearancePatentResultRowDto resultRow = finder.apply(parsedRow);
|
||||
AppearancePatentRowOutcome.Kind kind = AppearancePatentRowOutcome.classify(parsedRow, resultRow);
|
||||
String outcomeMissingText = AppearancePatentRowOutcome.missingText(kind);
|
||||
Row row = sheet.createRow(rowIndex++);
|
||||
int col = 0;
|
||||
row.createCell(col++).setCellValue(firstNonBlank(parsedRow.getDisplayId(), parsedRow.getSourceId()));
|
||||
@@ -102,17 +109,18 @@ public final class AppearancePatentSheetBuilder {
|
||||
row.createCell(col++).setCellValue(readValueByHeader(parsedRow, "卖家名称", "卖家名", "卖家", "店铺名称", "店铺名", "seller name", "seller_name", "seller-name", "sellername", "store name", "shop name"));
|
||||
row.createCell(col++).setCellValue(resolveBrand(resultRow, parsedRow));
|
||||
row.createCell(col++).setCellValue(resolvePrice(resultRow));
|
||||
row.createCell(col++).setCellValue(resultRow == null ? firstNonBlank(parsedRow.getTitle(), "") : firstNonBlank(resultRow.getTitle(), parsedRow.getTitle()));
|
||||
row.createCell(col++).setCellValue(resultRow == null ? firstNonBlank(parsedRow.getUrl(), "") : firstNonBlank(resultRow.getUrl(), parsedRow.getUrl()));
|
||||
row.createCell(col++).setCellValue(firstNonBlank(AppearancePatentRowOutcome.titleOf(parsedRow, resultRow), ""));
|
||||
row.createCell(col++).setCellValue(firstNonBlank(AppearancePatentRowOutcome.urlOf(parsedRow, resultRow), ""));
|
||||
row.createCell(col++).setCellValue(resultRow == null ? firstNonBlank(parsedRow.getSku(), "") : firstNonBlank(resultRow.getSku(), parsedRow.getSku()));
|
||||
String titleRiskCell = resultRow == null
|
||||
? NO_RESULT_TEXT
|
||||
// 行级文案只在"整行什么都没带回来"时接管:带着 LLM 错误原文的行必须照原样显示错误,
|
||||
// 否则用户和运维都失去归因线索(这条是老用例 test_sheet_builder_llm_failure_user_facing_cells 撞出来的)
|
||||
boolean rowLevelText = kind != AppearancePatentRowOutcome.Kind.JUDGED
|
||||
&& AppearancePatentRowOutcome.carriesNothingToShow(resultRow);
|
||||
String titleRiskCell = rowLevelText ? outcomeMissingText
|
||||
: firstNonBlank(userFacingLlmCellValue(resultRow, resultRow.getTitleRisk()), NO_RESULT_TEXT);
|
||||
String appearanceRiskCell = resultRow == null
|
||||
? NO_RESULT_TEXT
|
||||
String appearanceRiskCell = rowLevelText ? outcomeMissingText
|
||||
: firstNonBlank(userFacingLlmCellValue(resultRow, resultRow.getAppearanceRisk()), NO_RESULT_TEXT);
|
||||
String conclusionCell = resultRow == null
|
||||
? NO_RESULT_TEXT
|
||||
String conclusionCell = rowLevelText ? outcomeMissingText
|
||||
: firstNonBlank(userFacingConclusion(resultRow), NO_RESULT_TEXT);
|
||||
row.createCell(col++).setCellValue(titleRiskCell);
|
||||
row.createCell(col++).setCellValue(appearanceRiskCell);
|
||||
@@ -148,15 +156,24 @@ public final class AppearancePatentSheetBuilder {
|
||||
AppearancePatentResultRowDto resultRow = finder.apply(parsedRow);
|
||||
Row row = sheet.createRow(rowIndex++);
|
||||
row.createCell(0).setCellValue(asin);
|
||||
// 只有"整行没结果"才代写原因;有结果的行原本就没原因可写(无风险),不能污染成缺失说明
|
||||
String missingReason = resultRow == null ? NO_RESULT_REASON : "";
|
||||
row.createCell(1).setCellValue(resultRow == null ? missingReason : firstNonBlank(resultRow.getAppearanceReason(), ""));
|
||||
row.createCell(2).setCellValue(resultRow == null ? missingReason : firstNonBlank(resultRow.getPatentReason(), ""));
|
||||
row.createCell(3).setCellValue(resultRow == null ? missingReason : firstNonBlank(resultRow.getTitleReason(), ""));
|
||||
// 只有"这行没给出结论"才代写原因;已判定的行原本就没原因可写(无风险),不能污染成缺失说明
|
||||
String missingReason = missingReason(AppearancePatentRowOutcome.classify(parsedRow, resultRow));
|
||||
row.createCell(1).setCellValue(resultRow == null ? missingReason : firstNonBlank(resultRow.getAppearanceReason(), missingReason));
|
||||
row.createCell(2).setCellValue(resultRow == null ? missingReason : firstNonBlank(resultRow.getPatentReason(), missingReason));
|
||||
row.createCell(3).setCellValue(resultRow == null ? missingReason : firstNonBlank(resultRow.getTitleReason(), missingReason));
|
||||
rowIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
/** 结论没出来时,「原因」sheet 要说清是哪一种没出来:没数据 / 没跑到 / 跑了没答上。 */
|
||||
private static String missingReason(AppearancePatentRowOutcome.Kind kind) {
|
||||
return switch (kind) {
|
||||
case NO_DATA -> NO_DATA_REASON;
|
||||
case NOT_INSPECTED -> NOT_INSPECTED_REASON;
|
||||
case JUDGED -> "";
|
||||
};
|
||||
}
|
||||
|
||||
public static AppearancePatentResultRowDto findResultRow(AppearancePatentParsedRowVo parsedRow,
|
||||
Map<String, AppearancePatentResultRowDto> resultMap) {
|
||||
if (parsedRow == null || resultMap == null || resultMap.isEmpty()) {
|
||||
@@ -298,7 +315,7 @@ public final class AppearancePatentSheetBuilder {
|
||||
return preferred == null || preferred.isBlank() ? fallback : preferred.trim();
|
||||
}
|
||||
|
||||
private static String normalize(String val) {
|
||||
public static String normalize(String val) {
|
||||
return val == null ? "" : val.replace(String.valueOf((char) 0xFEFF), "").replace((char) 0x3000, ' ').trim().replaceAll("\\s+", " ");
|
||||
}
|
||||
}
|
||||
|
||||
+7
-3
@@ -19,9 +19,13 @@ import java.util.List;
|
||||
@RequiredArgsConstructor
|
||||
public class BrandTaskExpiredStopSpiImpl implements ExpiredAccountTaskStopSpi {
|
||||
|
||||
private static final String STATUS_PENDING = "pending";
|
||||
private static final String STATUS_RUNNING = "running";
|
||||
private static final String STATUS_CANCELLED = "cancelled";
|
||||
// 词表唯一出处:TaskStatuses.BrandTask(brand_crawl_tasks 状态是小写)。
|
||||
private static final String STATUS_PENDING =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.PENDING;
|
||||
private static final String STATUS_RUNNING =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.RUNNING;
|
||||
private static final String STATUS_CANCELLED =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.CANCELLED;
|
||||
|
||||
private final BrandCrawlTaskMapper brandCrawlTaskMapper;
|
||||
|
||||
|
||||
+15
-5
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.brand.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
@@ -101,11 +102,18 @@ public class BrandTaskService {
|
||||
return BLOCKED_SOURCE_HOSTS.contains(normalized) || normalized.endsWith(".localhost");
|
||||
}
|
||||
private static final long RESULT_SUBMIT_WAIT_MILLIS = 5 * 60 * 1000L;
|
||||
private static final String STATUS_PENDING = "pending";
|
||||
private static final String STATUS_RUNNING = "running";
|
||||
private static final String STATUS_SUCCESS = "success";
|
||||
private static final String STATUS_FAILED = "failed";
|
||||
private static final String STATUS_CANCELLED = "cancelled";
|
||||
// 状态词表唯一出处见 com.nanri.aiimage.common.task.TaskStatuses.BrandTask(brand_crawl_tasks 是小写表)。
|
||||
// 这里只留别名,不再抄字面量:这张表的值一旦和任务中心 UNION 的口径漂了,brand 任务会整批静默消失。
|
||||
private static final String STATUS_PENDING =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.PENDING;
|
||||
private static final String STATUS_RUNNING =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.RUNNING;
|
||||
private static final String STATUS_SUCCESS =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.SUCCESS;
|
||||
private static final String STATUS_FAILED =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.FAILED;
|
||||
private static final String STATUS_CANCELLED =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.CANCELLED;
|
||||
private static final String MODULE_TYPE = "BRAND";
|
||||
/** 结果文件并发上传数:OSS/MinIO 上传互不依赖,3 并发平衡收益与内存占用。 */
|
||||
private static final int RESULT_UPLOAD_CONCURRENCY = 3;
|
||||
@@ -1537,6 +1545,7 @@ public class BrandTaskService {
|
||||
for (BrandCrawlTaskEntity task : runningTasks) {
|
||||
TaskDistributedLockService.LockHandle taskLockHandle = acquireTaskLock(task.getId(), 0L);
|
||||
if (taskLockHandle == null) {
|
||||
LockSkipWitness.recordSkip("brand:stale-running-scan", MODULE_TYPE, task.getId());
|
||||
continue;
|
||||
}
|
||||
try (taskLockHandle) {
|
||||
@@ -1597,6 +1606,7 @@ public class BrandTaskService {
|
||||
for (BrandCrawlTaskEntity task : runningTasks) {
|
||||
TaskDistributedLockService.LockHandle taskLockHandle = acquireTaskLock(task.getId(), 0L);
|
||||
if (taskLockHandle == null) {
|
||||
LockSkipWitness.recordSkip("brand:long-running-scan", MODULE_TYPE, task.getId());
|
||||
continue;
|
||||
}
|
||||
try (taskLockHandle) {
|
||||
|
||||
+7
-3
@@ -18,9 +18,13 @@ import java.util.List;
|
||||
@RequiredArgsConstructor
|
||||
public class BrandTaskStaleRepairSpiImpl implements BrandTaskStaleRepairSpi {
|
||||
|
||||
private static final String STATUS_PENDING = "pending";
|
||||
private static final String STATUS_RUNNING = "running";
|
||||
private static final String STATUS_FAILED = "failed";
|
||||
// 词表唯一出处:TaskStatuses.BrandTask(brand_crawl_tasks 状态是小写)。
|
||||
private static final String STATUS_PENDING =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.PENDING;
|
||||
private static final String STATUS_RUNNING =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.RUNNING;
|
||||
private static final String STATUS_FAILED =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.BrandTask.FAILED;
|
||||
|
||||
private final BrandCrawlTaskMapper brandCrawlTaskMapper;
|
||||
|
||||
|
||||
+4
-3
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.collectdata.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.collectdata.model.dto.CollectDataCountryPreferenceSaveRequest;
|
||||
import com.nanri.aiimage.modules.collectdata.model.dto.CollectDataParseRequest;
|
||||
@@ -88,9 +89,9 @@ public class CollectDataController {
|
||||
@Parameter(description = "用户 ID,可选;传入时会校验任务归属")
|
||||
@RequestParam(value = "user_id", required = false) Long userId,
|
||||
@Parameter(description = "页码,从 1 开始", example = "1")
|
||||
@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
|
||||
@RequestParam(value = "page", required = false, defaultValue = PageDefaults.FIRST_PAGE) Integer page,
|
||||
@Parameter(description = "每页条数,默认 50,最大 200", example = "50")
|
||||
@RequestParam(value = "page_size", required = false, defaultValue = "50") Integer pageSize,
|
||||
@RequestParam(value = "page_size", required = false, defaultValue = PageDefaults.TASK_LIST_PAGE_SIZE) Integer pageSize,
|
||||
HttpServletRequest httpRequest) {
|
||||
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
|
||||
return ApiResponse.success(service.getItemsPage(taskId, userId, page, pageSize));
|
||||
@@ -121,7 +122,7 @@ public class CollectDataController {
|
||||
@Parameter(description = "当前用户 ID", required = true, example = "1")
|
||||
@RequestParam("user_id") Long userId,
|
||||
@Parameter(description = "返回数量上限,默认 50,最大 100", example = "50")
|
||||
@RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit,
|
||||
@RequestParam(value = "limit", required = false, defaultValue = PageDefaults.DEFAULT_RESULT_LIMIT) Integer limit,
|
||||
HttpServletRequest httpRequest) {
|
||||
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
|
||||
return ApiResponse.success(service.history(userId, limit));
|
||||
|
||||
+3
@@ -12,6 +12,7 @@ import com.nanri.aiimage.common.exception.BusinessCodes;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.util.ExcelStreamReader;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import com.nanri.aiimage.modules.asincache.service.AsinResultCacheService;
|
||||
import com.nanri.aiimage.modules.collectdata.mapper.CollectDataCountryPrefMapper;
|
||||
import com.nanri.aiimage.modules.collectdata.mapper.CollectDataItemMapper;
|
||||
@@ -568,6 +569,7 @@ public class CollectDataService {
|
||||
try (TaskDistributedLockService.LockHandle lock =
|
||||
taskDistributedLockService.acquire(MODULE_TYPE, taskId, 0L)) {
|
||||
if (lock == null) {
|
||||
LockSkipWitness.recordAbandoned("collect-data:stale-finalize", MODULE_TYPE, taskId);
|
||||
return;
|
||||
}
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
@@ -674,6 +676,7 @@ public class CollectDataService {
|
||||
try (TaskDistributedLockService.LockHandle lock =
|
||||
taskDistributedLockService.acquire(MODULE_TYPE, taskId, 0L)) {
|
||||
if (lock == null) {
|
||||
LockSkipWitness.recordAbandoned("collect-data:no-upload-stale-finalize", MODULE_TYPE, taskId);
|
||||
return;
|
||||
}
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.dedupe.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
@@ -78,8 +79,8 @@ public class DedupeTotalDataController {
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = DedupeTotalDataPageVo.class)))
|
||||
})
|
||||
public ApiResponse<DedupeTotalDataPageVo> page(
|
||||
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = "15") Long pageSize,
|
||||
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = PageDefaults.USER_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "数据值模糊搜索关键字") @RequestParam(name = "keyword", required = false) String keyword,
|
||||
@Parameter(description = "用户名模糊搜索关键字") @RequestParam(name = "username", required = false) String username,
|
||||
@Parameter(description = "开始日期(包含)")
|
||||
|
||||
+5
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.deletebrand.service;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import com.nanri.aiimage.config.DeleteBrandProgressProperties;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskService;
|
||||
import com.nanri.aiimage.modules.brand.service.BrandTaskService;
|
||||
@@ -236,6 +237,8 @@ public class DeleteBrandStaleTaskService {
|
||||
|
||||
TaskDistributedLockService.LockHandle taskLockHandle = acquireTaskLock(MODULE_TYPE_DELETE_BRAND, task.getId());
|
||||
if (taskLockHandle == null) {
|
||||
LockSkipWitness.recordSkip("delete-brand:stale-heartbeat-scan",
|
||||
MODULE_TYPE_DELETE_BRAND, task.getId());
|
||||
continue;
|
||||
}
|
||||
boolean finalizeThrew;
|
||||
@@ -947,6 +950,8 @@ public class DeleteBrandStaleTaskService {
|
||||
for (FileTaskEntity task : runningTasks) {
|
||||
TaskDistributedLockService.LockHandle taskLockHandle = acquireTaskLock(MODULE_TYPE_DELETE_BRAND, task.getId());
|
||||
if (taskLockHandle == null) {
|
||||
LockSkipWitness.recordSkip("delete-brand:partial-result-scan",
|
||||
MODULE_TYPE_DELETE_BRAND, task.getId());
|
||||
continue;
|
||||
}
|
||||
try (taskLockHandle) {
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.devicelog.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
@@ -66,8 +67,8 @@ public class AdminDeviceLogController {
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "结束日期(含)") @RequestParam(required = false)
|
||||
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
|
||||
@RequestParam(defaultValue = "1") Long page,
|
||||
@RequestParam(defaultValue = "20") Long pageSize,
|
||||
@RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@RequestParam(defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "公司 ID(超管 tab;不传=不筛)")
|
||||
@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
AdminUserEntity operator = requireSuperAdmin(request);
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.imagehistory.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
@@ -34,8 +35,8 @@ public class ImageHistoryController {
|
||||
@GetMapping("/history")
|
||||
@Operation(summary = "分页查询所有用户生成历史")
|
||||
public ApiResponse<ImageHistoryListVo> listHistory(HttpServletRequest request,
|
||||
@RequestParam(required = false, defaultValue = "1") Integer page,
|
||||
@RequestParam(name = "page_size", required = false, defaultValue = "15") Integer pageSize,
|
||||
@RequestParam(required = false, defaultValue = PageDefaults.FIRST_PAGE) Integer page,
|
||||
@RequestParam(name = "page_size", required = false, defaultValue = PageDefaults.USER_LIST_PAGE_SIZE) Integer pageSize,
|
||||
@RequestParam(name = "user_id", required = false) Long userId,
|
||||
@RequestParam(name = "time_start", required = false) String timeStart,
|
||||
@RequestParam(name = "time_end", required = false) String timeEnd,
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.imagevideo.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
@@ -78,8 +79,8 @@ public class AdminImageVideoTaskController {
|
||||
@GetMapping
|
||||
@Operation(summary = "分页查询图生视频任务", description = "管理端按用户/任务状态/提交时间等条件分页查询近 3 天的工作流任务")
|
||||
public ApiResponse<Map<String, Object>> page(
|
||||
@RequestParam(defaultValue = "1") Integer page,
|
||||
@RequestParam(name = "page_size", defaultValue = "20") Integer pageSize,
|
||||
@RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Integer page,
|
||||
@RequestParam(name = "page_size", defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Integer pageSize,
|
||||
@RequestParam(name = "user_id", required = false) Long userId,
|
||||
@RequestParam(required = false) String username,
|
||||
@RequestParam(required = false) String status,
|
||||
|
||||
+2
@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import com.nanri.aiimage.config.ImageVideoProperties;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
@@ -115,6 +116,7 @@ public class ImageVideoArchiveService {
|
||||
DistributedJobLockService.LockHandle jobLock = distributedJobLockService.tryLock(
|
||||
"image-video:retention-cleanup", java.time.Duration.ofMinutes(20));
|
||||
if (jobLock == null) {
|
||||
LockSkipWitness.abandoned("image-video:retention-cleanup");
|
||||
return;
|
||||
}
|
||||
try (jobLock) {
|
||||
|
||||
+5
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
|
||||
import com.nanri.aiimage.config.InstanceMetadata;
|
||||
@@ -141,6 +142,7 @@ public class ImageVideoAsyncTaskService {
|
||||
DistributedJobLockService.LockHandle jobLock =
|
||||
distributedJobLockService.tryLock("image-video:dispatch", java.time.Duration.ofSeconds(5));
|
||||
if (jobLock == null) {
|
||||
LockSkipWitness.abandoned("image-video:dispatch");
|
||||
return;
|
||||
}
|
||||
try (jobLock) {
|
||||
@@ -163,6 +165,7 @@ public class ImageVideoAsyncTaskService {
|
||||
DistributedJobLockService.LockHandle jobLock =
|
||||
distributedJobLockService.tryLock("image-video:poll", java.time.Duration.ofSeconds(30));
|
||||
if (jobLock == null) {
|
||||
LockSkipWitness.abandoned("image-video:poll");
|
||||
return;
|
||||
}
|
||||
try (jobLock) {
|
||||
@@ -208,6 +211,7 @@ public class ImageVideoAsyncTaskService {
|
||||
DistributedJobLockService.LockHandle jobLock =
|
||||
distributedJobLockService.tryLock("image-video:owner-takeover", java.time.Duration.ofSeconds(30));
|
||||
if (jobLock == null) {
|
||||
LockSkipWitness.abandoned("image-video:owner-takeover");
|
||||
return;
|
||||
}
|
||||
try (jobLock) {
|
||||
@@ -244,6 +248,7 @@ public class ImageVideoAsyncTaskService {
|
||||
DistributedJobLockService.LockHandle jobLock =
|
||||
distributedJobLockService.tryLock("image-video:failed-task-cleanup", java.time.Duration.ofSeconds(120));
|
||||
if (jobLock == null) {
|
||||
LockSkipWitness.abandoned("image-video:failed-task-cleanup");
|
||||
return;
|
||||
}
|
||||
try (jobLock) {
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.invalidasin.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
@@ -57,8 +58,8 @@ public class InvalidAsinDataController {
|
||||
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = InvalidAsinDataPageVo.class)))
|
||||
})
|
||||
public ApiResponse<InvalidAsinDataPageVo> page(
|
||||
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = "15") Long pageSize,
|
||||
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = PageDefaults.USER_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "模糊搜索关键字") @RequestParam(name = "keyword", required = false) String keyword,
|
||||
@Parameter(description = "ASIN 模糊搜索") @RequestParam(name = "data_value", required = false) String dataValue,
|
||||
@Parameter(description = "品牌模糊搜索") @RequestParam(name = "brand", required = false) String brand,
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.notification.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.notification.model.dto.NotificationPageQuery;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
|
||||
@@ -49,8 +50,8 @@ public class AdminNotificationController {
|
||||
+ "startDate/endDate 为年月日闭区间。")
|
||||
public ApiResponse<NotificationPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = "20") Long pageSize,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "只看未读") @RequestParam(required = false, defaultValue = "false") Boolean onlyUnread,
|
||||
@Parameter(description = "关键字(标题/内容)") @RequestParam(required = false) String keyword,
|
||||
@Parameter(description = "类型大类:system_error/task_error/config_error/system_notice")
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.notification.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.notification.model.dto.NotificationPageQuery;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
|
||||
@@ -49,8 +50,8 @@ public class NotificationController {
|
||||
+ "startDate/endDate 为年月日闭区间。")
|
||||
public ApiResponse<NotificationPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = "20") Long pageSize,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "只看未读") @RequestParam(required = false, defaultValue = "false") Boolean onlyUnread,
|
||||
@Parameter(description = "关键字(标题/内容)") @RequestParam(required = false) String keyword,
|
||||
@Parameter(description = "类型大类:system_error/task_error/config_error/system_notice")
|
||||
|
||||
+2
-1
@@ -105,7 +105,8 @@ public class PatrolDeleteTaskService {
|
||||
validateUserId(userId);
|
||||
ProductRiskDashboardVo vo = new ProductRiskDashboardVo();
|
||||
vo.setCandidateCount(patrolDeleteResolveService.countCandidates(userId));
|
||||
vo.setProcessedTaskCount(countTasks(userId, List.of("SUCCESS", "FAILED")));
|
||||
vo.setProcessedTaskCount(countTasks(userId,
|
||||
com.nanri.aiimage.common.task.TaskStatuses.FileTask.FINISHED_ORDERED));
|
||||
vo.setSuccessTaskCount(countTasks(userId, List.of("SUCCESS")));
|
||||
vo.setFailedTaskCount(countTasks(userId, List.of("FAILED")));
|
||||
return vo;
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.pricetrack.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackCandidateAddRequest;
|
||||
import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackCountryPreferenceSaveRequest;
|
||||
@@ -142,9 +143,9 @@ public class PriceTrackController {
|
||||
@Parameter(description = "任务编号", required = true, example = "200")
|
||||
@PathVariable Long taskId,
|
||||
@Parameter(description = "页码,从 1 开始", example = "1")
|
||||
@RequestParam(value = "page", defaultValue = "1") Integer page,
|
||||
@RequestParam(value = "page", defaultValue = PageDefaults.FIRST_PAGE) Integer page,
|
||||
@Parameter(description = "每页条数,默认 1000,最大 2000", example = "1000")
|
||||
@RequestParam(value = "page_size", defaultValue = "1000") Integer pageSize,
|
||||
@RequestParam(value = "page_size", defaultValue = PageDefaults.FULL_EXPORT_PAGE_SIZE) Integer pageSize,
|
||||
@Parameter(description = "店铺名称过滤条件,可重复传入,也可用英文逗号分隔;仅在任务关联店铺范围内生效", example = "测试店铺A")
|
||||
@RequestParam(value = "shop_name", required = false) List<String> shopNames,
|
||||
@Parameter(description = "国家代码过滤条件,可重复传入,也可用英文逗号分隔;仅在任务国家范围内生效", example = "DE")
|
||||
|
||||
+2
-1
@@ -65,7 +65,8 @@ public class PriceTrackLoopRunStaleService {
|
||||
private static final String STATUS_STOPPED = "STOPPED";
|
||||
|
||||
/** 子任务终态集合,与 PriceTrackLoopRunService.isChildTaskTerminal 口径一致。 */
|
||||
private static final Set<String> CHILD_TERMINAL_STATUSES = Set.of("SUCCESS", "FAILED", "STOPPED");
|
||||
private static final Set<String> CHILD_TERMINAL_STATUSES =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.LoopRun.TERMINAL;
|
||||
|
||||
/** 单轮最多扫描的轮次数,其余留给下一轮(每 2 分钟一次),避免一次扫太多拖慢巡检。 */
|
||||
static final int MAX_LOOP_RUNS_PER_SCAN = 200;
|
||||
|
||||
+2
-1
@@ -142,7 +142,8 @@ public class PriceTrackTaskService {
|
||||
Long processed = fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
|
||||
.eq(FileTaskEntity::getUserId, userId)
|
||||
.in(FileTaskEntity::getStatus, List.of("SUCCESS", "FAILED")));
|
||||
.in(FileTaskEntity::getStatus,
|
||||
com.nanri.aiimage.common.task.TaskStatuses.FileTask.FINISHED_ORDERED));
|
||||
Long success = fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
|
||||
.eq(FileTaskEntity::getUserId, userId)
|
||||
|
||||
+5
-4
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.productcategory.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.util.DownloadHeaderUtil;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
@@ -61,8 +62,8 @@ public class ProductCategoryController {
|
||||
public ApiResponse<ProductCategoryListVo> children(
|
||||
HttpServletRequest request,
|
||||
@RequestParam(value = "parent_id", required = false) Long parentId,
|
||||
@RequestParam(value = "page", defaultValue = "1") Long page,
|
||||
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize) {
|
||||
@RequestParam(value = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@RequestParam(value = "page_size", defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Long pageSize) {
|
||||
requireOperator(request);
|
||||
return ApiResponse.success(productCategoryService.children(parentId, page, pageSize));
|
||||
}
|
||||
@@ -72,8 +73,8 @@ public class ProductCategoryController {
|
||||
public ApiResponse<ProductCategoryListVo> search(
|
||||
HttpServletRequest request,
|
||||
@RequestParam(value = "keyword", required = false) String keyword,
|
||||
@RequestParam(value = "page", defaultValue = "1") Long page,
|
||||
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize) {
|
||||
@RequestParam(value = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@RequestParam(value = "page_size", defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Long pageSize) {
|
||||
requireOperator(request);
|
||||
return ApiResponse.success(productCategoryService.search(keyword, page, pageSize));
|
||||
}
|
||||
|
||||
+2
-1
@@ -128,7 +128,8 @@ public class ProductRiskTaskService {
|
||||
Long processed = fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
|
||||
.eq(FileTaskEntity::getUserId, userId)
|
||||
.in(FileTaskEntity::getStatus, List.of("SUCCESS", "FAILED")));
|
||||
.in(FileTaskEntity::getStatus,
|
||||
com.nanri.aiimage.common.task.TaskStatuses.FileTask.FINISHED_ORDERED));
|
||||
Long success = fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
|
||||
.eq(FileTaskEntity::getUserId, userId)
|
||||
|
||||
+4
-3
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.publish.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.publish.model.dto.PublishParseRequest;
|
||||
import com.nanri.aiimage.modules.publish.model.dto.PublishSubmitResultRequest;
|
||||
@@ -94,9 +95,9 @@ public class PublishController {
|
||||
@Parameter(description = "任务内文件 ID", required = true, example = "9101")
|
||||
@RequestParam("file_id") Long fileId,
|
||||
@Parameter(description = "页码,从 1 开始", example = "1")
|
||||
@RequestParam(value = "page", defaultValue = "1") Integer page,
|
||||
@RequestParam(value = "page", defaultValue = PageDefaults.FIRST_PAGE) Integer page,
|
||||
@Parameter(description = "每页条数,默认 50,最大 200", example = "50")
|
||||
@RequestParam(value = "page_size", defaultValue = "50") Integer pageSize,
|
||||
@RequestParam(value = "page_size", defaultValue = PageDefaults.TASK_LIST_PAGE_SIZE) Integer pageSize,
|
||||
HttpServletRequest httpRequest) {
|
||||
return ApiResponse.success(publishTaskService.getItemsPage(taskId,
|
||||
adminAuthSupport.resolveOwnershipUserId(httpRequest, userId), fileId, page, pageSize));
|
||||
@@ -164,7 +165,7 @@ public class PublishController {
|
||||
@Parameter(description = "当前登录用户 ID;服务端按会话身份校验,与登录账号不一致即拒绝", required = true, example = "1")
|
||||
@RequestParam("user_id") Long userId,
|
||||
@Parameter(description = "返回数量上限,默认 50,最大 100", example = "50")
|
||||
@RequestParam(value = "limit", defaultValue = "50") Integer limit,
|
||||
@RequestParam(value = "limit", defaultValue = PageDefaults.DEFAULT_RESULT_LIMIT) Integer limit,
|
||||
HttpServletRequest httpRequest) {
|
||||
// 上限钳制(2026-09):文档写"最多返回 100 条"但此前无实际校验
|
||||
int safeLimit = limit == null ? 100 : Math.min(Math.max(1, limit), 100);
|
||||
|
||||
+4
-1
@@ -12,6 +12,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import com.nanri.aiimage.config.InstanceMetadata;
|
||||
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
@@ -103,7 +104,7 @@ public class PublishTaskService {
|
||||
* PENDING/RUNNING 绝不在此列;PUBLISH 实际只会写 SUCCESS/FAILED,取消态是无害的超集。
|
||||
*/
|
||||
private static final Set<String> RETENTION_TERMINAL_STATUSES =
|
||||
Set.of(STATUS_SUCCESS, STATUS_FAILED, "CANCELLED", "CANCELED");
|
||||
com.nanri.aiimage.common.task.TaskStatuses.FileTask.TERMINAL;
|
||||
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
private final LocalFileStorageService localFileStorageService;
|
||||
@@ -520,6 +521,7 @@ public class PublishTaskService {
|
||||
try (TaskDistributedLockService.LockHandle lock =
|
||||
taskDistributedLockService.acquire(MODULE_TYPE, candidate.getId(), 0L)) {
|
||||
if (lock == null) {
|
||||
LockSkipWitness.recordSkip("publish:stale-heartbeat-scan", MODULE_TYPE, candidate.getId());
|
||||
continue;
|
||||
}
|
||||
transactionTemplate.executeWithoutResult(status -> failStaleTaskLocked(candidate.getId(), threshold));
|
||||
@@ -967,6 +969,7 @@ public class PublishTaskService {
|
||||
try (TaskDistributedLockService.LockHandle lock =
|
||||
taskDistributedLockService.acquire(MODULE_TYPE, candidate.getId(), 0L)) {
|
||||
if (lock == null) {
|
||||
LockSkipWitness.recordAbandoned("publish:no-upload-stale-finalize", MODULE_TYPE, candidate.getId());
|
||||
return;
|
||||
}
|
||||
transactionTemplate.executeWithoutResult(status -> failStaleTaskLockedInternal(
|
||||
|
||||
+2
-1
@@ -116,7 +116,8 @@ public class QueryAsinTaskService {
|
||||
validateUserId(userId);
|
||||
ProductRiskDashboardVo vo = new ProductRiskDashboardVo();
|
||||
vo.setCandidateCount(queryAsinResolveService.countCandidates(userId));
|
||||
vo.setProcessedTaskCount(countTasks(userId, List.of("SUCCESS", "FAILED")));
|
||||
vo.setProcessedTaskCount(countTasks(userId,
|
||||
com.nanri.aiimage.common.task.TaskStatuses.FileTask.FINISHED_ORDERED));
|
||||
vo.setSuccessTaskCount(countTasks(userId, List.of("SUCCESS")));
|
||||
vo.setFailedTaskCount(countTasks(userId, List.of("FAILED")));
|
||||
return vo;
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.shopdatacrawl.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
|
||||
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCountryPreferenceSaveRequest;
|
||||
@@ -158,9 +159,9 @@ public class ShopDataCrawlTaskController {
|
||||
in = ParameterIn.QUERY, example = "1")
|
||||
@RequestParam("user_id") Long userId,
|
||||
@Parameter(name = "page", description = "页号,从 1 开始", in = ParameterIn.QUERY, example = "1")
|
||||
@RequestParam(value = "page", defaultValue = "1") int page,
|
||||
@RequestParam(value = "page", defaultValue = PageDefaults.FIRST_PAGE) int page,
|
||||
@Parameter(name = "limit", description = "每页条数,最大 100;默认 100 与旧版返回最近 100 条的行为一致", in = ParameterIn.QUERY, example = "20")
|
||||
@RequestParam(value = "limit", defaultValue = "100") int limit,
|
||||
@RequestParam(value = "limit", defaultValue = PageDefaults.ADMIN_SCAN_LIMIT) int limit,
|
||||
HttpServletRequest httpRequest) {
|
||||
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
|
||||
return ApiResponse.success(taskService.listHistory(userId, page, limit));
|
||||
|
||||
+2
-1
@@ -345,7 +345,8 @@ public class ShopDataCrawlTaskService {
|
||||
validateUserId(userId);
|
||||
ProductRiskDashboardVo vo = new ProductRiskDashboardVo();
|
||||
vo.setCandidateCount(shopDataCrawlResolveService.countCandidates(userId));
|
||||
vo.setProcessedTaskCount(countTasks(userId, List.of("SUCCESS", "FAILED")));
|
||||
vo.setProcessedTaskCount(countTasks(userId,
|
||||
com.nanri.aiimage.common.task.TaskStatuses.FileTask.FINISHED_ORDERED));
|
||||
vo.setSuccessTaskCount(countTasks(userId, List.of("SUCCESS")));
|
||||
vo.setFailedTaskCount(countTasks(userId, List.of("FAILED")));
|
||||
return vo;
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.shopkey.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.util.DownloadHeaderUtil;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
@@ -60,8 +61,8 @@ public class QueryAsinController {
|
||||
@Operation(summary = "分页查询 ASIN", description = "company_id 只收窄可见集、不放大,跨公司查看仅超管")
|
||||
public ApiResponse<QueryAsinPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = "15") Long pageSize,
|
||||
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = PageDefaults.USER_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "分组ID") @RequestParam(name = "group_id", required = false) Long groupId,
|
||||
@Parameter(description = "店铺名") @RequestParam(name = "shop_name", required = false) String shopName,
|
||||
@Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin,
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.shopkey.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.service.DataReadScope;
|
||||
@@ -58,8 +59,8 @@ public class ShopKeyController {
|
||||
})
|
||||
public ApiResponse<ShopKeyPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = PageDefaults.USER_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "按公司筛选(仅超管生效;非超管一律按会话公司裁剪)")
|
||||
@RequestParam(name = "company_id", required = false) Long companyId,
|
||||
@Parameter(description = "备注名 / 紫鸟账号 模糊词")
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.shopkey.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
@@ -79,8 +80,8 @@ public class ShopManageController {
|
||||
})
|
||||
public ApiResponse<ShopManagePageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = PageDefaults.USER_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "分组 ID") @RequestParam(required = false) Long groupId,
|
||||
@Parameter(description = "店铺名称") @RequestParam(required = false) String shopName,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.shopkey.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.util.DownloadHeaderUtil;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
@@ -60,8 +61,8 @@ public class SkipPriceAsinController {
|
||||
@Operation(summary = "分页查询跳过跟价 ASIN", description = "支持按分组、店铺名、ASIN 和当前操作人可见范围筛选。")
|
||||
public ApiResponse<SkipPriceAsinPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = "1") Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = "15") Long pageSize,
|
||||
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = PageDefaults.USER_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "分组 ID") @RequestParam(name = "group_id", required = false) Long groupId,
|
||||
@Parameter(description = "店铺名称") @RequestParam(name = "shop_name", required = false) String shopName,
|
||||
@Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin,
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.shopmatch.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
|
||||
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCountryPreferenceSaveRequest;
|
||||
@@ -186,9 +187,9 @@ public class ShopMatchController {
|
||||
public ApiResponse<ShopMatchSkipAsinPageVo> getTaskSkipAsinsPaginated(
|
||||
@Parameter(description = "任务编号", required = true, example = "200") @PathVariable Long taskId,
|
||||
@Parameter(description = "页码,从 1 开始", example = "1")
|
||||
@RequestParam(value = "page", defaultValue = "1") Integer page,
|
||||
@RequestParam(value = "page", defaultValue = PageDefaults.FIRST_PAGE) Integer page,
|
||||
@Parameter(description = "每页条数,默认 1000,最大 2000", example = "1000")
|
||||
@RequestParam(value = "page_size", defaultValue = "1000") Integer pageSize,
|
||||
@RequestParam(value = "page_size", defaultValue = PageDefaults.FULL_EXPORT_PAGE_SIZE) Integer pageSize,
|
||||
@Parameter(description = "店铺名称过滤条件,可重复传入,也可用英文逗号分隔", example = "测试店铺A")
|
||||
@RequestParam(value = "shop_name", required = false) List<String> shopNames,
|
||||
@Parameter(description = "国家代码过滤条件,可重复传入,也可用英文逗号分隔", example = "DE")
|
||||
|
||||
+2
-1
@@ -204,7 +204,8 @@ public class ShopMatchTaskService {
|
||||
Long processed = fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
|
||||
.eq(FileTaskEntity::getUserId, userId)
|
||||
.in(FileTaskEntity::getStatus, List.of("SUCCESS", "FAILED")));
|
||||
.in(FileTaskEntity::getStatus,
|
||||
com.nanri.aiimage.common.task.TaskStatuses.FileTask.FINISHED_ORDERED));
|
||||
Long success = fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
|
||||
.eq(FileTaskEntity::getUserId, userId)
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.similarasin.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinFilterConditionAddRequest;
|
||||
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinParseRequest;
|
||||
@@ -129,7 +130,7 @@ public class SimilarAsinController {
|
||||
@Parameter(description = "当前用户 ID", required = true, example = "1")
|
||||
@RequestParam("user_id") Long userId,
|
||||
@Parameter(description = "历史记录条数,默认 50,最大 100", example = "50")
|
||||
@RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit,
|
||||
@RequestParam(value = "limit", required = false, defaultValue = PageDefaults.DEFAULT_RESULT_LIMIT) Integer limit,
|
||||
HttpServletRequest httpRequest) {
|
||||
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
|
||||
return ApiResponse.success(service.history(userId, limit));
|
||||
|
||||
+7
@@ -20,4 +20,11 @@ public class SimilarAsinTaskLightVo {
|
||||
private Boolean fileReady;
|
||||
@Schema(description = "最后更新时间,ISO 本地时间字符串。", example = "2026-04-26T10:05:00")
|
||||
private String updatedAt;
|
||||
/** 客户端心跳上报的执行进度,三者同生同灭;无进度信息时全为 null(前端不画进度轨)。 */
|
||||
@Schema(description = "已处理数(客户端心跳上报;无进度信息时为 null)。", example = "12")
|
||||
private Integer progressCurrent;
|
||||
@Schema(description = "总处理单位数(相似ASIN 为待检测 ASIN 行数)。", example = "50")
|
||||
private Integer progressTotal;
|
||||
@Schema(description = "位置标签(中文,按「,」整段截短;无则为 null)。", example = "ASIN B0ABCD1234(12/50)")
|
||||
private String progressLabel;
|
||||
}
|
||||
|
||||
+34
@@ -11,6 +11,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.common.util.FailedStatusRowFilter;
|
||||
import com.nanri.aiimage.common.util.StaleTaskDeathReason;
|
||||
@@ -627,6 +629,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
Map<Long, FileTaskEntity> taskMap = new LinkedHashMap<>();
|
||||
for (FileTaskEntity task : fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.select(FileTaskEntity::getId,
|
||||
FileTaskEntity::getModuleType,
|
||||
FileTaskEntity::getStatus,
|
||||
FileTaskEntity::getUpdatedAt)
|
||||
.in(FileTaskEntity::getId, normalizedIds))) {
|
||||
@@ -635,6 +638,15 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
}
|
||||
}
|
||||
Map<Long, TaskFileJobEntity> jobMap = taskFileJobService.findAssembleJobsByTaskIds(MODULE_TYPE, new ArrayList<>(taskMap.keySet()));
|
||||
List<Long> activeTaskIds = new ArrayList<>();
|
||||
for (Long taskId : normalizedIds) {
|
||||
FileTaskEntity active = taskMap.get(taskId);
|
||||
if (active != null && !TaskStatuses.FileTask.TERMINAL.contains(active.getStatus())) {
|
||||
activeTaskIds.add(taskId);
|
||||
}
|
||||
}
|
||||
Map<Long, TaskHeartbeatPositionService.Position> positions =
|
||||
taskHeartbeatPositionService.readDrawablePositions(activeTaskIds);
|
||||
for (Long taskId : normalizedIds) {
|
||||
FileTaskEntity task = taskMap.get(taskId);
|
||||
if (task == null) {
|
||||
@@ -652,11 +664,28 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
item.setFileStatus(job == null ? null : job.getStatus());
|
||||
item.setFileError(job == null ? null : job.getErrorMessage());
|
||||
item.setUpdatedAt(fmt(task.getUpdatedAt()));
|
||||
fillProgressFromHeartbeat(item, positions.get(taskId));
|
||||
vo.getItems().add(item);
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 透传客户端心跳上报的处理位置,让相似ASIN 的 light 轮询也能画进度条。
|
||||
*
|
||||
* <p>口径与共享 {@code TaskProgressLightAssembler} 一致:终态任务不读、读不到或分母非正数时
|
||||
* 三个字段一起留 null,由前端决定「不画」。(相似ASIN 的私有 LightVo 是历史遗留的第二份实现,
|
||||
* 两边行为必须同步,否则这一模块的进度条会跟着轮询闪烁。)
|
||||
*/
|
||||
private void fillProgressFromHeartbeat(SimilarAsinTaskLightVo item, TaskHeartbeatPositionService.Position drawable) {
|
||||
if (drawable == null) {
|
||||
return;
|
||||
}
|
||||
item.setProgressCurrent(drawable.current());
|
||||
item.setProgressTotal(drawable.total());
|
||||
item.setProgressLabel(drawable.label());
|
||||
}
|
||||
|
||||
public SimilarAsinTaskBatchVo progressBatch(List<Long> taskIds) {
|
||||
SimilarAsinTaskBatchVo vo = new SimilarAsinTaskBatchVo();
|
||||
List<Long> requestedIds = taskIds == null ? List.of() : taskIds.stream()
|
||||
@@ -877,6 +906,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
TaskDistributedLockService.LockHandle taskLockHandle = ownershipSupport().acquireTaskLock(task.getId(), 0L);
|
||||
if (taskLockHandle == null) {
|
||||
// 锁被 owner 实例/文件任务 worker 占用说明其仍活跃,静默跳过等下一轮(2 分钟后再判)
|
||||
LockSkipWitness.recordSkip("similar-asin:heartbeat-stale-scan", MODULE_TYPE, task.getId());
|
||||
continue;
|
||||
}
|
||||
try (taskLockHandle) {
|
||||
@@ -892,6 +922,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
}
|
||||
TaskDistributedLockService.LockHandle taskLockHandle = ownershipSupport().acquireTaskLock(taskId, 0L);
|
||||
if (taskLockHandle == null) {
|
||||
LockSkipWitness.recordAbandoned("similar-asin:debug-finalize-stale", MODULE_TYPE, taskId);
|
||||
return;
|
||||
}
|
||||
try (taskLockHandle) {
|
||||
@@ -1023,6 +1054,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
TaskDistributedLockService.LockHandle neverReportedLock =
|
||||
ownershipSupport().acquireTaskLock(task.getId(), 0L);
|
||||
if (neverReportedLock == null) {
|
||||
LockSkipWitness.recordSkip("similar-asin:never-reported-stale-scan", MODULE_TYPE, task.getId());
|
||||
continue;
|
||||
}
|
||||
try (neverReportedLock) {
|
||||
@@ -1049,6 +1081,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
}
|
||||
TaskDistributedLockService.LockHandle taskLockHandle = ownershipSupport().acquireTaskLock(task.getId(), 0L);
|
||||
if (taskLockHandle == null) {
|
||||
LockSkipWitness.recordSkip("similar-asin:no-result-shard-stale-scan", MODULE_TYPE, task.getId());
|
||||
continue;
|
||||
}
|
||||
try (taskLockHandle) {
|
||||
@@ -1488,6 +1521,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
DistributedJobLockService.LockHandle lockHandle =
|
||||
distributedJobLockService.tryLock("similar-asin:llm-poll", Duration.ofMinutes(1));
|
||||
if (lockHandle == null) {
|
||||
LockSkipWitness.abandoned("similar-asin:llm-poll");
|
||||
return;
|
||||
}
|
||||
try (lockHandle) {
|
||||
|
||||
+5
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinParsedPayloadDto;
|
||||
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinResultGroupDto;
|
||||
@@ -984,6 +985,7 @@ public class SimilarAsinPipelineSupport {
|
||||
taskQueueExecutor.execute(() -> {
|
||||
TaskDistributedLockService.LockHandle taskLockHandle = ownershipSupport.acquireTaskLock(taskId, 0L);
|
||||
if (taskLockHandle == null) {
|
||||
LockSkipWitness.recordAbandoned("similar-asin:direct-llm-poll-fallback", MODULE_TYPE, taskId);
|
||||
return;
|
||||
}
|
||||
try (taskLockHandle) {
|
||||
@@ -1014,6 +1016,7 @@ public class SimilarAsinPipelineSupport {
|
||||
}
|
||||
TaskDistributedLockService.LockHandle taskLockHandle = ownershipSupport.acquireTaskLock(taskId, 0L);
|
||||
if (taskLockHandle == null) {
|
||||
LockSkipWitness.recordAbandoned("similar-asin:resubmit-pending-llm-states", MODULE_TYPE, taskId);
|
||||
return;
|
||||
}
|
||||
try (taskLockHandle) {
|
||||
@@ -1484,6 +1487,7 @@ public class SimilarAsinPipelineSupport {
|
||||
}
|
||||
TaskDistributedLockService.LockHandle lockHandle = ownershipSupport.acquireTaskLock(taskId, 0L);
|
||||
if (lockHandle == null) {
|
||||
LockSkipWitness.recordAbandoned("similar-asin:maybe-finalize-llm-job", MODULE_TYPE, taskId);
|
||||
return;
|
||||
}
|
||||
try (lockHandle) {
|
||||
@@ -1509,6 +1513,7 @@ public class SimilarAsinPipelineSupport {
|
||||
DistributedJobLockService.LockHandle lockHandle =
|
||||
distributedJobLockService.tryLock("similar-asin:llm-finalize:" + taskId, Duration.ofMinutes(5));
|
||||
if (lockHandle == null) {
|
||||
LockSkipWitness.recordAbandoned("similar-asin:llm-finalize-job-lock", MODULE_TYPE, taskId);
|
||||
return;
|
||||
}
|
||||
try (lockHandle) {
|
||||
|
||||
+11
@@ -94,6 +94,17 @@ public final class SimilarAsinResultTextSupport {
|
||||
return !normalized.isBlank() && !isTechnicalLlmFailure(normalized);
|
||||
}
|
||||
|
||||
/**
|
||||
* 交付口径:结果表真正给用户的两个判定列(相似度、是否同款)都得有可用文本,才算这行给出了结论。
|
||||
* 与 {@link #hasResolvedLlmFields} 的区别是后者是「十一个字段任一可用」——只填上 category 或 status
|
||||
* 的行会被读成「已经检测」,而它在表格里两列都是空的。这条先只做度量入口,不改既有行为。
|
||||
*/
|
||||
public static boolean hasDeliverableResult(SimilarAsinResultRowDto row) {
|
||||
return row != null
|
||||
&& hasUsableLlmField(row.getSimilarity())
|
||||
&& hasUsableLlmField(row.getIsConform());
|
||||
}
|
||||
|
||||
public static boolean hasResolvedLlmFields(SimilarAsinResultRowDto row) {
|
||||
if (row == null) {
|
||||
return false;
|
||||
|
||||
+20
-5
@@ -189,11 +189,16 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
List.of("不符合"),
|
||||
"[similar-asin] taskId=" + task.getId()
|
||||
);
|
||||
long undeliveredRows = captured.rows().stream()
|
||||
.map(row -> SimilarAsinChunkMergeSupport.findResultRow(row, sourceResultMap))
|
||||
.filter(java.util.Objects::nonNull)
|
||||
.filter(resultRow -> !SimilarAsinResultTextSupport.hasDeliverableResult(resultRow))
|
||||
.count();
|
||||
writeResultWorkbook(xlsx, captured.rows(), sourceResultMap, taskImageCache, imageSpool);
|
||||
ensureResultAssemblyNotInterrupted();
|
||||
return new SourceResultWorkbook(
|
||||
xlsx, filename, captured.rows().size(), persistedRows,
|
||||
sourceResultMap.size(), resolvedRows, conformPropagated);
|
||||
sourceResultMap.size(), resolvedRows, conformPropagated, undeliveredRows);
|
||||
}));
|
||||
}
|
||||
try {
|
||||
@@ -235,9 +240,18 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
int conformPropagated = workbooks.stream()
|
||||
.mapToInt(SourceResultWorkbook::conformPropagated)
|
||||
.sum();
|
||||
log.info("[similar-asin] bounded assemble workbook taskId={} parsedRows={} persistedRows={} resultRows={} resolvedRows={} propagated={} sources={} costMs={}",
|
||||
long undeliveredRows = workbooks.stream()
|
||||
.mapToLong(SourceResultWorkbook::undeliveredRows)
|
||||
.sum();
|
||||
if (undeliveredRows > 0) {
|
||||
// 交付行账:货源这一面还没有覆盖率闸,先把「表格里两列空着的行」数出来并报警,
|
||||
// 有了真实分布才谈得上定阈值(不拿别的模块的数字当这里的基线)
|
||||
log.warn("[similar-asin] 交付行账不完整 taskId={} resultRows={} undeliveredRows={} sources={}",
|
||||
task.getId(), resultRows, undeliveredRows, sourceRows.size());
|
||||
}
|
||||
log.info("[similar-asin] bounded assemble workbook taskId={} parsedRows={} persistedRows={} resultRows={} resolvedRows={} propagated={} undeliveredRows={} sources={} costMs={}",
|
||||
task.getId(), parsedRows.size(), persistedResultRows, resultRows,
|
||||
resolvedRows, conformPropagated, sourceRows.size(),
|
||||
resolvedRows, conformPropagated, undeliveredRows, sourceRows.size(),
|
||||
System.currentTimeMillis() - assembleStart);
|
||||
if (resultRows == 0) {
|
||||
String failureSummary = chunkPayloadSupport.collectChunkReadFailureSummary(task.getId());
|
||||
@@ -1084,9 +1098,10 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
int persistedRows,
|
||||
int resultRows,
|
||||
long resolvedRows,
|
||||
int conformPropagated) {
|
||||
int conformPropagated,
|
||||
long undeliveredRows) {
|
||||
private SourceResultWorkbook(File file, String filename, int rowCount) {
|
||||
this(file, filename, rowCount, 0, 0, 0L, 0);
|
||||
this(file, filename, rowCount, 0, 0, 0L, 0, 0L);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.task.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -30,7 +31,7 @@ public class TaskFileJobController {
|
||||
@RequestParam(value = "status", required = false) String status,
|
||||
@RequestParam(value = "module_type", required = false) String moduleType,
|
||||
@RequestParam(value = "task_id", required = false) Long taskId,
|
||||
@RequestParam(value = "limit", defaultValue = "100") int limit) {
|
||||
@RequestParam(value = "limit", defaultValue = PageDefaults.ADMIN_SCAN_LIMIT) int limit) {
|
||||
// 上限钳制(2026-09):该运维端点此前对 limit 无校验
|
||||
return ApiResponse.success(taskFileJobService.listJobs(status, moduleType, taskId,
|
||||
Math.min(Math.max(1, limit), 1000)));
|
||||
@@ -47,7 +48,7 @@ public class TaskFileJobController {
|
||||
@Operation(summary = "手动扫描并复位卡住的 RUNNING Job")
|
||||
public ApiResponse<Map<String, Object>> resetStuck(
|
||||
@RequestParam(value = "timeout_minutes", defaultValue = "30") int timeoutMinutes,
|
||||
@RequestParam(value = "limit", defaultValue = "100") int limit) {
|
||||
@RequestParam(value = "limit", defaultValue = PageDefaults.ADMIN_SCAN_LIMIT) int limit) {
|
||||
int reset = taskFileJobService.resetStuckRunningJobs(timeoutMinutes, limit);
|
||||
return ApiResponse.success(Map.of("reset", reset));
|
||||
}
|
||||
|
||||
+4
@@ -42,4 +42,8 @@ public class TaskHeartbeatRequest {
|
||||
@Schema(description = "客户端归一化后的当前处理位置描述(如「店铺 张三(2/10),国家 德国(1/3)」),"
|
||||
+ "用于判死日志与排查;老客户端不传,服务端不得以位置为空作为判死依据", example = "店铺 魏振峰(2/10)")
|
||||
private String progressText;
|
||||
|
||||
@Schema(description = "客户端实际采用的进度粒度:asins/shops/countries/items/rows/units。"
|
||||
+ "units 表示 current/total 是「国家数×1000」的摊平当量,展示前要折算", example = "countries")
|
||||
private String progressGrain;
|
||||
}
|
||||
|
||||
+10
@@ -31,4 +31,14 @@ public class TaskProgressLightVo {
|
||||
*/
|
||||
@Schema(description = "结果行版本(毫秒),用于行数据按需拉取。", example = "1757788800000")
|
||||
private String rowsVersion;
|
||||
/**
|
||||
* 客户端心跳上报的执行进度。三者同生同灭:读不到位置就全为 null(前端据此不画进度轨),
|
||||
* 不会出现 progressTotal=0 配上 progressCurrent=0 那种「0% 空轨」。
|
||||
*/
|
||||
@Schema(description = "已处理数(客户端心跳上报;无进度信息时为 null)。", example = "12")
|
||||
private Integer progressCurrent;
|
||||
@Schema(description = "总处理单位数(粒度按模块而定:ASIN 行/店铺×国家/累计页)。", example = "50")
|
||||
private Integer progressTotal;
|
||||
@Schema(description = "位置标签(中文,按「,」整段截短;无则为 null)。", example = "国家 US(2/5)")
|
||||
private String progressLabel;
|
||||
}
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ public class CompletedTaskActiveJobInspector {
|
||||
|
||||
public ActiveJobReport inspectTerminalTasksWithActiveJobs(int limit) {
|
||||
List<FileTaskEntity> tasks = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.in(FileTaskEntity::getStatus, List.of("SUCCESS", "FAILED"))
|
||||
.in(FileTaskEntity::getStatus, com.nanri.aiimage.common.task.TaskStatuses.FileTask.FINISHED_ORDERED)
|
||||
.orderByAsc(FileTaskEntity::getUpdatedAt)
|
||||
.last("limit " + Math.max(1, Math.min(limit, 500))));
|
||||
if (tasks == null || tasks.isEmpty()) {
|
||||
|
||||
+2
@@ -7,6 +7,7 @@ import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.spi.ExpiredAccountTaskStopSpi;
|
||||
@@ -62,6 +63,7 @@ public class ExpiredAccountTaskStopService {
|
||||
public void stopTasksOfExpiredAccounts() {
|
||||
var lock = distributedJobLockService.tryLock("expired-account-task-stop", Duration.ofSeconds(55));
|
||||
if (lock == null) {
|
||||
LockSkipWitness.abandoned("expired-account-task-stop");
|
||||
return;
|
||||
}
|
||||
try (lock) {
|
||||
|
||||
+2
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.common.util.LockSkipWitness;
|
||||
import com.nanri.aiimage.config.InspectionProperties;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
@@ -59,6 +60,7 @@ public class InspectionSqlReportTask {
|
||||
return;
|
||||
}
|
||||
if (distributedJobLockService == null) {
|
||||
LockSkipWitness.abandoned("inspection:sql-report-lock-service-missing");
|
||||
return;
|
||||
}
|
||||
DistributedJobLockService.LockHandle lockHandle =
|
||||
|
||||
+2
-1
@@ -40,7 +40,8 @@ import java.util.Set;
|
||||
@Service
|
||||
public class ModuleHistoryCleanupService {
|
||||
|
||||
private static final Set<String> TERMINAL_STATUSES = Set.of("SUCCESS", "FAILED", "CANCELLED", "CANCELED");
|
||||
private static final Set<String> TERMINAL_STATUSES =
|
||||
com.nanri.aiimage.common.task.TaskStatuses.FileTask.TERMINAL;
|
||||
private static final Duration CLEANUP_LOCK_TTL = Duration.ofHours(2);
|
||||
private static final String COLLECT_DATA_MODULE_TYPE = "COLLECT_DATA";
|
||||
private static final int DEFAULT_BATCH_SIZE = 500;
|
||||
|
||||
+7
-7
@@ -152,7 +152,7 @@ public class TaskFileJobService {
|
||||
|
||||
public List<TaskFileJobEntity> listRunnableJobs(int limit) {
|
||||
return taskFileJobMapper.selectList(new LambdaQueryWrapper<TaskFileJobEntity>()
|
||||
.in(TaskFileJobEntity::getStatus, List.of("PENDING", "FAILED"))
|
||||
.in(TaskFileJobEntity::getStatus, com.nanri.aiimage.common.task.TaskStatuses.Job.RETRYABLE_ORDERED)
|
||||
.lt(TaskFileJobEntity::getRetryCount, MAX_RETRY_COUNT)
|
||||
.orderByAsc(TaskFileJobEntity::getUpdatedAt)
|
||||
.last("limit " + Math.max(1, Math.min(limit, 100))));
|
||||
@@ -178,7 +178,7 @@ public class TaskFileJobService {
|
||||
int safeLimit = Math.max(1, Math.min(limit, 100));
|
||||
|
||||
List<TaskFileJobEntity> ownerJobs = taskFileJobMapper.selectList(new LambdaQueryWrapper<TaskFileJobEntity>()
|
||||
.in(TaskFileJobEntity::getStatus, List.of("PENDING", "FAILED"))
|
||||
.in(TaskFileJobEntity::getStatus, com.nanri.aiimage.common.task.TaskStatuses.Job.RETRYABLE_ORDERED)
|
||||
.lt(TaskFileJobEntity::getRetryCount, MAX_RETRY_COUNT)
|
||||
.in(TaskFileJobEntity::getModuleType, List.of("APPEARANCE_PATENT", "SIMILAR_ASIN", "PUBLISH", "SHOP_DATA_CRAWL"))
|
||||
.eq(TaskFileJobEntity::getOwner, normalizedOwner)
|
||||
@@ -188,7 +188,7 @@ public class TaskFileJobService {
|
||||
List<TaskFileJobEntity> candidates = new ArrayList<>(ownerJobs);
|
||||
if (ownerJobs.size() < safeLimit) {
|
||||
LambdaQueryWrapper<TaskFileJobEntity> genericWrapper = new LambdaQueryWrapper<TaskFileJobEntity>()
|
||||
.in(TaskFileJobEntity::getStatus, List.of("PENDING", "FAILED"))
|
||||
.in(TaskFileJobEntity::getStatus, com.nanri.aiimage.common.task.TaskStatuses.Job.RETRYABLE_ORDERED)
|
||||
.lt(TaskFileJobEntity::getRetryCount, MAX_RETRY_COUNT)
|
||||
.and(wrapper -> wrapper
|
||||
.notIn(TaskFileJobEntity::getModuleType, List.of("APPEARANCE_PATENT", "SIMILAR_ASIN", "PUBLISH", "SHOP_DATA_CRAWL"))
|
||||
@@ -236,7 +236,7 @@ public class TaskFileJobService {
|
||||
int safeLimit = Math.max(1, Math.min(limit, 100));
|
||||
|
||||
List<TaskFileJobEntity> ownerJobs = taskFileJobMapper.selectList(new LambdaQueryWrapper<TaskFileJobEntity>()
|
||||
.in(TaskFileJobEntity::getStatus, List.of("PENDING", "FAILED"))
|
||||
.in(TaskFileJobEntity::getStatus, com.nanri.aiimage.common.task.TaskStatuses.Job.RETRYABLE_ORDERED)
|
||||
.lt(TaskFileJobEntity::getRetryCount, MAX_RETRY_COUNT)
|
||||
.in(TaskFileJobEntity::getModuleType, List.of("APPEARANCE_PATENT", "SIMILAR_ASIN", "PUBLISH", "SHOP_DATA_CRAWL"))
|
||||
.eq(TaskFileJobEntity::getOwner, normalizedOwner)
|
||||
@@ -248,7 +248,7 @@ public class TaskFileJobService {
|
||||
|
||||
List<TaskFileJobEntity> jobs = new ArrayList<>(ownerJobs);
|
||||
LambdaQueryWrapper<TaskFileJobEntity> genericWrapper = new LambdaQueryWrapper<TaskFileJobEntity>()
|
||||
.in(TaskFileJobEntity::getStatus, List.of("PENDING", "FAILED"))
|
||||
.in(TaskFileJobEntity::getStatus, com.nanri.aiimage.common.task.TaskStatuses.Job.RETRYABLE_ORDERED)
|
||||
.lt(TaskFileJobEntity::getRetryCount, MAX_RETRY_COUNT)
|
||||
.and(wrapper -> wrapper
|
||||
.notIn(TaskFileJobEntity::getModuleType, List.of("APPEARANCE_PATENT", "SIMILAR_ASIN", "PUBLISH", "SHOP_DATA_CRAWL"))
|
||||
@@ -521,7 +521,7 @@ public class TaskFileJobService {
|
||||
}
|
||||
return taskFileJobMapper.update(null, new LambdaUpdateWrapper<TaskFileJobEntity>()
|
||||
.eq(TaskFileJobEntity::getId, jobId)
|
||||
.in(TaskFileJobEntity::getStatus, List.of("PENDING", "FAILED"))
|
||||
.in(TaskFileJobEntity::getStatus, com.nanri.aiimage.common.task.TaskStatuses.Job.RETRYABLE_ORDERED)
|
||||
.and(wrapper -> wrapper.isNull(TaskFileJobEntity::getRetryCount)
|
||||
.or()
|
||||
.lt(TaskFileJobEntity::getRetryCount, MAX_RETRY_COUNT))
|
||||
@@ -831,7 +831,7 @@ public class TaskFileJobService {
|
||||
.eq(TaskFileJobEntity::getTaskId, taskId)
|
||||
.eq(TaskFileJobEntity::getModuleType, moduleType)
|
||||
.eq(TaskFileJobEntity::getJobType, JOB_TYPE_ASSEMBLE_RESULT)
|
||||
.in(TaskFileJobEntity::getStatus, List.of("PENDING", "RUNNING")));
|
||||
.in(TaskFileJobEntity::getStatus, com.nanri.aiimage.common.task.TaskStatuses.Job.ACTIVE_ORDERED));
|
||||
return count == null ? 0L : count;
|
||||
}
|
||||
|
||||
|
||||
+172
@@ -8,7 +8,9 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -27,6 +29,13 @@ public class TaskHeartbeatPositionService {
|
||||
private static final String KEY_PREFIX = "task:heartbeat:position:";
|
||||
private static final String STALL_KEY_PREFIX = "task:progress:stall:";
|
||||
private static final Duration POSITION_TTL = Duration.ofHours(24);
|
||||
private static final int POSITION_LABEL_MAX_LEN = 60;
|
||||
/** 计数字符串的最长位数:9 位以内 parseInt 必不溢出,所以这一处不需要 catch。 */
|
||||
private static final int MAX_COUNT_DIGITS = 9;
|
||||
/** 单次 light 轮询最多读多少个任务的心跳位置(Redis 往返上限,见 {@link #readDrawablePositions})。 */
|
||||
public static final int MAX_POSITION_LOOKUPS_PER_CALL = 20;
|
||||
/** 客户端 {@code config.PROGRESS_UNIT_SCALE} 的服务端镜像:units 粒度下 1 个自然单位 = 1000。 */
|
||||
public static final int PROGRESS_UNIT_SCALE = 1000;
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
@@ -44,6 +53,52 @@ public class TaskHeartbeatPositionService {
|
||||
UNKNOWN
|
||||
}
|
||||
|
||||
/**
|
||||
* 结构化位置读数。{@code current}/{@code total} 可能为 null——客户端只发了文本、
|
||||
* 没发计数(老版本按四级 key 归一化时 total 全为 0 就不发)。
|
||||
*/
|
||||
public record Position(Integer current, Integer total, String label, String grain) {
|
||||
|
||||
/** 老客户端没报粒度:grain 留空,调用方按「自然计数」处理。 */
|
||||
public Position(Integer current, Integer total, String label) {
|
||||
this(current, total, label, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化成「能画」的读数:total 非正数即视为没有进度(返回 null),
|
||||
* current 缺失/为负按 0、超过 total 按 total 钳住(客户端计数与分母不同源,会超)。
|
||||
*
|
||||
* <p>共享 {@code TaskProgressLightVo} 与 similarasin 自己那份私有 LightVo 都走这里,
|
||||
* 两个出口不会有第二种钳位口径。
|
||||
*/
|
||||
public Position drawable() {
|
||||
if (total == null || total <= 0) {
|
||||
return null;
|
||||
}
|
||||
int safeCurrent = current == null || current < 0 ? 0 : Math.min(current, total);
|
||||
return new Position(safeCurrent, total, label, grain);
|
||||
}
|
||||
|
||||
/**
|
||||
* 折算成「可以直接显示」的当量,供后台任务中心看板使用。
|
||||
*
|
||||
* <p>看板那一列的文案是「已完成 X / 总 Y」(2026-10-04 定的口径),而 {@code units} 这一档
|
||||
* 的 current/total 是客户端为「翻页进度单调不减」摊平出来的 国家数×1000——照原样显示会读成
|
||||
* 「已完成 1222 / 总 5000」,管理员只会问 5000 是什么。折算回国家当量后数字可读,
|
||||
* 代价是看板的条子比客户端粗一档(20% 对 24%),这个取舍是值得的。
|
||||
*
|
||||
* <p>客户端进度条不吃这个方法:它走 progress/light 拿原始千分位,要的是平滑。
|
||||
*/
|
||||
public Position displayUnits() {
|
||||
if (!"units".equals(grain) || total == null || total <= 0) {
|
||||
return this;
|
||||
}
|
||||
int shownTotal = Math.max(1, total / PROGRESS_UNIT_SCALE);
|
||||
int shownCurrent = current == null ? 0 : Math.min(shownTotal, current / PROGRESS_UNIT_SCALE);
|
||||
return new Position(shownCurrent, shownTotal, label, grain);
|
||||
}
|
||||
}
|
||||
|
||||
public void record(Long taskId, TaskHeartbeatRequest request) {
|
||||
if (taskId == null || taskId <= 0 || request == null) {
|
||||
return;
|
||||
@@ -62,6 +117,7 @@ public class TaskHeartbeatPositionService {
|
||||
values.put("current", request.getCurrent() == null ? "" : String.valueOf(request.getCurrent()));
|
||||
values.put("total", request.getTotal() == null ? "" : String.valueOf(request.getTotal()));
|
||||
values.put("progressText", progressText);
|
||||
values.put("grain", request.getProgressGrain() == null ? "" : request.getProgressGrain().trim());
|
||||
values.put("at", String.valueOf(Instant.now().toEpochMilli()));
|
||||
String key = KEY_PREFIX + taskId;
|
||||
stringRedisTemplate.opsForHash().putAll(key, values);
|
||||
@@ -106,6 +162,122 @@ public class TaskHeartbeatPositionService {
|
||||
return sb.length() == 0 ? null : sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取结构化进度读数,供 {@code progress/light} 轮询透传给前端画进度条。
|
||||
*
|
||||
* <p>与 {@link #describe} 的分工:那里给文案,这里给可参与除法的分子/分母。数据同源,
|
||||
* 都是客户端心跳写进 {@code task:heartbeat:position:{taskId}} 的那一份,<b>不另建存储</b>。
|
||||
*
|
||||
* <p>读不到时返回 {@code null},调用方必须按「这里没有进度可看」处理——<b>不得</b>把 null
|
||||
* 折成 {@code 0/0}:0/0 在前端会画成 0% 空轨,而空轨读起来是"进度 0%",与"没有进度"是两件事。
|
||||
*/
|
||||
public Position readPosition(Long taskId) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
return null;
|
||||
}
|
||||
Map<Object, Object> entries;
|
||||
try {
|
||||
entries = stringRedisTemplate.opsForHash().entries(KEY_PREFIX + taskId);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[heartbeat-position] 读取结构化位置失败 taskId={} msg={}", taskId, ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
Integer current = parseIntOrNull(value(entries, "current"));
|
||||
Integer total = parseIntOrNull(value(entries, "total"));
|
||||
if (current == null && total == null) {
|
||||
return null;
|
||||
}
|
||||
return new Position(current, total, trimLabel(value(entries, "progressText")), value(entries, "grain"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量取「能画」的位置读数,供 {@code progress/light} 轮询使用。
|
||||
*
|
||||
* <p>封顶 {@link #MAX_POSITION_LOOKUPS_PER_CALL} 次读取:light 是每 10 秒一次的轮询面、
|
||||
* 单次最多带 200 个任务 id,逐个 HGETALL 会把 Redis 读成这条链路的新瓶颈。调用方已筛掉终态,
|
||||
* 剩下的「真在跑」通常只有个位数;超出上限就宁可少画几条进度,也不给轮询加无界往返。
|
||||
*
|
||||
* <p>计数按<b>尝试次数</b>而非命中数:老客户端一个都不发位置时,命中数为 0 但往返数照样是 200。
|
||||
*
|
||||
* @return taskId → 可画读数;读不到位置或分母非正数的任务不出现在结果里
|
||||
*/
|
||||
public Map<Long, Position> readDrawablePositions(Collection<Long> taskIds) {
|
||||
return readDrawablePositions(taskIds, MAX_POSITION_LOOKUPS_PER_CALL);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同上,但由调用方给封顶值。
|
||||
*
|
||||
* <p>封顶必须跟着调用面的规模走:progress/light 一次最多 200 个 id、每 10 秒一轮,20 次够;
|
||||
* 后台看板一页可到 {@code MAX_PAGE_SIZE=100}、每 30 秒一轮,沿用 20 就会让第 21 行之后的任务
|
||||
* 永远读不到进度(还是那个「安静地没有条」的老形态)。
|
||||
*/
|
||||
public Map<Long, Position> readDrawablePositions(Collection<Long> taskIds, int maxLookups) {
|
||||
if (taskIds == null || taskIds.isEmpty() || maxLookups <= 0) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<Long, Position> result = new LinkedHashMap<>();
|
||||
int attempts = 0;
|
||||
for (Long taskId : taskIds) {
|
||||
if (attempts >= maxLookups) {
|
||||
break;
|
||||
}
|
||||
attempts++;
|
||||
Position position = readPosition(taskId);
|
||||
Position drawable = position == null ? null : position.drawable();
|
||||
if (drawable != null) {
|
||||
result.put(taskId, drawable);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redis 里的计数是客户端上报的裸字符串,脏值不能把整次轮询带崩。
|
||||
*
|
||||
* <p>这里<b>不用 try/catch</b>:那格「不重抛的吞异常」棘轮只许减(基线 559),加一处就得同批
|
||||
* 减掉一处别人的,不划算;而这一处本来也不需要——先按字符判掉非数字、再限长度防 int 溢出,
|
||||
* {@code Integer.valueOf} 就不可能抛。负号也算脏值(客户端不会报负数,真出现就当没有读数)。
|
||||
*/
|
||||
private static Integer parseIntOrNull(String raw) {
|
||||
if (raw == null || raw.isEmpty() || raw.length() > MAX_COUNT_DIGITS) {
|
||||
return null;
|
||||
}
|
||||
for (int index = 0; index < raw.length(); index++) {
|
||||
if (!Character.isDigit(raw.charAt(index))) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return Integer.valueOf(raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* 位置文案按「,」整段截短(light 每 10s 轮询、单次最多 200 个任务,不能把心跳全文搬过去)。
|
||||
* 按分隔符收口而不是定长切,避免截出「国家 U…」这种半截标签。
|
||||
*/
|
||||
private static String trimLabel(String text) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
StringBuilder kept = new StringBuilder();
|
||||
for (String segment : text.split(",")) {
|
||||
if (kept.length() > 0 && kept.length() + segment.length() + 1 > POSITION_LABEL_MAX_LEN) {
|
||||
break;
|
||||
}
|
||||
if (kept.length() == 0 && segment.length() > POSITION_LABEL_MAX_LEN) {
|
||||
return segment.substring(0, POSITION_LABEL_MAX_LEN);
|
||||
}
|
||||
if (kept.length() > 0) {
|
||||
kept.append(',');
|
||||
}
|
||||
kept.append(segment);
|
||||
}
|
||||
return kept.length() == 0 ? null : kept.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定客户端是否「仍在推进」,供封口/判死前的豁免使用。
|
||||
*
|
||||
|
||||
+31
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.model.dto.TaskRowsVersionDto;
|
||||
@@ -33,6 +34,7 @@ public class TaskProgressLightAssembler {
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final FileResultMapper fileResultMapper;
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final TaskHeartbeatPositionService taskHeartbeatPositionService;
|
||||
|
||||
public TaskProgressLightBatchVo assemble(String moduleType, Long userId, List<Long> taskIds) {
|
||||
TaskProgressLightBatchVo vo = new TaskProgressLightBatchVo();
|
||||
@@ -61,6 +63,16 @@ public class TaskProgressLightAssembler {
|
||||
}
|
||||
}
|
||||
Map<Long, TaskFileJobEntity> jobMap = taskFileJobService.findAssembleJobsByTaskIds(moduleType, new ArrayList<>(taskMap.keySet()));
|
||||
// 心跳位置只在非终态任务上取(终态的位置 24h 会过期,且跑完的任务该按状态显示而不是中途百分比)
|
||||
List<Long> activeTaskIds = new ArrayList<>();
|
||||
for (Long taskId : normalizedIds) {
|
||||
FileTaskEntity task = taskMap.get(taskId);
|
||||
if (task != null && !TaskStatuses.FileTask.TERMINAL.contains(task.getStatus())) {
|
||||
activeTaskIds.add(taskId);
|
||||
}
|
||||
}
|
||||
Map<Long, TaskHeartbeatPositionService.Position> positions =
|
||||
taskHeartbeatPositionService.readDrawablePositions(activeTaskIds);
|
||||
// 行数据版本:一次 GROUP BY 拿回每个任务结果行的(最后变更时间, 行数),作为行数据按需拉取的信号
|
||||
Map<Long, String> rowsVersions = new LinkedHashMap<>();
|
||||
if (!taskMap.isEmpty()) {
|
||||
@@ -90,8 +102,27 @@ public class TaskProgressLightAssembler {
|
||||
item.setFileError(job == null ? null : job.getErrorMessage());
|
||||
item.setUpdatedAt(task.getUpdatedAt() == null ? null : task.getUpdatedAt().toString());
|
||||
item.setRowsVersion(rowsVersions.get(taskId));
|
||||
applyPosition(item, positions.get(taskId));
|
||||
vo.getItems().add(item);
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把客户端心跳上报的处理位置透给前端画进度条。
|
||||
*
|
||||
* <p>入参已由 {@link #assemble} 筛过:只有非终态任务才会去读位置,且读不到/分母非正数时
|
||||
* {@code positions} 里根本没有这个任务。三种情况都落到「三个字段留 null」——前端
|
||||
* {@code TaskItemCard} 见 {@code progress=null} 就不渲染进度轨。这是有意的:
|
||||
* <b>没有进度</b>和<b>进度 0%</b>是两件事,把前者画成后者会让人以为任务卡住了
|
||||
* (2026-10-04 用户就「0/1 空轨」明确否过一次)。
|
||||
*/
|
||||
private void applyPosition(TaskProgressLightVo item, TaskHeartbeatPositionService.Position drawable) {
|
||||
if (drawable == null) {
|
||||
return;
|
||||
}
|
||||
item.setProgressCurrent(drawable.current());
|
||||
item.setProgressTotal(drawable.total());
|
||||
item.setProgressLabel(drawable.label());
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user