Files
crawler-plugin/admin-frontend-vue/src/pages/asin/DedupeRegistryPage.vue
T
huangzd1997 898e8a5ea9 feat(admin): 批量删除并入筛选行省一整行+公司管理加删除/批量删除(2026-11-23 用户口径)
- BatchDeleteActions margin-left:auto 右对齐、不再独占一行,14 页迁入各自筛选/工具行(Users/Groups/Menus/UserSecrets/QueryAsin/AsinInvalid/SkipPrice/DedupeRegistry/ProductCategory/DeviceLogs/DigitalHuman/ShopManage/ShopKeys/BrandGating);主按钮沿用全局 34px 同高,align-batch-toolbar-inline.test.ts 钉形状防回归
- 公司删除:DELETE /api/admin/companies/{id}(仅超管,名下有账号拒并带数量),只收公司行+columns 菜单树(PermissionMenuService.deleteTreeByCompany 与 copyTreeFromTemplate 对称),业务数据不级联;列表 VO 带 user_count 供前端置灰勾选/删除按钮;批量删除按用户管理同形走前端逐条循环
- CompaniesPage 加勾选列+行删除按钮(ops-cell 补 flex-wrap 过 ops-cell-must-wrap),删除后 refreshCompanyDirectory 同步 tab 条
- 测试:CompanyServiceDeleteTest 6+PermissionMenuServiceDeleteTreeTest 2+CompanyVoTest user_count 契约+CompanyControllerEndpointTest 翻转 exposesNoDeleteEndpoint→点名 DELETE 端点+CompanyReadPathMenuGateTest ensureSuperAdmin 3→4(delete 入册)+company-directory/row-buttons 补例;source-pin 基线重生成(265 文件/1859 例)
- 验证:admin-vue vue-tsc rc=0、node --test 1976 全绿、vitest mount 247 全绿;backend test-compile rc=0、Company*/PermissionMenu*/跨切守卫点名全绿(CatchSilenceRatchet 红因=另一路在飞件 JdPublishFillAiService 3 个 catch,归属京东窗不代抬)
2026-11-23 01:41:37 +08:00

575 lines
23 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import BatchDeleteActions from '@/components/BatchDeleteActions.vue'
import BatchDeleteCheckbox from '@/components/BatchDeleteCheckbox.vue'
import { useRowSelection } from '@/utils/use-row-selection'
import { createLatestRequestGate } from '@/utils/latest-request'
import { formatDateTime, orderedPair } from '@/utils/datetime'
/** 数据去重总数据(registry) · 像素复刻旧版 admin.html panel-dedupe-total-data(自绘:分组摘要 + 双行筛选 + 旧式表格/分页 + 编辑/导入弹窗 + 导出等待遮罩)。
* script 逻辑沿用现有 Vue 实现(查询/编辑/删除/导入轮询/导出秒表)。 */
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
fetchDedupeTotalList,
updateDedupeTotal,
deleteDedupeTotal,
fetchDedupeTotalGroups,
type DedupeGroupOption,
} from './dedupe-total-api.ts'
import type { DedupeTotalItem } from './dedupe-total-model.ts'
import { ASIN_COUNTRY_CODES, asinCountryLabel } from './asin-country.ts'
import { createDedupeTotalFilterState, toDedupeListParams } from './dedupe-total-filter.ts'
import {
fetchDedupeDeleteImportProgress,
fetchDedupeImportProgress,
startDedupeDeleteImport,
startDedupeImport,
} from './dedupe-import-api.ts'
import { importOutcomeText, importTaskFinished, isAllowedImportFile } from './dedupe-import-model.ts'
import type { DedupeImportProgress } from './dedupe-import-model.ts'
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()
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
const isSuperAdmin = computed(() => session.isSuperAdmin)
const loading = ref(false)
const loadFailure = ref('')
const rows = ref<DedupeTotalItem[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
/** 本页是累计台账,日期初值故意留空(默认当天会让首屏只剩今天新增的 ASIN);见 date-filter-default-today 护栏的 EXEMPT。 */
const filter = reactive(createDedupeTotalFilterState())
/** min/max 挡不住手输,落值后把倒挂的起止交换回来。 */
function clampDatePair(): void {
const [s, e] = orderedPair(filter.startDate, filter.endDate)
filter.startDate = s
filter.endDate = e
}
const groups = ref<DedupeGroupOption[]>([])
/** 非超管仅有一个可访问分组时,编辑/导入弹窗分组选择锁定为该组(保留展示、不可改)。 */
const lockedGroupId = computed<number | null>(() => {
if (isSuperAdmin.value) return null
return groups.value.length === 1 ? groups.value[0].id : null
})
const jumpPage = ref('')
/** 顺序翻页游标:上一页响应给的 nextLastId;仅在"下一页"时使用,跳页/筛选时清空走 OFFSET。 */
const pageCursor = ref<number | null>(null)
/** 本次请求实际使用的游标(load 时决定) */
let pendingCursor: number | null = null
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
const editVisible = ref(false)
const editSaving = ref(false)
const editTarget = ref<DedupeTotalItem | null>(null)
const editValue = ref('')
const editGroupId = ref<number | null>(null)
/** 弹窗分组下拉的清空回填值:EP 的 el-select 默认清空写 undefined,会破 editGroupId/importGroupId
* 的 `number | null` 契约(下游 saveEdit/importValid 按假值判「未选」、updateDedupeTotal 的入参是 number)
* ⇒ 清空一律钉回 null,与旧原生 select 空行(value=null)同语义。 */
const nullOnClear = (): null => null
type ImportMode = 'add' | 'delete'
const importVisible = ref(false)
const importMode = ref<ImportMode>('add')
const importGroupId = ref<number | null>(null)
const importFile = ref<File | null>(null)
const importRunning = ref(false)
const importProgress = ref('')
const exporting = ref(false)
/** 导出等待遮罩与秒表(对齐 admin.js showDedupeTotalDataExportWait)。 */
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
exportWaitVisible.value = true
exportWaitTimer = setInterval(() => {
exportWaitSeconds.value += 1
}, 1000)
}
function stopExportWait(): void {
if (exportWaitTimer) {
clearInterval(exportWaitTimer)
exportWaitTimer = null
}
exportWaitVisible.value = false
}
const batchListGate = createLatestRequestGate()
async function load(): Promise<void> {
const token = batchListGate.begin()
loading.value = true
loadFailure.value = ''
try {
const result = await fetchDedupeTotalList(
toDedupeListParams(filter, page.value, pageSize.value, pendingCursor, companyTab.requestCompanyId),
)
if (!batchListGate.isCurrent(token)) return
rows.value = result.items
total.value = result.total
if (result.page >= 1) page.value = result.page
// 本页响应回传的游标留作"下一页"用;空页则清空(没有更多)
pageCursor.value = result.nextLastId ?? null
pendingCursor = null
} catch (error) {
if (!batchListGate.isCurrent(token)) return
loadFailure.value = loadFailureMessage(error, '去重数据加载失败')
showAdminFeedback(loadFailure.value, 'error')
} finally {
if (batchListGate.isCurrent(token)) loading.value = false
}
}
function apply(): void {
page.value = 1
pageCursor.value = null
pendingCursor = null
void load()
}
function changePage(next: number): void {
if (next < 1 || next > totalPages.value) return
// 只有"顺序下一页"用 keyset 游标(避免深分页 offset);跳页/回退走 OFFSET,行为不变
pendingCursor = next === page.value + 1 ? pageCursor.value : null
page.value = next
void load()
}
function goJump(): void {
const n = Number.parseInt(jumpPage.value, 10)
if (Number.isNaN(n)) {
ElMessage.warning('请输入页码')
return
}
changePage(Math.min(Math.max(n, 1), totalPages.value))
}
function changeSize(size: number) {
pageSize.value = size
page.value = 1
pageCursor.value = null
pendingCursor = null
void load()
}
function openEdit(row: DedupeTotalItem): void {
editTarget.value = row
editValue.value = row.dataValue
editGroupId.value = row.groupId ?? lockedGroupId.value
editVisible.value = true
}
async function saveEdit(): Promise<void> {
const value = editValue.value.trim()
const target = editTarget.value
if (!target) return
if (!value) {
ElMessage.warning('请填写总数据值')
return
}
if (!editGroupId.value) {
ElMessage.warning('请选择分组')
return
}
editSaving.value = true
try {
await updateDedupeTotal(target.id, value, editGroupId.value)
editVisible.value = false
ElMessage.success('保存成功')
await load()
} catch (error) {
showAdminFeedback(loadFailureMessage(error, '保存失败'), 'error')
} finally {
editSaving.value = false
}
}
const batch = useRowSelection({
pageRows: () => rows.value,
rowId: (row) => row.id,
rowLabel: (row) => row.dataValue,
deleteOne: (id) => deleteDedupeTotal(id),
refresh: load,
blocked: () => loading.value || !!loadFailure.value,
scope: () => companyTab.activeId,
})
async function removeRow(row: DedupeTotalItem): Promise<void> {
if (batch.busy) return
// 对齐旧版:浏览器原生 confirm 确认后删除。
if (!(await openAdminConfirm({ message: `确定删除总数据“${row.dataValue}”吗?`, danger: true }))) return
try {
await deleteDedupeTotal(row.id)
batch.removeFromSelection(row.id)
ElMessage.success('删除成功')
await load()
} catch (error) {
showAdminFeedback(loadFailureMessage(error, '删除失败'), 'error')
}
}
function resetImport(): void {
importGroupId.value = lockedGroupId.value
importFile.value = null
importProgress.value = ''
importRunning.value = false
}
function openImportAdd(): void {
importMode.value = 'add'
resetImport()
importVisible.value = true
}
function openImportDelete(): void {
importMode.value = 'delete'
resetImport()
importVisible.value = true
}
function onPickFile(event: Event): void {
const input = event.target as HTMLInputElement
importFile.value = input.files?.[0] ?? null
}
function importValid(): boolean {
if (!importGroupId.value) {
ElMessage.warning('请先选择数据权限分组')
return false
}
if (!importFile.value) {
ElMessage.warning('请选择 Excel 文件')
return false
}
if (!isAllowedImportFile(importFile.value.name)) {
ElMessage.warning('仅支持 .xlsx/.xls 文件')
return false
}
return true
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
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
await sleep(1000)
}
throw new Error('查询导入进度超时,请稍后刷新列表确认结果')
}
async function submitImport(): Promise<void> {
if (!importValid()) return
const file = importFile.value as File
const groupId = importGroupId.value as number
if (importMode.value === 'delete') {
if (!(await openAdminConfirm({ message: '确定按 Excel 中的 ASIN 批量删除匹配的总数据吗?', danger: true }))) return
}
const mode = importMode.value
importRunning.value = true
importProgress.value = mode === 'add' ? '正在上传并解析文件…' : '正在上传删除清单…'
try {
const started =
mode === 'add'
? await startDedupeImport(file, groupId, companyTab.requestCompanyId)
: await startDedupeDeleteImport(file, groupId, companyTab.requestCompanyId)
const poll = mode === 'add' ? () => fetchDedupeImportProgress(started) : () => fetchDedupeDeleteImportProgress(started)
const finished = await pollImport(poll)
importVisible.value = false
resetImport()
if (finished.status === 'success') {
ElMessage.success(mode === 'add' ? '导入完成' : '删除导入完成')
await load()
} else {
showAdminFeedback(importOutcomeText(finished), 'error')
}
} catch (error) {
showAdminFeedback(loadFailureMessage(error, '导入失败'), 'error')
} finally {
importRunning.value = false
}
}
async function doExport(): Promise<void> {
if (exporting.value) return
exporting.value = true
startExportWait()
try {
// 对齐 admin.js:fetch 流式下载,带筛选参数;失败响应(JSON)解析错误提示。
const response = await window.fetch(toExportUrl(filter, companyTab.requestCompanyId), { credentials: 'include' })
const contentType = response.headers.get('content-type') || ''
if (!response.ok || contentType.includes('application/json')) {
const body = (await response.json().catch(() => ({}))) as { error?: string; message?: string; msg?: string }
throw new Error(body.error || body.message || body.msg || '导出失败')
}
const blob = await response.blob()
const disposition = response.headers.get('content-disposition') || ''
const matched = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(disposition)
const filename = matched ? decodeURIComponent(matched[1]) : 'dedupe-total-data.xlsx'
const url = URL.createObjectURL(blob)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = filename
document.body.appendChild(anchor)
anchor.click()
anchor.remove()
URL.revokeObjectURL(url)
ElMessage.success('导出完成')
} catch (error) {
showAdminFeedback(loadFailureMessage(error, '导出失败,请重试'), 'error')
} finally {
stopExportWait()
exporting.value = false
}
}
async function loadGroups(): Promise<void> {
try {
groups.value = await fetchDedupeTotalGroups(companyTab.requestCompanyId)
} catch {
groups.value = []
}
}
// 切公司 = 重新取数:列表与分组下拉共用这一个 watch(少一个 = 那半边的 tab 是装饰品)。
// groupId 与 keyset 游标必须一起清:上一家选中的分组在新一家不存在,而上一家响应回传的 lastId
// 拿到新一家去翻页会把「游标之后」当成条件,首屏直接筛成空列表。
watch(() => companyTab.activeId, () => { filter.groupId = null; pageCursor.value = null; pendingCursor = null; void loadGroups(); void load() })
onMounted(() => {
void load()
void loadGroups()
})
// 导出秒表是 setInterval:不随页面卸载收掉的话,离开本页后它仍在每秒改一个已经没人看的 ref。
onUnmounted(() => {
pageDisposed = true
stopExportWait()
})
</script>
<template>
<div class="dedupe-view">
<section class="panel-box">
<div class="dedupe-panel-head">
<h3>ASIN列表</h3>
<div class="dedupe-head-actions">
<button class="btn" type="button" @click="openImportAdd">新增导入</button>
<button class="btn" type="button" @click="openImportDelete">删除导入</button>
</div>
</div>
<div class="dedupe-filter-row">
<div class="form-group">
<label>ASIN</label>
<input v-model="filter.keyword" type="text" placeholder="输入 ASIN" @keyup.enter="apply" />
</div>
<div class="form-group">
<label>用户名(模糊搜索)</label>
<input v-model="filter.username" type="text" placeholder="输入用户名" @keyup.enter="apply" />
</div>
<div v-if="isSuperAdmin" class="form-group">
<label>分组</label>
<el-select v-model="filter.groupId" class="admin-filter" filterable clearable placeholder="全部分组">
<el-option v-for="group in groups" :key="group.id" :label="group.name" :value="group.id" />
</el-select>
</div>
<div class="form-group">
<label>国家</label>
<!-- 2026-11-17 用户口径「和亚马逊不统一」:原生 select 的弹层是浏览器直角原生物
⇒ 换 el-select(admin-filter 与亚马逊面同壳 42px/9px,弹层是 EP 圆角面板)。
「全部国家」保留为空值首行(value="" 与改前同语义,下发参数仍是空串=不限);
EP 把 '' 当空值 ⇒ 闭壳显示 placeholder,因此同时钉 placeholder="全部国家",视觉不变。 -->
<el-select v-model="filter.country" class="admin-filter" filterable placeholder="全部国家" aria-label="筛选国家">
<el-option label="全部国家" value="" />
<el-option v-for="code in ASIN_COUNTRY_CODES" :key="code" :label="asinCountryLabel(code)" :value="code" />
</el-select>
</div>
<div class="dedupe-filter-actions">
<button class="btn" type="button" @click="apply">查询</button>
</div>
<BatchDeleteActions :batch="batch" />
</div>
<div class="dedupe-filter-date-row">
<div class="form-group">
<label>开始日期</label>
<input v-model="filter.startDate" type="date" :max="filter.endDate" @change="clampDatePair" />
</div>
<div class="form-group">
<label>结束日期</label>
<input v-model="filter.endDate" type="date" :min="filter.startDate" @change="clampDatePair" />
</div>
<div class="dedupe-filter-actions">
<button class="btn btn-secondary" type="button" :disabled="exporting" @click="doExport">
{{ exporting ? '导出中...' : '导出 XLSX' }}
</button>
</div>
</div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<div class="table-scroll dedupe-table-scroll">
<table>
<thead>
<tr>
<th class="batch-delete-cell" scope="col">
<BatchDeleteCheckbox label="全选当前页可删除记录" :checked="batch.pageAll" :partial="batch.pageSome"
:disabled="batch.disabled || batch.pageEmpty" @change="batch.togglePage" />
</th>
<th>ID</th>
<th>ASIN</th>
<th>国家</th>
<th>用户名</th>
<th v-if="isSuperAdmin">分组</th>
<th>创建时间</th>
<th>更新时间</th>
<th style="width: 140px">操作</th>
</tr>
</thead>
<tbody>
<template v-if="rows.length">
<tr v-for="row in rows" :key="row.id" :class="{ 'batch-selected': batch.isSelected(row) }">
<td class="batch-delete-cell">
<BatchDeleteCheckbox :label="batch.reason(row) || `选择 ${batch.label(row)}`" :checked="batch.isSelected(row)"
:disabled="batch.disabled || !!batch.reason(row)" @change="batch.toggle(row)" />
</td>
<td>{{ row.id }}</td>
<td class="mono-cell">{{ row.dataValue }}</td>
<td>{{ asinCountryLabel(row.country || '') }}</td>
<td>{{ row.username || '-' }}</td>
<td v-if="isSuperAdmin">{{ row.groupName || '未分组' }}</td>
<td>{{ formatDateTime(row.createdAt) }}</td>
<td>{{ formatDateTime(row.updatedAt) }}</td>
<td class="ops-cell">
<button class="btn btn-sm" type="button" @click="openEdit(row)">编辑</button>
<button class="btn btn-sm btn-danger" type="button" :disabled="batch.busy" @click="removeRow(row)">删除</button>
</td>
</tr>
</template>
<tr v-else-if="loading">
<td :colspan="isSuperAdmin ? 9 : 8" class="empty-tip">加载中...</td>
</tr>
<tr v-else>
<td :colspan="isSuperAdmin ? 9 : 8" class="empty-tip">暂无总数据</td>
</tr>
</tbody>
</table>
</div>
<OldPagination :total="total" :page="page" :page-size="pageSize" @change="changePage" @size-change="changeSize" />
</section>
<div v-if="editVisible" class="modal-mask" @click.self="editVisible = false">
<div class="modal">
<h3>编辑ASIN</h3>
<div class="form-group">
<label>ASIN</label>
<input v-model="editValue" type="text" placeholder="请输入总数据值" />
</div>
<div class="form-group">
<label>分组</label>
<!-- 2026-11-17 用户口径「和亚马逊不统一」:原生 select 弹层是直角原生物 ⇒ el-select。
「未选」语义:原写法是 disabled 的空行(:value="null",选中后不可回退),这里改成
placeholder="请选择分组" + clearable,并用 :value-on-clear 把清空值钉回 null
(理由见上方 nullOnClear 注释:EP 默认回 undefined 会破 number | null 契约)。
值域仍是 null 或分组 id(number),下游 editGroupId 的假值判断与入参形状不变;
非超管单分组时照旧锁定展示(:disabled 与护栏测试钉住的写法一致)。 -->
<el-select
v-model="editGroupId"
class="admin-filter"
placeholder="请选择分组"
clearable
:value-on-clear="nullOnClear"
:disabled="lockedGroupId != null"
aria-label="编辑分组"
>
<el-option v-for="group in groups" :key="group.id" :label="group.name" :value="group.id" />
</el-select>
</div>
<div class="modal-actions">
<button class="btn" type="button" :disabled="editSaving" @click="saveEdit">保存</button>
<button class="btn btn-secondary" type="button" @click="editVisible = false">取消</button>
</div>
</div>
</div>
<div v-if="importVisible" class="modal-mask" @click.self="importVisible = false">
<div class="modal">
<h3>{{ importMode === 'add' ? '新增导入' : '删除导入' }}</h3>
<div class="form-group">
<label>{{ importMode === 'add' ? '上传 Excel 文件(读取 ASIN 列,可选 国家 列)' : '上传 Excel 文件(读取 ASIN 列)' }}</label>
<input type="file" accept=".xlsx,.xls" :disabled="importRunning" @change="onPickFile" />
</div>
<div class="form-group">
<label>分组</label>
<!-- 2026-11-17 用户口径「和亚马逊不统一」:原生 select 弹层是直角原生物 ⇒ el-select。
与编辑弹窗同款「未选」处理(placeholder + clearable + 清空钉回 null),
导入锁定条件(importRunning 或单分组)照旧挂在 :disabled 上。 -->
<el-select
v-model="importGroupId"
class="admin-filter"
placeholder="请选择分组"
clearable
:value-on-clear="nullOnClear"
:disabled="importRunning || lockedGroupId != null"
aria-label="导入分组"
>
<el-option v-for="group in groups" :key="group.id" :label="group.name" :value="group.id" />
</el-select>
</div>
<div v-if="importProgress" class="progress-wrap">
<div class="progress-text">{{ importProgress }}</div>
</div>
<div class="modal-actions">
<button
class="btn"
:class="{ 'btn-danger': importMode === 'delete' }"
type="button"
:disabled="importRunning"
@click="submitImport"
>
{{ importMode === 'add' ? '上传并导入' : '上传并删除' }}
</button>
<button class="btn btn-secondary" type="button" :disabled="importRunning" @click="importVisible = false">取消</button>
</div>
</div>
</div>
<div v-if="exportWaitVisible" class="dedupe-export-wait-mask" role="dialog" aria-modal="true" aria-labelledby="dedupe-export-wait-title">
<div class="dedupe-export-wait">
<span class="request-spinner" aria-hidden="true"></span>
<div>
<div class="dedupe-export-wait-title" id="dedupe-export-wait-title">正在生成导出文件</div>
<div class="dedupe-export-wait-detail">
数据量较大,请耐心等待并保持页面打开。已等待 <span>{{ exportWaitSeconds }}</span> 秒
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped src="./DedupeRegistryPage.css"></style>