feat: 完善后台导入日志权限与备份恢复
This commit is contained in:
@@ -16,6 +16,7 @@
|
||||
"dayjs": "^1.11.13",
|
||||
"echarts": "^5.5.1",
|
||||
"naive-ui": "^2.40.3",
|
||||
"photoswipe": "^5.4.4",
|
||||
"pinia": "^2.3.0",
|
||||
"vue": "^3.5.13",
|
||||
"vue-echarts": "^7.0.3",
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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> }> {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 },
|
||||
];
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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": "设置已保存"
|
||||
},
|
||||
|
||||
@@ -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') },
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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, '');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) }) },
|
||||
),
|
||||
},
|
||||
),
|
||||
]);
|
||||
}
|
||||
@@ -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'),
|
||||
|
||||
@@ -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'),
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
"@nestjs/serve-static": "^4.0.2",
|
||||
"@nestjs/swagger": "^8.1.0",
|
||||
"@prisma/client": "^5.22.0",
|
||||
"adm-zip": "^0.5.18",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"bullmq": "^5.34.6",
|
||||
"class-transformer": "^0.5.1",
|
||||
@@ -50,6 +51,7 @@
|
||||
"@nestjs/cli": "^10.4.9",
|
||||
"@nestjs/schematics": "^10.2.3",
|
||||
"@nestjs/testing": "^10.4.15",
|
||||
"@types/adm-zip": "^0.5.8",
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/jest": "^29.5.14",
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
-- Extend job types for import preview and backup/restore tasks.
|
||||
ALTER TABLE `job`
|
||||
MODIFY `type` ENUM('GEN_CODE','IMPORT_OUTBOUND','IMPORT_OUTBOUND_PREVIEW','WATERMARK','ONCHAIN','BACKUP','RESTORE') NOT NULL;
|
||||
|
||||
-- Trace codes now support multiple outbound photos while keeping the old single-photo field for compatibility.
|
||||
ALTER TABLE `trace_code`
|
||||
ADD COLUMN `out_images` JSON NULL;
|
||||
|
||||
CREATE TABLE `operation_log` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||
`user_id` INTEGER NULL,
|
||||
`username` VARCHAR(191) NULL,
|
||||
`role` ENUM('SUPER_ADMIN','OPERATOR','AUDITOR','VIEWER') NULL,
|
||||
`module` VARCHAR(191) NOT NULL,
|
||||
`action` VARCHAR(191) NOT NULL,
|
||||
`method` VARCHAR(20) NOT NULL,
|
||||
`path` VARCHAR(512) NOT NULL,
|
||||
`target_id` VARCHAR(191) NULL,
|
||||
`status` VARCHAR(32) NOT NULL,
|
||||
`message` TEXT NULL,
|
||||
`ip` VARCHAR(191) NULL,
|
||||
`user_agent` TEXT NULL,
|
||||
`duration_ms` INTEGER NULL,
|
||||
`request_summary` JSON NULL,
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
CREATE INDEX `operation_log_user_id_idx` ON `operation_log`(`user_id`);
|
||||
CREATE INDEX `operation_log_module_idx` ON `operation_log`(`module`);
|
||||
CREATE INDEX `operation_log_action_idx` ON `operation_log`(`action`);
|
||||
CREATE INDEX `operation_log_status_idx` ON `operation_log`(`status`);
|
||||
CREATE INDEX `operation_log_created_at_idx` ON `operation_log`(`created_at`);
|
||||
ALTER TABLE `operation_log`
|
||||
ADD CONSTRAINT `operation_log_user_id_fkey` FOREIGN KEY (`user_id`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
CREATE TABLE `outbound_import_session` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`status` ENUM('PARSING','READY','IMPORTING','IMPORTED','FAILED','EXPIRED') NOT NULL DEFAULT 'PARSING',
|
||||
`file_name` VARCHAR(191) NOT NULL,
|
||||
`file_key` VARCHAR(512) NULL,
|
||||
`total` INTEGER NOT NULL DEFAULT 0,
|
||||
`valid_count` INTEGER NOT NULL DEFAULT 0,
|
||||
`invalid_count` INTEGER NOT NULL DEFAULT 0,
|
||||
`error` TEXT NULL,
|
||||
`committed_at` DATETIME(3) NULL,
|
||||
`expires_at` DATETIME(3) NOT NULL,
|
||||
`created_by` INTEGER NULL,
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updated_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
CREATE INDEX `outbound_import_session_status_idx` ON `outbound_import_session`(`status`);
|
||||
CREATE INDEX `outbound_import_session_created_by_idx` ON `outbound_import_session`(`created_by`);
|
||||
CREATE INDEX `outbound_import_session_expires_at_idx` ON `outbound_import_session`(`expires_at`);
|
||||
ALTER TABLE `outbound_import_session`
|
||||
ADD CONSTRAINT `outbound_import_session_created_by_fkey` FOREIGN KEY (`created_by`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
CREATE TABLE `outbound_import_row` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||
`session_id` VARCHAR(191) NOT NULL,
|
||||
`row_no` INTEGER NOT NULL,
|
||||
`status` ENUM('VALID','INVALID','IMPORTED','FAILED') NOT NULL DEFAULT 'INVALID',
|
||||
`short_code` VARCHAR(191) NULL,
|
||||
`batch_no` VARCHAR(191) NULL,
|
||||
`out_time` DATETIME(3) NULL,
|
||||
`out_image_paths` JSON NULL,
|
||||
`out_image_keys` JSON NULL,
|
||||
`tx_hash` VARCHAR(255) NULL,
|
||||
`onchain_at` DATETIME(3) NULL,
|
||||
`block_height` BIGINT NULL,
|
||||
`remark` VARCHAR(255) NULL,
|
||||
`reason` TEXT NULL,
|
||||
`preview` JSON NULL,
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
CREATE INDEX `outbound_import_row_session_id_idx` ON `outbound_import_row`(`session_id`);
|
||||
CREATE INDEX `outbound_import_row_status_idx` ON `outbound_import_row`(`status`);
|
||||
CREATE INDEX `outbound_import_row_short_code_idx` ON `outbound_import_row`(`short_code`);
|
||||
ALTER TABLE `outbound_import_row`
|
||||
ADD CONSTRAINT `outbound_import_row_session_id_fkey` FOREIGN KEY (`session_id`) REFERENCES `outbound_import_session`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
CREATE TABLE `backup_record` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`file_name` VARCHAR(191) NOT NULL,
|
||||
`file_path` VARCHAR(1024) NOT NULL,
|
||||
`size` BIGINT NOT NULL DEFAULT 0,
|
||||
`status` ENUM('PENDING','PROCESSING','SUCCESS','FAILED') NOT NULL DEFAULT 'PENDING',
|
||||
`mode` VARCHAR(32) NOT NULL DEFAULT 'BACKUP',
|
||||
`manifest` JSON NULL,
|
||||
`error` TEXT NULL,
|
||||
`created_by` INTEGER NULL,
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updated_at` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
CREATE INDEX `backup_record_status_idx` ON `backup_record`(`status`);
|
||||
CREATE INDEX `backup_record_mode_idx` ON `backup_record`(`mode`);
|
||||
CREATE INDEX `backup_record_created_by_idx` ON `backup_record`(`created_by`);
|
||||
CREATE INDEX `backup_record_created_at_idx` ON `backup_record`(`created_at`);
|
||||
ALTER TABLE `backup_record`
|
||||
ADD CONSTRAINT `backup_record_created_by_fkey` FOREIGN KEY (`created_by`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -91,8 +91,11 @@ enum QueryResult {
|
||||
enum JobType {
|
||||
GEN_CODE
|
||||
IMPORT_OUTBOUND
|
||||
IMPORT_OUTBOUND_PREVIEW
|
||||
WATERMARK
|
||||
ONCHAIN
|
||||
BACKUP
|
||||
RESTORE
|
||||
}
|
||||
|
||||
enum JobStatus {
|
||||
@@ -103,6 +106,29 @@ enum JobStatus {
|
||||
FAILED
|
||||
}
|
||||
|
||||
enum OutboundImportSessionStatus {
|
||||
PARSING
|
||||
READY
|
||||
IMPORTING
|
||||
IMPORTED
|
||||
FAILED
|
||||
EXPIRED
|
||||
}
|
||||
|
||||
enum OutboundImportRowStatus {
|
||||
VALID
|
||||
INVALID
|
||||
IMPORTED
|
||||
FAILED
|
||||
}
|
||||
|
||||
enum BackupStatus {
|
||||
PENDING
|
||||
PROCESSING
|
||||
SUCCESS
|
||||
FAILED
|
||||
}
|
||||
|
||||
model SysUser {
|
||||
id Int @id @default(autoincrement())
|
||||
username String @unique
|
||||
@@ -115,6 +141,9 @@ model SysUser {
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
artworks Artwork[]
|
||||
operationLogs OperationLog[]
|
||||
outboundImportSessions OutboundImportSession[]
|
||||
backupRecords BackupRecord[]
|
||||
|
||||
@@map("sys_user")
|
||||
}
|
||||
@@ -251,6 +280,7 @@ model TraceCode {
|
||||
groupId Int? @map("group_id")
|
||||
outTime DateTime? @map("out_time")
|
||||
outImage String? @map("out_image")
|
||||
outImages Json? @map("out_images")
|
||||
remark String?
|
||||
status TraceCodeStatus @default(INACTIVE)
|
||||
queryCount Int @default(0) @map("query_count")
|
||||
@@ -336,6 +366,106 @@ model Job {
|
||||
@@map("job")
|
||||
}
|
||||
|
||||
model OperationLog {
|
||||
id BigInt @id @default(autoincrement())
|
||||
userId Int? @map("user_id")
|
||||
username String?
|
||||
role RoleType?
|
||||
module String
|
||||
action String
|
||||
method String
|
||||
path String
|
||||
targetId String? @map("target_id")
|
||||
status String
|
||||
message String? @db.Text
|
||||
ip String?
|
||||
userAgent String? @db.Text @map("user_agent")
|
||||
durationMs Int? @map("duration_ms")
|
||||
requestSummary Json? @map("request_summary")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
user SysUser? @relation(fields: [userId], references: [id])
|
||||
|
||||
@@index([userId])
|
||||
@@index([module])
|
||||
@@index([action])
|
||||
@@index([status])
|
||||
@@index([createdAt])
|
||||
@@map("operation_log")
|
||||
}
|
||||
|
||||
model OutboundImportSession {
|
||||
id String @id @default(cuid())
|
||||
status OutboundImportSessionStatus @default(PARSING)
|
||||
fileName String @map("file_name")
|
||||
fileKey String? @map("file_key")
|
||||
total Int @default(0)
|
||||
validCount Int @default(0) @map("valid_count")
|
||||
invalidCount Int @default(0) @map("invalid_count")
|
||||
error String? @db.Text
|
||||
committedAt DateTime? @map("committed_at")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
createdBy Int? @map("created_by")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
creator SysUser? @relation(fields: [createdBy], references: [id])
|
||||
rows OutboundImportRow[]
|
||||
|
||||
@@index([status])
|
||||
@@index([createdBy])
|
||||
@@index([expiresAt])
|
||||
@@map("outbound_import_session")
|
||||
}
|
||||
|
||||
model OutboundImportRow {
|
||||
id BigInt @id @default(autoincrement())
|
||||
sessionId String @map("session_id")
|
||||
rowNo Int @map("row_no")
|
||||
status OutboundImportRowStatus @default(INVALID)
|
||||
shortCode String? @map("short_code")
|
||||
batchNo String? @map("batch_no")
|
||||
outTime DateTime? @map("out_time")
|
||||
outImagePaths Json? @map("out_image_paths")
|
||||
outImageKeys Json? @map("out_image_keys")
|
||||
txHash String? @map("tx_hash")
|
||||
onchainAt DateTime? @map("onchain_at")
|
||||
blockHeight BigInt? @map("block_height")
|
||||
remark String?
|
||||
reason String? @db.Text
|
||||
preview Json?
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
session OutboundImportSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([sessionId])
|
||||
@@index([status])
|
||||
@@index([shortCode])
|
||||
@@map("outbound_import_row")
|
||||
}
|
||||
|
||||
model BackupRecord {
|
||||
id String @id @default(cuid())
|
||||
fileName String @map("file_name")
|
||||
filePath String @map("file_path")
|
||||
size BigInt @default(0)
|
||||
status BackupStatus @default(PENDING)
|
||||
mode String @default("BACKUP")
|
||||
manifest Json?
|
||||
error String? @db.Text
|
||||
createdBy Int? @map("created_by")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
creator SysUser? @relation(fields: [createdBy], references: [id])
|
||||
|
||||
@@index([status])
|
||||
@@index([mode])
|
||||
@@index([createdBy])
|
||||
@@index([createdAt])
|
||||
@@map("backup_record")
|
||||
}
|
||||
|
||||
model SystemSetting {
|
||||
id Int @id @default(autoincrement())
|
||||
key String @unique
|
||||
|
||||
@@ -22,6 +22,8 @@ import { OutboundModule } from './outbound/outbound.module';
|
||||
import { QueryLogModule } from './query-log/query-log.module';
|
||||
import { DashboardModule } from './dashboard/dashboard.module';
|
||||
import { SettingsModule } from './settings/settings.module';
|
||||
import { OperationLogModule } from './operation-log/operation-log.module';
|
||||
import { BackupModule } from './backup/backup.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -50,6 +52,8 @@ import { SettingsModule } from './settings/settings.module';
|
||||
QueryLogModule,
|
||||
DashboardModule,
|
||||
SettingsModule,
|
||||
OperationLogModule,
|
||||
BackupModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
})
|
||||
|
||||
@@ -3,10 +3,11 @@ import { Reflector } from '@nestjs/core';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Request } from 'express';
|
||||
import { ErrorCode } from '@artveris/shared';
|
||||
import { ErrorCode, UserStatus } from '@artveris/shared';
|
||||
import { IS_PUBLIC_KEY } from '../../common/decorators/public.decorator';
|
||||
import { BusinessException } from '../../common/exceptions/business.exception';
|
||||
import { AuthUser } from '../../common/decorators/current-user.decorator';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
@@ -14,43 +15,51 @@ export class JwtAuthGuard implements CanActivate {
|
||||
private readonly jwt: JwtService,
|
||||
private readonly reflector: Reflector,
|
||||
private readonly config: ConfigService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (isPublic) {
|
||||
return true;
|
||||
}
|
||||
if (isPublic) return true;
|
||||
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
const token = this.extractToken(req);
|
||||
if (!token) {
|
||||
throw new BusinessException(ErrorCode.UNAUTHORIZED, '未登录或登录已过期', 401);
|
||||
}
|
||||
|
||||
let payload: AuthUser & { sub: number };
|
||||
try {
|
||||
const payload = this.jwt.verify<AuthUser & { sub: number }>(token, {
|
||||
payload = this.jwt.verify<AuthUser & { sub: number }>(token, {
|
||||
secret: this.config.get<string>('jwt.secret'),
|
||||
});
|
||||
(req as Request & { user: AuthUser }).user = {
|
||||
id: payload.sub ?? payload.id,
|
||||
username: payload.username,
|
||||
role: payload.role,
|
||||
realName: payload.realName,
|
||||
};
|
||||
return true;
|
||||
} catch {
|
||||
throw new BusinessException(ErrorCode.TOKEN_EXPIRED, '登录已过期,请重新登录', 401);
|
||||
}
|
||||
|
||||
const userId = payload.sub ?? payload.id;
|
||||
const user = await this.prisma.sysUser.findUnique({
|
||||
where: { id: userId },
|
||||
select: { id: true, username: true, realName: true, role: true, status: true },
|
||||
});
|
||||
if (!user || user.status === UserStatus.DISABLED) {
|
||||
throw new BusinessException(ErrorCode.UNAUTHORIZED, '账号不存在或已被停用', 401);
|
||||
}
|
||||
(req as Request & { user: AuthUser }).user = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
role: user.role,
|
||||
realName: user.realName ?? undefined,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
private extractToken(req: Request): string | null {
|
||||
const auth = req.headers.authorization;
|
||||
if (auth && auth.startsWith('Bearer ')) {
|
||||
return auth.slice(7);
|
||||
}
|
||||
if (auth && auth.startsWith('Bearer ')) return auth.slice(7);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
import { existsSync, rmSync } from 'fs';
|
||||
import { BackupStatus } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { BackupService } from './backup.service';
|
||||
|
||||
@Injectable()
|
||||
export class BackupRetentionService {
|
||||
private readonly logger = new Logger(BackupRetentionService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly settings: SettingsService,
|
||||
private readonly backups: BackupService,
|
||||
) {}
|
||||
|
||||
@Cron(CronExpression.EVERY_DAY_AT_2AM)
|
||||
async scheduledBackup(): Promise<void> {
|
||||
const enabled = (await this.settings.get('backupEnabled')) === 'true';
|
||||
if (!enabled) return;
|
||||
const schedule = (await this.settings.get('backupSchedule')) || 'daily';
|
||||
if (schedule === 'weekly' && new Date().getDay() !== 1) return;
|
||||
|
||||
const admin = await this.prisma.sysUser.findFirst({
|
||||
where: { role: 'SUPER_ADMIN', status: 'ACTIVE' },
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
if (!admin) return;
|
||||
await this.backups.createBackup(
|
||||
{ id: admin.id, username: admin.username, role: admin.role, realName: admin.realName ?? undefined },
|
||||
'SCHEDULED',
|
||||
);
|
||||
await this.cleanup();
|
||||
}
|
||||
|
||||
async cleanup(): Promise<void> {
|
||||
const days = Number((await this.settings.get('backupRetentionDays')) ?? 30);
|
||||
const count = Number((await this.settings.get('backupRetentionCount')) ?? 10);
|
||||
const cutoff = days > 0 ? new Date(Date.now() - days * 24 * 60 * 60 * 1000) : null;
|
||||
const old = await this.prisma.backupRecord.findMany({
|
||||
where: {
|
||||
mode: { in: ['BACKUP', 'SCHEDULED'] },
|
||||
status: BackupStatus.SUCCESS,
|
||||
...(cutoff ? { createdAt: { lt: cutoff } } : {}),
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
const all = await this.prisma.backupRecord.findMany({
|
||||
where: { mode: { in: ['BACKUP', 'SCHEDULED'] }, status: BackupStatus.SUCCESS },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
const overflow = count > 0 ? all.slice(count) : [];
|
||||
const ids = new Set([...old, ...overflow].map((r) => r.id));
|
||||
for (const id of ids) {
|
||||
const record = [...old, ...overflow].find((r) => r.id === id);
|
||||
if (record?.filePath && existsSync(record.filePath)) rmSync(record.filePath, { force: true });
|
||||
await this.prisma.backupRecord.delete({ where: { id } });
|
||||
}
|
||||
if (ids.size) this.logger.log(`已清理备份 ${ids.size} 个`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Body, Controller, Delete, Get, Param, Post, Query, Res, UploadedFile, UseInterceptors } from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Response } from 'express';
|
||||
import { MAX_FILE_SIZE, RoleType } from '@artveris/shared';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
||||
import { BackupService } from './backup.service';
|
||||
import { QueryBackupDto, RestoreCommitDto } from './dto/backup.dto';
|
||||
|
||||
@ApiTags('备份与恢复')
|
||||
@ApiBearerAuth()
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@Controller('backups')
|
||||
export class BackupController {
|
||||
constructor(private readonly backups: BackupService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: '备份记录列表' })
|
||||
list(@Query() query: QueryBackupDto) {
|
||||
return this.backups.list(query);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiOperation({ summary: '创建备份' })
|
||||
create(@CurrentUser() user: AuthUser) {
|
||||
return this.backups.createBackup(user);
|
||||
}
|
||||
|
||||
@Get(':id/download')
|
||||
@ApiOperation({ summary: '下载备份包' })
|
||||
download(@Param('id') id: string, @Res() res: Response) {
|
||||
return this.backups.download(id, res);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@ApiOperation({ summary: '删除备份记录与文件' })
|
||||
remove(@Param('id') id: string) {
|
||||
return this.backups.remove(id);
|
||||
}
|
||||
|
||||
@Post('restore/preview')
|
||||
@ApiOperation({ summary: '上传备份包并预校验' })
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE * 10 } }))
|
||||
restorePreview(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) {
|
||||
return this.backups.previewRestore(file, user);
|
||||
}
|
||||
|
||||
@Post('restore/commit')
|
||||
@ApiOperation({ summary: '确认整库覆盖恢复' })
|
||||
restoreCommit(@Body() dto: RestoreCommitDto, @CurrentUser() user: AuthUser) {
|
||||
return this.backups.commitRestore(dto.restoreId, user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { BackupController } from './backup.controller';
|
||||
import { BackupRetentionService } from './backup-retention.service';
|
||||
import { BackupService } from './backup.service';
|
||||
|
||||
@Module({
|
||||
controllers: [BackupController],
|
||||
providers: [BackupService, BackupRetentionService],
|
||||
exports: [BackupService],
|
||||
})
|
||||
export class BackupModule {}
|
||||
@@ -0,0 +1,260 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Response } from 'express';
|
||||
import AdmZip from 'adm-zip';
|
||||
import dayjs from 'dayjs';
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
|
||||
import { dirname, join, relative, resolve } from 'path';
|
||||
import { BackupStatus, ErrorCode } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
import { AuthUser } from '../common/decorators/current-user.decorator';
|
||||
import { QueryBackupDto } from './dto/backup.dto';
|
||||
|
||||
const MODELS = [
|
||||
'sysUser',
|
||||
'template',
|
||||
'templateField',
|
||||
'artwork',
|
||||
'traceNode',
|
||||
'certificate',
|
||||
'traceCodeGroup',
|
||||
'batch',
|
||||
'traceCode',
|
||||
'blockchainProof',
|
||||
'queryLog',
|
||||
'job',
|
||||
'systemSetting',
|
||||
'operationLog',
|
||||
'outboundImportSession',
|
||||
'outboundImportRow',
|
||||
] as const;
|
||||
|
||||
const DELETE_ORDER = [...MODELS].reverse();
|
||||
const DATE_KEYS = new Set([
|
||||
'lastLoginAt',
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'deletedAt',
|
||||
'auditedAt',
|
||||
'occurredAt',
|
||||
'issuedAt',
|
||||
'outTime',
|
||||
'firstActivatedAt',
|
||||
'lastQueriedAt',
|
||||
'onchainAt',
|
||||
'queriedAt',
|
||||
'expiresAt',
|
||||
'committedAt',
|
||||
]);
|
||||
|
||||
function jsonReplacer(_key: string, value: unknown) {
|
||||
if (typeof value === 'bigint') return { __bigint: value.toString() };
|
||||
return value;
|
||||
}
|
||||
|
||||
function reviveRow(row: Record<string, any>): Record<string, any> {
|
||||
const out: Record<string, any> = {};
|
||||
for (const [key, value] of Object.entries(row)) {
|
||||
if (value && typeof value === 'object' && '__bigint' in value) {
|
||||
out[key] = BigInt(String(value.__bigint));
|
||||
} else if (DATE_KEYS.has(key) && typeof value === 'string') {
|
||||
out[key] = new Date(value);
|
||||
} else {
|
||||
out[key] = value;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isSafeZipPath(path: string): boolean {
|
||||
return !path.includes('\\') && !path.includes('..') && !path.startsWith('/') && !/^[a-z]:/i.test(path);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class BackupService {
|
||||
private readonly storageRoot: string;
|
||||
private readonly backupRoot: string;
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly config: ConfigService,
|
||||
) {
|
||||
this.storageRoot = resolve(this.config.get<string>('storage.localDir') || './storage');
|
||||
this.backupRoot = resolve(process.env.BACKUP_DIR || join(dirname(this.storageRoot), 'backups'));
|
||||
mkdirSync(this.backupRoot, { recursive: true });
|
||||
}
|
||||
|
||||
async list(query: QueryBackupDto) {
|
||||
const where: any = {};
|
||||
if (query.status) where.status = query.status;
|
||||
if (query.mode) where.mode = query.mode;
|
||||
const [list, total] = await this.prisma.$transaction([
|
||||
this.prisma.backupRecord.findMany({ where, orderBy: { createdAt: 'desc' }, skip: query.skip, take: query.take }),
|
||||
this.prisma.backupRecord.count({ where }),
|
||||
]);
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
}
|
||||
|
||||
async createBackup(user: AuthUser, mode = 'BACKUP') {
|
||||
const stamp = dayjs().format('YYYYMMDDHHmmss');
|
||||
const fileName = `artveris-${mode.toLowerCase()}-${stamp}.zip`;
|
||||
const filePath = join(this.backupRoot, fileName);
|
||||
const record = await this.prisma.backupRecord.create({
|
||||
data: { fileName, filePath, status: BackupStatus.PROCESSING, mode, createdBy: user.id },
|
||||
});
|
||||
try {
|
||||
const db = await this.dumpDatabase();
|
||||
const zip = new AdmZip();
|
||||
const fileList = this.addStorageFiles(zip);
|
||||
const manifest = {
|
||||
app: 'artveris',
|
||||
version: '0.1.0',
|
||||
createdAt: new Date().toISOString(),
|
||||
mode,
|
||||
models: Object.fromEntries(Object.entries(db).map(([key, rows]) => [key, (rows as unknown[]).length])),
|
||||
files: fileList,
|
||||
};
|
||||
zip.addFile('manifest.json', Buffer.from(JSON.stringify(manifest, null, 2), 'utf8'));
|
||||
zip.addFile('database.json', Buffer.from(JSON.stringify(db, jsonReplacer), 'utf8'));
|
||||
writeFileSync(filePath, zip.toBuffer());
|
||||
const size = BigInt(statSync(filePath).size);
|
||||
return this.prisma.backupRecord.update({
|
||||
where: { id: record.id },
|
||||
data: { status: BackupStatus.SUCCESS, size, manifest: manifest as any },
|
||||
});
|
||||
} catch (e) {
|
||||
await this.prisma.backupRecord.update({
|
||||
where: { id: record.id },
|
||||
data: { status: BackupStatus.FAILED, error: (e as Error).message },
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async download(id: string, res: Response) {
|
||||
const record = await this.prisma.backupRecord.findUnique({ where: { id } });
|
||||
if (!record || record.status !== BackupStatus.SUCCESS || !existsSync(record.filePath)) {
|
||||
throw new BusinessException(ErrorCode.NOT_FOUND, '备份文件不存在', 404);
|
||||
}
|
||||
res.setHeader('Content-Type', 'application/zip');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${record.fileName}"`);
|
||||
res.end(readFileSync(record.filePath));
|
||||
}
|
||||
|
||||
async remove(id: string) {
|
||||
const record = await this.prisma.backupRecord.findUnique({ where: { id } });
|
||||
if (!record) throw new BusinessException(ErrorCode.NOT_FOUND, '备份记录不存在', 404);
|
||||
if (existsSync(record.filePath)) rmSync(record.filePath, { force: true });
|
||||
await this.prisma.backupRecord.delete({ where: { id } });
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async previewRestore(file: Express.Multer.File, user: AuthUser) {
|
||||
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传备份 ZIP 文件');
|
||||
const zip = new AdmZip(file.buffer);
|
||||
const manifestEntry = zip.getEntry('manifest.json');
|
||||
const dbEntry = zip.getEntry('database.json');
|
||||
if (!manifestEntry || !dbEntry) throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包缺少 manifest.json 或 database.json');
|
||||
const manifest = JSON.parse(manifestEntry.getData().toString('utf8'));
|
||||
if (manifest.app !== 'artveris') throw new BusinessException(ErrorCode.BAD_REQUEST, '不是 Artveris 备份包');
|
||||
|
||||
const fileName = `restore-${dayjs().format('YYYYMMDDHHmmss')}.zip`;
|
||||
const filePath = join(this.backupRoot, fileName);
|
||||
writeFileSync(filePath, file.buffer);
|
||||
const record = await this.prisma.backupRecord.create({
|
||||
data: {
|
||||
fileName,
|
||||
filePath,
|
||||
size: BigInt(file.buffer.length),
|
||||
status: BackupStatus.PENDING,
|
||||
mode: 'RESTORE',
|
||||
manifest,
|
||||
createdBy: user.id,
|
||||
},
|
||||
});
|
||||
return { restoreId: record.id, manifest };
|
||||
}
|
||||
|
||||
async commitRestore(restoreId: string, user: AuthUser) {
|
||||
const record = await this.prisma.backupRecord.findUnique({ where: { id: restoreId } });
|
||||
if (!record || record.mode !== 'RESTORE' || !existsSync(record.filePath)) {
|
||||
throw new BusinessException(ErrorCode.NOT_FOUND, '恢复记录不存在', 404);
|
||||
}
|
||||
await this.prisma.backupRecord.update({ where: { id: restoreId }, data: { status: BackupStatus.PROCESSING } });
|
||||
const snapshot = await this.createBackup(user, 'AUTO_BEFORE_RESTORE');
|
||||
try {
|
||||
const zip = new AdmZip(readFileSync(record.filePath));
|
||||
await this.restoreDatabase(zip);
|
||||
this.restoreStorage(zip);
|
||||
return this.prisma.backupRecord.update({
|
||||
where: { id: restoreId },
|
||||
data: { status: BackupStatus.SUCCESS, error: null },
|
||||
});
|
||||
} catch (e) {
|
||||
await this.prisma.backupRecord.update({
|
||||
where: { id: restoreId },
|
||||
data: { status: BackupStatus.FAILED, error: `${(e as Error).message};恢复前快照:${snapshot.fileName}` },
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private async dumpDatabase() {
|
||||
const db: Record<string, unknown[]> = {};
|
||||
for (const model of MODELS) {
|
||||
db[model] = await (this.prisma as any)[model].findMany();
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
private addStorageFiles(zip: AdmZip) {
|
||||
const files: string[] = [];
|
||||
if (!existsSync(this.storageRoot)) return files;
|
||||
const walk = (dir: string) => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const full = join(dir, name);
|
||||
const st = statSync(full);
|
||||
if (st.isDirectory()) {
|
||||
walk(full);
|
||||
} else {
|
||||
const rel = relative(this.storageRoot, full).replace(/\\/g, '/');
|
||||
if (!isSafeZipPath(rel)) continue;
|
||||
files.push(rel);
|
||||
zip.addFile(`storage/${rel}`, readFileSync(full));
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(this.storageRoot);
|
||||
return files;
|
||||
}
|
||||
|
||||
private async restoreDatabase(zip: AdmZip) {
|
||||
const entry = zip.getEntry('database.json');
|
||||
if (!entry) throw new Error('备份包缺少 database.json');
|
||||
const db = JSON.parse(entry.getData().toString('utf8'));
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
for (const model of DELETE_ORDER) {
|
||||
await (tx as any)[model].deleteMany();
|
||||
}
|
||||
for (const model of MODELS) {
|
||||
const rows = Array.isArray(db[model]) ? db[model].map(reviveRow) : [];
|
||||
if (rows.length) await (tx as any)[model].createMany({ data: rows });
|
||||
}
|
||||
}, { timeout: 120000 });
|
||||
}
|
||||
|
||||
private restoreStorage(zip: AdmZip) {
|
||||
if (existsSync(this.storageRoot)) rmSync(this.storageRoot, { recursive: true, force: true });
|
||||
mkdirSync(this.storageRoot, { recursive: true });
|
||||
for (const entry of zip.getEntries()) {
|
||||
if (entry.isDirectory || !entry.entryName.startsWith('storage/')) continue;
|
||||
const rel = entry.entryName.slice('storage/'.length);
|
||||
if (!isSafeZipPath(rel)) throw new Error(`备份包包含不安全文件路径:${entry.entryName}`);
|
||||
const full = join(this.storageRoot, rel);
|
||||
mkdirSync(dirname(full), { recursive: true });
|
||||
writeFileSync(full, entry.getData());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
|
||||
export class QueryBackupDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '状态' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '类型 BACKUP / RESTORE' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
mode?: string;
|
||||
}
|
||||
|
||||
export class RestoreCommitDto {
|
||||
@ApiPropertyOptional({ description: '恢复预校验记录 ID' })
|
||||
@IsString()
|
||||
restoreId!: string;
|
||||
}
|
||||
@@ -37,6 +37,7 @@ export class AttestationService {
|
||||
outbound: {
|
||||
outTime: code.outTime,
|
||||
outImage: code.outImage,
|
||||
outImages: code.outImages,
|
||||
},
|
||||
dynamicFields: code.artwork.dynamicFields,
|
||||
nodes: code.artwork.traceNodes.map((n) => ({ type: n.nodeType, title: n.title })),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Controller, Get, Param, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { JobsService } from './jobs.service';
|
||||
import { QueryJobDto } from './dto/query-job.dto';
|
||||
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
||||
|
||||
@ApiTags('异步任务')
|
||||
@ApiBearerAuth()
|
||||
@@ -11,13 +12,13 @@ export class JobsController {
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: '任务列表' })
|
||||
list(@Query() query: QueryJobDto) {
|
||||
return this.jobsService.list(query);
|
||||
list(@Query() query: QueryJobDto, @CurrentUser() user: AuthUser) {
|
||||
return this.jobsService.list(query, user);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: '任务进度详情' })
|
||||
get(@Param('id') id: string) {
|
||||
return this.jobsService.get(id);
|
||||
get(@Param('id') id: string, @CurrentUser() user: AuthUser) {
|
||||
return this.jobsService.get(id, user);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { ErrorCode, JobStatus, JobType } from '@artveris/shared';
|
||||
import { ErrorCode, JobStatus, JobType, RoleType } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
import { AuthUser } from '../common/decorators/current-user.decorator';
|
||||
import { QueryJobDto } from './dto/query-job.dto';
|
||||
|
||||
@Injectable()
|
||||
@@ -37,18 +38,20 @@ export class JobsService {
|
||||
return this.prisma.job.update({ where: { id }, data });
|
||||
}
|
||||
|
||||
async get(id: string) {
|
||||
async get(id: string, user?: AuthUser) {
|
||||
const job = await this.prisma.job.findUnique({ where: { id } });
|
||||
if (!job) {
|
||||
throw new BusinessException(ErrorCode.JOB_NOT_FOUND, '任务不存在', 404);
|
||||
if (!job) throw new BusinessException(ErrorCode.JOB_NOT_FOUND, '任务不存在', 404);
|
||||
if (user && user.role !== RoleType.SUPER_ADMIN && job.createdBy !== user.id) {
|
||||
throw new BusinessException(ErrorCode.FORBIDDEN, '没有访问该任务的权限', 403);
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
async list(query: QueryJobDto) {
|
||||
async list(query: QueryJobDto, user?: AuthUser) {
|
||||
const where: Prisma.JobWhereInput = {};
|
||||
if (query.type) where.type = query.type;
|
||||
if (query.status) where.status = query.status;
|
||||
if (user && user.role !== RoleType.SUPER_ADMIN) where.createdBy = user.id;
|
||||
const [list, total] = await this.prisma.$transaction([
|
||||
this.prisma.job.findMany({
|
||||
where,
|
||||
|
||||
@@ -9,6 +9,7 @@ import { resolve } from 'path';
|
||||
import { AppModule } from './app.module';
|
||||
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
|
||||
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
|
||||
import { OperationLogInterceptor } from './operation-log/operation-log.interceptor';
|
||||
|
||||
// 让 BigInt 可被 JSON 序列化为字符串,避免精度问题。
|
||||
(BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () {
|
||||
@@ -44,7 +45,7 @@ async function bootstrap(): Promise<void> {
|
||||
}),
|
||||
);
|
||||
app.useGlobalFilters(new AllExceptionsFilter());
|
||||
app.useGlobalInterceptors(new TransformInterceptor());
|
||||
app.useGlobalInterceptors(app.get(OperationLogInterceptor), new TransformInterceptor());
|
||||
|
||||
// 本地文件存储静态访问
|
||||
const localDir = resolve(config.get<string>('storage.localDir') || './storage');
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsInt, IsOptional, IsString } from 'class-validator';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
|
||||
export class QueryOperationLogDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '账号 ID' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
userId?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: '模块' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
module?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '操作' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
action?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '结果 SUCCESS / FAILED' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '关键词(账号/路径/消息/目标 ID)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
keyword?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '开始时间' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
startTime?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '结束时间' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
endTime?: string;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { OperationLogService } from './operation-log.service';
|
||||
|
||||
@Injectable()
|
||||
export class OperationLogRetentionService {
|
||||
private readonly logger = new Logger(OperationLogRetentionService.name);
|
||||
|
||||
constructor(
|
||||
private readonly settings: SettingsService,
|
||||
private readonly logs: OperationLogService,
|
||||
) {}
|
||||
|
||||
@Cron(CronExpression.EVERY_DAY_AT_4AM)
|
||||
async cleanup(): Promise<void> {
|
||||
const raw = await this.settings.get('operationLogRetentionDays');
|
||||
const days = Number(raw ?? 365);
|
||||
if (!days || days <= 0) return;
|
||||
const count = await this.logs.cleanup(days);
|
||||
this.logger.log(`操作日志清理完成:${count} 条,保留 ${days} 天`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Controller, Get, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { RoleType } from '@artveris/shared';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { OperationLogService } from './operation-log.service';
|
||||
import { QueryOperationLogDto } from './dto/query-operation-log.dto';
|
||||
|
||||
@ApiTags('操作日志')
|
||||
@ApiBearerAuth()
|
||||
@Roles(RoleType.SUPER_ADMIN)
|
||||
@Controller('operation-logs')
|
||||
export class OperationLogController {
|
||||
constructor(private readonly logs: OperationLogService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: '操作日志列表' })
|
||||
list(@Query() query: QueryOperationLogDto) {
|
||||
return this.logs.list(query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
import { Observable, throwError } from 'rxjs';
|
||||
import { catchError, tap } from 'rxjs/operators';
|
||||
import { AuthUser } from '../common/decorators/current-user.decorator';
|
||||
import { OperationLogService } from './operation-log.service';
|
||||
|
||||
const SENSITIVE_KEYS = new Set(['password', 'oldPassword', 'newPassword', 'token', 'authorization']);
|
||||
|
||||
function sanitize(value: unknown, depth = 0): unknown {
|
||||
if (depth > 3) return '[Truncated]';
|
||||
if (value === null || value === undefined) return value;
|
||||
if (typeof value !== 'object') return value;
|
||||
if (Array.isArray(value)) return value.slice(0, 20).map((item) => sanitize(item, depth + 1));
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [key, val] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (SENSITIVE_KEYS.has(key)) {
|
||||
out[key] = '[Redacted]';
|
||||
} else if (typeof val === 'string' && val.length > 300) {
|
||||
out[key] = `${val.slice(0, 300)}...`;
|
||||
} else {
|
||||
out[key] = sanitize(val, depth + 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function moduleOf(path: string): string {
|
||||
const p = path.replace(/^\/api\/?/, '');
|
||||
const first = p.split('/').filter(Boolean)[0] || 'root';
|
||||
if (p.includes('/export')) return 'export';
|
||||
if (p.includes('/download')) return 'download';
|
||||
return first;
|
||||
}
|
||||
|
||||
function actionOf(method: string, path: string): string {
|
||||
if (path.includes('/login')) return 'login';
|
||||
if (path.includes('/export')) return 'export';
|
||||
if (path.includes('/download')) return 'download';
|
||||
if (path.includes('/upload')) return 'upload';
|
||||
if (path.includes('/audit')) return 'audit';
|
||||
if (path.includes('/onchain')) return 'onchain';
|
||||
if (path.includes('/backup')) return 'backup';
|
||||
if (path.includes('/restore')) return 'restore';
|
||||
if (method === 'POST') return 'create';
|
||||
if (method === 'PUT' || method === 'PATCH') return 'update';
|
||||
if (method === 'DELETE') return 'delete';
|
||||
return method.toLowerCase();
|
||||
}
|
||||
|
||||
function shouldLog(method: string, path: string): boolean {
|
||||
if (path.includes('/operation-logs')) return false;
|
||||
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) return true;
|
||||
return path.includes('/export') || path.includes('/download');
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class OperationLogInterceptor implements NestInterceptor {
|
||||
constructor(private readonly logs: OperationLogService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const req = context.switchToHttp().getRequest<Request & { user?: AuthUser }>();
|
||||
const method = req.method.toUpperCase();
|
||||
const path = req.originalUrl || req.url;
|
||||
if (!shouldLog(method, path)) return next.handle();
|
||||
|
||||
const started = Date.now();
|
||||
const user = req.user;
|
||||
const base = {
|
||||
userId: user?.id ?? null,
|
||||
username: user?.username ?? (req.body as any)?.username ?? null,
|
||||
role: user?.role ?? null,
|
||||
module: moduleOf(path),
|
||||
action: actionOf(method, path),
|
||||
method,
|
||||
path,
|
||||
targetId: String(req.params?.id ?? req.params?.shortCode ?? ''),
|
||||
ip: (req.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim() || req.ip,
|
||||
userAgent: req.headers['user-agent'] || null,
|
||||
requestSummary: sanitize({ params: req.params, query: req.query, body: req.body }) as any,
|
||||
};
|
||||
|
||||
return next.handle().pipe(
|
||||
tap(() => {
|
||||
void this.logs.create({
|
||||
...base,
|
||||
status: 'SUCCESS',
|
||||
durationMs: Date.now() - started,
|
||||
});
|
||||
}),
|
||||
catchError((err) => {
|
||||
void this.logs.create({
|
||||
...base,
|
||||
status: 'FAILED',
|
||||
message: (err as Error)?.message || String(err),
|
||||
durationMs: Date.now() - started,
|
||||
});
|
||||
return throwError(() => err);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { OperationLogController } from './operation-log.controller';
|
||||
import { OperationLogInterceptor } from './operation-log.interceptor';
|
||||
import { OperationLogRetentionService } from './operation-log-retention.service';
|
||||
import { OperationLogService } from './operation-log.service';
|
||||
|
||||
@Module({
|
||||
controllers: [OperationLogController],
|
||||
providers: [OperationLogService, OperationLogInterceptor, OperationLogRetentionService],
|
||||
exports: [OperationLogService, OperationLogInterceptor],
|
||||
})
|
||||
export class OperationLogModule {}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
import { QueryOperationLogDto } from './dto/query-operation-log.dto';
|
||||
|
||||
export interface OperationLogInput {
|
||||
userId?: number | null;
|
||||
username?: string | null;
|
||||
role?: string | null;
|
||||
module: string;
|
||||
action: string;
|
||||
method: string;
|
||||
path: string;
|
||||
targetId?: string | null;
|
||||
status: string;
|
||||
message?: string | null;
|
||||
ip?: string | null;
|
||||
userAgent?: string | null;
|
||||
durationMs?: number | null;
|
||||
requestSummary?: Prisma.InputJsonValue | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class OperationLogService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async create(input: OperationLogInput): Promise<void> {
|
||||
await this.prisma.operationLog.create({
|
||||
data: {
|
||||
userId: input.userId ?? null,
|
||||
username: input.username ?? null,
|
||||
role: (input.role as any) ?? null,
|
||||
module: input.module,
|
||||
action: input.action,
|
||||
method: input.method,
|
||||
path: input.path,
|
||||
targetId: input.targetId ?? null,
|
||||
status: input.status,
|
||||
message: input.message ?? null,
|
||||
ip: input.ip ?? null,
|
||||
userAgent: input.userAgent ?? null,
|
||||
durationMs: input.durationMs ?? null,
|
||||
requestSummary: input.requestSummary ?? undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async list(query: QueryOperationLogDto) {
|
||||
const where: Prisma.OperationLogWhereInput = {};
|
||||
if (query.userId) where.userId = query.userId;
|
||||
if (query.module) where.module = query.module;
|
||||
if (query.action) where.action = query.action;
|
||||
if (query.status) where.status = query.status;
|
||||
if (query.keyword) {
|
||||
where.OR = [
|
||||
{ username: { contains: query.keyword } },
|
||||
{ path: { contains: query.keyword } },
|
||||
{ message: { contains: query.keyword } },
|
||||
{ targetId: { contains: query.keyword } },
|
||||
];
|
||||
}
|
||||
if (query.startTime || query.endTime) {
|
||||
where.createdAt = {};
|
||||
if (query.startTime) where.createdAt.gte = new Date(query.startTime);
|
||||
if (query.endTime) where.createdAt.lte = new Date(query.endTime);
|
||||
}
|
||||
const [list, total] = await this.prisma.$transaction([
|
||||
this.prisma.operationLog.findMany({
|
||||
where,
|
||||
orderBy: { id: 'desc' },
|
||||
skip: query.skip,
|
||||
take: query.take,
|
||||
}),
|
||||
this.prisma.operationLog.count({ where }),
|
||||
]);
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
}
|
||||
|
||||
async cleanup(days: number): Promise<number> {
|
||||
if (!days || days <= 0) return 0;
|
||||
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
||||
const res = await this.prisma.operationLog.deleteMany({ where: { createdAt: { lt: cutoff } } });
|
||||
return res.count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
import { OutboundImportRowStatus } from '@artveris/shared';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
|
||||
export class QueryImportRowsDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '行状态', enum: OutboundImportRowStatus })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: OutboundImportRowStatus;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsDateString, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
|
||||
import { IsArray, IsDateString, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
|
||||
|
||||
export class OutboundDto {
|
||||
@ApiPropertyOptional({ description: '出库时间' })
|
||||
@@ -13,6 +13,12 @@ export class OutboundDto {
|
||||
@IsString()
|
||||
outImageKey?: string | null;
|
||||
|
||||
@ApiPropertyOptional({ description: '出库实况图存储 key 列表' })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
outImageKeys?: string[];
|
||||
|
||||
@ApiPropertyOptional({ description: '上链哈希值(填写则记录上链结果)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import AdmZip from 'adm-zip';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import sharp from 'sharp';
|
||||
import { JobStatus, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { JobsService } from '../jobs/jobs.service';
|
||||
|
||||
interface PreviewJobData {
|
||||
jobId: string;
|
||||
sessionId: string;
|
||||
fileKey: string;
|
||||
}
|
||||
|
||||
function cellToString(v: unknown): string {
|
||||
if (v === null || v === undefined) return '';
|
||||
if (v instanceof Date) return v.toISOString();
|
||||
if (typeof v === 'object') {
|
||||
const o = v as Record<string, unknown>;
|
||||
if (typeof o.text === 'string') return o.text.trim();
|
||||
if (o.result !== undefined && o.result !== null) return String(o.result).trim();
|
||||
if (Array.isArray(o.richText)) return o.richText.map((r: any) => r.text).join('').trim();
|
||||
if (o.hyperlink) return String(o.hyperlink).trim();
|
||||
}
|
||||
return String(v).trim();
|
||||
}
|
||||
|
||||
function parseDate(v?: string): Date | undefined | null {
|
||||
if (!v) return undefined;
|
||||
const d = new Date(v);
|
||||
return Number.isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
function normalizeImagePath(raw: string): string {
|
||||
const p = raw.trim().replace(/^image\//i, 'images/');
|
||||
if (!p) return '';
|
||||
if (p.includes('\\') || p.includes('..') || p.startsWith('/') || /^[a-z]:/i.test(p)) {
|
||||
throw new Error(`图片路径不安全:${raw}`);
|
||||
}
|
||||
if (!/^images\/[^/][\w.\- /()\u4e00-\u9fa5]+$/i.test(p)) {
|
||||
throw new Error(`图片必须位于 images 目录:${raw}`);
|
||||
}
|
||||
const ext = p.slice(p.lastIndexOf('.')).toLowerCase();
|
||||
if (!['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {
|
||||
throw new Error(`不支持的图片格式:${raw}`);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
@Processor(QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW)
|
||||
export class ImportPreviewProcessor extends WorkerHost {
|
||||
private readonly logger = new Logger(ImportPreviewProcessor.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly jobs: JobsService,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async process(job: Job<PreviewJobData>): Promise<void> {
|
||||
const { jobId, sessionId, fileKey } = job.data;
|
||||
await this.jobs.start(jobId);
|
||||
try {
|
||||
const buffer = await this.storage.read(fileKey);
|
||||
const zip = new AdmZip(buffer);
|
||||
const entries = zip.getEntries().filter((e) => !e.isDirectory);
|
||||
const xlsxEntries = entries.filter((e) => e.entryName.toLowerCase().endsWith('.xlsx'));
|
||||
if (xlsxEntries.length !== 1) throw new Error('ZIP 中必须且只能包含一个 xlsx 文件');
|
||||
|
||||
const imageEntries = new Map<string, Buffer>();
|
||||
for (const entry of entries) {
|
||||
const name = entry.entryName.replace(/\\/g, '/');
|
||||
if (name === xlsxEntries[0].entryName || name.endsWith('说明.txt')) continue;
|
||||
const normalized = normalizeImagePath(name);
|
||||
const data = entry.getData();
|
||||
if (data.length > 10 * 1024 * 1024) throw new Error(`图片超过 10MB:${name}`);
|
||||
imageEntries.set(normalized, data);
|
||||
}
|
||||
|
||||
const wb = new ExcelJS.Workbook();
|
||||
await wb.xlsx.load(xlsxEntries[0].getData() as unknown as ArrayBuffer);
|
||||
const ws = wb.worksheets[0];
|
||||
const headerToKey = new Map<string, string>();
|
||||
OUTBOUND_IMPORT_COLUMNS.forEach((c) => headerToKey.set(c.header, c.key));
|
||||
const colToKey = new Map<number, string>();
|
||||
ws.getRow(1).eachCell((cell, col) => {
|
||||
const key = headerToKey.get(String(cell.value ?? '').trim());
|
||||
if (key) colToKey.set(col, key);
|
||||
});
|
||||
|
||||
const storedImages = new Map<string, { key: string; url: string; name: string; type: string }>();
|
||||
const rows: any[] = [];
|
||||
let valid = 0;
|
||||
let invalid = 0;
|
||||
|
||||
for (let r = 2; r <= ws.rowCount; r++) {
|
||||
const row = ws.getRow(r);
|
||||
const values: Record<string, string> = {};
|
||||
let empty = true;
|
||||
colToKey.forEach((key, col) => {
|
||||
const text = cellToString(row.getCell(col).value);
|
||||
if (text) empty = false;
|
||||
values[key] = text;
|
||||
});
|
||||
if (empty) continue;
|
||||
|
||||
const result: any = {
|
||||
sessionId,
|
||||
rowNo: r,
|
||||
status: 'INVALID',
|
||||
shortCode: values.shortCode || null,
|
||||
batchNo: values.batchNo || null,
|
||||
txHash: values.txHash || null,
|
||||
remark: values.remark || null,
|
||||
reason: '',
|
||||
preview: values,
|
||||
};
|
||||
|
||||
try {
|
||||
if (!values.shortCode) throw new Error('短码为空');
|
||||
const code = await this.prisma.traceCode.findUnique({
|
||||
where: { shortCode: values.shortCode },
|
||||
include: { batch: true },
|
||||
});
|
||||
if (!code) throw new Error('短码不存在');
|
||||
if (values.batchNo && values.batchNo !== (code.batch?.batchNo ?? '')) {
|
||||
throw new Error(`批次编号不匹配,实际为 ${code.batch?.batchNo ?? '-'}`);
|
||||
}
|
||||
const outTime = parseDate(values.outTime);
|
||||
if (outTime === null) throw new Error('出库时间格式不正确');
|
||||
const onchainAt = parseDate(values.onchainAt);
|
||||
if (onchainAt === null) throw new Error('上链时间格式不正确');
|
||||
let blockHeight: bigint | null = null;
|
||||
if (values.blockHeight) {
|
||||
if (!/^\d+$/.test(values.blockHeight)) throw new Error('区块高度应为整数');
|
||||
blockHeight = BigInt(values.blockHeight);
|
||||
}
|
||||
|
||||
const imagePaths = (values.outImages || '')
|
||||
.split(';')
|
||||
.map((p) => p.trim())
|
||||
.filter(Boolean)
|
||||
.map(normalizeImagePath);
|
||||
const imageItems: Array<{ key: string; url: string; name: string; type: string }> = [];
|
||||
for (const p of imagePaths) {
|
||||
const img = imageEntries.get(p);
|
||||
if (!img) throw new Error(`图片不存在:${p}`);
|
||||
if (!storedImages.has(p)) {
|
||||
await sharp(img).metadata();
|
||||
const saved = await this.storage.save(img, p.split('/').pop() || 'outbound.jpg', `image/${p.endsWith('.png') ? 'png' : 'jpeg'}`);
|
||||
storedImages.set(p, { key: saved.key, url: saved.url, name: saved.name, type: 'image' });
|
||||
}
|
||||
imageItems.push(storedImages.get(p)!);
|
||||
}
|
||||
|
||||
Object.assign(result, {
|
||||
status: 'VALID',
|
||||
outTime,
|
||||
onchainAt,
|
||||
blockHeight,
|
||||
outImagePaths: imagePaths,
|
||||
outImageKeys: imageItems,
|
||||
preview: { ...values, images: imageItems },
|
||||
});
|
||||
valid++;
|
||||
} catch (e) {
|
||||
result.reason = (e as Error).message;
|
||||
invalid++;
|
||||
}
|
||||
rows.push(result);
|
||||
}
|
||||
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.outboundImportRow.deleteMany({ where: { sessionId } }),
|
||||
...rows.map((row) => this.prisma.outboundImportRow.create({ data: row })),
|
||||
this.prisma.outboundImportSession.update({
|
||||
where: { id: sessionId },
|
||||
data: { status: invalid ? 'FAILED' : 'READY', total: rows.length, validCount: valid, invalidCount: invalid },
|
||||
}),
|
||||
]);
|
||||
await this.jobs.finish(jobId, {
|
||||
status: invalid ? JobStatus.FAILED : JobStatus.SUCCESS,
|
||||
successCount: valid,
|
||||
failCount: invalid,
|
||||
});
|
||||
} catch (e) {
|
||||
const message = (e as Error).message;
|
||||
await this.prisma.outboundImportSession.update({
|
||||
where: { id: sessionId },
|
||||
data: { status: 'FAILED', error: message },
|
||||
});
|
||||
await this.jobs.finish(jobId, { status: JobStatus.FAILED, error: message });
|
||||
this.logger.error(`导入预览失败:${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,41 +3,18 @@ import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import { createHash } from 'crypto';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import { JobStatus, OUTBOUND_IMPORT_COLUMNS, ProofStatus, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { JobStatus, ProofStatus, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { JobsService } from '../jobs/jobs.service';
|
||||
|
||||
// 将 ExcelJS 单元格值规整为字符串(兼容 Date / 富文本 / 公式结果 / 超链接 / 数字)
|
||||
function cellToString(v: unknown): string {
|
||||
if (v === null || v === undefined) return '';
|
||||
if (v instanceof Date) return v.toISOString();
|
||||
if (typeof v === 'object') {
|
||||
const o = v as Record<string, unknown>;
|
||||
if (typeof o.text === 'string') return o.text.trim();
|
||||
if (o.result !== undefined && o.result !== null) return String(o.result).trim();
|
||||
if (Array.isArray(o.richText)) return o.richText.map((r: any) => r.text).join('').trim();
|
||||
if (o.hyperlink) return String(o.hyperlink).trim();
|
||||
}
|
||||
return String(v).trim();
|
||||
}
|
||||
|
||||
// 校验并解析日期,非法返回 null(区分 undefined=未填)
|
||||
function parseDate(v?: string): Date | undefined | null {
|
||||
if (!v) return undefined;
|
||||
const d = new Date(v);
|
||||
return isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
interface ImportJobData {
|
||||
jobId: string;
|
||||
fileKey: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
interface RowResult {
|
||||
values: Record<string, string>;
|
||||
ok: boolean;
|
||||
reason: string;
|
||||
function jsonArray<T>(value: unknown): T[] {
|
||||
return Array.isArray(value) ? (value as T[]) : [];
|
||||
}
|
||||
|
||||
@Processor(QUEUE_NAMES.IMPORT_OUTBOUND)
|
||||
@@ -53,158 +30,108 @@ export class ImportProcessor extends WorkerHost {
|
||||
}
|
||||
|
||||
async process(job: Job<ImportJobData>): Promise<void> {
|
||||
const { jobId, fileKey } = job.data;
|
||||
const { jobId, sessionId } = job.data;
|
||||
await this.jobs.start(jobId);
|
||||
try {
|
||||
const buffer = await this.storage.read(fileKey);
|
||||
const wb = new ExcelJS.Workbook();
|
||||
await wb.xlsx.load(buffer as unknown as ArrayBuffer);
|
||||
const ws = wb.worksheets[0];
|
||||
const rows = await this.prisma.outboundImportRow.findMany({
|
||||
where: { sessionId, status: 'VALID' },
|
||||
orderBy: { rowNo: 'asc' },
|
||||
});
|
||||
|
||||
// 建立 表头文本 -> 字段键 映射
|
||||
const headerToKey = new Map<string, string>();
|
||||
OUTBOUND_IMPORT_COLUMNS.forEach((c) => headerToKey.set(c.header, c.key));
|
||||
const colToKey = new Map<number, string>();
|
||||
const headerRow = ws.getRow(1);
|
||||
headerRow.eachCell((cell, col) => {
|
||||
const key = headerToKey.get(String(cell.value ?? '').trim());
|
||||
if (key) colToKey.set(col, key);
|
||||
});
|
||||
|
||||
const rows: RowResult[] = [];
|
||||
for (let r = 2; r <= ws.rowCount; r++) {
|
||||
const row = ws.getRow(r);
|
||||
const values: Record<string, string> = {};
|
||||
let empty = true;
|
||||
colToKey.forEach((key, col) => {
|
||||
const text = cellToString(row.getCell(col).value);
|
||||
if (text) empty = false;
|
||||
values[key] = text;
|
||||
let success = 0;
|
||||
let fail = 0;
|
||||
for (const row of rows) {
|
||||
try {
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { shortCode: row.shortCode || '' } });
|
||||
if (!code) throw new Error('短码不存在');
|
||||
const imageItems = jsonArray<{ key: string; url?: string; name?: string; type?: string }>(row.outImageKeys);
|
||||
await this.prisma.traceCode.update({
|
||||
where: { id: code.id },
|
||||
data: {
|
||||
outTime: row.outTime ?? undefined,
|
||||
outImage: imageItems[0]?.key || undefined,
|
||||
outImages: imageItems.length
|
||||
? imageItems.map((item) => ({ key: item.key, name: item.name, type: item.type || 'image' }))
|
||||
: undefined,
|
||||
remark: row.remark || undefined,
|
||||
},
|
||||
});
|
||||
if (empty) continue;
|
||||
rows.push({ values, ok: false, reason: '' });
|
||||
}
|
||||
|
||||
await this.jobs.progress(jobId, 0, 0);
|
||||
let success = 0;
|
||||
let fail = 0;
|
||||
for (const row of rows) {
|
||||
const shortCode = row.values.shortCode;
|
||||
if (!shortCode) {
|
||||
row.reason = '短码为空';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
const code = await this.prisma.traceCode.findUnique({
|
||||
where: { shortCode },
|
||||
include: { batch: true },
|
||||
});
|
||||
if (!code) {
|
||||
row.reason = '短码不存在';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
// 批次编号核对:填写则必须与该码实际批次一致
|
||||
if (row.values.batchNo && row.values.batchNo !== (code.batch?.batchNo ?? '')) {
|
||||
row.reason = `批次编号与该码实际批次不符(实际:${code.batch?.batchNo ?? '无'})`;
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
// 字段格式校验
|
||||
const outTime = parseDate(row.values.outTime);
|
||||
if (outTime === null) {
|
||||
row.reason = '出库时间格式不正确(应为 YYYY-MM-DD HH:mm)';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
const onchainAt = parseDate(row.values.onchainAt);
|
||||
if (onchainAt === null) {
|
||||
row.reason = '上链时间格式不正确(应为 YYYY-MM-DD HH:mm)';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
let blockHeight: bigint | undefined;
|
||||
if (row.values.blockHeight) {
|
||||
if (!/^\d+$/.test(row.values.blockHeight)) {
|
||||
row.reason = '区块高度应为整数';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
blockHeight = BigInt(row.values.blockHeight);
|
||||
}
|
||||
try {
|
||||
await this.prisma.traceCode.update({
|
||||
where: { id: code.id },
|
||||
data: {
|
||||
outTime: outTime ?? undefined,
|
||||
outImage: row.values.outImage || undefined,
|
||||
remark: row.values.remark || undefined,
|
||||
},
|
||||
if (row.txHash) {
|
||||
const dup = await this.prisma.blockchainProof.findFirst({
|
||||
where: { traceCodeId: code.id, txHash: row.txHash },
|
||||
});
|
||||
// 录入上链哈希则登记一条已上链存证(同码同哈希去重,避免重复导入污染)
|
||||
if (row.values.txHash) {
|
||||
const dup = await this.prisma.blockchainProof.findFirst({
|
||||
where: { traceCodeId: code.id, txHash: row.values.txHash },
|
||||
if (!dup) {
|
||||
const dataHash = '0x' + createHash('sha256').update(`${code.code}:${row.txHash}`).digest('hex');
|
||||
await this.prisma.blockchainProof.create({
|
||||
data: {
|
||||
traceCodeId: code.id,
|
||||
dataHash,
|
||||
txHash: row.txHash,
|
||||
blockHeight: row.blockHeight ?? null,
|
||||
chainName: '手工登记',
|
||||
onchainAt: row.onchainAt ?? new Date(),
|
||||
status: ProofStatus.ONCHAIN,
|
||||
rawResponse: { source: 'import' },
|
||||
},
|
||||
});
|
||||
if (!dup) {
|
||||
const dataHash =
|
||||
'0x' + createHash('sha256').update(`${code.code}:${row.values.txHash}`).digest('hex');
|
||||
await this.prisma.blockchainProof.create({
|
||||
data: {
|
||||
traceCodeId: code.id,
|
||||
dataHash,
|
||||
txHash: row.values.txHash,
|
||||
blockHeight: blockHeight ?? null,
|
||||
chainName: '手工登记',
|
||||
onchainAt: onchainAt ?? new Date(),
|
||||
status: ProofStatus.ONCHAIN,
|
||||
rawResponse: { source: 'import' },
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
row.ok = true;
|
||||
success++;
|
||||
} catch (e) {
|
||||
row.reason = (e as Error).message;
|
||||
fail++;
|
||||
}
|
||||
await this.prisma.outboundImportRow.update({ where: { id: row.id }, data: { status: 'IMPORTED', reason: null } });
|
||||
success++;
|
||||
} catch (e) {
|
||||
await this.prisma.outboundImportRow.update({
|
||||
where: { id: row.id },
|
||||
data: { status: 'FAILED', reason: (e as Error).message },
|
||||
});
|
||||
fail++;
|
||||
}
|
||||
|
||||
await this.jobs.progress(jobId, success, fail);
|
||||
|
||||
// 生成结果明细文件
|
||||
const resultUrl = await this.buildResultFile(rows);
|
||||
const status =
|
||||
fail === 0 ? JobStatus.SUCCESS : success === 0 ? JobStatus.FAILED : JobStatus.PARTIAL;
|
||||
await this.prisma.job.update({
|
||||
where: { id: jobId },
|
||||
data: {
|
||||
total: rows.length,
|
||||
successCount: success,
|
||||
failCount: fail,
|
||||
status,
|
||||
resultFileUrl: resultUrl,
|
||||
},
|
||||
});
|
||||
this.logger.log(`导入完成:成功 ${success},失败 ${fail}`);
|
||||
} catch (e) {
|
||||
await this.jobs.finish(jobId, { status: JobStatus.FAILED, error: (e as Error).message });
|
||||
this.logger.error(`导入失败:${(e as Error).message}`);
|
||||
}
|
||||
|
||||
const resultUrl = await this.buildResultFile(sessionId);
|
||||
const status = fail === 0 ? JobStatus.SUCCESS : success === 0 ? JobStatus.FAILED : JobStatus.PARTIAL;
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.outboundImportSession.update({
|
||||
where: { id: sessionId },
|
||||
data: { status: fail === 0 ? 'IMPORTED' : 'FAILED' },
|
||||
}),
|
||||
this.prisma.job.update({
|
||||
where: { id: jobId },
|
||||
data: { total: rows.length, successCount: success, failCount: fail, status, resultFileUrl: resultUrl },
|
||||
}),
|
||||
]);
|
||||
this.logger.log(`出库导入完成:成功 ${success},失败 ${fail}`);
|
||||
}
|
||||
|
||||
private async buildResultFile(rows: RowResult[]): Promise<string> {
|
||||
private async buildResultFile(sessionId: string): Promise<string> {
|
||||
const rows = await this.prisma.outboundImportRow.findMany({
|
||||
where: { sessionId },
|
||||
orderBy: { rowNo: 'asc' },
|
||||
});
|
||||
const wb = new ExcelJS.Workbook();
|
||||
const ws = wb.addWorksheet('导入结果');
|
||||
ws.columns = [
|
||||
...OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: 22 })),
|
||||
{ header: '处理状态', key: 'status', width: 12 },
|
||||
{ header: '失败原因', key: 'reason', width: 30 },
|
||||
{ header: '行号', key: 'rowNo', width: 10 },
|
||||
{ header: '短码', key: 'shortCode', width: 18 },
|
||||
{ header: '批次编号', key: 'batchNo', width: 22 },
|
||||
{ header: '出库时间', key: 'outTime', width: 22 },
|
||||
{ header: '图片数量', key: 'imageCount', width: 10 },
|
||||
{ header: '上链哈希', key: 'txHash', width: 30 },
|
||||
{ header: '处理状态', key: 'status', width: 14 },
|
||||
{ header: '原因', key: 'reason', width: 40 },
|
||||
];
|
||||
ws.getRow(1).font = { bold: true };
|
||||
for (const row of rows) {
|
||||
ws.addRow({ ...row.values, status: row.ok ? '成功' : '失败', reason: row.reason });
|
||||
ws.addRow({
|
||||
rowNo: row.rowNo,
|
||||
shortCode: row.shortCode || '',
|
||||
batchNo: row.batchNo || '',
|
||||
outTime: row.outTime?.toISOString() || '',
|
||||
imageCount: jsonArray(row.outImageKeys).length,
|
||||
txHash: row.txHash || '',
|
||||
status: row.status,
|
||||
reason: row.reason || '',
|
||||
});
|
||||
}
|
||||
const buf = Buffer.from(await wb.xlsx.writeBuffer());
|
||||
const saved = await this.storage.save(buf, 'import-result.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
Res,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
@@ -15,6 +16,7 @@ import { Response } from 'express';
|
||||
import { MAX_FILE_SIZE, RoleType } from '@artveris/shared';
|
||||
import { OutboundService } from './outbound.service';
|
||||
import { OutboundDto } from './dto/outbound.dto';
|
||||
import { QueryImportRowsDto } from './dto/import-session.dto';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
||||
|
||||
@@ -26,22 +28,50 @@ export class OutboundController {
|
||||
|
||||
@Put('trace-codes/:id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '单条录入出库信息' })
|
||||
@ApiOperation({ summary: '单条登记出库 / 上链信息' })
|
||||
updateSingle(@Param('id') id: string, @Body() dto: OutboundDto) {
|
||||
return this.outboundService.updateSingle(BigInt(id), dto);
|
||||
}
|
||||
|
||||
@Get('import/template')
|
||||
@ApiOperation({ summary: '下载出库导入模板(xlsx)' })
|
||||
@ApiOperation({ summary: '下载出库导入 ZIP 模板' })
|
||||
template(@Res() res: Response) {
|
||||
return this.outboundService.generateTemplate(res);
|
||||
}
|
||||
|
||||
@Post('import/preview')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '上传 ZIP 并异步解析预览' })
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE * 2 } }))
|
||||
preview(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) {
|
||||
return this.outboundService.startPreview(file, user.id);
|
||||
}
|
||||
|
||||
@Get('import-sessions/:id')
|
||||
@ApiOperation({ summary: '导入会话详情' })
|
||||
getSession(@Param('id') id: string, @CurrentUser() user: AuthUser) {
|
||||
return this.outboundService.getSession(id, user);
|
||||
}
|
||||
|
||||
@Get('import-sessions/:id/rows')
|
||||
@ApiOperation({ summary: '导入预览行列表' })
|
||||
rows(@Param('id') id: string, @Query() query: QueryImportRowsDto, @CurrentUser() user: AuthUser) {
|
||||
return this.outboundService.listRows(id, query, user);
|
||||
}
|
||||
|
||||
@Post('import-sessions/:id/commit')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '确认导入预览数据' })
|
||||
commit(@Param('id') id: string, @CurrentUser() user: AuthUser) {
|
||||
return this.outboundService.commitSession(id, user);
|
||||
}
|
||||
|
||||
@Post('import')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '批量导入出库信息(异步)' })
|
||||
@ApiOperation({ summary: '兼容旧入口:上传 ZIP 并异步解析预览' })
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE } }))
|
||||
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE * 2 } }))
|
||||
import(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) {
|
||||
return this.outboundService.startImport(file, user.id);
|
||||
}
|
||||
|
||||
@@ -4,11 +4,17 @@ import { QUEUE_NAMES } from '@artveris/shared';
|
||||
import { OutboundService } from './outbound.service';
|
||||
import { OutboundController } from './outbound.controller';
|
||||
import { ImportProcessor } from './import.processor';
|
||||
import { ImportPreviewProcessor } from './import-preview.processor';
|
||||
|
||||
@Module({
|
||||
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.IMPORT_OUTBOUND })],
|
||||
imports: [
|
||||
BullModule.registerQueue(
|
||||
{ name: QUEUE_NAMES.IMPORT_OUTBOUND },
|
||||
{ name: QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW },
|
||||
),
|
||||
],
|
||||
controllers: [OutboundController],
|
||||
providers: [OutboundService, ImportProcessor],
|
||||
providers: [OutboundService, ImportProcessor, ImportPreviewProcessor],
|
||||
exports: [OutboundService],
|
||||
})
|
||||
export class OutboundModule {}
|
||||
|
||||
@@ -4,7 +4,9 @@ import { Queue } from 'bullmq';
|
||||
import { Response } from 'express';
|
||||
import { createHash } from 'crypto';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import AdmZip from 'adm-zip';
|
||||
import sharp from 'sharp';
|
||||
import { Prisma, RoleType } from '@prisma/client';
|
||||
import {
|
||||
ErrorCode,
|
||||
JobType,
|
||||
@@ -16,13 +18,15 @@ import { PrismaService } from '../prisma/prisma.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { JobsService } from '../jobs/jobs.service';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
import { AuthUser } from '../common/decorators/current-user.decorator';
|
||||
import { OutboundDto } from './dto/outbound.dto';
|
||||
import { QueryImportRowsDto } from './dto/import-session.dto';
|
||||
|
||||
const XLSX_MIME_TYPES = [
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.ms-excel',
|
||||
'application/octet-stream', // 某些浏览器对 .xlsx 的兜底类型
|
||||
];
|
||||
const ZIP_MAX_SIZE = 30 * 1024 * 1024;
|
||||
const IMAGE_MAX_SIZE = 10 * 1024 * 1024;
|
||||
const SESSION_TTL_DAYS = 2;
|
||||
const ALLOWED_IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp']);
|
||||
|
||||
@Injectable()
|
||||
export class OutboundService {
|
||||
@@ -30,21 +34,27 @@ export class OutboundService {
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly jobs: JobsService,
|
||||
@InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND) private readonly queue: Queue,
|
||||
@InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND) private readonly importQueue: Queue,
|
||||
@InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW) private readonly previewQueue: Queue,
|
||||
) {}
|
||||
|
||||
async updateSingle(traceCodeId: bigint, dto: OutboundDto) {
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId } });
|
||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
||||
const imageKeys = dto.outImageKeys ?? (dto.outImageKey ? [dto.outImageKey] : []);
|
||||
const data: Prisma.TraceCodeUpdateInput = {};
|
||||
if ('outTime' in dto) data.outTime = dto.outTime ? new Date(dto.outTime) : null;
|
||||
if ('outImageKey' in dto) data.outImage = dto.outImageKey || null;
|
||||
if ('outImageKeys' in dto || 'outImageKey' in dto) {
|
||||
data.outImage = imageKeys[0] || null;
|
||||
data.outImages = imageKeys.length
|
||||
? imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' }))
|
||||
: Prisma.JsonNull;
|
||||
}
|
||||
if ('remark' in dto) data.remark = dto.remark || null;
|
||||
const updated = await this.prisma.traceCode.update({
|
||||
where: { id: traceCodeId },
|
||||
data,
|
||||
});
|
||||
// 录入了上链哈希则记录一条已上链存证(手工登记,不触发 Mock 链)
|
||||
if (dto.txHash) {
|
||||
await this.recordProof(traceCodeId, code.code, {
|
||||
txHash: dto.txHash,
|
||||
@@ -55,8 +65,6 @@ export class OutboundService {
|
||||
return updated;
|
||||
}
|
||||
|
||||
// 手工登记上链结果:写入一条 ONCHAIN 存证(数据哈希由 code+txHash 派生)
|
||||
// 同码同哈希去重:重复保存不会产生多条存证
|
||||
private async recordProof(
|
||||
traceCodeId: bigint,
|
||||
code: string,
|
||||
@@ -66,8 +74,7 @@ export class OutboundService {
|
||||
where: { traceCodeId, txHash: p.txHash },
|
||||
});
|
||||
if (dup) return;
|
||||
const dataHash =
|
||||
'0x' + createHash('sha256').update(`${code}:${p.txHash}`).digest('hex');
|
||||
const dataHash = '0x' + createHash('sha256').update(`${code}:${p.txHash}`).digest('hex');
|
||||
await this.prisma.blockchainProof.create({
|
||||
data: {
|
||||
traceCodeId,
|
||||
@@ -85,42 +92,141 @@ export class OutboundService {
|
||||
async generateTemplate(res: Response): Promise<void> {
|
||||
const wb = new ExcelJS.Workbook();
|
||||
const ws = wb.addWorksheet('导入模板');
|
||||
ws.columns = OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: 22 }));
|
||||
ws.columns = OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: c.key === 'outImages' ? 36 : 22 }));
|
||||
ws.getRow(1).font = { bold: true };
|
||||
const example: Record<string, string> = {};
|
||||
OUTBOUND_IMPORT_COLUMNS.forEach((c) => (example[c.key] = c.example));
|
||||
ws.addRow(example);
|
||||
ws.addRow({
|
||||
shortCode: '请替换为真实短码1',
|
||||
batchNo: 'B20260704001',
|
||||
outTime: '2026-07-04 10:00',
|
||||
outImages: 'images/out-001.jpg',
|
||||
txHash: '0xabc123',
|
||||
onchainAt: '2026-07-04 10:30',
|
||||
blockHeight: '8500001',
|
||||
remark: '单图示例',
|
||||
});
|
||||
ws.addRow({
|
||||
shortCode: '请替换为真实短码2',
|
||||
batchNo: 'B20260704001',
|
||||
outTime: '2026-07-04 11:00',
|
||||
outImages: 'images/out-002.png;images/out-003.jpg',
|
||||
txHash: '',
|
||||
onchainAt: '',
|
||||
blockHeight: '',
|
||||
remark: '多图示例',
|
||||
});
|
||||
|
||||
const note = wb.addWorksheet('字段说明');
|
||||
note.columns = [
|
||||
{ header: '列名', key: 'header', width: 18 },
|
||||
{ header: '是否必填', key: 'required', width: 12 },
|
||||
{ header: '说明', key: 'note', width: 50 },
|
||||
{ header: '说明', key: 'note', width: 70 },
|
||||
];
|
||||
note.getRow(1).font = { bold: true };
|
||||
OUTBOUND_IMPORT_COLUMNS.forEach((c) =>
|
||||
note.addRow({ header: c.header, required: c.required ? '是' : '否', note: c.note }),
|
||||
);
|
||||
|
||||
res.setHeader(
|
||||
'Content-Type',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
);
|
||||
res.setHeader('Content-Disposition', 'attachment; filename="outbound-import-template.xlsx"');
|
||||
await wb.xlsx.write(res);
|
||||
res.end();
|
||||
const zip = new AdmZip();
|
||||
zip.addFile('outbound-import-template.xlsx', Buffer.from(await wb.xlsx.writeBuffer()));
|
||||
zip.addFile('说明.txt', Buffer.from(
|
||||
[
|
||||
'出库批量导入说明',
|
||||
'',
|
||||
'1. ZIP 根目录必须包含一个 xlsx 文件和 images 文件夹。',
|
||||
'2. 出库实况图路径填写 images/xxx.jpg,多张图片使用英文分号 ; 分隔。',
|
||||
'3. 不允许使用绝对路径、..、反斜杠或 images 目录之外的路径。',
|
||||
'4. 上传 ZIP 后系统会先预览校验,确认无误后才正式导入。',
|
||||
].join('\r\n'),
|
||||
'utf8',
|
||||
));
|
||||
zip.addFile('images/out-001.jpg', await this.sampleImage('#13a8a8'));
|
||||
zip.addFile('images/out-002.png', await this.sampleImage('#3b82f6', 'png'));
|
||||
zip.addFile('images/out-003.jpg', await this.sampleImage('#f59e0b'));
|
||||
|
||||
res.setHeader('Content-Type', 'application/zip');
|
||||
res.setHeader('Content-Disposition', 'attachment; filename="outbound-import-template.zip"');
|
||||
res.end(zip.toBuffer());
|
||||
}
|
||||
|
||||
async startImport(file: Express.Multer.File, userId: number) {
|
||||
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入文件');
|
||||
private sampleImage(color: string, format: 'jpeg' | 'png' = 'jpeg') {
|
||||
const img = sharp({
|
||||
create: {
|
||||
width: 720,
|
||||
height: 480,
|
||||
channels: 3,
|
||||
background: color,
|
||||
},
|
||||
});
|
||||
return format === 'png' ? img.png().toBuffer() : img.jpeg({ quality: 86 }).toBuffer();
|
||||
}
|
||||
|
||||
async startPreview(file: Express.Multer.File, userId: number) {
|
||||
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入 ZIP 文件');
|
||||
const name = (file.originalname || '').toLowerCase();
|
||||
const okType = XLSX_MIME_TYPES.includes(file.mimetype) || name.endsWith('.xlsx') || name.endsWith('.xls');
|
||||
if (!okType) {
|
||||
throw new BusinessException(ErrorCode.FILE_TYPE_NOT_ALLOWED, '仅支持 Excel(.xlsx/.xls)文件导入');
|
||||
if (!name.endsWith('.zip') || file.size > ZIP_MAX_SIZE) {
|
||||
throw new BusinessException(ErrorCode.FILE_TYPE_NOT_ALLOWED, '仅支持 30MB 以内的 ZIP 文件');
|
||||
}
|
||||
const saved = await this.storage.save(file.buffer, file.originalname || 'import.xlsx', file.mimetype);
|
||||
const job = await this.jobs.create(JobType.IMPORT_OUTBOUND, 0, userId, { fileKey: saved.key });
|
||||
await this.queue.add('import', { jobId: job.id, fileKey: saved.key });
|
||||
return { jobId: job.id };
|
||||
const saved = await this.storage.save(file.buffer, file.originalname || 'outbound-import.zip', 'application/zip');
|
||||
const session = await this.prisma.outboundImportSession.create({
|
||||
data: {
|
||||
fileName: file.originalname || 'outbound-import.zip',
|
||||
fileKey: saved.key,
|
||||
createdBy: userId,
|
||||
expiresAt: new Date(Date.now() + SESSION_TTL_DAYS * 24 * 60 * 60 * 1000),
|
||||
},
|
||||
});
|
||||
const job = await this.jobs.create(JobType.IMPORT_OUTBOUND_PREVIEW, 0, userId, {
|
||||
sessionId: session.id,
|
||||
fileKey: saved.key,
|
||||
});
|
||||
await this.previewQueue.add('preview', { jobId: job.id, sessionId: session.id, fileKey: saved.key });
|
||||
return { sessionId: session.id, jobId: job.id };
|
||||
}
|
||||
|
||||
// 兼容旧入口:上传后只做预览,不直接入库。
|
||||
startImport(file: Express.Multer.File, userId: number) {
|
||||
return this.startPreview(file, userId);
|
||||
}
|
||||
|
||||
async getSession(id: string, user: AuthUser) {
|
||||
const session = await this.prisma.outboundImportSession.findUnique({ where: { id } });
|
||||
if (!session) throw new BusinessException(ErrorCode.NOT_FOUND, '导入会话不存在', 404);
|
||||
if (user.role !== RoleType.SUPER_ADMIN && session.createdBy !== user.id) {
|
||||
throw new BusinessException(ErrorCode.FORBIDDEN, '没有访问该导入会话的权限', 403);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
async listRows(id: string, query: QueryImportRowsDto, user: AuthUser) {
|
||||
await this.getSession(id, user);
|
||||
const where: Prisma.OutboundImportRowWhereInput = { sessionId: id };
|
||||
if (query.status) where.status = query.status as any;
|
||||
const [list, total] = await this.prisma.$transaction([
|
||||
this.prisma.outboundImportRow.findMany({
|
||||
where,
|
||||
orderBy: { rowNo: 'asc' },
|
||||
skip: query.skip,
|
||||
take: query.take,
|
||||
}),
|
||||
this.prisma.outboundImportRow.count({ where }),
|
||||
]);
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
}
|
||||
|
||||
async commitSession(id: string, user: AuthUser) {
|
||||
const session = await this.getSession(id, user);
|
||||
if (session.status !== 'READY') {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '导入会话尚未准备完成或已处理');
|
||||
}
|
||||
if (session.invalidCount > 0) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '预览存在错误行,请修正后重新上传');
|
||||
}
|
||||
const job = await this.jobs.create(JobType.IMPORT_OUTBOUND, session.validCount, user.id, { sessionId: id });
|
||||
await this.prisma.outboundImportSession.update({
|
||||
where: { id },
|
||||
data: { status: 'IMPORTING', committedAt: new Date() },
|
||||
});
|
||||
await this.importQueue.add('import', { jobId: job.id, sessionId: id });
|
||||
return { jobId: job.id, sessionId: id };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ export class PublicTraceService {
|
||||
description: string | null;
|
||||
mediaFiles: unknown;
|
||||
}>,
|
||||
code: { outTime?: Date | null; outImage?: string | null },
|
||||
code: { outTime?: Date | null; outImage?: string | null; outImages?: unknown },
|
||||
) {
|
||||
const timeline = nodes.map((n) => ({
|
||||
nodeType: n.nodeType,
|
||||
@@ -55,16 +55,23 @@ export class PublicTraceService {
|
||||
media: this.mapMedia(n.mediaFiles),
|
||||
}));
|
||||
|
||||
if (code.outTime || code.outImage) {
|
||||
const outMedia = Array.isArray(code.outImages)
|
||||
? (code.outImages as Array<{ key?: string; name?: string; type?: string }>)
|
||||
.map((item) => (typeof item === 'string' ? { key: item } : item))
|
||||
.filter((item) => item?.key)
|
||||
.map((item) => ({ name: item.name || '出库实况图', type: item.type || 'image', url: this.storage.getUrl(item.key as string) }))
|
||||
: code.outImage
|
||||
? [{ name: '出库实况图', type: 'image', url: this.storage.getUrl(code.outImage) }]
|
||||
: [];
|
||||
|
||||
if (code.outTime || outMedia.length) {
|
||||
timeline.push({
|
||||
nodeType: 'OUTBOUND',
|
||||
title: OUTBOUND_TRACE_TITLE,
|
||||
occurredAt: code.outTime ?? null,
|
||||
location: null,
|
||||
description: OUTBOUND_TRACE_DESC,
|
||||
media: code.outImage
|
||||
? [{ name: '出库实况图', type: 'image', url: this.storage.getUrl(code.outImage) }]
|
||||
: [],
|
||||
media: outMedia,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,17 @@ import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
const EDITABLE_KEYS = ['appName', 'logRetentionDays', 'watermarkText', 'carouselInterval'];
|
||||
const EDITABLE_KEYS = [
|
||||
'appName',
|
||||
'logRetentionDays',
|
||||
'operationLogRetentionDays',
|
||||
'watermarkText',
|
||||
'carouselInterval',
|
||||
'backupEnabled',
|
||||
'backupSchedule',
|
||||
'backupRetentionDays',
|
||||
'backupRetentionCount',
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class SettingsService {
|
||||
@@ -16,9 +26,13 @@ export class SettingsService {
|
||||
const map: Record<string, string> = {
|
||||
appName: this.config.get<string>('appName') || '',
|
||||
logRetentionDays: String(this.config.get<number>('logRetentionDays') || 365),
|
||||
operationLogRetentionDays: '365',
|
||||
watermarkText: this.config.get<string>('watermarkText') || '仅供溯源核验使用',
|
||||
// C 端顶部媒体轮播:单张停留秒数(支持小数),0 表示不自动切换
|
||||
carouselInterval: '3',
|
||||
backupEnabled: 'false',
|
||||
backupSchedule: 'daily',
|
||||
backupRetentionDays: '30',
|
||||
backupRetentionCount: '10',
|
||||
};
|
||||
for (const r of rows) map[r.key] = r.value;
|
||||
return map;
|
||||
|
||||
@@ -166,6 +166,14 @@ export class BatchMoveDto {
|
||||
batchNo?: string;
|
||||
}
|
||||
|
||||
export class BatchDeleteDto {
|
||||
@ApiProperty({ description: '追溯码 ID 列表', type: [String] })
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsString({ each: true })
|
||||
ids!: string[];
|
||||
}
|
||||
|
||||
export class QueryBatchDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '作品/款式 ID' })
|
||||
@IsOptional()
|
||||
@@ -180,11 +188,6 @@ export class QueryBatchDto extends PaginationDto {
|
||||
}
|
||||
|
||||
export class ExportTraceCodeDto {
|
||||
@ApiPropertyOptional({ description: '导出格式', enum: ['xlsx', 'csv'] })
|
||||
@IsOptional()
|
||||
@IsIn(['xlsx', 'csv'])
|
||||
format?: 'xlsx' | 'csv';
|
||||
|
||||
@ApiPropertyOptional({ description: '作品(款)ID' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
|
||||
@@ -15,6 +15,7 @@ import { Response } from 'express';
|
||||
import { RoleType } from '@artveris/shared';
|
||||
import { TraceCodeService } from './trace-code.service';
|
||||
import {
|
||||
BatchDeleteDto,
|
||||
BatchGroupDto,
|
||||
BatchMoveDto,
|
||||
BatchStatusDto,
|
||||
@@ -26,7 +27,6 @@ import {
|
||||
UpdateTraceCodeDto,
|
||||
} from './dto/trace-code.dto';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { Public } from '../common/decorators/public.decorator';
|
||||
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
||||
|
||||
@ApiTags('批量生码')
|
||||
@@ -96,6 +96,13 @@ export class TraceCodeController {
|
||||
return this.service.batchMove(dto, user.id);
|
||||
}
|
||||
|
||||
@Post('trace-codes/batch/delete')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '批量删除追溯码' })
|
||||
batchDelete(@Body() dto: BatchDeleteDto) {
|
||||
return this.service.batchDelete(dto);
|
||||
}
|
||||
|
||||
@Put('trace-codes/:id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '更新单个追溯码' })
|
||||
@@ -123,7 +130,6 @@ export class TraceCodeController {
|
||||
return this.service.exportCodes(query, res);
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Get('trace-codes/:id/qrcode')
|
||||
@ApiOperation({ summary: '获取追溯码二维码 PNG' })
|
||||
async qrcode(@Param('id') id: string, @Res() res: Response) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectQueue } from '@nestjs/bullmq';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Queue } from 'bullmq';
|
||||
@@ -14,6 +14,7 @@ import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
import { JobsService } from '../jobs/jobs.service';
|
||||
import {
|
||||
BatchDeleteDto,
|
||||
BatchGroupDto,
|
||||
BatchMoveDto,
|
||||
BatchStatusDto,
|
||||
@@ -41,12 +42,26 @@ export class TraceCodeService {
|
||||
return `${base}${path}/${shortCode}`;
|
||||
}
|
||||
|
||||
private mapOutImages(code: { outImage?: string | null; outImages?: unknown }) {
|
||||
const keys = Array.isArray(code.outImages)
|
||||
? (code.outImages as Array<{ key?: string; name?: string; type?: string }>)
|
||||
.map((item) => (typeof item === 'string' ? { key: item } : item))
|
||||
.filter((item) => item?.key)
|
||||
: [];
|
||||
if (!keys.length && code.outImage) keys.push({ key: code.outImage });
|
||||
return keys.map((item) => ({
|
||||
...item,
|
||||
url: this.storage.getUrl(item.key as string),
|
||||
type: item.type || 'image',
|
||||
name: item.name || (item.key as string).split('/').pop() || '出库实况图',
|
||||
}));
|
||||
}
|
||||
|
||||
async generateBatch(dto: GenerateBatchDto, userId: number) {
|
||||
// 必须指定作品档案/款式;每条 TraceCode 对应一套实物,仍是一物一码。
|
||||
const artwork = await this.prisma.artwork.findFirst({
|
||||
where: { id: dto.artworkId, deletedAt: null },
|
||||
});
|
||||
if (!artwork) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
|
||||
if (!artwork) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '鑹烘湳鍝佷笉瀛樺湪', 404);
|
||||
|
||||
const batchNo = dto.batchNo || `B${dayjs().format('YYYYMMDDHHmmss')}`;
|
||||
const exists = await this.prisma.batch.findUnique({ where: { batchNo } });
|
||||
@@ -71,7 +86,7 @@ export class TraceCodeService {
|
||||
return { batchId: batch.id, batchNo, jobId: job.id, quantity: dto.quantity };
|
||||
}
|
||||
|
||||
// ===== 分组管理 =====
|
||||
// ===== 鍒嗙粍绠$悊 =====
|
||||
listGroups() {
|
||||
return this.prisma.traceCodeGroup.findMany({
|
||||
orderBy: { id: 'desc' },
|
||||
@@ -101,7 +116,7 @@ export class TraceCodeService {
|
||||
return g;
|
||||
}
|
||||
|
||||
// ===== 批量操作 =====
|
||||
// ===== 鎵归噺鎿嶄綔 =====
|
||||
async batchSetGroup(dto: BatchGroupDto) {
|
||||
const ids = dto.ids.map((i) => BigInt(i));
|
||||
await this.prisma.traceCode.updateMany({
|
||||
@@ -114,7 +129,7 @@ export class TraceCodeService {
|
||||
async batchSetStatus(dto: BatchStatusDto) {
|
||||
const ids = dto.ids.map((i) => BigInt(i));
|
||||
if (dto.abnormal) {
|
||||
// 标记异常:用于运营人为标注疑似被复制/盗用的码
|
||||
// 鏍囪寮傚父锛氱敤浜庤繍钀ヤ汉涓烘爣娉ㄧ枒浼艰澶嶅埗/鐩楃敤鐨勭爜
|
||||
await this.prisma.traceCode.updateMany({
|
||||
where: { id: { in: ids } },
|
||||
data: { status: TraceCodeStatus.ABNORMAL },
|
||||
@@ -125,7 +140,7 @@ export class TraceCodeService {
|
||||
data: { status: TraceCodeStatus.DISABLED },
|
||||
});
|
||||
} else {
|
||||
// 启用:已激活过的恢复为 ACTIVE,否则恢复为 INACTIVE
|
||||
// 鍚敤锛氬凡婵€娲昏繃鐨勬仮澶嶄负 ACTIVE锛屽惁鍒欐仮澶嶄负 INACTIVE
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.traceCode.updateMany({
|
||||
where: { id: { in: ids }, firstActivatedAt: { not: null } },
|
||||
@@ -164,12 +179,12 @@ export class TraceCodeService {
|
||||
}
|
||||
|
||||
if (!options.batchId) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '请选择目标批次或填写新批次编号');
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '璇烽€夋嫨鐩爣鎵规鎴栧~鍐欐柊鎵规缂栧彿');
|
||||
}
|
||||
|
||||
const targetBatch = await this.prisma.batch.findUnique({ where: { id: options.batchId } });
|
||||
if (!targetBatch || targetBatch.artworkId !== options.artworkId) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '目标批次不存在或不属于当前艺术品档案');
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '鐩爣鎵规涓嶅瓨鍦ㄦ垨涓嶅睘浜庡綋鍓嶈壓鏈搧妗f');
|
||||
}
|
||||
return targetBatch;
|
||||
}
|
||||
@@ -193,11 +208,11 @@ export class TraceCodeService {
|
||||
select: { id: true, artworkId: true, batchId: true },
|
||||
});
|
||||
if (codes.length !== ids.length) {
|
||||
throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '部分追溯码不存在', 404);
|
||||
throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '閮ㄥ垎杩芥函鐮佷笉瀛樺湪', 404);
|
||||
}
|
||||
const artworkIds = new Set(codes.map((c) => c.artworkId));
|
||||
if (artworkIds.size !== 1) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '只能批量移动同一艺术品档案下的追溯码');
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '鍙兘鎵归噺绉诲姩鍚屼竴鑹烘湳鍝佹。妗堜笅鐨勮拷婧爜');
|
||||
}
|
||||
|
||||
const artworkId = codes[0].artworkId;
|
||||
@@ -243,7 +258,7 @@ export class TraceCodeService {
|
||||
async updateOne(id: string, dto: UpdateTraceCodeDto, userId?: number) {
|
||||
const traceCodeId = BigInt(id);
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId } });
|
||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '杩芥函鐮佷笉瀛樺湪', 404);
|
||||
|
||||
const data: Prisma.TraceCodeUncheckedUpdateInput = {};
|
||||
let targetBatchId: number | undefined;
|
||||
@@ -309,23 +324,36 @@ export class TraceCodeService {
|
||||
}
|
||||
|
||||
async removeOne(id: string) {
|
||||
const traceCodeId = BigInt(id);
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId } });
|
||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
||||
return this.batchDelete({ ids: [id] });
|
||||
}
|
||||
|
||||
async batchDelete(dto: BatchDeleteDto) {
|
||||
const ids = dto.ids.map((item) => BigInt(item));
|
||||
const codes = await this.prisma.traceCode.findMany({
|
||||
where: { id: { in: ids } },
|
||||
select: { id: true, batchId: true },
|
||||
});
|
||||
if (codes.length !== ids.length) {
|
||||
throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '閮ㄥ垎杩芥函鐮佷笉瀛樺湪', 404);
|
||||
}
|
||||
const batchCounts = new Map<number, number>();
|
||||
for (const code of codes) {
|
||||
batchCounts.set(code.batchId, (batchCounts.get(code.batchId) ?? 0) + 1);
|
||||
}
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.queryLog.updateMany({
|
||||
where: { traceCodeId },
|
||||
where: { traceCodeId: { in: ids } },
|
||||
data: { traceCodeId: null },
|
||||
}),
|
||||
this.prisma.traceCode.delete({ where: { id: traceCodeId } }),
|
||||
this.prisma.batch.update({
|
||||
where: { id: code.batchId },
|
||||
data: { quantity: { decrement: 1 }, generatedCount: { decrement: 1 } },
|
||||
}),
|
||||
this.prisma.traceCode.deleteMany({ where: { id: { in: ids } } }),
|
||||
...[...batchCounts.entries()].map(([batchId, count]) =>
|
||||
this.prisma.batch.update({
|
||||
where: { id: batchId },
|
||||
data: { quantity: { decrement: count }, generatedCount: { decrement: count } },
|
||||
}),
|
||||
),
|
||||
]);
|
||||
|
||||
return { success: true };
|
||||
return { success: true, count: ids.length };
|
||||
}
|
||||
|
||||
async listBatches(query: QueryBatchDto) {
|
||||
@@ -399,6 +427,7 @@ export class TraceCodeService {
|
||||
return {
|
||||
...rest,
|
||||
outImageUrl: code.outImage ? this.storage.getUrl(code.outImage) : null,
|
||||
outImages: this.mapOutImages(code),
|
||||
latestProof: latestOnchainProof,
|
||||
latestAnyProof: proofs[0] ?? null,
|
||||
};
|
||||
@@ -411,7 +440,7 @@ export class TraceCodeService {
|
||||
|
||||
async getQrPng(id: bigint): Promise<Buffer> {
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { id } });
|
||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '杩芥函鐮佷笉瀛樺湪', 404);
|
||||
return QRCode.toBuffer(code.url || this.buildTraceUrl(code.shortCode), {
|
||||
type: 'png',
|
||||
width: 320,
|
||||
@@ -446,21 +475,21 @@ export class TraceCodeService {
|
||||
const ws = wb.addWorksheet('追溯码');
|
||||
ws.columns = [
|
||||
{ header: '档案编号', key: 'archiveNo', width: 18 },
|
||||
{ header: '作品名称', key: 'title', width: 20 },
|
||||
{ header: '名称', key: 'title', width: 20 },
|
||||
{ header: '批次编号', key: 'batchNo', width: 22 },
|
||||
{ header: '分组', key: 'group', width: 14 },
|
||||
{ header: '追溯码', key: 'code', width: 24 },
|
||||
{ header: '随机短码', key: 'shortCode', width: 16 },
|
||||
{ header: '短链', key: 'url', width: 40 },
|
||||
{ header: '二维码数据', key: 'qr', width: 50 },
|
||||
{ header: '二维码', key: 'qr', width: 18 },
|
||||
{ header: '生成时间', key: 'createdAt', width: 22 },
|
||||
];
|
||||
ws.getRow(1).font = { bold: true };
|
||||
ws.getColumn('qr').width = 18;
|
||||
|
||||
for (const c of codes) {
|
||||
const url = c.url || this.buildTraceUrl(c.shortCode);
|
||||
const qr = await QRCode.toDataURL(url, { margin: 1, width: 200 });
|
||||
ws.addRow({
|
||||
const row = ws.addRow({
|
||||
archiveNo: c.artwork?.archiveNo ?? '',
|
||||
title: c.artwork?.title ?? '',
|
||||
batchNo: c.batch?.batchNo ?? '',
|
||||
@@ -468,28 +497,25 @@ export class TraceCodeService {
|
||||
code: c.code,
|
||||
shortCode: c.shortCode,
|
||||
url,
|
||||
qr,
|
||||
qr: '',
|
||||
createdAt: dayjs(c.createdAt).format('YYYY-MM-DD HH:mm:ss'),
|
||||
});
|
||||
row.height = 72;
|
||||
const qr = await QRCode.toDataURL(url, { margin: 1, width: 220 });
|
||||
const imageId = wb.addImage({ base64: qr, extension: 'png' });
|
||||
ws.addImage(imageId, {
|
||||
tl: { col: 7.15, row: row.number - 0.9 },
|
||||
ext: { width: 84, height: 84 },
|
||||
});
|
||||
}
|
||||
|
||||
const format = dto.format === 'csv' ? 'csv' : 'xlsx';
|
||||
const stamp = dayjs().format('YYYYMMDDHHmmss');
|
||||
if (format === 'csv') {
|
||||
const csvBuf = (await wb.csv.writeBuffer()) as unknown as Uint8Array;
|
||||
// 加 UTF-8 BOM 以便 Excel 正确识别中文
|
||||
const out = Buffer.concat([Buffer.from('\uFEFF', 'utf8'), Buffer.from(csvBuf)]);
|
||||
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="trace-codes-${stamp}.csv"`);
|
||||
res.end(out);
|
||||
} else {
|
||||
res.setHeader(
|
||||
'Content-Type',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
);
|
||||
res.setHeader('Content-Disposition', `attachment; filename="trace-codes-${stamp}.xlsx"`);
|
||||
await wb.xlsx.write(res);
|
||||
res.end();
|
||||
}
|
||||
res.setHeader(
|
||||
'Content-Type',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
);
|
||||
res.setHeader('Content-Disposition', `attachment; filename="trace-codes-${stamp}.xlsx"`);
|
||||
await wb.xlsx.write(res);
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user