fix: 优化后台体验与导出日志交互

This commit is contained in:
Nixevol
2026-07-05 00:04:35 +08:00
parent 935375a904
commit 4122897725
44 changed files with 798 additions and 221 deletions
+3 -1
View File
@@ -5,6 +5,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { buildPage } from '../common/utils/pagination.util';
import { buildOrderBy } from '../common/utils/sort.util';
import { AuditArtworkDto, CreateArtworkDto, QueryArtworkDto, UpdateArtworkDto } from './dto/artwork.dto';
interface MediaItem {
@@ -68,6 +69,7 @@ export class ArtworkService {
if (query.auditStatus) where.auditStatus = query.auditStatus;
if (query.templateId) where.templateId = query.templateId;
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt', 'updatedAt'] as const, { id: 'desc' });
const [rows, total] = await this.prisma.$transaction([
this.prisma.artwork.findMany({
where,
@@ -75,7 +77,7 @@ export class ArtworkService {
template: { select: { id: true, name: true } },
_count: { select: { traceCodes: true } },
},
orderBy: { id: 'desc' },
orderBy,
skip: query.skip,
take: query.take,
}),
+3 -1
View File
@@ -9,6 +9,7 @@ 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 { buildOrderBy } from '../common/utils/sort.util';
import { AuthUser } from '../common/decorators/current-user.decorator';
import { QueryBackupDto } from './dto/backup.dto';
@@ -90,8 +91,9 @@ export class BackupService {
const where: any = {};
if (query.status) where.status = query.status;
if (query.mode) where.mode = query.mode;
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt'] as const, { createdAt: 'desc' });
const [list, total] = await this.prisma.$transaction([
this.prisma.backupRecord.findMany({ where, orderBy: { createdAt: 'desc' }, skip: query.skip, take: query.take }),
this.prisma.backupRecord.findMany({ where, orderBy, skip: query.skip, take: query.take }),
this.prisma.backupRecord.count({ where }),
]);
return buildPage(list, total, query.page, query.pageSize);
+11 -1
View File
@@ -1,6 +1,6 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsInt, IsOptional, Min } from 'class-validator';
import { IsIn, IsInt, IsOptional, IsString, Min } from 'class-validator';
export class PaginationDto {
@ApiPropertyOptional({ description: '页码,从 1 开始', default: 1 })
@@ -17,6 +17,16 @@ export class PaginationDto {
@Min(0)
pageSize = 20;
@ApiPropertyOptional({ description: '排序字段' })
@IsOptional()
@IsString()
sortField?: string;
@ApiPropertyOptional({ description: '排序方向', enum: ['ascend', 'descend', 'asc', 'desc'] })
@IsOptional()
@IsIn(['ascend', 'descend', 'asc', 'desc'])
sortOrder?: 'ascend' | 'descend' | 'asc' | 'desc';
get skip(): number {
return (this.page - 1) * this.pageSize;
}
+18
View File
@@ -0,0 +1,18 @@
export type SortOrderInput = 'ascend' | 'descend' | 'asc' | 'desc' | undefined;
export function normalizeSortOrder(order: SortOrderInput): 'asc' | 'desc' | null {
if (order === 'asc' || order === 'ascend') return 'asc';
if (order === 'desc' || order === 'descend') return 'desc';
return null;
}
export function buildOrderBy<T extends string>(
field: string | undefined,
order: SortOrderInput,
allowed: readonly T[],
fallback: Record<string, 'asc' | 'desc'>,
): Record<string, 'asc' | 'desc'> {
const normalized = normalizeSortOrder(order);
if (!field || !normalized || !allowed.includes(field as T)) return fallback;
return { [field]: normalized };
}
+1 -1
View File
@@ -34,7 +34,7 @@ export interface AppConfig {
export default (): AppConfig => {
const clientOrigin = process.env.CLIENT_ORIGIN || 'http://localhost:5174';
return {
appName: process.env.APP_NAME || '艺术品可信溯源与认证平台',
appName: process.env.APP_NAME || '艺术品溯源平台',
env: process.env.NODE_ENV || 'development',
port: parseInt(process.env.API_PORT || '3000', 10),
baseUrl: process.env.BASE_URL || 'http://localhost:3000',
+26 -4
View File
@@ -1,7 +1,29 @@
import { Controller, Get } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Controller, Get, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiPropertyOptional, ApiTags } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsInt, IsOptional, IsString, Max, Min } from 'class-validator';
import { DashboardService } from './dashboard.service';
class DashboardQueryDto {
@ApiPropertyOptional({ description: '近 N 日', default: 7 })
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(365)
days?: number;
@ApiPropertyOptional({ description: '开始时间' })
@IsOptional()
@IsString()
startTime?: string;
@ApiPropertyOptional({ description: '结束时间' })
@IsOptional()
@IsString()
endTime?: string;
}
@ApiTags('数据看板')
@ApiBearerAuth()
@Controller('dashboard')
@@ -10,7 +32,7 @@ export class DashboardController {
@Get('overview')
@ApiOperation({ summary: '看板总览' })
overview() {
return this.dashboardService.overview();
overview(@Query() query: DashboardQueryDto) {
return this.dashboardService.overview(query);
}
}
+35 -16
View File
@@ -3,12 +3,29 @@ import dayjs from 'dayjs';
import { QueryResult, TraceCodeStatus } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
export interface DashboardOverviewQuery {
days?: number;
startTime?: string;
endTime?: string;
}
@Injectable()
export class DashboardService {
constructor(private readonly prisma: PrismaService) {}
async overview() {
private resolveRange(query: DashboardOverviewQuery) {
const end = query.endTime ? dayjs(query.endTime) : dayjs().endOf('day');
const days = Math.min(Math.max(Number(query.days || 7), 1), 365);
const start = query.startTime ? dayjs(query.startTime) : end.startOf('day').subtract(days - 1, 'day');
return {
start: start.isValid() ? start : dayjs().startOf('day').subtract(6, 'day'),
end: end.isValid() ? end : dayjs().endOf('day'),
};
}
async overview(query: DashboardOverviewQuery = {}) {
const todayStart = dayjs().startOf('day').toDate();
const range = this.resolveRange(query);
const [
totalArtworks,
@@ -35,16 +52,17 @@ export class DashboardService {
totalQueries,
todayQueries,
abnormalQueries,
trend: await this.trend(7),
topArtworks: await this.topArtworks(5),
trend: await this.trend(range.start.toDate(), range.end.toDate()),
topArtworks: await this.topArtworks(5, range.start.toDate(), range.end.toDate()),
};
}
// 近 n 天查询趋势
async trend(days: number) {
const start = dayjs().startOf('day').subtract(days - 1, 'day');
async trend(startDate: Date, endDate: Date) {
const start = dayjs(startDate).startOf('day');
const end = dayjs(endDate).endOf('day');
const days = Math.min(Math.max(end.diff(start, 'day') + 1, 1), 365);
const logs = await this.prisma.queryLog.findMany({
where: { queriedAt: { gte: start.toDate() } },
where: { queriedAt: { gte: start.toDate(), lte: end.toDate() } },
select: { queriedAt: true },
});
const buckets: Record<string, number> = {};
@@ -58,15 +76,16 @@ export class DashboardService {
return Object.entries(buckets).map(([date, count]) => ({ date, count }));
}
// 高频查询作品榜:按款聚合(该款所有码查询次数之和)
async topArtworks(limit: number) {
const grouped = await this.prisma.traceCode.groupBy({
// 高频查询作品榜:按选定时间范围内的查询日志聚合。
async topArtworks(limit: number, startDate: Date, endDate: Date) {
const grouped = await this.prisma.queryLog.groupBy({
by: ['artworkId'],
_sum: { queryCount: true },
orderBy: { _sum: { queryCount: 'desc' } },
where: { artworkId: { not: null }, queriedAt: { gte: startDate, lte: endDate } },
_count: { _all: true },
orderBy: { _count: { artworkId: 'desc' } },
take: limit,
});
const ids = grouped.map((g) => g.artworkId);
const ids = grouped.map((g) => g.artworkId).filter((id): id is number => id !== null);
if (!ids.length) return [];
const artworks = await this.prisma.artwork.findMany({
where: { id: { in: ids } },
@@ -75,9 +94,9 @@ export class DashboardService {
const map = new Map(artworks.map((a) => [a.id, a]));
return grouped.map((g) => ({
artworkId: g.artworkId,
title: map.get(g.artworkId)?.title ?? '-',
archiveNo: map.get(g.artworkId)?.archiveNo ?? '',
queryCount: g._sum.queryCount ?? 0,
title: map.get(g.artworkId!)?.title ?? '-',
archiveNo: map.get(g.artworkId!)?.archiveNo ?? '',
queryCount: g._count._all ?? 0,
}));
}
}
@@ -1,6 +1,7 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsInt, IsOptional, IsString } from 'class-validator';
import { IsEnum, IsInt, IsOptional, IsString } from 'class-validator';
import { RoleType } from '@artveris/shared';
import { PaginationDto } from '../../common/dto/pagination.dto';
export class QueryOperationLogDto extends PaginationDto {
@@ -10,6 +11,11 @@ export class QueryOperationLogDto extends PaginationDto {
@IsInt()
userId?: number;
@ApiPropertyOptional({ description: '角色', enum: RoleType })
@IsOptional()
@IsEnum(RoleType)
role?: RoleType;
@ApiPropertyOptional({ description: '模块' })
@IsOptional()
@IsString()
@@ -3,6 +3,7 @@ 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';
import { buildOrderBy } from '../common/utils/sort.util';
export interface OperationLogInput {
userId?: number | null;
@@ -49,6 +50,7 @@ export class OperationLogService {
async list(query: QueryOperationLogDto) {
const where: Prisma.OperationLogWhereInput = {};
if (query.userId) where.userId = query.userId;
if (query.role) where.role = query.role as any;
if (query.module) where.module = query.module;
if (query.action) where.action = query.action;
if (query.status) where.status = query.status;
@@ -65,10 +67,11 @@ export class OperationLogService {
if (query.startTime) where.createdAt.gte = new Date(query.startTime);
if (query.endTime) where.createdAt.lte = new Date(query.endTime);
}
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt'] as const, { id: 'desc' });
const [list, total] = await this.prisma.$transaction([
this.prisma.operationLog.findMany({
where,
orderBy: { id: 'desc' },
orderBy,
skip: query.skip,
take: query.take,
}),
@@ -122,12 +122,12 @@ export class ImportPreviewProcessor extends WorkerHost {
};
try {
if (!values.shortCode) throw new Error('短码为空');
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 (!code) throw new Error('追溯码不存在');
if (values.batchNo && values.batchNo !== (code.batch?.batchNo ?? '')) {
throw new Error(`批次编号不匹配,实际为 ${code.batch?.batchNo ?? '-'}`);
}
+2 -2
View File
@@ -42,7 +42,7 @@ export class ImportProcessor extends WorkerHost {
for (const row of rows) {
try {
const code = await this.prisma.traceCode.findUnique({ where: { shortCode: row.shortCode || '' } });
if (!code) throw new Error('短码不存在');
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 },
@@ -112,7 +112,7 @@ export class ImportProcessor extends WorkerHost {
const ws = wb.addWorksheet('导入结果');
ws.columns = [
{ header: '行号', key: 'rowNo', width: 10 },
{ header: '短码', key: 'shortCode', width: 18 },
{ header: '追溯码', key: 'shortCode', width: 18 },
{ header: '批次编号', key: 'batchNo', width: 22 },
{ header: '出库时间', key: 'outTime', width: 22 },
{ header: '图片数量', key: 'imageCount', width: 10 },
@@ -0,0 +1,65 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { OutboundImportSessionStatus, Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
function collectImageKeys(value: Prisma.JsonValue | null): string[] {
if (!Array.isArray(value)) return [];
return value
.map((item) => {
if (typeof item === 'string') return item;
if (item && typeof item === 'object' && 'key' in item) return String((item as { key?: unknown }).key || '');
return '';
})
.filter(Boolean);
}
@Injectable()
export class OutboundImportCleanupService {
private readonly logger = new Logger(OutboundImportCleanupService.name);
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
) {}
@Cron(CronExpression.EVERY_HOUR)
async cleanupExpiredPreviewSessions(): Promise<void> {
const sessions = await this.prisma.outboundImportSession.findMany({
where: {
expiresAt: { lt: new Date() },
status: {
in: [
OutboundImportSessionStatus.PARSING,
OutboundImportSessionStatus.READY,
OutboundImportSessionStatus.FAILED,
OutboundImportSessionStatus.EXPIRED,
],
},
},
include: { rows: { select: { outImageKeys: true } } },
take: 50,
});
if (!sessions.length) return;
let removed = 0;
for (const session of sessions) {
const keys = new Set<string>();
if (session.fileKey) keys.add(session.fileKey);
for (const row of session.rows) {
collectImageKeys(row.outImageKeys as Prisma.JsonValue | null).forEach((key) => keys.add(key));
}
for (const key of keys) {
try {
await this.storage.remove(key);
} catch (e) {
this.logger.warn(`清理出库导入临时文件失败:${key} ${(e as Error).message}`);
}
}
await this.prisma.outboundImportSession.delete({ where: { id: session.id } });
removed++;
}
this.logger.log(`已清理过期出库导入预览会话:${removed}`);
}
}
+2 -1
View File
@@ -5,6 +5,7 @@ import { OutboundService } from './outbound.service';
import { OutboundController } from './outbound.controller';
import { ImportProcessor } from './import.processor';
import { ImportPreviewProcessor } from './import-preview.processor';
import { OutboundImportCleanupService } from './outbound-import-cleanup.service';
@Module({
imports: [
@@ -14,7 +15,7 @@ import { ImportPreviewProcessor } from './import-preview.processor';
),
],
controllers: [OutboundController],
providers: [OutboundService, ImportProcessor, ImportPreviewProcessor],
providers: [OutboundService, ImportProcessor, ImportPreviewProcessor, OutboundImportCleanupService],
exports: [OutboundService],
})
export class OutboundModule {}
+5 -3
View File
@@ -19,6 +19,7 @@ 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 { buildOrderBy } from '../common/utils/sort.util';
import { AuthUser } from '../common/decorators/current-user.decorator';
import { OutboundDto } from './dto/outbound.dto';
import { QueryImportRowsDto } from './dto/import-session.dto';
@@ -95,7 +96,7 @@ export class OutboundService {
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 };
ws.addRow({
shortCode: '请替换为真实短码1',
shortCode: '请替换为真实追溯码1',
batchNo: 'B20260704001',
outTime: '2026-07-04 10:00',
outImages: 'images/out-001.jpg',
@@ -105,7 +106,7 @@ export class OutboundService {
remark: '单图示例',
});
ws.addRow({
shortCode: '请替换为真实短码2',
shortCode: '请替换为真实追溯码2',
batchNo: 'B20260704001',
outTime: '2026-07-04 11:00',
outImages: 'images/out-002.png;images/out-003.jpg',
@@ -201,10 +202,11 @@ export class OutboundService {
await this.getSession(id, user);
const where: Prisma.OutboundImportRowWhereInput = { sessionId: id };
if (query.status) where.status = query.status as any;
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['outTime', 'createdAt'] as const, { rowNo: 'asc' });
const [list, total] = await this.prisma.$transaction([
this.prisma.outboundImportRow.findMany({
where,
orderBy: { rowNo: 'asc' },
orderBy,
skip: query.skip,
take: query.take,
}),
@@ -6,9 +6,10 @@ import { QueryResult } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { buildPage } from '../common/utils/pagination.util';
import { PaginationDto } from '../common/dto/pagination.dto';
import { buildOrderBy } from '../common/utils/sort.util';
class QueryLogQueryDto extends PaginationDto {
@ApiPropertyOptional({ description: '关键词(短码 / 追溯码 / 档案编号)' })
@ApiPropertyOptional({ description: '关键词(追溯码 / 完整编码 / 档案编号)' })
@IsOptional()
@IsString()
keyword?: string;
@@ -64,10 +65,11 @@ export class QueryLogController {
if (query.startTime) where.queriedAt.gte = new Date(query.startTime);
if (query.endTime) where.queriedAt.lte = new Date(query.endTime);
}
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['queriedAt', 'firstActivatedAt'] as const, { id: 'desc' });
const [list, total] = await this.prisma.$transaction([
this.prisma.queryLog.findMany({
where,
orderBy: { id: 'desc' },
orderBy,
skip: query.skip,
take: query.take,
}),
+3 -1
View File
@@ -34,7 +34,9 @@ export class SettingsService {
backupRetentionDays: '30',
backupRetentionCount: '10',
};
for (const r of rows) map[r.key] = r.value;
for (const r of rows) {
map[r.key] = r.key === 'appName' && r.value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : r.value;
}
return map;
}
+3 -1
View File
@@ -4,6 +4,7 @@ import { ErrorCode, TemplateStatus } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { buildPage } from '../common/utils/pagination.util';
import { buildOrderBy } from '../common/utils/sort.util';
import { CreateTemplateDto, QueryTemplateDto, UpdateTemplateDto, TemplateFieldDto } from './dto/template.dto';
@Injectable()
@@ -35,11 +36,12 @@ export class TemplateService {
const where: Prisma.TemplateWhereInput = { deletedAt: null };
if (query.keyword) where.name = { contains: query.keyword };
if (query.status) where.status = query.status;
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt', 'updatedAt'] as const, { id: 'desc' });
const [list, total] = await this.prisma.$transaction([
this.prisma.template.findMany({
where,
include: { fields: { orderBy: { sortOrder: 'asc' } }, _count: { select: { artworks: true } } },
orderBy: { id: 'desc' },
orderBy,
skip: query.skip,
take: query.take,
}),
@@ -71,7 +71,7 @@ export class QueryTraceCodeDto extends PaginationDto {
@IsInt()
groupId?: number;
@ApiPropertyOptional({ description: '关键词(短码/追溯码/档案号/作品名称)' })
@ApiPropertyOptional({ description: '关键词(追溯码/完整编码/档案号/作品名称)' })
@IsOptional()
@IsString()
keyword?: string;
@@ -125,7 +125,7 @@ export class TraceCodeController {
@Get('trace-codes/export')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '批量导出追溯码(Excel / CSV,可按筛选或所选)' })
@ApiOperation({ summary: '批量导出追溯码 ZIP(xlsx + 二维码图片)' })
export(@Query() query: ExportTraceCodeDto, @Res() res: Response) {
return this.service.exportCodes(query, res);
}
+21 -14
View File
@@ -6,12 +6,14 @@ import { Prisma } from '@prisma/client';
import { Response } from 'express';
import * as ExcelJS from 'exceljs';
import * as QRCode from 'qrcode';
import AdmZip from 'adm-zip';
import dayjs from 'dayjs';
import { ArtworkStatus, BatchStatus, ErrorCode, JobType, QUEUE_NAMES, TraceCodeStatus } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { buildPage } from '../common/utils/pagination.util';
import { buildOrderBy } from '../common/utils/sort.util';
import { JobsService } from '../jobs/jobs.service';
import {
BatchDeleteDto,
@@ -360,10 +362,11 @@ export class TraceCodeService {
const where: Prisma.BatchWhereInput = {};
if (query.artworkId) where.artworkId = query.artworkId;
if (query.keyword) where.batchNo = { contains: query.keyword };
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt'] as const, { id: 'desc' });
const [list, total] = await this.prisma.$transaction([
this.prisma.batch.findMany({
where,
orderBy: { id: 'desc' },
orderBy,
skip: query.skip,
take: query.take,
}),
@@ -402,6 +405,7 @@ export class TraceCodeService {
async list(query: QueryTraceCodeDto) {
const where = this.buildTraceCodeWhere(query);
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt', 'outTime', 'firstActivatedAt'] as const, { id: 'desc' });
const [list, total] = await this.prisma.$transaction([
this.prisma.traceCode.findMany({
where,
@@ -414,7 +418,7 @@ export class TraceCodeService {
take: 10,
},
},
orderBy: { id: 'desc' },
orderBy,
skip: query.skip,
take: query.take,
}),
@@ -478,15 +482,16 @@ export class TraceCodeService {
{ 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: 'shortCode', width: 16 },
{ header: '完整编码', key: 'code', width: 24 },
{ header: '链接', key: 'url', width: 40 },
{ header: '二维码', key: 'qr', width: 18 },
{ header: '生成时间', key: 'createdAt', width: 22 },
];
ws.getRow(1).font = { bold: true };
ws.getColumn('qr').width = 18;
const qrImages: Array<{ name: string; buffer: Buffer }> = [];
for (const c of codes) {
const url = c.url || this.buildTraceUrl(c.shortCode);
const row = ws.addRow({
@@ -501,8 +506,9 @@ export class TraceCodeService {
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' });
const qr = await QRCode.toBuffer(url, { type: 'png', margin: 1, width: 320 });
qrImages.push({ name: `images/${c.shortCode}.png`, buffer: qr });
const imageId = wb.addImage({ buffer: qr as unknown as ExcelJS.Buffer, extension: 'png' });
ws.addImage(imageId, {
tl: { col: 7.15, row: row.number - 0.9 },
ext: { width: 84, height: 84 },
@@ -510,12 +516,13 @@ export class TraceCodeService {
}
const stamp = dayjs().format('YYYYMMDDHHmmss');
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();
const archiveNos = new Set(codes.map((c) => c.artwork?.archiveNo).filter(Boolean));
const baseName = archiveNos.size === 1 ? [...archiveNos][0]! : 'ARTVERIS';
const zip = new AdmZip();
zip.addFile(`${baseName}_${stamp}.xlsx`, Buffer.from(await wb.xlsx.writeBuffer()));
for (const image of qrImages) zip.addFile(image.name, image.buffer);
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', `attachment; filename="${baseName}_${stamp}.zip"`);
res.end(zip.toBuffer());
}
}
+5 -1
View File
@@ -5,6 +5,7 @@ import { 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 { buildOrderBy } from '../common/utils/sort.util';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { QueryUserDto } from './dto/query-user.dto';
@@ -26,7 +27,9 @@ export class UserService {
async list(query: QueryUserDto) {
const where: Prisma.SysUserWhereInput = {};
if (query.keyword) {
const id = Number(query.keyword);
where.OR = [
...(Number.isInteger(id) && id > 0 ? [{ id }] : []),
{ username: { contains: query.keyword } },
{ realName: { contains: query.keyword } },
];
@@ -34,11 +37,12 @@ export class UserService {
if (query.role) where.role = query.role;
if (query.status) where.status = query.status;
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt', 'lastLoginAt'] as const, { id: 'desc' });
const [list, total] = await this.prisma.$transaction([
this.prisma.sysUser.findMany({
where,
select: userSelect,
orderBy: { id: 'desc' },
orderBy,
skip: query.skip,
take: query.take,
}),