feat: 完善后台导入日志权限与备份恢复
This commit is contained in:
@@ -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