Files
FileCodeBoxFronted2026/src/views/manage/TrashView.vue
T

211 lines
19 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.
<template>
<div class="p-4 sm:p-6">
<header class="mb-5 flex flex-col gap-3 sm:mb-6 sm:flex-row sm:items-end sm:justify-between">
<div>
<p class="hidden text-xs font-medium tracking-[0.16em] sm:block" :class="mutedTextClass">RECYCLE BIN</p>
<h2 class="mt-1 text-xl font-bold sm:text-2xl" :class="primaryTextClass">回收站</h2>
<p class="mt-1 text-xs leading-5 sm:text-sm" :class="mutedTextClass">删除文件会先保留在这里;恢复后沿用原取件码。</p>
</div>
<div class="grid grid-cols-2 items-center gap-2 sm:flex">
<BaseButton variant="secondary" :disabled="busy" @click="openRetentionSettings"><template #icon><Settings2Icon class="mr-2 h-4 w-4" /></template>清理设置</BaseButton>
<BaseButton variant="secondary" :loading="isLoading" :disabled="busy" @click="loadTrash"><template #icon><RefreshCwIcon class="mr-2 h-4 w-4" /></template>刷新回收站</BaseButton>
</div>
</header>
<section class="fcb-summary-grid mb-5 grid grid-cols-3 gap-2 sm:mb-6 sm:gap-3">
<div v-for="stat in stats" :key="stat.label" class="theme-2026-card theme-2026-card-hover fcb-secondary-card min-w-0 rounded-[20px] border p-2.5 shadow-sm sm:p-4" :class="panelClass">
<p class="text-xs" :class="mutedTextClass">{{ stat.label }}</p><strong class="mt-1 block text-xl sm:text-2xl" :class="primaryTextClass">{{ stat.value }}</strong>
</div>
</section>
<section class="theme-2026-card mb-5 rounded-[24px] border p-3 sm:p-4" :class="panelClass" aria-label="回收站筛选">
<form class="fcb-filter-grid grid grid-cols-2 gap-3 xl:grid-cols-[minmax(0,1fr)_180px_180px_auto]" @submit.prevent="applyFilters">
<label class="col-span-2 min-w-0 xl:col-span-1"><span class="mb-1 block text-xs font-medium" :class="mutedTextClass">关键词</span><input v-model="draft.keyword" :disabled="busy || !supportsFilters" class="w-full rounded-xl border px-3" placeholder="搜索文件名或原取件码" /></label>
<label><span class="mb-1 block text-xs font-medium" :class="mutedTextClass">记录状态</span><select v-model="draft.state" :disabled="busy || !supportsFilters" class="w-full rounded-xl border px-3"><option value="all">全部状态</option><option value="recoverable">可恢复</option><option value="scheduled">定时清理</option><option value="permanent">永久保留</option><option value="purged">仅审计记录</option></select></label>
<label><span class="mb-1 block text-xs font-medium" :class="mutedTextClass">移入原因</span><select v-model="draft.reason" :disabled="busy || !supportsFilters" class="w-full rounded-xl border px-3"><option value="">全部原因</option><option value="manual">手动删除</option><option value="batch_delete">批量删除</option><option value="expired_time">保存到期</option><option value="expired_count">次数用尽</option><option value="expired_both">到期且次数用尽</option><option value="expired">历史自动回收</option></select></label>
<div class="col-span-2 flex justify-end gap-2 xl:col-span-1"><BaseButton type="submit" :disabled="busy || !supportsFilters" :loading="isLoading">筛选</BaseButton><BaseButton variant="secondary" :disabled="busy || !supportsFilters" @click="resetFilters">重置</BaseButton></div>
</form>
<p v-if="!isLoading && !supportsFilters" class="mt-3 text-xs" :class="mutedTextClass">当前服务尚未支持回收站筛选和批量操作,更新服务后即可使用。</p>
</section>
<div v-if="resultText" role="status" class="mb-4 rounded-2xl border p-3 text-sm" :class="panelClass">
<p>{{ resultText }}</p>
<ul v-if="operationResult" class="mt-2 max-h-36 overflow-auto text-xs leading-6">
<li v-for="failure in operationResult.failed" :key="failure.id">#{{ failure.id }}:{{ failure.reason }}</li>
<li v-for="entry in restoredEntries" :key="entry.id">#{{ entry.id }} 取件码:<code class="font-semibold">{{ entry.code }}</code></li>
</ul>
</div>
<p v-if="errorText" role="alert" class="mb-4 rounded-2xl border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-800 dark:bg-red-950 dark:text-red-200">{{ errorText }}</p>
<section class="theme-2026-card overflow-hidden rounded-[24px] border sm:rounded-[30px]" :class="panelClass">
<div class="flex flex-wrap items-center justify-between gap-3 border-b px-4 py-3 sm:px-6" :class="dividerClass">
<div><h3 class="text-base font-semibold" :class="primaryTextClass">文件记录</h3><p class="mt-0.5 text-xs" :class="mutedTextClass">{{ supportsFilters ? `筛选结果 ${total} 条 · ` : '' }}恢复文件,或调整保留期限。</p></div>
<span class="inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs" :class="isDarkMode ? 'bg-[#303946] text-[#dbe9ee]' : 'bg-[#e5f0f1] text-[#365a66]'"><ShieldCheckIcon class="h-3.5 w-3.5" />历史保留</span>
</div>
<div v-if="supportsBatch && items.length" class="flex flex-wrap items-center justify-between gap-3 border-b px-4 py-3 sm:px-6" :class="dividerClass">
<label class="flex min-h-9 cursor-pointer items-center gap-2 text-sm"><input type="checkbox" :checked="allSelected" :indeterminate="partiallySelected" :disabled="busy || isLoading || !eligibleIds.length" @change="toggleAll" />{{ selectedIds.length ? `已选择 ${selectedIds.length} 项` : '选择当前页可操作记录' }}</label>
<div v-if="selectedIds.length" class="grid w-full grid-cols-2 gap-2 sm:flex sm:w-auto sm:flex-wrap">
<BaseButton size="sm" variant="success" :disabled="busy || isLoading" @click="executeBatch('restore', selectedIds)">批量恢复</BaseButton>
<BaseButton size="sm" variant="outline" :disabled="busy || isLoading" @click="openRetention(selectedIds)">设置清理时间</BaseButton>
<BaseButton size="sm" variant="outline" :disabled="busy || isLoading" @click="executeBatch('retention', selectedIds, { retentionDays: 0 })">永久保留</BaseButton>
<BaseButton size="sm" variant="danger" :disabled="busy || isLoading" @click="askPurge(selectedIds)">批量清理</BaseButton>
<BaseButton size="sm" variant="secondary" :disabled="busy" @click="selectedIds = []">清空选择</BaseButton>
</div>
</div>
<div v-if="isLoading" class="flex min-h-40 items-center justify-center text-sm" :class="mutedTextClass"><RefreshCwIcon class="mr-2 h-4 w-4 animate-spin" />正在加载回收站…</div>
<div v-else-if="!items.length" class="px-4 py-12 text-center" :class="mutedTextClass"><Trash2Icon class="mx-auto h-9 w-9" /><p class="mt-3 text-sm">{{ hasFilters ? '没有匹配的回收站记录' : '回收站目前为空' }}</p></div>
<div v-else class="divide-y" :class="dividerClass">
<article v-for="item in items" :key="item.id" class="fcb-interactive-row grid grid-cols-[auto_minmax(0,1fr)] gap-3 px-3 py-4 sm:px-6" :class="{ 'trash-row-selected': selectedIds.includes(item.id) }">
<label v-if="supportsBatch" class="flex h-11 items-center" :title="item.isTrashPurged ? '已清理记录不能操作' : ''"><input type="checkbox" v-model="selectedIds" :value="item.id" :aria-label="`选择 ${fileName(item)}`" :disabled="busy || item.isTrashPurged" /></label>
<TrashItemInfo :item="item" :is-dark-mode="isDarkMode" :now="now" :class="!supportsBatch ? 'col-span-2' : ''">
<template v-if="!item.isTrashPurged" #actions>
<BaseButton size="sm" variant="success" :disabled="busy" @click="restore(item)"><template #icon><RotateCcwIcon class="mr-1 h-4 w-4" /></template>恢复</BaseButton>
<BaseButton size="sm" variant="outline" :disabled="busy || !supportsCustomRetention" @click="openRetention([item.id])"><template #icon><CalendarClockIcon class="mr-1 h-4 w-4" /></template>清理时间</BaseButton>
<BaseButton size="sm" variant="outline" :disabled="busy || item.isTrashPermanent" @click="makePermanent(item)"><template #icon><InfinityIcon class="mr-1 h-4 w-4" /></template>永久保留</BaseButton>
<BaseButton size="sm" variant="danger" :disabled="busy" @click="askPurge([item.id])"><template #icon><EraserIcon class="mr-1 h-4 w-4" /></template>彻底删除</BaseButton>
</template>
</TrashItemInfo>
</article>
</div>
<DataPagination v-if="total > 0" :current-page="page" :page-size="size" :total="total" @page-change="changePage" @page-size-change="changePageSize" />
</section>
<BaseModal :show="retentionOpen" title="设置自动清理时间" :closable="!busy" @close="retentionOpen = false">
<p class="mb-4 text-sm" :class="mutedTextClass">为 {{ retentionIds.length }} 条记录设置相同的回收站保留期限。</p>
<label class="mb-4 flex cursor-pointer items-center gap-2 text-sm"><input v-model="retainForever" type="checkbox" :disabled="busy" />永久保留,不自动清理</label>
<NativeDateSelect v-if="!retainForever" v-model="cleanupTime" aria-label="自动清理时间" include-time />
<p class="mt-3 text-xs" :class="mutedTextClass">可选择未来 365 天内的时间。</p>
<p v-if="dialogError" role="alert" class="mt-3 text-sm text-red-700 dark:text-red-200">{{ dialogError }}</p>
<template #footer><BaseButton variant="secondary" :disabled="busy" @click="retentionOpen = false">取消</BaseButton><BaseButton :loading="busy" @click="saveRetention">保存时间</BaseButton></template>
</BaseModal>
<BaseModal :show="purgeOpen" title="确认彻底删除" :closable="!busy" @close="purgeOpen = false">
<p class="text-sm leading-6">将永久清理所选 <strong>{{ purgeIds.length }}</strong> 条记录的文件本体。此操作不可恢复,审计记录和取件历史仍保留。</p>
<p v-if="errorText" role="alert" class="mt-3 text-sm text-red-700 dark:text-red-200">{{ errorText }}</p>
<template #footer><BaseButton variant="secondary" :disabled="busy" @click="purgeOpen = false">取消</BaseButton><BaseButton variant="danger" :loading="busy" @click="confirmPurge">确认清理 {{ purgeIds.length }} 项</BaseButton></template>
</BaseModal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { CalendarClockIcon, EraserIcon, InfinityIcon, RefreshCwIcon, RotateCcwIcon, Settings2Icon, ShieldCheckIcon, Trash2Icon } from 'lucide-vue-next'
import BaseButton from '@/components/common/BaseButton.vue'
import BaseModal from '@/components/common/BaseModal.vue'
import NativeDateSelect from '@/components/common/NativeDateSelect.vue'
import TrashItemInfo from '@/components/manage/TrashItemInfo.vue'
import DataPagination from '@/components/common/DataPagination.vue'
import { useAdminTrash, useInjectedDarkMode } from '@/composables'
import type { TrashFileItem, TrashListParams, TrashListResponse, TrashBatchRequest, TrashBatchResult, TrashRetentionRequest } from '@/types'
import { getErrorMessage } from '@/utils/common'
import { selectableTrashIds, buildTrashRetention, summarizeTrashBatch } from '@/utils/trashSelection'
const isDarkMode = useInjectedDarkMode()
const router = useRouter()
const { fetchTrash, purgeTrashItem, restoreTrashItem, updateTrashRetention, batchTrash } = useAdminTrash()
const items = ref<TrashFileItem[]>([]), page = ref(1), size = ref(20), total = ref(0)
const summary = ref<TrashListResponse['summary']>()
const capabilities = ref<TrashListResponse['capabilities']>()
const supportsFilters = computed(() => capabilities.value?.filters === true)
const supportsBatch = computed(() => capabilities.value?.batch === true)
const supportsCustomRetention = computed(() => capabilities.value?.customRetention === true)
const blankFilters = () => ({ keyword: '', state: 'all' as NonNullable<TrashListParams['state']>, reason: '' as NonNullable<TrashListParams['reason']> })
const draft = ref(blankFilters()), applied = ref(blankFilters())
const hasFilters = computed(() => Boolean(applied.value.keyword || applied.value.reason || applied.value.state !== 'all'))
const isLoading = ref(false), busy = ref(false), errorText = ref(''), resultText = ref('')
const operationResult = ref<TrashBatchResult | null>(null)
const restoredEntries = computed(() => operationResult.value?.succeeded.filter(entry => entry.code) || [])
const selectedIds = ref<number[]>([])
const eligibleIds = computed(() => selectableTrashIds(items.value))
const allSelected = computed(() => eligibleIds.value.length > 0 && eligibleIds.value.every(id => selectedIds.value.includes(id)))
const partiallySelected = computed(() => selectedIds.value.length > 0 && !allSelected.value)
const toggleAll = () => { selectedIds.value = allSelected.value ? [] : [...eligibleIds.value] }
const now = ref(Date.now())
let clockTimer: ReturnType<typeof setInterval> | undefined
onMounted(() => { clockTimer = setInterval(() => { now.value = Date.now() }, 60_000) })
onUnmounted(() => { clearInterval(clockTimer); loadVersion++ })
const primaryTextClass = computed(() => isDarkMode.value ? 'text-white' : 'text-[#1f3c45]')
const mutedTextClass = computed(() => isDarkMode.value ? 'text-[#adbec6]' : 'text-[#617980]')
const panelClass = computed(() => isDarkMode.value ? 'border-[#495765] bg-[#252b34]' : 'border-[#d7e3e5] bg-[#f8fbfb]')
const dividerClass = computed(() => isDarkMode.value ? 'divide-[#495765] border-[#495765]' : 'divide-[#d7e3e5] border-[#d7e3e5]')
const stats = computed(() => [
{ label: '回收站记录', value: summary.value?.total ?? total.value },
{ label: '可恢复', value: summary.value?.recoverable ?? (total.value <= size.value ? items.value.filter(item => !item.isTrashPurged).length : '—') },
{ label: '仅审计记录', value: summary.value?.purged ?? (total.value <= size.value ? items.value.filter(item => item.isTrashPurged).length : '—') }
])
const fileName = (item: TrashFileItem) => item.name || `${item.prefix || ''}${item.suffix || ''}` || '未命名文件'
const openRetentionSettings = () => { void router.push({ path: '/admin/settings', hash: '#settings-upload' }) }
let loadVersion = 0
const loadTrash = async () => {
const version = ++loadVersion
isLoading.value = true; errorText.value = ''
try {
let detail = await fetchTrash({ page: page.value, size: size.value, ...applied.value })
if (version !== loadVersion) return
const lastPage = Math.max(1, Math.ceil((detail?.total || 0) / size.value))
if (page.value > lastPage) { page.value = lastPage; detail = await fetchTrash({ page: page.value, size: size.value, ...applied.value }) }
if (version !== loadVersion) return
items.value = detail?.data || []; total.value = Number(detail?.total || 0)
summary.value = detail?.summary; capabilities.value = detail?.capabilities
selectedIds.value = selectedIds.value.filter(id => eligibleIds.value.includes(id))
} catch (error) { if (version === loadVersion) errorText.value = getErrorMessage(error, '回收站加载失败,请重试') }
finally { if (version === loadVersion) isLoading.value = false }
}
const applyFilters = () => { if (!supportsFilters.value || busy.value) return; applied.value = { ...draft.value, keyword: draft.value.keyword.trim() }; selectedIds.value = []; page.value = 1; void loadTrash() }
const resetFilters = () => { draft.value = blankFilters(); applyFilters() }
const changePage = (value: number) => { if (busy.value) return; page.value = value; selectedIds.value = []; void loadTrash() }
const changePageSize = (value: number) => { if (busy.value) return; size.value = value; page.value = 1; selectedIds.value = []; void loadTrash() }
const runSingle = async (operation: () => Promise<unknown>, message: string) => {
if (busy.value) return false
busy.value = true; errorText.value = ''; resultText.value = ''; operationResult.value = null
try { await operation(); resultText.value = message; await loadTrash(); return true }
catch (error) { errorText.value = getErrorMessage(error, '操作失败,请重试'); return false }
finally { busy.value = false }
}
const executeBatch = async (action: TrashBatchRequest['action'], ids: number[], retention: TrashRetentionRequest = {}) => {
if (busy.value || !ids.length || !supportsBatch.value) return false
busy.value = true; errorText.value = ''; resultText.value = ''; operationResult.value = null
try {
const response = await batchTrash({ action, ids: [...ids], ...retention })
if (!response.detail) throw new Error('未收到操作结果,请刷新后核对')
operationResult.value = response.detail; resultText.value = summarizeTrashBatch(response.detail)
selectedIds.value = response.detail.failed.map(entry => entry.id)
await loadTrash()
return response.detail.failed.length === 0
} catch (error) { errorText.value = getErrorMessage(error, '操作失败,请重试'); return false }
finally { busy.value = false }
}
const restore = (item: TrashFileItem) => supportsBatch.value ? executeBatch('restore', [item.id]) : runSingle(() => restoreTrashItem(item.id), '已恢复,请到文件管理查看取件码')
const makePermanent = (item: TrashFileItem) => supportsBatch.value ? executeBatch('retention', [item.id], { retentionDays: 0 }) : runSingle(() => updateTrashRetention(item.id, { retentionDays: 0 }), '已设为永久保留')
const retentionOpen = ref(false), retentionIds = ref<number[]>([]), retainForever = ref(false), cleanupTime = ref(''), dialogError = ref('')
const localDateTime = (date: Date) => `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}T${String(date.getHours()).padStart(2,'0')}:${String(date.getMinutes()).padStart(2,'0')}`
const openRetention = (ids: number[]) => {
retentionIds.value = [...ids]; dialogError.value = ''
const item = ids.length === 1 ? items.value.find(item => item.id === ids[0]) : undefined
const current = new Date(item?.trashExpiresAt || '').getTime()
retainForever.value = item?.isTrashPermanent === true
cleanupTime.value = localDateTime(new Date(Number.isFinite(current) && current > Date.now() ? current : Date.now()+30*86400000))
retentionOpen.value = true
}
const saveRetention = async () => {
try {
dialogError.value = ''
const payload = buildTrashRetention(retainForever.value, cleanupTime.value, Date.now())
const ok = await executeBatch('retention', retentionIds.value, payload)
if (ok) retentionOpen.value = false
else dialogError.value = errorText.value || resultText.value || '操作未完成,请重试'
} catch (error) { dialogError.value = getErrorMessage(error, '请选择有效的清理时间') }
}
const purgeOpen = ref(false), purgeIds = ref<number[]>([])
const askPurge = (ids: number[]) => { errorText.value = ''; purgeIds.value = [...ids]; purgeOpen.value = true }
const confirmPurge = async () => {
const ok = supportsBatch.value ? await executeBatch('purge', purgeIds.value) : await runSingle(() => purgeTrashItem(purgeIds.value[0]), '文件本体已清理,审计记录已保留')
if (ok || operationResult.value) purgeOpen.value = false
}
void loadTrash()
</script>
<style scoped>
.trash-row-selected { background: var(--fcb-row-hover); }
</style>