feat: 实现出库导入、区块链存证、查询日志、看板与系统设置

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-28 16:25:03 +08:00
co-authored by Cursor
parent 63c0488ff7
commit 23cbf37aa1
20 changed files with 720 additions and 6 deletions
+1
View File
@@ -55,4 +55,5 @@
- 阶段 4(核心业务)已完成:模板(动态字段,增删改查、options、停用软删、在用校验);艺术品建档(模板驱动动态字段、多图、软删、状态,媒体以 key 存储、读取转绝对 URL);溯源节点(时间轴增删改查 + reorder);认证文件(上传原件→入 WATERMARK 队列用 sharp 生成平铺水印图,水印文案取 system_setting/config,原件 key 存 originFileUrl、水印 key 存 watermarkFileUrl,读取转 URL)。已验证模板→作品→节点→证书→水印异步生成→可访问。
- 约定:媒体统一以存储 key 存库,响应时经 StorageService.getUrl 转绝对 URL(便于 CDN/OSS 切换);写操作需 OPERATOR+(SUPER_ADMIN 全通),读操作任意已登录角色。
- 阶段 5(生码与公开溯源)已完成:批量生码(GEN_CODE 队列异步,nanoid 短码 10 位/追溯码 18 位,url=`BASE_URL/t/{shortCode}`,分块 createMany,回写 batch/job 进度);批次/追溯码列表、二维码 PNG(qrcode)、Excel 导出(exceljs 含二维码 DataURL)、绑定/解绑作品(UNBOUND→INACTIVE);public-trace 公开匿名:短码经 Redis 映射缓存解析→校验→未激活则激活计数=1+首次激活时间、已激活则原子 increment→聚合作品(动态字段映射label)/时间轴/证书(仅水印图)/链上凭证→写查询日志(IP/地区/设备/结果);`/t/:shortCode` 302 跳转 C 端。已验证生码→绑定→首扫激活→复扫+1→无效码 INVALID。
- 阶段 6(出库/上链/日志/看板/设置)已完成:出库单条录入 + 批量导入(IMPORT_OUTBOUND 队列异步,按 OUTBOUND_IMPORT_COLUMNS 解析、逐行校验、生成成功/失败明细 xlsx 至存储并回写 job.resultFileUrl)+ 导入模板下载(含字段说明);区块链存证触发 `POST /trace-codes/:id/onchain`(建 PENDING 证据 + ONCHAIN 队列 Mock 上链回写 txHash/blockHash/blockHeight/explorerUrl)+ 重试;查询日志检索(短码/结果/时间);数据看板总览(计数+近7天趋势+高频榜);系统设置(appName/logRetentionDays/watermarkText,超管可改,app-info/settings/public 公开读)。已端到端验证看板/上链/日志/模板/导入(PARTIAL 成功失败明细)。后端功能已全部完成。
+5 -4
View File
@@ -1,12 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { Public } from './common/decorators/public.decorator';
import { SettingsService } from './settings/settings.service';
@ApiTags('系统')
@Controller()
export class AppController {
constructor(private readonly config: ConfigService) {}
constructor(private readonly settings: SettingsService) {}
@Public()
@Get('health')
@@ -18,7 +18,8 @@ export class AppController {
@Public()
@Get('app-info')
@ApiOperation({ summary: '应用基本信息(公开)' })
appInfo() {
return { appName: this.config.get<string>('appName') };
async appInfo() {
const appName = await this.settings.get('appName');
return { appName };
}
}
+8
View File
@@ -18,6 +18,10 @@ import { TraceNodeModule } from './trace-node/trace-node.module';
import { CertificateModule } from './certificate/certificate.module';
import { TraceCodeModule } from './trace-code/trace-code.module';
import { PublicTraceModule } from './public-trace/public-trace.module';
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';
@Module({
imports: [
@@ -42,6 +46,10 @@ import { PublicTraceModule } from './public-trace/public-trace.module';
CertificateModule,
TraceCodeModule,
PublicTraceModule,
OutboundModule,
QueryLogModule,
DashboardModule,
SettingsModule,
],
controllers: [AppController],
})
@@ -0,0 +1,58 @@
import { Injectable } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { ErrorCode, ProofStatus, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { BlockchainService } from './blockchain.service';
@Injectable()
export class AttestationService {
constructor(
private readonly prisma: PrismaService,
private readonly blockchain: BlockchainService,
@InjectQueue(QUEUE_NAMES.ONCHAIN) private readonly queue: Queue,
) {}
async trigger(traceCodeId: bigint) {
const code = await this.prisma.traceCode.findUnique({
where: { id: traceCodeId },
include: {
artwork: { include: { traceNodes: true, certificates: true } },
},
});
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
if (!code.artworkId || !code.artwork) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '追溯码未绑定作品,无法上链');
}
const summary = {
shortCode: code.shortCode,
code: code.code,
title: code.artwork.title,
artist: code.artwork.artist,
dynamicFields: code.artwork.dynamicFields,
sku: code.sku,
archiveNo: code.archiveNo,
nodes: code.artwork.traceNodes.map((n) => ({ type: n.nodeType, title: n.title })),
certificates: code.artwork.certificates.map((c) => c.name),
};
const dataHash = this.blockchain.hashData(summary);
const proof = await this.prisma.blockchainProof.create({
data: { traceCodeId, dataHash, status: ProofStatus.PENDING },
});
await this.queue.add('onchain', { proofId: proof.id });
return proof;
}
async retry(proofId: number) {
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '存证记录不存在', 404);
await this.prisma.blockchainProof.update({
where: { id: proofId },
data: { status: ProofStatus.PENDING, onchainAt: null },
});
await this.queue.add('onchain', { proofId });
return { success: true };
}
}
@@ -0,0 +1,26 @@
import { Controller, Param, ParseIntPipe, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { RoleType } from '@artveris/shared';
import { AttestationService } from './attestation.service';
import { Roles } from '../common/decorators/roles.decorator';
@ApiTags('区块链存证')
@ApiBearerAuth()
@Controller()
export class BlockchainController {
constructor(private readonly attestation: AttestationService) {}
@Post('trace-codes/:id/onchain')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '为追溯码触发数据存证上链' })
onchain(@Param('id') id: string) {
return this.attestation.trigger(BigInt(id));
}
@Post('blockchain-proofs/:id/retry')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '重试上链' })
retry(@Param('id', ParseIntPipe) id: number) {
return this.attestation.retry(id);
}
}
+9 -2
View File
@@ -1,9 +1,16 @@
import { Global, Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { QUEUE_NAMES } from '@artveris/shared';
import { BlockchainService } from './blockchain.service';
import { AttestationService } from './attestation.service';
import { BlockchainController } from './blockchain.controller';
import { OnchainProcessor } from './onchain.processor';
@Global()
@Module({
providers: [BlockchainService],
exports: [BlockchainService],
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.ONCHAIN })],
controllers: [BlockchainController],
providers: [BlockchainService, AttestationService, OnchainProcessor],
exports: [BlockchainService, AttestationService],
})
export class BlockchainModule {}
@@ -0,0 +1,51 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import { ProofStatus, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BlockchainService } from './blockchain.service';
interface OnchainJobData {
proofId: number;
}
@Processor(QUEUE_NAMES.ONCHAIN)
export class OnchainProcessor extends WorkerHost {
private readonly logger = new Logger(OnchainProcessor.name);
constructor(
private readonly prisma: PrismaService,
private readonly blockchain: BlockchainService,
) {
super();
}
async process(job: Job<OnchainJobData>): Promise<void> {
const { proofId } = job.data;
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
if (!proof) return;
try {
const result = await this.blockchain.attest({ dataHash: proof.dataHash });
await this.prisma.blockchainProof.update({
where: { id: proofId },
data: {
status: ProofStatus.ONCHAIN,
txHash: result.txHash,
blockHash: result.blockHash,
blockHeight: BigInt(result.blockHeight),
chainName: result.chainName,
explorerUrl: result.explorerUrl,
onchainAt: result.onchainAt,
rawResponse: result.raw as object,
},
});
this.logger.log(`存证 ${proofId} 上链成功`);
} catch (e) {
await this.prisma.blockchainProof.update({
where: { id: proofId },
data: { status: ProofStatus.FAILED },
});
this.logger.error(`存证 ${proofId} 上链失败: ${(e as Error).message}`);
}
}
}
@@ -0,0 +1,16 @@
import { Controller, Get } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { DashboardService } from './dashboard.service';
@ApiTags('数据看板')
@ApiBearerAuth()
@Controller('dashboard')
export class DashboardController {
constructor(private readonly dashboardService: DashboardService) {}
@Get('overview')
@ApiOperation({ summary: '看板总览' })
overview() {
return this.dashboardService.overview();
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { DashboardService } from './dashboard.service';
import { DashboardController } from './dashboard.controller';
@Module({
controllers: [DashboardController],
providers: [DashboardService],
})
export class DashboardModule {}
@@ -0,0 +1,76 @@
import { Injectable } from '@nestjs/common';
import dayjs from 'dayjs';
import { QueryResult, TraceCodeStatus } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class DashboardService {
constructor(private readonly prisma: PrismaService) {}
async overview() {
const todayStart = dayjs().startOf('day').toDate();
const [
totalArtworks,
boundCodes,
activatedCodes,
totalQueries,
todayQueries,
abnormalQueries,
] = await this.prisma.$transaction([
this.prisma.artwork.count({ where: { deletedAt: null } }),
this.prisma.traceCode.count({ where: { artworkId: { not: null } } }),
this.prisma.traceCode.count({ where: { status: TraceCodeStatus.ACTIVE } }),
this.prisma.queryLog.count(),
this.prisma.queryLog.count({ where: { queriedAt: { gte: todayStart } } }),
this.prisma.queryLog.count({
where: { queryResult: { in: [QueryResult.INVALID, QueryResult.DISABLED, QueryResult.ABNORMAL] } },
}),
]);
return {
totalArtworks,
boundCodes,
activatedCodes,
totalQueries,
todayQueries,
abnormalQueries,
trend: await this.trend(7),
topArtworks: await this.topArtworks(5),
};
}
// 近 n 天查询趋势
async trend(days: number) {
const start = dayjs().startOf('day').subtract(days - 1, 'day');
const logs = await this.prisma.queryLog.findMany({
where: { queriedAt: { gte: start.toDate() } },
select: { queriedAt: true },
});
const buckets: Record<string, number> = {};
for (let i = 0; i < days; i++) {
buckets[start.add(i, 'day').format('MM-DD')] = 0;
}
for (const l of logs) {
const k = dayjs(l.queriedAt).format('MM-DD');
if (k in buckets) buckets[k] += 1;
}
return Object.entries(buckets).map(([date, count]) => ({ date, count }));
}
// 高频查询作品榜
async topArtworks(limit: number) {
const codes = await this.prisma.traceCode.findMany({
where: { artworkId: { not: null }, queryCount: { gt: 0 } },
orderBy: { queryCount: 'desc' },
take: limit,
include: { artwork: { select: { id: true, title: true } } },
});
return codes.map((c) => ({
artworkId: c.artworkId,
title: c.artwork?.title ?? '-',
shortCode: c.shortCode,
queryCount: c.queryCount,
}));
}
}
+32
View File
@@ -0,0 +1,32 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsDateString, IsOptional, IsString, MaxLength } from 'class-validator';
export class OutboundDto {
@ApiPropertyOptional({ description: 'SKU' })
@IsOptional()
@IsString()
@MaxLength(80)
sku?: string;
@ApiPropertyOptional({ description: '档案编号' })
@IsOptional()
@IsString()
@MaxLength(80)
archiveNo?: string;
@ApiPropertyOptional({ description: '出库时间' })
@IsOptional()
@IsDateString()
outTime?: string;
@ApiPropertyOptional({ description: '出库实况图存储 key' })
@IsOptional()
@IsString()
outImageKey?: string;
@ApiPropertyOptional({ description: '备注' })
@IsOptional()
@IsString()
@MaxLength(255)
remark?: string;
}
+140
View File
@@ -0,0 +1,140 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import * as ExcelJS from 'exceljs';
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 ImportJobData {
jobId: string;
fileKey: string;
}
interface RowResult {
values: Record<string, string>;
ok: boolean;
reason: string;
}
@Processor(QUEUE_NAMES.IMPORT_OUTBOUND)
export class ImportProcessor extends WorkerHost {
private readonly logger = new Logger(ImportProcessor.name);
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly jobs: JobsService,
) {
super();
}
async process(job: Job<ImportJobData>): Promise<void> {
const { jobId, fileKey } = 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 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 v = row.getCell(col).value;
const text = v === null || v === undefined ? '' : String(v).trim();
if (text) empty = false;
values[key] = text;
});
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 } });
if (!code) {
row.reason = '短码不存在';
fail++;
continue;
}
try {
await this.prisma.traceCode.update({
where: { id: code.id },
data: {
sku: row.values.sku || undefined,
archiveNo: row.values.archiveNo || undefined,
outTime: row.values.outTime ? new Date(row.values.outTime) : undefined,
remark: row.values.remark || undefined,
},
});
row.ok = true;
success++;
} catch (e) {
row.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}`);
}
}
private async buildResultFile(rows: RowResult[]): Promise<string> {
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 },
];
ws.getRow(1).font = { bold: true };
for (const row of rows) {
ws.addRow({ ...row.values, status: row.ok ? '成功' : '失败', 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');
return saved.url;
}
}
@@ -0,0 +1,48 @@
import {
Body,
Controller,
Get,
Param,
Post,
Put,
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 { OutboundService } from './outbound.service';
import { OutboundDto } from './dto/outbound.dto';
import { Roles } from '../common/decorators/roles.decorator';
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
@ApiTags('出库与上链')
@ApiBearerAuth()
@Controller('outbound')
export class OutboundController {
constructor(private readonly outboundService: OutboundService) {}
@Put('trace-codes/:id')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '单条录入出库信息' })
updateSingle(@Param('id') id: string, @Body() dto: OutboundDto) {
return this.outboundService.updateSingle(BigInt(id), dto);
}
@Get('import/template')
@ApiOperation({ summary: '下载出库导入模板(xlsx)' })
template(@Res() res: Response) {
return this.outboundService.generateTemplate(res);
}
@Post('import')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '批量导入出库信息(异步)' })
@ApiConsumes('multipart/form-data')
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE } }))
import(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) {
return this.outboundService.startImport(file, user.id);
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { QUEUE_NAMES } from '@artveris/shared';
import { OutboundService } from './outbound.service';
import { OutboundController } from './outbound.controller';
import { ImportProcessor } from './import.processor';
@Module({
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.IMPORT_OUTBOUND })],
controllers: [OutboundController],
providers: [OutboundService, ImportProcessor],
exports: [OutboundService],
})
export class OutboundModule {}
+73
View File
@@ -0,0 +1,73 @@
import { Injectable } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { Response } from 'express';
import * as ExcelJS from 'exceljs';
import { ErrorCode, JobType, 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';
import { BusinessException } from '../common/exceptions/business.exception';
import { OutboundDto } from './dto/outbound.dto';
@Injectable()
export class OutboundService {
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly jobs: JobsService,
@InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND) private readonly queue: 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);
return this.prisma.traceCode.update({
where: { id: traceCodeId },
data: {
sku: dto.sku,
archiveNo: dto.archiveNo,
outTime: dto.outTime ? new Date(dto.outTime) : undefined,
outImage: dto.outImageKey,
remark: dto.remark,
},
});
}
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.getRow(1).font = { bold: true };
const example: Record<string, string> = {};
OUTBOUND_IMPORT_COLUMNS.forEach((c) => (example[c.key] = c.example));
ws.addRow(example);
const note = wb.addWorksheet('字段说明');
note.columns = [
{ header: '列名', key: 'header', width: 18 },
{ header: '是否必填', key: 'required', width: 12 },
{ header: '说明', key: 'note', width: 50 },
];
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();
}
async startImport(file: Express.Multer.File, userId: number) {
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入文件');
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 };
}
}
@@ -0,0 +1,60 @@
import { Controller, Get, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiPropertyOptional, ApiTags } from '@nestjs/swagger';
import { IsEnum, IsOptional, IsString } from 'class-validator';
import { Prisma } from '@prisma/client';
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';
class QueryLogQueryDto extends PaginationDto {
@ApiPropertyOptional({ description: '关键词(短码)' })
@IsOptional()
@IsString()
keyword?: string;
@ApiPropertyOptional({ description: '查询结果', enum: QueryResult })
@IsOptional()
@IsEnum(QueryResult)
result?: QueryResult;
@ApiPropertyOptional({ description: '开始时间' })
@IsOptional()
@IsString()
startTime?: string;
@ApiPropertyOptional({ description: '结束时间' })
@IsOptional()
@IsString()
endTime?: string;
}
@ApiTags('查询日志')
@ApiBearerAuth()
@Controller('query-logs')
export class QueryLogController {
constructor(private readonly prisma: PrismaService) {}
@Get()
@ApiOperation({ summary: '查询日志列表' })
async list(@Query() query: QueryLogQueryDto) {
const where: Prisma.QueryLogWhereInput = {};
if (query.keyword) where.shortCode = { contains: query.keyword };
if (query.result) where.queryResult = query.result;
if (query.startTime || query.endTime) {
where.queriedAt = {};
if (query.startTime) where.queriedAt.gte = new Date(query.startTime);
if (query.endTime) where.queriedAt.lte = new Date(query.endTime);
}
const [list, total] = await this.prisma.$transaction([
this.prisma.queryLog.findMany({
where,
orderBy: { id: 'desc' },
skip: query.skip,
take: query.take,
}),
this.prisma.queryLog.count({ where }),
]);
return buildPage(list, total, query.page, query.pageSize);
}
}
@@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { QueryLogController } from './query-log.controller';
@Module({
controllers: [QueryLogController],
})
export class QueryLogModule {}
@@ -0,0 +1,35 @@
import { Body, Controller, Get, Put } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { RoleType } from '@artveris/shared';
import { SettingsService } from './settings.service';
import { Roles } from '../common/decorators/roles.decorator';
import { Public } from '../common/decorators/public.decorator';
@ApiTags('系统设置')
@Controller('settings')
export class SettingsController {
constructor(private readonly settingsService: SettingsService) {}
@ApiBearerAuth()
@Get()
@ApiOperation({ summary: '获取全部系统设置' })
getAll() {
return this.settingsService.getAll();
}
@Public()
@Get('public')
@ApiOperation({ summary: '获取公开设置(应用名等)' })
async getPublic() {
const all = await this.settingsService.getAll();
return { appName: all.appName };
}
@ApiBearerAuth()
@Roles(RoleType.SUPER_ADMIN)
@Put()
@ApiOperation({ summary: '更新系统设置' })
update(@Body() body: Record<string, string>) {
return this.settingsService.update(body);
}
}
+11
View File
@@ -0,0 +1,11 @@
import { Global, Module } from '@nestjs/common';
import { SettingsService } from './settings.service';
import { SettingsController } from './settings.controller';
@Global()
@Module({
controllers: [SettingsController],
providers: [SettingsService],
exports: [SettingsService],
})
export class SettingsModule {}
+41
View File
@@ -0,0 +1,41 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../prisma/prisma.service';
const EDITABLE_KEYS = ['appName', 'logRetentionDays', 'watermarkText'];
@Injectable()
export class SettingsService {
constructor(
private readonly prisma: PrismaService,
private readonly config: ConfigService,
) {}
async getAll(): Promise<Record<string, string>> {
const rows = await this.prisma.systemSetting.findMany();
const map: Record<string, string> = {
appName: this.config.get<string>('appName') || '',
logRetentionDays: String(this.config.get<number>('logRetentionDays') || 365),
watermarkText: this.config.get<string>('watermarkText') || '仅供溯源核验使用',
};
for (const r of rows) map[r.key] = r.value;
return map;
}
async get(key: string): Promise<string | null> {
const row = await this.prisma.systemSetting.findUnique({ where: { key } });
return row?.value ?? null;
}
async update(values: Record<string, string>): Promise<Record<string, string>> {
for (const [key, value] of Object.entries(values)) {
if (!EDITABLE_KEYS.includes(key)) continue;
await this.prisma.systemSetting.upsert({
where: { key },
update: { value: String(value) },
create: { key, value: String(value) },
});
}
return this.getAll();
}
}