feat: 完善后台导入日志权限与备份恢复

This commit is contained in:
Nixevol
2026-07-04 09:06:35 +08:00
parent 5ae3b12fff
commit d484da3862
61 changed files with 2743 additions and 436 deletions
+18
View File
@@ -53,7 +53,9 @@ export const traceCodeApi = {
update: (id: string, data: { groupId?: number | null; batchId?: number; batchNo?: string; disabled?: boolean }) =>
put(`/trace-codes/${id}`, data),
remove: (id: string) => del(`/trace-codes/${id}`),
batchDelete: (ids: string[]) => post('/trace-codes/batch/delete', { ids }),
qrUrl: (id: string) => `/api/trace-codes/${id}/qrcode`,
qrBlob: (id: string) => download(`/trace-codes/${id}/qrcode`),
onchain: (id: string) => post(`/trace-codes/${id}/onchain`, {}),
// 分组
groups: () => get<any[]>('/trace-code-groups'),
@@ -73,6 +75,10 @@ export const traceCodeApi = {
export const outboundApi = {
updateSingle: (id: string, data: object) => put(`/outbound/trace-codes/${id}`, data),
templateUrl: '/api/outbound/import/template',
preview: (data: FormData) => post('/outbound/import/preview', data),
session: (id: string) => get(`/outbound/import-sessions/${id}`),
rows: (id: string, params: object) => get<PageResult<any>>(`/outbound/import-sessions/${id}/rows`, params),
commit: (id: string) => post(`/outbound/import-sessions/${id}/commit`, {}),
};
export const auditApi = {
@@ -102,4 +108,16 @@ export const settingsApi = {
update: (data: object) => put('/settings', data),
};
export const operationLogApi = {
list: (params: object) => get<PageResult<any>>('/operation-logs', params),
};
export const backupApi = {
list: (params: object) => get<PageResult<any>>('/backups', params),
create: () => post('/backups', {}),
remove: (id: string) => del(`/backups/${id}`),
restorePreview: (data: FormData) => post('/backups/restore/preview', data),
restoreCommit: (restoreId: string) => post('/backups/restore/commit', { restoreId }),
};
export { download, get, post, put, del };
+2 -2
View File
@@ -69,8 +69,8 @@ export function post<T = unknown>(url: string, data?: object, config?: AxiosRequ
export function put<T = unknown>(url: string, data?: object): Promise<T> {
return instance.put(url, data) as unknown as Promise<T>;
}
export function del<T = unknown>(url: string): Promise<T> {
return instance.delete(url) as unknown as Promise<T>;
export function del<T = unknown>(url: string, data?: object): Promise<T> {
return instance.delete(url, { data }) as unknown as Promise<T>;
}
export function download(url: string, params?: object): Promise<{ data: Blob; headers: Record<string, string> }> {
+19 -10
View File
@@ -3,9 +3,10 @@
<div class="grid">
<div v-for="(m, i) in list" :key="m.key" class="item">
<div
class="cell"
class="cell previewable"
:class="{ dragging: dragIndex === i, over: overIndex === i }"
draggable="true"
@click="preview(i)"
@dragstart="onDragStart(i)"
@dragover.prevent="onDragOver(i)"
@drop="onDrop(i)"
@@ -15,7 +16,7 @@
<img v-else class="thumb" :src="m.url" :alt="m.name" />
<div v-if="isVideo(m)" class="play"><n-icon :component="PlayCircleOutline" :size="26" /></div>
<div class="order">{{ i + 1 }}</div>
<button class="del" type="button" :title="t('common.action.delete')" @click="remove(i)">×</button>
<button class="del" type="button" :title="t('common.action.delete')" @click.stop="remove(i)">×</button>
</div>
<n-input
v-if="captionable"
@@ -27,12 +28,10 @@
/>
</div>
<!-- 上传中占位 -->
<div v-for="u in uploading" :key="u.id" class="item">
<div class="cell uploading"><n-spin size="small" /></div>
</div>
<!-- 上传按钮 -->
<label v-if="list.length + uploading.length < max" class="item">
<span class="cell add">
<input ref="inputRef" type="file" accept="image/*,video/*" multiple hidden @change="onPick" />
@@ -52,6 +51,7 @@ import { NIcon, NSpin, NInput } from 'naive-ui';
import { AddOutline, PlayCircleOutline } from '@vicons/ionicons5';
import { post } from '@/api/request';
import { message } from '@/utils/feedback';
import { openMediaViewer } from '@/composables/openMediaViewer';
interface MediaItem {
key: string;
@@ -67,16 +67,16 @@ const props = withDefaults(
const emit = defineEmits<{ (e: 'update:modelValue', v: MediaItem[]): void }>();
const { t } = useI18n();
function updateCaption(i: number, v: string) {
const arr = list.value.map((m, idx) => (idx === i ? { ...m, name: v } : m));
emit('update:modelValue', arr);
}
const inputRef = ref<HTMLInputElement | null>(null);
const list = computed<MediaItem[]>(() => props.modelValue || []);
const uploading = ref<{ id: number }[]>([]);
let seq = 0;
function updateCaption(i: number, v: string) {
const arr = list.value.map((m, idx) => (idx === i ? { ...m, name: v } : m));
emit('update:modelValue', arr);
}
function isVideo(m: MediaItem) {
return m.type === 'video' || /\.(mp4|webm|mov|m4v|ogg)$/i.test(m.url || m.key || '');
}
@@ -117,7 +117,13 @@ function remove(i: number) {
emit('update:modelValue', list.value.filter((_, idx) => idx !== i));
}
/* 拖拽排序 */
function preview(index: number) {
void openMediaViewer(
list.value.map((m) => ({ url: m.url || m.key, name: m.name || m.key, type: m.type })),
index,
);
}
const dragIndex = ref<number | null>(null);
const overIndex = ref<number | null>(null);
function onDragStart(i: number) {
@@ -183,6 +189,9 @@ function onDragEnd() {
.cell[draggable='true'] {
cursor: grab;
}
.previewable {
cursor: zoom-in;
}
.play {
position: absolute;
inset: 0;
+16 -4
View File
@@ -1,10 +1,10 @@
<template>
<div class="media-upload" :class="{ text: listType === 'text' }">
<div v-if="listType === 'image-card'" class="image-grid">
<div v-for="m in items" :key="m.key" class="image-item">
<div v-for="(m, i) in items" :key="m.key" class="image-item previewable" @click="preview(i)">
<img v-if="isImage(m)" class="image-thumb" :src="m.url || m.key" :alt="m.name || m.key" />
<div v-else class="file-thumb">{{ fileExt(m) }}</div>
<button class="remove" type="button" :title="t('common.action.delete')" @click="remove(m.key)">×</button>
<button class="remove" type="button" :title="t('common.action.delete')" @click.stop="remove(m.key)">×</button>
</div>
<div v-for="u in uploading" :key="u.id" class="image-item uploading">
<n-spin size="small" />
@@ -17,8 +17,8 @@
</div>
<div v-else class="file-list">
<div v-for="m in items" :key="m.key" class="file-row">
<span class="file-name" :title="m.name || m.key">{{ m.name || m.key }}</span>
<div v-for="(m, i) in items" :key="m.key" class="file-row">
<span class="file-name" :title="m.name || m.key" @click="preview(i)">{{ m.name || m.key }}</span>
<n-button quaternary circle size="tiny" type="error" :title="t('common.action.delete')" @click="remove(m.key)">
×
</n-button>
@@ -45,6 +45,7 @@ import { NButton, NIcon, NSpin } from 'naive-ui';
import { AddOutline, CloudUploadOutline } from '@vicons/ionicons5';
import { post } from '@/api/request';
import { message } from '@/utils/feedback';
import { openMediaViewer } from '@/composables/openMediaViewer';
interface MediaItem {
key: string;
@@ -115,6 +116,13 @@ async function uploadOne(file: File) {
function remove(key: string) {
emit('update:modelValue', items.value.filter((m) => m.key !== key));
}
function preview(index: number) {
void openMediaViewer(
items.value.map((m) => ({ url: m.url || m.key, name: m.name || m.key, type: m.type })),
index,
);
}
</script>
<style scoped>
@@ -143,6 +151,10 @@ function remove(key: string) {
height: 100%;
object-fit: cover;
}
.previewable,
.file-name {
cursor: zoom-in;
}
.file-thumb {
font-size: 12px;
color: #6b7280;
+49 -13
View File
@@ -41,6 +41,7 @@
<n-button size="small" @click="openBatchModal()">{{ t('pages.traceCode.batchMove') }}</n-button>
<n-button size="small" @click="batchStatus(false)">{{ t('pages.traceCode.batchEnable') }}</n-button>
<n-button size="small" type="warning" @click="batchStatus(true)">{{ t('pages.traceCode.batchDisable') }}</n-button>
<n-button size="small" type="error" @click="batchDelete">{{ t('common.action.delete') }}</n-button>
</n-space>
</n-card>
@@ -154,7 +155,7 @@
</n-form-item-gi>
</n-grid>
<n-form-item :label="t('pages.outbound.outImage')">
<media-upload v-model="outImages" type="image" :max="1" />
<media-upload v-model="outImages" type="image" :max="8" />
</n-form-item>
<n-divider style="margin: 4px 0 14px">{{ t('pages.outbound.onchainSection') }}</n-divider>
<n-grid :cols="2" :x-gap="16">
@@ -187,7 +188,7 @@
</template>
<script setup lang="ts">
import { computed, h, onMounted, reactive, ref, watch } from 'vue';
import { computed, h, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { NButton, NDropdown, NIcon, NTag, NText, type DataTableColumns, type DropdownOption } from 'naive-ui';
@@ -272,6 +273,7 @@ let artworkTimer: ReturnType<typeof setTimeout> | null = null;
const qrModal = ref(false);
const qrSrc = ref('');
const qrUrl = ref('');
let qrBlobUrl = '';
const groupModal = ref(false);
const groupForm = reactive<{ name: string }>({ name: '' });
@@ -309,7 +311,7 @@ const columns = computed<DataTableColumns<any>>(() => {
key: 'outboundStatus',
width: 96,
render: (r) =>
r.outTime || r.outImage
r.outTime || r.outImage || getOutImages(r).length
? h(NTag, { size: 'small', type: 'success' }, { default: () => t('pages.traceCode.outRegistered') })
: h(NText, { depth: 3 }, { default: () => t('pages.traceCode.notOutbound') }),
},
@@ -533,8 +535,11 @@ async function generate() {
}
}
function showQr(r: any) {
qrSrc.value = traceCodeApi.qrUrl(r.id);
async function showQr(r: any) {
if (qrBlobUrl) URL.revokeObjectURL(qrBlobUrl);
const res = await traceCodeApi.qrBlob(String(r.id));
qrBlobUrl = URL.createObjectURL(res.data);
qrSrc.value = qrBlobUrl;
qrUrl.value = r.url;
qrModal.value = true;
}
@@ -542,20 +547,18 @@ function showQr(r: any) {
const exportOptions = computed(() => {
const cur = t('pages.traceCode.exportCurrent');
const opts: Array<{ label: string; key: string }> = [
{ label: `Excel - ${cur}`, key: 'filter:xlsx' },
{ label: `CSV - ${cur}`, key: 'filter:csv' },
{ label: `Excel - ${cur}`, key: 'filter' },
];
if (checkedKeys.value.length) {
const sel = t('pages.traceCode.selected', { n: checkedKeys.value.length });
opts.push({ label: `Excel - ${sel}`, key: 'selected:xlsx' });
opts.push({ label: `CSV - ${sel}`, key: 'selected:csv' });
opts.push({ label: `Excel - ${sel}`, key: 'selected' });
}
return opts;
});
async function onExport(key: string) {
const [scope, format] = key.split(':');
const params: Record<string, unknown> = { format };
const scope = key;
const params: Record<string, unknown> = {};
if (scope === 'selected') {
params.ids = checkedKeys.value.map(String).join(',');
} else {
@@ -567,7 +570,7 @@ async function onExport(key: string) {
if (query.outboundStatus) params.outboundStatus = query.outboundStatus;
if (query.keyword) params.keyword = query.keyword;
}
await downloadFile('/trace-codes/export', `trace-codes.${format}`, params);
await downloadFile('/trace-codes/export', 'trace-codes.xlsx', params);
}
async function batchAssignGroup(key: string) {
@@ -585,6 +588,24 @@ async function batchStatus(disabled: boolean) {
emit('changed');
}
function batchDelete() {
if (!checkedKeys.value.length) return;
dialog.warning({
title: t('common.action.delete'),
content: t('common.msg.confirmDelete'),
positiveText: t('common.action.confirm'),
negativeText: t('common.action.cancel'),
onPositiveClick: async () => {
await traceCodeApi.batchDelete(checkedKeys.value.map(String));
checkedKeys.value = [];
message.success(t('common.msg.deleted'));
await loadBatches();
await load();
emit('changed');
},
});
}
function rowActionOptions(row: any): DropdownOption[] {
return [
{ label: t('pages.traceCode.changeGroup'), key: 'changeGroup', children: rowGroupOptions.value },
@@ -684,6 +705,16 @@ function fileName(key: string) {
return key.split('/').pop() || key;
}
function getOutImages(row: any) {
const list = Array.isArray(row.outImages) ? row.outImages : [];
if (list.length) {
return list.map((item: any) =>
typeof item === 'string' ? { key: item, url: item, name: fileName(item), type: 'image' } : item,
);
}
return row.outImage ? [{ key: row.outImage, url: row.outImageUrl || row.outImage, name: fileName(row.outImage), type: 'image' }] : [];
}
function openOutboundModal(row: any) {
outboundTarget.value = row;
const latestProof = row.latestProof;
@@ -692,7 +723,7 @@ function openOutboundModal(row: any) {
outboundForm.txHash = latestProof?.txHash || '';
outboundForm.onchainAt = formatDateTime(latestProof?.onchainAt);
outboundForm.blockHeight = toNumber(latestProof?.blockHeight);
outImages.value = row.outImage ? [{ key: row.outImage, url: row.outImageUrl || row.outImage, name: fileName(row.outImage) }] : [];
outImages.value = getOutImages(row);
outboundModal.value = true;
}
@@ -707,6 +738,7 @@ async function saveOutbound(triggerOnchain: boolean) {
await outboundApi.updateSingle(String(outboundTarget.value.id), {
outTime: outboundForm.outTime ? dayjs(outboundForm.outTime).toISOString() : null,
outImageKey: outImages.value[0]?.key ?? null,
outImageKeys: outImages.value.map((item) => item.key).filter(Boolean),
txHash: outboundForm.txHash || undefined,
onchainAt: outboundForm.onchainAt ? dayjs(outboundForm.onchainAt).toISOString() : undefined,
blockHeight: outboundForm.blockHeight ?? undefined,
@@ -786,6 +818,10 @@ onMounted(async () => {
await Promise.all([loadBatches(), loadGroups()]);
await load();
});
onUnmounted(() => {
if (qrBlobUrl) URL.revokeObjectURL(qrBlobUrl);
});
</script>
<style scoped>
@@ -0,0 +1,92 @@
import PhotoSwipe from 'photoswipe';
import PhotoSwipeLightbox from 'photoswipe/lightbox';
import 'photoswipe/style.css';
export interface MediaViewerItem {
url?: string;
name?: string;
type?: string;
}
const sizeCache = new Map<string, { width: number; height: number }>();
function isVideo(item: MediaViewerItem): boolean {
return item.type === 'video' || /\.(mp4|webm|mov|m4v|ogg)$/i.test(item.url || '');
}
function getImageSize(url: string): Promise<{ width: number; height: number }> {
const cached = sizeCache.get(url);
if (cached) return Promise.resolve(cached);
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const size = {
width: img.naturalWidth || 1600,
height: img.naturalHeight || 1200,
};
sizeCache.set(url, size);
resolve(size);
};
img.onerror = () => resolve({ width: 1600, height: 1200 });
img.src = url;
});
}
export async function openMediaViewer(items: MediaViewerItem[], index = 0): Promise<void> {
const list = (items || []).filter((item) => item.url);
if (!list.length) return;
const start = Math.min(Math.max(index, 0), list.length - 1);
const dataSource = await Promise.all(
list.map(async (item) => {
if (isVideo(item)) {
return { type: 'video', src: item.url, title: item.name };
}
const size = await getImageSize(item.url as string);
return {
src: item.url,
width: size.width,
height: size.height,
alt: item.name,
title: item.name,
};
}),
);
const lightbox = new PhotoSwipeLightbox({
dataSource,
index: start,
pswpModule: PhotoSwipe as any,
loop: true,
bgOpacity: 0.96,
wheelToZoom: true,
});
lightbox.on('contentLoad', (event: any) => {
const { content } = event;
if (content?.data?.type !== 'video') return;
event.preventDefault();
const wrap = document.createElement('div');
wrap.style.cssText = 'width:100%;height:100%;display:flex;align-items:center;justify-content:center;';
const video = document.createElement('video');
video.src = content.data.src;
video.controls = true;
video.playsInline = true;
video.preload = 'metadata';
video.style.cssText = 'max-width:100%;max-height:100%;background:#000;';
wrap.appendChild(video);
content.element = wrap;
});
const pauseVideo = (event: any) => {
const video = event?.content?.element?.querySelector?.('video') as HTMLVideoElement | null;
video?.pause();
};
lightbox.on('contentDeactivate', pauseVideo);
lightbox.on('close', () => {
const video = document.querySelector('.pswp video') as HTMLVideoElement | null;
video?.pause();
});
lightbox.init();
lightbox.loadAndOpen(start);
}
+2
View File
@@ -99,6 +99,8 @@ const menuOptions = computed<MenuOption[]>(() => {
{ label: t('menu.outbound'), key: 'outbound', icon: renderIcon(CubeOutline) },
{ label: t('menu.audit'), key: 'audit', icon: renderIcon(ShieldCheckmarkOutline), auditOnly: true },
{ label: t('menu.queryLogs'), key: 'queryLogs', icon: renderIcon(ListOutline) },
{ label: t('menu.operationLogs'), key: 'operationLogs', icon: renderIcon(ListOutline), superOnly: true },
{ label: t('menu.backups'), key: 'backups', icon: renderIcon(SettingsOutline), superOnly: true },
{ label: t('menu.users'), key: 'users', icon: renderIcon(PeopleOutline), superOnly: true },
{ label: t('menu.settings'), key: 'settings', icon: renderIcon(SettingsOutline), superOnly: true },
];
+2
View File
@@ -130,6 +130,8 @@
"outbound": "Outbound & Chain",
"audit": "Content Audit",
"queryLogs": "Query Logs",
"operationLogs": "Operation Logs",
"backups": "Backup & Restore",
"users": "Users",
"settings": "Settings",
"profile": "Profile"
+8 -6
View File
@@ -130,6 +130,8 @@
"outbound": "出库与上链",
"audit": "内容审核",
"queryLogs": "查询日志",
"operationLogs": "操作日志",
"backups": "备份与恢复",
"users": "用户管理",
"settings": "系统设置",
"profile": "个人中心"
@@ -171,7 +173,7 @@
"edit": "编辑模板",
"namePlaceholder": "请输入模板名称",
"fieldKeyTip": "英文唯一标识,如 craft",
"sortHint": "字段顺序即 C 端展示顺序,可用上下箭头调整"
"sortHint": "字段顺序即客户端展示顺序,可用上下箭头调整"
},
"audit": {
"status": "审核状态",
@@ -181,9 +183,9 @@
"rejected": "已驳回",
"remark": "审核意见",
"remarkPlaceholder": "请填写驳回原因或修改建议",
"approveConfirm": "确认通过《{title}》的审核?通过后将对 C 端可见。",
"approveConfirm": "确认通过《{title}》的审核?通过后将对客户端可见。",
"rejectedTip": "该作品审核未通过,请按意见修改后保存再次提交审核",
"pendingTip": "该作品待审核,审核通过后方可在 C 端展示;保存修改会重新进入待审核"
"pendingTip": "该作品待审核,审核通过后方可在客户端展示;保存修改会重新进入待审核"
},
"artwork": {
"title": "名称",
@@ -201,8 +203,8 @@
"selectArtwork": "选择作品",
"selectArtworkTip": "搜索档案号 / 作品名选择作品(款)",
"images": "作品",
"mediaHint": "支持图片与视频,拖拽可调整顺序(顺序即 C 端展示顺序)",
"mediaHintCaption": "支持图片与视频,可为每张填写标题(如设计稿、选胚图),拖拽调整顺序(即 C 端展示顺序)",
"mediaHint": "支持图片与视频,拖拽可调整顺序(顺序即客户端展示顺序)",
"mediaHintCaption": "支持图片与视频,可为每张填写标题(如设计稿、选胚图),拖拽调整顺序(即客户端展示顺序)",
"imageCaption": "图片标题",
"nodeMedia": "节点图片 / 视频",
"basicInfo": "基础信息",
@@ -335,7 +337,7 @@
"appName": "平台名称",
"logRetentionDays": "日志保留天数",
"watermarkText": "证书水印文案",
"carouselInterval": "C 端轮播间隔(秒)",
"carouselInterval": "客户端轮播间隔(秒)",
"carouselIntervalHint": "每张媒体停留秒数,支持小数;填 0 则不自动切换(仍可手动循环切换)",
"saved": "设置已保存"
},
+2
View File
@@ -24,6 +24,8 @@ export const routes: RouteRecordRaw[] = [
{ path: 'outbound', name: 'outbound', component: () => import('@/views/Outbound.vue') },
{ path: 'audit', name: 'audit', component: () => import('@/views/Audit.vue'), meta: { roles: ['SUPER_ADMIN', 'AUDITOR'] } },
{ path: 'query-logs', name: 'queryLogs', component: () => import('@/views/QueryLogs.vue') },
{ path: 'operation-logs', name: 'operationLogs', component: () => import('@/views/OperationLogs.vue'), meta: { roles: ['SUPER_ADMIN'] } },
{ path: 'backups', name: 'backups', component: () => import('@/views/Backups.vue'), meta: { roles: ['SUPER_ADMIN'] } },
{ path: 'users', name: 'users', component: () => import('@/views/Users.vue'), meta: { roles: ['SUPER_ADMIN'] } },
{ path: 'settings', name: 'settings', component: () => import('@/views/Settings.vue'), meta: { roles: ['SUPER_ADMIN'] } },
{ path: 'profile', name: 'profile', component: () => import('@/views/Profile.vue') },
+28
View File
@@ -86,3 +86,31 @@ body,
text-overflow: ellipsis;
white-space: nowrap;
}
.row-actions {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
width: 100%;
}
.filter-title {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
width: 100%;
min-width: 0;
}
.filter-title-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.filter-trigger {
flex: 0 0 auto;
opacity: 0.62;
}
.filter-trigger.active {
color: var(--brand);
opacity: 1;
}
+12 -1
View File
@@ -13,5 +13,16 @@ export function saveBlob(blob: Blob, filename: string): void {
export async function downloadFile(url: string, filename: string, params?: object): Promise<void> {
const res = await download(url, params);
saveBlob(res.data, filename);
saveBlob(res.data, pickFilename(res.headers, filename));
}
function pickFilename(headers: Record<string, string>, fallback: string): string {
const disposition = headers['content-disposition'] || headers['Content-Disposition'];
const match = disposition?.match(/filename\*?=(?:UTF-8''|")?([^";]+)/i);
if (!match?.[1]) return fallback;
try {
return decodeURIComponent(match[1].replace(/"/g, ''));
} catch {
return match[1].replace(/"/g, '');
}
}
+41
View File
@@ -0,0 +1,41 @@
import { h } from 'vue';
import { NButton, NDropdown, NIcon, type DropdownOption } from 'naive-ui';
import { FilterOutline } from '@vicons/ionicons5';
export interface TableFilterOption {
label: string;
value: string | number;
}
export function renderTableFilterTitle(
label: string,
value: string | number | null | undefined,
options: TableFilterOption[],
onSelect: (value: string | number | null) => void,
allLabel = '全部',
) {
const active = value !== null && value !== undefined && value !== '';
const dropdownOptions: DropdownOption[] = [
{ label: allLabel, key: '__all__' },
...options.map((item) => ({ label: item.label, key: item.value })),
];
return h('div', { class: 'filter-title' }, [
h('span', { class: 'filter-title-text' }, label),
h(
NDropdown,
{
trigger: 'click',
options: dropdownOptions,
onSelect: (key) => onSelect(key === '__all__' ? null : (key as string | number)),
},
{
default: () =>
h(
NButton,
{ quaternary: true, circle: true, size: 'tiny', class: ['filter-trigger', { active }], title: '筛选' },
{ icon: () => h(NIcon, null, { default: () => h(FilterOutline) }) },
),
},
),
]);
}
+25 -13
View File
@@ -8,14 +8,6 @@
style="width: 220px"
@keyup.enter="onSearch"
/>
<n-select
v-model:value="query.status"
:options="statusOptions"
clearable
:placeholder="t('common.label.status')"
style="width: 140px"
@update:value="onSearch"
/>
<n-button type="primary" @click="onSearch">
<template #icon><n-icon :component="SearchOutline" /></template>
{{ t('common.action.search') }}
@@ -50,12 +42,14 @@ import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { NButton, NIcon, NTag, NAvatar, type DataTableColumns } from 'naive-ui';
import { SearchOutline, AddOutline, CreateOutline, BarChartOutline, TrashOutline } from '@vicons/ionicons5';
import { ArtworkStatus } from '@artveris/shared';
import { ArtworkStatus, AuditStatus } from '@artveris/shared';
import { artworkApi } from '@/api';
import { useAuthStore } from '@/stores/auth';
import { fmt, statusType } from '@/utils/format';
import { useTablePage } from '@/composables/useTablePage';
import { dialog, message } from '@/utils/feedback';
import { renderTableFilterTitle } from '@/utils/tableFilter';
import { openMediaViewer } from '@/composables/openMediaViewer';
const { t } = useI18n();
const router = useRouter();
@@ -63,12 +57,14 @@ const auth = useAuthStore();
const rows = ref<any[]>([]);
const loading = ref(false);
const query = reactive<{ keyword: string; status: string | null }>({
const query = reactive<{ keyword: string; status: string | null; auditStatus: string | null }>({
keyword: '',
status: null,
auditStatus: null,
});
const { pagination, page, pageSize, resetPage, setPageResult } = useTablePage(load);
const statusOptions = Object.values(ArtworkStatus).map((v) => ({ label: t(`common.status.${v}`), value: v }));
const auditStatusOptions = Object.values(AuditStatus).map((v) => ({ label: t(`common.auditStatus.${v}`), value: v }));
const columns: DataTableColumns<any> = [
{
@@ -77,7 +73,12 @@ const columns: DataTableColumns<any> = [
width: 76,
render: (r) =>
r.images?.[0]?.url
? h(NAvatar, { src: r.images[0].url, size: 44, style: 'border-radius:8px' })
? h(NAvatar, {
src: r.images[0].url,
size: 44,
style: 'border-radius:8px;cursor:zoom-in',
onClick: () => previewArtworkImages(r.images),
})
: h(NAvatar, { size: 44, style: 'border-radius:8px' }, { default: () => '—' }),
},
{ title: () => t('pages.artwork.archiveNo'), key: 'archiveNo', width: 140, render: (r) => r.archiveNo || '-' },
@@ -87,13 +88,13 @@ const columns: DataTableColumns<any> = [
{ title: () => t('pages.artwork.codeCount'), key: 'codeCount', width: 80, render: (r) => r.codeCount ?? 0 },
{ title: () => t('pages.artwork.queryTotal'), key: 'queryTotal', width: 90, render: (r) => r.queryTotal ?? 0 },
{
title: () => t('common.label.status'),
title: () => renderTableFilterTitle(t('common.label.status'), query.status, statusOptions, (value) => setFilter('status', value)),
key: 'status',
width: 84,
render: (r) => h(NTag, { type: statusType(r.status), size: 'small' }, { default: () => t(`common.status.${r.status}`) }),
},
{
title: () => t('pages.audit.status'),
title: () => renderTableFilterTitle(t('pages.audit.status'), query.auditStatus, auditStatusOptions, (value) => setFilter('auditStatus', value)),
key: 'auditStatus',
width: 90,
render: (r) =>
@@ -159,6 +160,7 @@ async function load() {
const res: any = await artworkApi.list({
keyword: query.keyword,
status: query.status || undefined,
auditStatus: query.auditStatus || undefined,
page: page.value,
pageSize: pageSize.value,
});
@@ -172,9 +174,19 @@ function onSearch() {
resetPage();
load();
}
function setFilter(field: 'status' | 'auditStatus', value: string | number | null) {
query[field] = value ? String(value) : null;
onSearch();
}
function goCreate() {
router.push('/artworks/new');
}
function previewArtworkImages(images: any[]) {
void openMediaViewer(
(images || []).map((item) => ({ url: item.url || item.key, name: item.name || item.key, type: item.type || 'image' })),
0,
);
}
function remove(r: any) {
dialog.warning({
title: t('common.action.delete'),
+20 -11
View File
@@ -8,14 +8,6 @@
style="width: 220px"
@keyup.enter="onSearch"
/>
<n-select
v-model:value="query.auditStatus"
:options="auditStatusOptions"
clearable
:placeholder="t('pages.audit.status')"
style="width: 150px"
@update:value="onSearch"
/>
<n-button type="primary" @click="onSearch">
<template #icon><n-icon :component="SearchOutline" /></template>
{{ t('common.action.search') }}
@@ -64,6 +56,8 @@ import { auditApi } from '@/api';
import { message, dialog } from '@/utils/feedback';
import { fmt } from '@/utils/format';
import { useTablePage } from '@/composables/useTablePage';
import { renderTableFilterTitle } from '@/utils/tableFilter';
import { openMediaViewer } from '@/composables/openMediaViewer';
const { t } = useI18n();
const router = useRouter();
@@ -93,13 +87,18 @@ const columns: DataTableColumns<any> = [
width: 70,
render: (r) =>
r.images?.[0]?.url
? h(NAvatar, { src: r.images[0].url, size: 40, style: 'border-radius:8px' })
? h(NAvatar, {
src: r.images[0].url,
size: 40,
style: 'border-radius:8px;cursor:zoom-in',
onClick: () => previewArtworkImages(r.images),
})
: h(NAvatar, { size: 40, style: 'border-radius:8px' }, { default: () => '—' }),
},
{ title: () => t('pages.artwork.title'), key: 'title', width: 220, ellipsis: { tooltip: true } },
{ title: () => t('pages.artwork.artist'), key: 'artist', width: 110, render: (r) => r.artist || '-' },
{
title: () => t('pages.audit.status'),
title: () => renderTableFilterTitle(t('pages.audit.status'), query.auditStatus, auditStatusOptions, (value) => setAuditFilter(value)),
key: 'auditStatus',
width: 100,
render: (r) => h(NTag, { size: 'small', type: auditTagType(r.auditStatus) }, { default: () => t(`common.auditStatus.${r.auditStatus}`) }),
@@ -113,7 +112,7 @@ const columns: DataTableColumns<any> = [
fixed: 'right',
align: 'center',
render: (r) =>
h('div', { style: 'display:flex;gap:2px' }, [
h('div', { class: 'row-actions' }, [
h(NButton, { quaternary: true, circle: true, size: 'small', title: t('common.action.detail'), onClick: () => router.push(`/artworks/${r.id}`) }, { icon: () => h(NIcon, null, { default: () => h(EyeOutline) }) }),
h(NButton, { quaternary: true, circle: true, size: 'small', type: 'success', title: t('pages.audit.approve'), disabled: r.auditStatus === 'APPROVED', onClick: () => approve(r) }, { icon: () => h(NIcon, null, { default: () => h(CheckmarkCircleOutline) }) }),
h(NButton, { quaternary: true, circle: true, size: 'small', type: 'error', title: t('pages.audit.reject'), disabled: r.auditStatus === 'REJECTED', onClick: () => openReject(r) }, { icon: () => h(NIcon, null, { default: () => h(CloseCircleOutline) }) }),
@@ -140,6 +139,16 @@ function onSearch() {
resetPage();
load();
}
function previewArtworkImages(images: any[]) {
void openMediaViewer(
(images || []).map((item) => ({ url: item.url || item.key, name: item.name || item.key, type: item.type || 'image' })),
0,
);
}
function setAuditFilter(value: string | number | null) {
query.auditStatus = value ? String(value) : null;
onSearch();
}
function approve(r: any) {
dialog.success({
title: t('pages.audit.approve'),
+234
View File
@@ -0,0 +1,234 @@
<template>
<div class="page table-page backups-page">
<div class="page-toolbar">
<n-button type="primary" :loading="creating" @click="createBackup">创建备份</n-button>
<n-upload :show-file-list="false" accept=".zip" :custom-request="previewRestore" :disabled="restoring">
<n-button :loading="restoring">上传备份包预校验</n-button>
</n-upload>
<div class="spacer" />
<n-button @click="load">刷新</n-button>
</div>
<n-alert v-if="restorePreviewResult" type="warning" class="restore-alert" :show-icon="true">
已通过备份包预校验:{{ restorePreviewResult.manifest?.createdAt || '-' }}。
恢复会整库覆盖当前系统,确认前会自动生成当前快照。
<n-button size="small" type="error" :loading="restoring" @click="commitRestore">确认恢复</n-button>
</n-alert>
<n-data-table
:columns="columns"
:data="rows"
:loading="loading"
:pagination="false"
class="table-fill"
flex-height
remote
:scroll-x="1280"
:row-key="(r) => r.id"
/>
<div class="table-pagination">
<n-pagination v-bind="pagination" :disabled="loading" />
</div>
</div>
</template>
<script setup lang="ts">
import { computed, h, onMounted, reactive, ref } from 'vue';
import type { UploadCustomRequestOptions } from 'naive-ui';
import { NButton, NDropdown, NIcon, NTag, type DataTableColumns, type DropdownOption } from 'naive-ui';
import { DownloadOutline, FilterOutline, TrashOutline } from '@vicons/ionicons5';
import { backupApi } from '@/api';
import { dialog, message } from '@/utils/feedback';
import { downloadFile } from '@/utils/download';
import { fmt, statusType } from '@/utils/format';
import { useTablePage } from '@/composables/useTablePage';
const rows = ref<any[]>([]);
const loading = ref(false);
const creating = ref(false);
const restoring = ref(false);
const restorePreviewResult = ref<any>(null);
const query = reactive({ status: null as string | null, mode: null as string | null });
const { pagination, page, pageSize, resetPage, setPageResult } = useTablePage(load, 20);
const statusOptions = ['PENDING', 'PROCESSING', 'SUCCESS', 'FAILED'].map((value) => ({ label: value, value }));
const modeOptions = ['BACKUP', 'RESTORE', 'SCHEDULED', 'AUTO_BEFORE_RESTORE'].map((value) => ({ label: value, value }));
const columns = computed<DataTableColumns<any>>(() => [
{ title: '创建时间', key: 'createdAt', width: 170, render: (row) => fmt(row.createdAt) },
{ title: '文件名', key: 'fileName', minWidth: 260, ellipsis: { tooltip: true } },
{
title: () => renderFilterTitle('类型', query.mode, modeOptions, (value) => setFilter('mode', value)),
key: 'mode',
width: 170,
},
{
title: () => renderFilterTitle('状态', query.status, statusOptions, (value) => setFilter('status', value)),
key: 'status',
width: 130,
align: 'center',
render: (row) => h(NTag, { size: 'small', type: statusType(row.status) }, { default: () => row.status }),
},
{ title: '大小', key: 'size', width: 120, render: (row) => formatSize(row.size) },
{ title: '错误', key: 'error', minWidth: 260, ellipsis: { tooltip: true }, render: (row) => row.error || '-' },
{
title: '操作',
key: 'ops',
width: 110,
align: 'center',
fixed: 'right',
render: (row) =>
h('div', { class: 'row-actions' }, [
h(
NButton,
{
quaternary: true,
circle: true,
size: 'small',
disabled: row.status !== 'SUCCESS',
title: '下载',
onClick: () => downloadBackup(row),
},
{ icon: () => h(NIcon, null, { default: () => h(DownloadOutline) }) },
),
h(
NButton,
{ quaternary: true, circle: true, size: 'small', type: 'error', title: '删除', onClick: () => removeBackup(row) },
{ icon: () => h(NIcon, null, { default: () => h(TrashOutline) }) },
),
]),
},
]);
function renderFilterTitle(label: string, value: string | null, options: { label: string; value: string }[], onSelect: (value: string | null) => void) {
const dropdownOptions: DropdownOption[] = [{ label: '全部', key: '__all__' }, ...options.map((item) => ({ label: item.label, key: item.value }))];
return h('div', { class: 'filter-title' }, [
h('span', { class: 'filter-title-text' }, label),
h(
NDropdown,
{ trigger: 'click', options: dropdownOptions, onSelect: (key) => onSelect(key === '__all__' ? null : String(key)) },
{
default: () =>
h(
NButton,
{ quaternary: true, circle: true, size: 'tiny', class: ['filter-trigger', { active: !!value }], title: '筛选' },
{ icon: () => h(NIcon, null, { default: () => h(FilterOutline) }) },
),
},
),
]);
}
function setFilter(field: 'status' | 'mode', value: string | null) {
query[field] = value;
resetPage();
void load();
}
function formatSize(value: unknown) {
const n = Number(value || 0);
if (!n) return '-';
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / 1024 / 1024).toFixed(1)} MB`;
}
async function load() {
loading.value = true;
try {
const res: any = await backupApi.list({
status: query.status || undefined,
mode: query.mode || undefined,
page: page.value,
pageSize: pageSize.value,
});
rows.value = res.list;
setPageResult(res);
} finally {
loading.value = false;
}
}
async function createBackup() {
creating.value = true;
try {
await backupApi.create();
message.success('备份已创建');
await load();
} finally {
creating.value = false;
}
}
async function downloadBackup(row: any) {
await downloadFile(`/backups/${row.id}/download`, row.fileName || 'artveris-backup.zip');
}
function removeBackup(row: any) {
dialog.warning({
title: '删除备份',
content: '确认删除该备份记录和服务器上的备份包?',
positiveText: '确认',
negativeText: '取消',
onPositiveClick: async () => {
await backupApi.remove(row.id);
message.success('已删除');
await load();
},
});
}
async function previewRestore({ file, onFinish, onError }: UploadCustomRequestOptions) {
restoring.value = true;
try {
const fd = new FormData();
fd.append('file', file.file as File);
restorePreviewResult.value = await backupApi.restorePreview(fd);
message.success('备份包预校验通过');
await load();
onFinish();
} catch (e) {
message.error((e as Error)?.message || '预校验失败');
onError();
} finally {
restoring.value = false;
}
}
function commitRestore() {
if (!restorePreviewResult.value?.restoreId) return;
dialog.warning({
title: '确认恢复',
content: '恢复会覆盖当前数据库和上传文件。系统会先自动备份当前状态,确认继续?',
positiveText: '确认恢复',
negativeText: '取消',
onPositiveClick: async () => {
restoring.value = true;
try {
await backupApi.restoreCommit(restorePreviewResult.value.restoreId);
restorePreviewResult.value = null;
message.success('恢复完成,请重新检查数据');
await load();
} finally {
restoring.value = false;
}
},
});
}
onMounted(load);
</script>
<style scoped>
.backups-page {
min-width: 0;
}
.restore-alert {
margin-bottom: 12px;
}
.restore-alert :deep(.n-alert-body__content) {
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
</style>
+144
View File
@@ -0,0 +1,144 @@
<template>
<div class="page table-page">
<div class="page-toolbar">
<n-input v-model:value="query.keyword" clearable placeholder="账号 / 路径 / 目标 ID" style="width: 240px" @keyup.enter="onSearch" />
<n-date-picker v-model:value="range" type="datetimerange" clearable style="width: 360px" />
<n-button type="primary" @click="onSearch">查询</n-button>
</div>
<n-data-table
:columns="columns"
:data="rows"
:loading="loading"
:pagination="false"
class="table-fill"
flex-height
remote
:scroll-x="1460"
:row-key="(r) => r.id"
/>
<div class="table-pagination">
<n-pagination v-bind="pagination" :disabled="loading" />
</div>
</div>
</template>
<script setup lang="ts">
import { computed, h, onMounted, reactive, ref, watch } from 'vue';
import { NButton, NDropdown, NIcon, NTag, type DataTableColumns, type DropdownOption } from 'naive-ui';
import { FilterOutline } from '@vicons/ionicons5';
import { operationLogApi } from '@/api';
import { fmt, statusType } from '@/utils/format';
import { useTablePage } from '@/composables/useTablePage';
const rows = ref<any[]>([]);
const loading = ref(false);
const range = ref<[number, number] | null>(null);
const query = reactive({ keyword: '', module: null as string | null, action: null as string | null, status: null as string | null });
const { pagination, page, pageSize, resetPage, setPageResult } = useTablePage(load, 20);
const moduleOptions = [
{ label: 'auth', value: 'auth' },
{ label: 'artworks', value: 'artworks' },
{ label: 'trace-codes', value: 'trace-codes' },
{ label: 'outbound', value: 'outbound' },
{ label: 'backups', value: 'backups' },
{ label: 'settings', value: 'settings' },
{ label: 'users', value: 'users' },
];
const actionOptions = [
{ label: 'POST', value: 'POST' },
{ label: 'PUT', value: 'PUT' },
{ label: 'PATCH', value: 'PATCH' },
{ label: 'DELETE', value: 'DELETE' },
{ label: 'download', value: 'download' },
{ label: 'export', value: 'export' },
];
const resultOptions = [
{ label: 'SUCCESS', value: 'SUCCESS' },
{ label: 'FAILED', value: 'FAILED' },
];
const columns = computed<DataTableColumns<any>>(() => [
{ title: '时间', key: 'createdAt', width: 170, render: (row) => fmt(row.createdAt) },
{ title: '账号', key: 'username', width: 130, render: (row) => row.username || '-' },
{ title: '角色', key: 'role', width: 120 },
{
title: () => renderFilterTitle('模块', query.module, moduleOptions, (value) => setFilter('module', value)),
key: 'module',
width: 140,
},
{
title: () => renderFilterTitle('操作', query.action, actionOptions, (value) => setFilter('action', value)),
key: 'action',
width: 110,
},
{
title: () => renderFilterTitle('结果', query.status, resultOptions, (value) => setFilter('status', value)),
key: 'status',
width: 110,
align: 'center',
render: (row) => h(NTag, { size: 'small', type: statusType(row.status) }, { default: () => row.status }),
},
{ title: '目标 ID', key: 'targetId', width: 150, ellipsis: { tooltip: true }, render: (row) => row.targetId || '-' },
{ title: '路径', key: 'path', width: 260, ellipsis: { tooltip: true } },
{ title: 'IP', key: 'ip', width: 150, ellipsis: { tooltip: true } },
{ title: '耗时', key: 'durationMs', width: 90, render: (row) => `${row.durationMs || 0}ms` },
{ title: '消息', key: 'message', minWidth: 260, ellipsis: { tooltip: true }, render: (row) => row.message || '-' },
]);
function renderFilterTitle(label: string, value: string | null, options: { label: string; value: string }[], onSelect: (value: string | null) => void) {
const dropdownOptions: DropdownOption[] = [{ label: '全部', key: '__all__' }, ...options.map((item) => ({ label: item.label, key: item.value }))];
return h('div', { class: 'filter-title' }, [
h('span', { class: 'filter-title-text' }, label),
h(
NDropdown,
{ trigger: 'click', options: dropdownOptions, onSelect: (key) => onSelect(key === '__all__' ? null : String(key)) },
{
default: () =>
h(
NButton,
{ quaternary: true, circle: true, size: 'tiny', class: ['filter-trigger', { active: !!value }], title: '筛选' },
{ icon: () => h(NIcon, null, { default: () => h(FilterOutline) }) },
),
},
),
]);
}
function setFilter(field: 'module' | 'action' | 'status', value: string | null) {
query[field] = value;
onSearch();
}
async function load() {
loading.value = true;
try {
const params: Record<string, unknown> = {
keyword: query.keyword || undefined,
module: query.module || undefined,
action: query.action || undefined,
status: query.status || undefined,
page: page.value,
pageSize: pageSize.value,
};
if (range.value) {
params.startTime = new Date(range.value[0]).toISOString();
params.endTime = new Date(range.value[1]).toISOString();
}
const res: any = await operationLogApi.list(params);
rows.value = res.list;
setPageResult(res);
} finally {
loading.value = false;
}
}
function onSearch() {
resetPage();
void load();
}
watch(range, onSearch);
onMounted(load);
</script>
+281 -59
View File
@@ -1,90 +1,312 @@
<template>
<div class="page">
<n-card :title="t('pages.outbound.import')" :bordered="false">
<n-alert type="info" :show-icon="true" style="margin-bottom: 16px">
{{ t('pages.outbound.tip') }}
</n-alert>
<n-space>
<n-button @click="downloadTemplate">
<template #icon><n-icon :component="DownloadOutline" /></template>
{{ t('common.action.downloadTemplate') }}
</n-button>
<n-upload
:show-file-list="false"
accept=".xlsx,.xls"
:custom-request="doImport"
:disabled="importing || !auth.canWrite"
>
<n-button type="primary" :loading="importing">
<template #icon><n-icon :component="CloudUploadOutline" /></template>
{{ t('pages.outbound.selectFile') }}
</n-button>
</n-upload>
</n-space>
<n-card v-if="result" embedded :title="t('pages.outbound.importResult')" style="margin-top: 16px">
<n-space align="center" size="large">
<n-statistic :label="t('common.label.total', { n: result.total })" :value="result.total" />
<n-statistic :label="t('pages.outbound.successCount')">
<span style="color: #138a72">{{ result.successCount }}</span>
</n-statistic>
<n-statistic :label="t('pages.outbound.failCount')">
<span style="color: #c0392b">{{ result.failCount }}</span>
</n-statistic>
<n-tag :type="statusType(result.status)">{{ t(`common.status.${result.status}`) }}</n-tag>
<n-button v-if="result.resultFileUrl" text tag="a" :href="result.resultFileUrl" target="_blank" type="primary">
<div class="page table-page outbound-page">
<n-card :bordered="false" class="outbound-card">
<template #header>出库批量导入</template>
<template #header-extra>
<n-space>
<n-button @click="downloadTemplate">
<template #icon><n-icon :component="DownloadOutline" /></template>
{{ t('pages.outbound.downloadResult') }}
下载 ZIP 模板
</n-button>
<n-upload
:show-file-list="false"
accept=".zip"
:custom-request="uploadPreview"
:disabled="busy || !auth.canWrite"
>
<n-button type="primary" :loading="previewing">
<template #icon><n-icon :component="CloudUploadOutline" /></template>
上传 ZIP 并预览
</n-button>
</n-upload>
</n-space>
</template>
<n-alert type="info" :show-icon="true" class="section-alert">
ZIP 内需要包含 1 个 xlsx 文件和 images 文件夹;xlsx 中出库实况图路径填写 images/xxx.jpg,多张用英文分号分隔。
</n-alert>
<n-card v-if="session" embedded class="summary-card" :bordered="false">
<n-space align="center" size="large" wrap>
<n-statistic label="总行数" :value="session.total || 0" />
<n-statistic label="有效行">
<span class="success-text">{{ session.validCount || 0 }}</span>
</n-statistic>
<n-statistic label="错误行">
<span class="danger-text">{{ session.invalidCount || 0 }}</span>
</n-statistic>
<n-tag :type="statusType(session.status)">{{ session.status }}</n-tag>
<n-progress
v-if="busy"
type="line"
:percentage="progressPercent"
:indicator-placement="'inside'"
class="progress"
/>
<n-button
v-if="auth.canWrite"
type="primary"
:disabled="!canCommit"
:loading="committing"
@click="commitImport"
>
确认导入
</n-button>
<n-button v-if="result?.resultFileUrl" tag="a" :href="result.resultFileUrl" target="_blank">
<template #icon><n-icon :component="DownloadOutline" /></template>
下载导入结果
</n-button>
</n-space>
<n-text v-if="session.error" type="error" class="session-error">{{ session.error }}</n-text>
</n-card>
<n-data-table
:columns="columns"
:data="rows"
:loading="loading"
:pagination="false"
class="table-fill"
flex-height
remote
:scroll-x="1320"
:row-key="(r) => r.id"
/>
<div class="table-pagination">
<n-pagination v-bind="pagination" :disabled="loading" />
</div>
</n-card>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { computed, h, ref } from 'vue';
import type { UploadCustomRequestOptions } from 'naive-ui';
import { DownloadOutline, CloudUploadOutline } from '@vicons/ionicons5';
import { jobApi, post } from '@/api';
import { NButton, NIcon, NImage, NTag, NText, type DataTableColumns } from 'naive-ui';
import { CloudUploadOutline, DownloadOutline } from '@vicons/ionicons5';
import { jobApi, outboundApi } from '@/api';
import { useAuthStore } from '@/stores/auth';
import { message } from '@/utils/feedback';
import { statusType } from '@/utils/format';
import { downloadFile } from '@/utils/download';
import { fmt, statusType } from '@/utils/format';
import { useTablePage } from '@/composables/useTablePage';
import { openMediaViewer } from '@/composables/openMediaViewer';
const { t } = useI18n();
const auth = useAuthStore();
const importing = ref(false);
const rows = ref<any[]>([]);
const session = ref<any>(null);
const result = ref<any>(null);
const sessionId = ref('');
const loading = ref(false);
const previewing = ref(false);
const committing = ref(false);
const progressPercent = ref(0);
async function downloadTemplate() {
await downloadFile('/outbound/import/template', 'outbound-import-template.xlsx');
const busy = computed(() => previewing.value || committing.value);
const canCommit = computed(() => session.value?.status === 'READY' && Number(session.value?.invalidCount || 0) === 0);
const { pagination, page, pageSize, resetPage, setPageResult } = useTablePage(loadRows, 20);
const columns = computed<DataTableColumns<any>>(() => [
{ title: '行号', key: 'rowNo', width: 80 },
{
title: '状态',
key: 'status',
width: 110,
align: 'center',
render: (row) => h(NTag, { size: 'small', type: row.status === 'VALID' || row.status === 'IMPORTED' ? 'success' : 'error' }, { default: () => row.status }),
},
{ title: '追溯短码', key: 'shortCode', width: 150, ellipsis: { tooltip: true } },
{ title: '批次编号', key: 'batchNo', width: 180, ellipsis: { tooltip: true } },
{ title: '出库时间', key: 'outTime', width: 170, render: (row) => fmt(row.outTime || row.preview?.outTime) },
{
title: '出库实况图',
key: 'images',
width: 240,
render: (row) => renderImages(row),
},
{ title: '上链哈希', key: 'txHash', width: 240, ellipsis: { tooltip: true } },
{ title: '备注', key: 'remark', width: 180, ellipsis: { tooltip: true } },
{
title: '错误原因',
key: 'reason',
minWidth: 260,
ellipsis: { tooltip: true },
render: (row) => row.reason || h(NText, { depth: 3 }, { default: () => '-' }),
},
]);
function rowImages(row: any) {
const list = Array.isArray(row.outImageKeys) && row.outImageKeys.length ? row.outImageKeys : row.preview?.images;
return Array.isArray(list) ? list.filter((item) => item?.url || item?.key) : [];
}
async function doImport({ file, onFinish, onError }: UploadCustomRequestOptions) {
importing.value = true;
function renderImages(row: any) {
const images = rowImages(row);
if (!images.length) return h(NText, { depth: 3 }, { default: () => '-' });
const visible = images.slice(0, 3);
return h('div', { class: 'preview-images' }, [
...visible.map((item: any, index: number) =>
h(NImage, {
width: 38,
height: 38,
objectFit: 'cover',
src: item.url || item.key,
previewDisabled: true,
onClick: () => previewImages(images, index),
}),
),
images.length > visible.length
? h(
NButton,
{ size: 'tiny', quaternary: true, onClick: () => previewImages(images, visible.length) },
{ default: () => `+${images.length - visible.length}` },
)
: null,
]);
}
function previewImages(images: any[], index: number) {
void openMediaViewer(
images.map((item) => ({ url: item.url || item.key, name: item.name || item.key, type: item.type || 'image' })),
index,
);
}
async function downloadTemplate() {
await downloadFile('/outbound/import/template', 'outbound-import-template.zip');
}
async function uploadPreview({ file, onFinish, onError }: UploadCustomRequestOptions) {
previewing.value = true;
result.value = null;
progressPercent.value = 5;
try {
const fd = new FormData();
fd.append('file', file.file as File);
const res: any = await post('/outbound/import', fd);
const jobId = res.jobId;
let job: any = null;
for (let i = 0; i < 40; i++) {
await new Promise((r) => setTimeout(r, 700));
job = await jobApi.get(jobId);
if (['SUCCESS', 'FAILED', 'PARTIAL'].includes(job.status)) break;
}
result.value = job;
message.success(t('common.msg.operationSuccess'));
const res: any = await outboundApi.preview(fd);
sessionId.value = res.sessionId;
await pollJob(res.jobId, 'preview');
await refreshSession();
resetPage();
await loadRows();
message.success('预览解析完成');
onFinish();
} catch (e) {
message.error((e as Error)?.message || 'import failed');
message.error((e as Error)?.message || '上传失败');
onError();
} finally {
importing.value = false;
previewing.value = false;
progressPercent.value = 0;
}
}
async function commitImport() {
if (!sessionId.value) return;
committing.value = true;
result.value = null;
progressPercent.value = 5;
try {
const res: any = await outboundApi.commit(sessionId.value);
const job = await pollJob(res.jobId, 'commit');
result.value = job;
await refreshSession();
await loadRows();
message.success('导入完成');
} finally {
committing.value = false;
progressPercent.value = 0;
}
}
async function pollJob(jobId: string, phase: 'preview' | 'commit') {
let job: any = null;
for (let i = 0; i < 120; i++) {
await new Promise((resolve) => setTimeout(resolve, 700));
job = await jobApi.get(jobId);
const total = Number(job.total || session.value?.total || 0);
const done = Number(job.successCount || 0) + Number(job.failCount || 0);
progressPercent.value = total ? Math.min(99, Math.round((done / total) * 100)) : Math.min(95, 10 + i);
if (['SUCCESS', 'FAILED', 'PARTIAL'].includes(job.status)) {
progressPercent.value = 100;
break;
}
if (phase === 'preview' && sessionId.value) {
await refreshSession(false);
}
}
return job;
}
async function refreshSession(showLoading = true) {
if (!sessionId.value) return;
if (showLoading) loading.value = true;
try {
session.value = await outboundApi.session(sessionId.value);
} finally {
if (showLoading) loading.value = false;
}
}
async function loadRows() {
if (!sessionId.value) {
rows.value = [];
setPageResult({ total: 0, page: page.value, pageSize: pageSize.value });
return;
}
loading.value = true;
try {
const res: any = await outboundApi.rows(sessionId.value, { page: page.value, pageSize: pageSize.value });
rows.value = res.list;
setPageResult(res);
} finally {
loading.value = false;
}
}
</script>
<style scoped>
.outbound-page {
min-width: 0;
}
.outbound-card {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.outbound-card :deep(.n-card__content) {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.section-alert {
margin-bottom: 12px;
}
.summary-card {
margin-bottom: 12px;
flex: 0 0 auto;
}
.success-text {
color: #138a72;
}
.danger-text {
color: #c0392b;
}
.progress {
width: 180px;
}
.session-error {
display: block;
margin-top: 8px;
}
.preview-images {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
}
.preview-images :deep(img) {
border-radius: 4px;
cursor: zoom-in;
}
</style>
+6 -9
View File
@@ -22,14 +22,6 @@
style="width: 150px"
@keyup.enter="onSearch"
/>
<n-select
v-model:value="query.result"
:options="resultOptions"
clearable
:placeholder="t('pages.queryLog.result')"
style="width: 140px"
@update:value="onSearch"
/>
<n-date-picker
v-model:value="range"
type="datetimerange"
@@ -70,6 +62,7 @@ import { QueryResult } from '@artveris/shared';
import { queryLogApi } from '@/api';
import { fmt, statusType } from '@/utils/format';
import { useTablePage } from '@/composables/useTablePage';
import { renderTableFilterTitle } from '@/utils/tableFilter';
const { t } = useI18n();
const rows = ref<any[]>([]);
@@ -89,7 +82,7 @@ const columns: DataTableColumns<any> = [
{ title: () => t('pages.artwork.archiveNo'), key: 'archiveNo', width: 140, ellipsis: { tooltip: true }, render: (r) => r.archiveNo || '-' },
{ title: () => t('pages.traceCode.batchNo'), key: 'batchNo', width: 130, ellipsis: { tooltip: true }, render: (r) => r.batchNo || '-' },
{
title: () => t('pages.queryLog.result'),
title: () => renderTableFilterTitle(t('pages.queryLog.result'), query.result, resultOptions, (value) => setResultFilter(value)),
key: 'queryResult',
width: 104,
render: (r) => h(NTag, { size: 'small', type: statusType(r.queryResult) }, { default: () => t(`common.queryResult.${r.queryResult}`) }),
@@ -146,6 +139,10 @@ function onSearch() {
resetPage();
load();
}
function setResultFilter(value: string | number | null) {
query.result = value ? String(value) : null;
onSearch();
}
onMounted(load);
</script>
+54 -9
View File
@@ -1,6 +1,6 @@
<template>
<div class="page">
<n-card :title="t('menu.settings')" :bordered="false" style="max-width: 640px">
<n-card :title="t('menu.settings')" :bordered="false" style="max-width: 760px">
<n-form label-placement="top">
<n-form-item :label="t('pages.settings.appName')">
<n-input v-model:value="form.appName" />
@@ -8,11 +8,14 @@
<n-form-item :label="t('pages.settings.logRetentionDays')">
<n-input-number v-model:value="form.logRetentionDays" :min="1" style="width: 220px" />
</n-form-item>
<n-form-item label="操作日志保留天数">
<n-input-number v-model:value="form.operationLogRetentionDays" :min="1" style="width: 220px" />
</n-form-item>
<n-form-item :label="t('pages.settings.watermarkText')">
<n-input v-model:value="form.watermarkText" />
</n-form-item>
<n-form-item :label="t('pages.settings.carouselInterval')">
<div style="display: flex; flex-direction: column; gap: 4px">
<div class="field-stack">
<n-input-number
v-model:value="form.carouselInterval"
:min="0"
@@ -21,9 +24,24 @@
:precision="1"
style="width: 220px"
/>
<span style="font-size: 12px; color: #999">{{ t('pages.settings.carouselIntervalHint') }}</span>
<span class="field-tip">{{ t('pages.settings.carouselIntervalHint') }}</span>
</div>
</n-form-item>
<n-divider>备份策略</n-divider>
<n-form-item label="启用定时备份">
<n-switch v-model:value="form.backupEnabled" />
</n-form-item>
<n-form-item label="备份周期">
<n-select v-model:value="form.backupSchedule" :options="backupScheduleOptions" style="width: 220px" />
</n-form-item>
<n-form-item label="备份保留天数">
<n-input-number v-model:value="form.backupRetentionDays" :min="1" style="width: 220px" />
</n-form-item>
<n-form-item label="最多保留备份数量">
<n-input-number v-model:value="form.backupRetentionCount" :min="1" style="width: 220px" />
</n-form-item>
<n-button type="primary" :loading="saving" @click="save">{{ t('common.action.save') }}</n-button>
</n-form>
</n-card>
@@ -38,33 +56,48 @@ import { message } from '@/utils/feedback';
const { t } = useI18n();
const saving = ref(false);
const form = reactive<{
appName: string;
logRetentionDays: number;
watermarkText: string;
carouselInterval: number;
}>({
const backupScheduleOptions = [
{ label: '每天', value: 'daily' },
{ label: '每周', value: 'weekly' },
];
const form = reactive({
appName: '',
logRetentionDays: 365,
operationLogRetentionDays: 180,
watermarkText: '',
carouselInterval: 3,
backupEnabled: false,
backupSchedule: 'daily',
backupRetentionDays: 30,
backupRetentionCount: 10,
});
async function load() {
const s = await settingsApi.getAll();
form.appName = s.appName || '';
form.logRetentionDays = Number(s.logRetentionDays || 365);
form.operationLogRetentionDays = Number(s.operationLogRetentionDays || 180);
form.watermarkText = s.watermarkText || '';
form.carouselInterval = Number(s.carouselInterval ?? 3);
form.backupEnabled = s.backupEnabled === 'true';
form.backupSchedule = s.backupSchedule || 'daily';
form.backupRetentionDays = Number(s.backupRetentionDays || 30);
form.backupRetentionCount = Number(s.backupRetentionCount || 10);
}
async function save() {
saving.value = true;
try {
await settingsApi.update({
appName: form.appName,
logRetentionDays: String(form.logRetentionDays),
operationLogRetentionDays: String(form.operationLogRetentionDays),
watermarkText: form.watermarkText,
carouselInterval: String(form.carouselInterval),
backupEnabled: String(form.backupEnabled),
backupSchedule: form.backupSchedule,
backupRetentionDays: String(form.backupRetentionDays),
backupRetentionCount: String(form.backupRetentionCount),
});
message.success(t('pages.settings.saved'));
} finally {
@@ -73,3 +106,15 @@ async function save() {
}
onMounted(load);
</script>
<style scoped>
.field-stack {
display: flex;
flex-direction: column;
gap: 4px;
}
.field-tip {
font-size: 12px;
color: #999;
}
</style>
+15 -4
View File
@@ -110,16 +110,18 @@ import { useAuthStore } from '@/stores/auth';
import { message, dialog } from '@/utils/feedback';
import { fmt, statusType } from '@/utils/format';
import { useTablePage } from '@/composables/useTablePage';
import { renderTableFilterTitle } from '@/utils/tableFilter';
const { t } = useI18n();
const auth = useAuthStore();
const rows = ref<any[]>([]);
const loading = ref(false);
const query = reactive({ keyword: '' });
const query = reactive<{ keyword: string; status: string | null }>({ keyword: '', status: null });
const { pagination, page, pageSize, resetPage, setPageResult } = useTablePage(load);
const fieldTypeOptions = Object.values(FieldType).map((v) => ({ label: t(`common.fieldType.${v}`), value: v }));
const statusOptions = Object.values(TemplateStatus).map((v) => ({ label: t(`common.status.${v}`), value: v }));
const showModal = ref(false);
const editing = ref<number | null>(null);
@@ -139,7 +141,7 @@ const columns: DataTableColumns<any> = [
render: (r) => (r.fields || []).map((f: any) => f.label).join('、') || '-',
},
{
title: () => t('common.label.status'),
title: () => renderTableFilterTitle(t('common.label.status'), query.status, statusOptions, (value) => setStatusFilter(value)),
key: 'status',
width: 90,
render: (r) => h(NTag, { type: statusType(r.status), size: 'small' }, { default: () => t(`common.status.${r.status}`) }),
@@ -154,7 +156,7 @@ const columns: DataTableColumns<any> = [
align: 'center',
render: (r) =>
auth.canWrite
? h('div', { style: 'display:flex;gap:4px' }, [
? h('div', { class: 'row-actions' }, [
h(
NButton,
{ quaternary: true, circle: true, size: 'small', title: t('common.action.edit'), onClick: () => openEdit(r) },
@@ -192,7 +194,12 @@ async function toggleStatus(r: any) {
async function load() {
loading.value = true;
try {
const res: any = await templateApi.list({ keyword: query.keyword, page: page.value, pageSize: pageSize.value });
const res: any = await templateApi.list({
keyword: query.keyword,
status: query.status || undefined,
page: page.value,
pageSize: pageSize.value,
});
rows.value = res.list;
setPageResult(res);
} finally {
@@ -203,6 +210,10 @@ function onSearch() {
resetPage();
load();
}
function setStatusFilter(value: string | number | null) {
query.status = value ? String(value) : null;
onSearch();
}
function addField() {
form.fields.push({ fieldKey: '', label: '', type: FieldType.TEXT, required: false });
+21 -5
View File
@@ -76,11 +76,12 @@ import { userApi } from '@/api';
import { message, dialog } from '@/utils/feedback';
import { fmt, statusType } from '@/utils/format';
import { useTablePage } from '@/composables/useTablePage';
import { renderTableFilterTitle } from '@/utils/tableFilter';
const { t } = useI18n();
const rows = ref<any[]>([]);
const loading = ref(false);
const query = reactive({ keyword: '' });
const query = reactive<{ keyword: string; role: string | null; status: string | null }>({ keyword: '', role: null, status: null });
const { pagination, page, pageSize, resetPage, setPageResult } = useTablePage(load);
const roleOptions = Object.values(RoleType).map((v) => ({ label: t(`common.role.${v}`), value: v }));
const statusOptions = Object.values(UserStatus).map((v) => ({ label: t(`common.status.${v}`), value: v }));
@@ -103,9 +104,14 @@ const columns: DataTableColumns<any> = [
{ title: 'ID', key: 'id', width: 64 },
{ title: () => t('pages.user.username'), key: 'username', width: 160, ellipsis: { tooltip: true } },
{ title: () => t('pages.user.realName'), key: 'realName', width: 160, ellipsis: { tooltip: true }, render: (r) => r.realName || '-' },
{ title: () => t('pages.user.role'), key: 'role', width: 120, render: (r) => t(`common.role.${r.role}`) },
{
title: () => t('common.label.status'),
title: () => renderTableFilterTitle(t('pages.user.role'), query.role, roleOptions, (value) => setFilter('role', value)),
key: 'role',
width: 120,
render: (r) => t(`common.role.${r.role}`),
},
{
title: () => renderTableFilterTitle(t('common.label.status'), query.status, statusOptions, (value) => setFilter('status', value)),
key: 'status',
width: 90,
render: (r) => h(NTag, { size: 'small', type: statusType(r.status) }, { default: () => t(`common.status.${r.status}`) }),
@@ -118,7 +124,7 @@ const columns: DataTableColumns<any> = [
fixed: 'right',
align: 'center',
render: (r) =>
h('div', { style: 'display:flex;gap:2px' }, [
h('div', { class: 'row-actions' }, [
h(NButton, { quaternary: true, circle: true, size: 'small', onClick: () => openEdit(r) }, { icon: () => h(NIcon, null, { default: () => h(CreateOutline) }) }),
h(NButton, { quaternary: true, circle: true, size: 'small', onClick: () => openReset(r) }, { icon: () => h(NIcon, null, { default: () => h(KeyOutline) }) }),
h(NButton, { quaternary: true, circle: true, size: 'small', type: 'error', onClick: () => remove(r) }, { icon: () => h(NIcon, null, { default: () => h(TrashOutline) }) }),
@@ -129,7 +135,13 @@ const columns: DataTableColumns<any> = [
async function load() {
loading.value = true;
try {
const res: any = await userApi.list({ keyword: query.keyword, page: page.value, pageSize: pageSize.value });
const res: any = await userApi.list({
keyword: query.keyword,
role: query.role || undefined,
status: query.status || undefined,
page: page.value,
pageSize: pageSize.value,
});
rows.value = res.list;
setPageResult(res);
} finally {
@@ -140,6 +152,10 @@ function onSearch() {
resetPage();
load();
}
function setFilter(field: 'role' | 'status', value: string | number | null) {
query[field] = value ? String(value) : null;
onSearch();
}
function openCreate() {
editing.value = null;