feat: 实现模板、艺术品建档、溯源节点与证书水印

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-28 16:05:13 +08:00
co-authored by Cursor
parent 6e5c767a53
commit b4108d7434
20 changed files with 1087 additions and 1 deletions
@@ -0,0 +1,40 @@
import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { RoleType } from '@artveris/shared';
import { CertificateService } from './certificate.service';
import { CreateCertificateDto, UpdateCertificateDto } from './dto/certificate.dto';
import { Roles } from '../common/decorators/roles.decorator';
@ApiTags('认证文件')
@ApiBearerAuth()
@Controller()
export class CertificateController {
constructor(private readonly certService: CertificateService) {}
@Get('artworks/:artworkId/certificates')
@ApiOperation({ summary: '作品的认证文件列表' })
list(@Param('artworkId', ParseIntPipe) artworkId: number) {
return this.certService.listByArtwork(artworkId);
}
@Post('artworks/:artworkId/certificates')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '新增认证文件(自动生成水印图)' })
create(@Param('artworkId', ParseIntPipe) artworkId: number, @Body() dto: CreateCertificateDto) {
return this.certService.create(artworkId, dto);
}
@Put('certificates/:id')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '更新认证文件' })
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateCertificateDto) {
return this.certService.update(id, dto);
}
@Delete('certificates/:id')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '删除认证文件' })
remove(@Param('id', ParseIntPipe) id: number) {
return this.certService.remove(id);
}
}
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { QUEUE_NAMES } from '@artveris/shared';
import { CertificateService } from './certificate.service';
import { CertificateController } from './certificate.controller';
import { WatermarkProcessor } from './watermark.processor';
@Module({
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.WATERMARK })],
controllers: [CertificateController],
providers: [CertificateService, WatermarkProcessor],
exports: [CertificateService],
})
export class CertificateModule {}
@@ -0,0 +1,90 @@
import { Injectable } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { ErrorCode, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { CreateCertificateDto, UpdateCertificateDto } from './dto/certificate.dto';
@Injectable()
export class CertificateService {
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
@InjectQueue(QUEUE_NAMES.WATERMARK) private readonly watermarkQueue: Queue,
) {}
private withUrls<T extends { originFileUrl: string; watermarkFileUrl: string | null }>(c: T) {
return {
...c,
originUrl: c.originFileUrl ? this.storage.getUrl(c.originFileUrl) : null,
watermarkUrl: c.watermarkFileUrl ? this.storage.getUrl(c.watermarkFileUrl) : null,
};
}
private async ensureArtwork(artworkId: number) {
const a = await this.prisma.artwork.findFirst({ where: { id: artworkId, deletedAt: null } });
if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
}
async listByArtwork(artworkId: number) {
const list = await this.prisma.certificate.findMany({
where: { artworkId },
orderBy: { id: 'asc' },
});
return list.map((c) => this.withUrls(c));
}
async create(artworkId: number, dto: CreateCertificateDto) {
await this.ensureArtwork(artworkId);
const cert = await this.prisma.certificate.create({
data: {
artworkId,
name: dto.name,
issuer: dto.issuer,
issuedAt: dto.issuedAt ? new Date(dto.issuedAt) : null,
type: dto.type,
originFileUrl: dto.originKey,
},
});
await this.enqueueWatermark(cert.id, dto.originKey);
return this.withUrls(cert);
}
async update(id: number, dto: UpdateCertificateDto) {
const cert = await this.ensureCert(id);
const updated = await this.prisma.certificate.update({
where: { id },
data: {
name: dto.name,
issuer: dto.issuer,
issuedAt: dto.issuedAt ? new Date(dto.issuedAt) : undefined,
type: dto.type,
originFileUrl: dto.originKey ?? undefined,
// 重新上传原件则清空水印,等待重做
watermarkFileUrl: dto.originKey ? null : undefined,
},
});
if (dto.originKey) {
await this.enqueueWatermark(id, dto.originKey);
}
return this.withUrls(updated);
}
async remove(id: number) {
await this.ensureCert(id);
await this.prisma.certificate.delete({ where: { id } });
return { success: true };
}
private async enqueueWatermark(certificateId: number, originKey: string) {
await this.watermarkQueue.add('generate', { certificateId, originKey });
}
private async ensureCert(id: number) {
const c = await this.prisma.certificate.findUnique({ where: { id } });
if (!c) throw new BusinessException(ErrorCode.CERTIFICATE_NOT_FOUND, '认证文件不存在', 404);
return c;
}
}
@@ -0,0 +1,60 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsDateString, IsEnum, IsNotEmpty, IsOptional, IsString, MaxLength } from 'class-validator';
import { CertType } from '@artveris/shared';
export class CreateCertificateDto {
@ApiProperty({ description: '证书名称' })
@IsString()
@IsNotEmpty()
@MaxLength(120)
name!: string;
@ApiPropertyOptional({ description: '颁发机构' })
@IsOptional()
@IsString()
@MaxLength(120)
issuer?: string;
@ApiPropertyOptional({ description: '颁发时间' })
@IsOptional()
@IsDateString()
issuedAt?: string;
@ApiProperty({ description: '类型', enum: CertType })
@IsEnum(CertType)
type!: CertType;
@ApiProperty({ description: '原始文件存储 key(上传接口返回)' })
@IsString()
@IsNotEmpty()
originKey!: string;
}
export class UpdateCertificateDto {
@ApiPropertyOptional({ description: '证书名称' })
@IsOptional()
@IsString()
@MaxLength(120)
name?: string;
@ApiPropertyOptional({ description: '颁发机构' })
@IsOptional()
@IsString()
@MaxLength(120)
issuer?: string;
@ApiPropertyOptional({ description: '颁发时间' })
@IsOptional()
@IsDateString()
issuedAt?: string;
@ApiPropertyOptional({ description: '类型', enum: CertType })
@IsOptional()
@IsEnum(CertType)
type?: CertType;
@ApiPropertyOptional({ description: '重新上传的原始文件 key(提供则重做水印)' })
@IsOptional()
@IsString()
originKey?: string;
}
@@ -0,0 +1,50 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Job } from 'bullmq';
import { QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { addWatermark } from './watermark.util';
interface WatermarkJobData {
certificateId: number;
originKey: string;
}
@Processor(QUEUE_NAMES.WATERMARK)
export class WatermarkProcessor extends WorkerHost {
private readonly logger = new Logger(WatermarkProcessor.name);
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly config: ConfigService,
) {
super();
}
async process(job: Job<WatermarkJobData>): Promise<void> {
const { certificateId, originKey } = job.data;
try {
const text = await this.resolveWatermarkText();
const original = await this.storage.read(originKey);
const watermarked = await addWatermark(original, text);
const wmKey = this.storage.derivedKey(originKey, 'wm');
await this.storage.putKey(wmKey, watermarked, 'image/jpeg');
await this.prisma.certificate.update({
where: { id: certificateId },
data: { watermarkFileUrl: wmKey },
});
this.logger.log(`证书 ${certificateId} 水印已生成`);
} catch (e) {
this.logger.error(`证书 ${certificateId} 水印生成失败: ${(e as Error).message}`);
throw e;
}
}
private async resolveWatermarkText(): Promise<string> {
const setting = await this.prisma.systemSetting.findUnique({ where: { key: 'watermarkText' } });
return setting?.value || this.config.get<string>('watermarkText') || '仅供溯源核验使用';
}
}
@@ -0,0 +1,46 @@
import sharp from 'sharp';
function escapeXml(s: string): string {
return s.replace(/[<>&'"]/g, (c) => {
switch (c) {
case '<':
return '&lt;';
case '>':
return '&gt;';
case '&':
return '&amp;';
case "'":
return '&apos;';
case '"':
return '&quot;';
default:
return c;
}
});
}
// 在图片上平铺半透明文字水印,输出 JPEG。
export async function addWatermark(input: Buffer, text: string): Promise<Buffer> {
const image = sharp(input).rotate(); // 处理 EXIF 方向
const meta = await image.metadata();
const width = meta.width || 1000;
const height = meta.height || 1000;
const fontSize = Math.max(18, Math.round(width / 24));
const tileW = Math.max(220, Math.round(width / 2));
const tileH = Math.max(120, Math.round(height / 5));
const safe = escapeXml(text);
const svg = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="wm" width="${tileW}" height="${tileH}" patternUnits="userSpaceOnUse" patternTransform="rotate(-28)">
<text x="10" y="${Math.round(tileH / 2)}" font-family="Microsoft YaHei, SimHei, sans-serif" font-size="${fontSize}" fill="rgba(255,255,255,0.38)" stroke="rgba(0,0,0,0.12)" stroke-width="0.5">${safe}</text>
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#wm)" />
</svg>`;
return image
.composite([{ input: Buffer.from(svg), top: 0, left: 0 }])
.jpeg({ quality: 86 })
.toBuffer();
}