feat: 实现模板、艺术品建档、溯源节点与证书水印
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -51,5 +51,7 @@
|
||||
- 阶段 1(后端基础设施)已完成:`apps/api` NestJS 工程;Prisma 全量建模并迁移(init),生成客户端;全局统一响应拦截器/异常过滤器/校验管道/BigInt 序列化;ConfigModule 读根 `.env`(dotenv-cli 供 Prisma CLI 用 `dotenv -e ../../.env`);静态目录 `/uploads`;Swagger 在 `/api/docs`。已验证启动、DB 连接、health/app-info 正常。
|
||||
- 踩坑:pnpm 10 默认禁用原生构建脚本,已在根 `pnpm.onlyBuiltDependencies` 放行 prisma/sharp 等;Prisma migrate 需 shadow db 权限,开发库已对 `artveris` 用户授予全部权限;nanoid 固定 ^3(CJS);`tsconfig.json` 的 include 仅 `src`(含 prisma 会让 tsc 改变 rootDir 导致 dist/main.js 路径错位)。
|
||||
- 阶段 2(鉴权与用户)已完成:JWT 登录(bcryptjs)、全局 JwtAuthGuard + RolesGuard(`@Public`/`@Roles` 元数据,SUPER_ADMIN 全通)、用户 CRUD(仅超管)、改密、`auth/profile`;种子超管 `admin/Admin@12345` 与系统默认设置。已用 PowerShell 验证登录/鉴权/RBAC/401。
|
||||
- 阶段 3(平台能力)已完成:StorageService 抽象(LocalDriver 默认 + OssDriver 基于 @aws-sdk/client-s3 S3 兼容,env `STORAGE_DRIVER`/`CDN_BASE_URL` 切换,getUrl 返回绝对地址);`POST /api/upload`(按 image/video/file 校验类型与大小);QueueModule(BullMQ 连 Redis)+ JobsModule(Job 表进度,`GET /api/jobs`、`/jobs/:id`);BlockchainModule(AttestationProvider 接口 + MockProvider 拟真返回 + TianheProvider 占位,`hashData` 摘要);GeoModule(Mock 归属地)+ UA 解析工具。已验证上传→静态访问→jobs 列表。
|
||||
- 阶段 3(平台能力)已完成:StorageService 抽象(LocalDriver 默认 + OssDriver 基于 @aws-sdk/client-s3 S3 兼容,env `STORAGE_DRIVER`/`CDN_BASE_URL` 切换,getUrl 返回绝对地址,支持 read/putKey/derivedKey);`POST /api/upload`(按 image/video/file 校验类型与大小);QueueModule(BullMQ 连 Redis)+ JobsModule(Job 表进度,`GET /api/jobs`、`/jobs/:id`);BlockchainModule(AttestationProvider 接口 + MockProvider 拟真返回 + TianheProvider 占位,`hashData` 摘要);GeoModule(Mock 归属地)+ UA 解析工具。已验证上传→静态访问→jobs 列表。
|
||||
- 阶段 4(核心业务)已完成:模板(动态字段,增删改查、options、停用软删、在用校验);艺术品建档(模板驱动动态字段、多图、软删、状态,媒体以 key 存储、读取转绝对 URL);溯源节点(时间轴增删改查 + reorder);认证文件(上传原件→入 WATERMARK 队列用 sharp 生成平铺水印图,水印文案取 system_setting/config,原件 key 存 originFileUrl、水印 key 存 watermarkFileUrl,读取转 URL)。已验证模板→作品→节点→证书→水印异步生成→可访问。
|
||||
- 约定:媒体统一以存储 key 存库,响应时经 StorageService.getUrl 转绝对 URL(便于 CDN/OSS 切换);写操作需 OPERATOR+(SUPER_ADMIN 全通),读操作任意已登录角色。
|
||||
|
||||
|
||||
@@ -11,6 +11,10 @@ import { QueueModule } from './queue/queue.module';
|
||||
import { JobsModule } from './jobs/jobs.module';
|
||||
import { BlockchainModule } from './blockchain/blockchain.module';
|
||||
import { GeoModule } from './geo/geo.module';
|
||||
import { TemplateModule } from './template/template.module';
|
||||
import { ArtworkModule } from './artwork/artwork.module';
|
||||
import { TraceNodeModule } from './trace-node/trace-node.module';
|
||||
import { CertificateModule } from './certificate/certificate.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -28,6 +32,10 @@ import { GeoModule } from './geo/geo.module';
|
||||
AuthModule,
|
||||
UserModule,
|
||||
UploadModule,
|
||||
TemplateModule,
|
||||
ArtworkModule,
|
||||
TraceNodeModule,
|
||||
CertificateModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { RoleType } from '@artveris/shared';
|
||||
import { ArtworkService } from './artwork.service';
|
||||
import { CreateArtworkDto, QueryArtworkDto, UpdateArtworkDto } from './dto/artwork.dto';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
||||
|
||||
@ApiTags('艺术品建档')
|
||||
@ApiBearerAuth()
|
||||
@Controller('artworks')
|
||||
export class ArtworkController {
|
||||
constructor(private readonly artworkService: ArtworkService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: '艺术品列表' })
|
||||
list(@Query() query: QueryArtworkDto) {
|
||||
return this.artworkService.list(query);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: '艺术品详情' })
|
||||
get(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.artworkService.get(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '创建艺术品档案' })
|
||||
create(@Body() dto: CreateArtworkDto, @CurrentUser() user: AuthUser) {
|
||||
return this.artworkService.create(dto, user.id);
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '更新艺术品档案' })
|
||||
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateArtworkDto) {
|
||||
return this.artworkService.update(id, dto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '停用/删除艺术品(软删除)' })
|
||||
remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.artworkService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ArtworkService } from './artwork.service';
|
||||
import { ArtworkController } from './artwork.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [ArtworkController],
|
||||
providers: [ArtworkService],
|
||||
exports: [ArtworkService],
|
||||
})
|
||||
export class ArtworkModule {}
|
||||
@@ -0,0 +1,130 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { ArtworkStatus, ErrorCode } 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 { CreateArtworkDto, QueryArtworkDto, UpdateArtworkDto } from './dto/artwork.dto';
|
||||
|
||||
interface MediaItem {
|
||||
key: string;
|
||||
name?: string;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ArtworkService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly storage: StorageService,
|
||||
) {}
|
||||
|
||||
private mapMedia(items: unknown): Array<MediaItem & { url: string }> {
|
||||
if (!Array.isArray(items)) return [];
|
||||
return (items as MediaItem[])
|
||||
.filter((i) => i && i.key)
|
||||
.map((i) => ({ ...i, url: this.storage.getUrl(i.key) }));
|
||||
}
|
||||
|
||||
async create(dto: CreateArtworkDto, userId: number) {
|
||||
const tpl = await this.prisma.template.findFirst({
|
||||
where: { id: dto.templateId, deletedAt: null },
|
||||
});
|
||||
if (!tpl) throw new BusinessException(ErrorCode.TEMPLATE_NOT_FOUND, '模板不存在', 404);
|
||||
const artwork = await this.prisma.artwork.create({
|
||||
data: {
|
||||
templateId: dto.templateId,
|
||||
title: dto.title,
|
||||
artist: dto.artist,
|
||||
dynamicFields: (dto.dynamicFields ?? {}) as Prisma.InputJsonValue,
|
||||
images: (dto.images ?? []) as unknown as Prisma.InputJsonValue,
|
||||
createdBy: userId,
|
||||
},
|
||||
});
|
||||
return this.get(artwork.id);
|
||||
}
|
||||
|
||||
async list(query: QueryArtworkDto) {
|
||||
const where: Prisma.ArtworkWhereInput = { deletedAt: null };
|
||||
if (query.keyword) {
|
||||
where.OR = [
|
||||
{ title: { contains: query.keyword } },
|
||||
{ artist: { contains: query.keyword } },
|
||||
];
|
||||
}
|
||||
if (query.status) where.status = query.status;
|
||||
if (query.templateId) where.templateId = query.templateId;
|
||||
|
||||
const [rows, total] = await this.prisma.$transaction([
|
||||
this.prisma.artwork.findMany({
|
||||
where,
|
||||
include: {
|
||||
template: { select: { id: true, name: true } },
|
||||
traceCode: { select: { id: true, code: true, shortCode: true, status: true } },
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
skip: query.skip,
|
||||
take: query.take,
|
||||
}),
|
||||
this.prisma.artwork.count({ where }),
|
||||
]);
|
||||
const list = rows.map((a) => ({
|
||||
...a,
|
||||
images: this.mapMedia(a.images),
|
||||
}));
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
}
|
||||
|
||||
async get(id: number) {
|
||||
const a = await this.prisma.artwork.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
template: { include: { fields: { orderBy: { sortOrder: 'asc' } } } },
|
||||
traceNodes: { orderBy: { sortOrder: 'asc' } },
|
||||
certificates: { orderBy: { id: 'asc' } },
|
||||
traceCode: { include: { proofs: { orderBy: { id: 'desc' } } } },
|
||||
},
|
||||
});
|
||||
if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
|
||||
return {
|
||||
...a,
|
||||
images: this.mapMedia(a.images),
|
||||
traceNodes: a.traceNodes.map((n) => ({ ...n, mediaFiles: this.mapMedia(n.mediaFiles) })),
|
||||
certificates: a.certificates.map((c) => ({
|
||||
...c,
|
||||
originUrl: c.originFileUrl ? this.storage.getUrl(c.originFileUrl) : null,
|
||||
watermarkUrl: c.watermarkFileUrl ? this.storage.getUrl(c.watermarkFileUrl) : null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateArtworkDto) {
|
||||
await this.ensureExists(id);
|
||||
const data: Prisma.ArtworkUpdateInput = {
|
||||
title: dto.title,
|
||||
artist: dto.artist,
|
||||
status: dto.status,
|
||||
};
|
||||
if (dto.dynamicFields !== undefined) {
|
||||
data.dynamicFields = dto.dynamicFields as Prisma.InputJsonValue;
|
||||
}
|
||||
if (dto.images !== undefined) {
|
||||
data.images = dto.images as unknown as Prisma.InputJsonValue;
|
||||
}
|
||||
await this.prisma.artwork.update({ where: { id }, data });
|
||||
return this.get(id);
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
await this.ensureExists(id);
|
||||
await this.prisma.artwork.update({ where: { id }, data: { deletedAt: new Date() } });
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
private async ensureExists(id: number) {
|
||||
const a = await this.prisma.artwork.findFirst({ where: { id, deletedAt: null } });
|
||||
if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
|
||||
return a;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsObject,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { ArtworkStatus } from '@artveris/shared';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
|
||||
export class MediaItemDto {
|
||||
@ApiProperty({ description: '存储 key(上传接口返回)' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
key!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '原始文件名' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
name?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '类型:image | video' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
type?: string;
|
||||
}
|
||||
|
||||
export class CreateArtworkDto {
|
||||
@ApiProperty({ description: '模板 ID' })
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
templateId!: number;
|
||||
|
||||
@ApiProperty({ description: '作品名称' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(120)
|
||||
title!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '艺术家 / 创作者' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
artist?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '动态字段数据(按模板字段键存储)' })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
dynamicFields?: Record<string, unknown>;
|
||||
|
||||
@ApiPropertyOptional({ description: '作品图片', type: [MediaItemDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => MediaItemDto)
|
||||
images?: MediaItemDto[];
|
||||
}
|
||||
|
||||
export class UpdateArtworkDto {
|
||||
@ApiPropertyOptional({ description: '作品名称' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
title?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '艺术家 / 创作者' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
artist?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '动态字段数据' })
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
dynamicFields?: Record<string, unknown>;
|
||||
|
||||
@ApiPropertyOptional({ description: '作品图片', type: [MediaItemDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => MediaItemDto)
|
||||
images?: MediaItemDto[];
|
||||
|
||||
@ApiPropertyOptional({ description: '状态', enum: ArtworkStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(ArtworkStatus)
|
||||
status?: ArtworkStatus;
|
||||
}
|
||||
|
||||
export class QueryArtworkDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '关键词(名称/艺术家)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
keyword?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '状态', enum: ArtworkStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(ArtworkStatus)
|
||||
status?: ArtworkStatus;
|
||||
|
||||
@ApiPropertyOptional({ description: '模板 ID' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
templateId?: number;
|
||||
}
|
||||
@@ -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 '<';
|
||||
case '>':
|
||||
return '>';
|
||||
case '&':
|
||||
return '&';
|
||||
case "'":
|
||||
return ''';
|
||||
case '"':
|
||||
return '"';
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
ArrayMinSize,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { FieldType, TemplateStatus } from '@artveris/shared';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
|
||||
export class TemplateFieldDto {
|
||||
@ApiProperty({ description: '字段键(英文唯一标识)' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(50)
|
||||
fieldKey!: string;
|
||||
|
||||
@ApiProperty({ description: '字段名称' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(50)
|
||||
label!: string;
|
||||
|
||||
@ApiProperty({ description: '字段类型', enum: FieldType })
|
||||
@IsEnum(FieldType)
|
||||
type!: FieldType;
|
||||
|
||||
@ApiPropertyOptional({ description: '是否必填' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
required?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ description: '排序' })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
export class CreateTemplateDto {
|
||||
@ApiProperty({ description: '模板名称' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(80)
|
||||
name!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '备注' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
remark?: string;
|
||||
|
||||
@ApiProperty({ description: '字段列表', type: [TemplateFieldDto] })
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => TemplateFieldDto)
|
||||
fields!: TemplateFieldDto[];
|
||||
}
|
||||
|
||||
export class UpdateTemplateDto {
|
||||
@ApiPropertyOptional({ description: '模板名称' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(80)
|
||||
name?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '备注' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
remark?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '状态', enum: TemplateStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(TemplateStatus)
|
||||
status?: TemplateStatus;
|
||||
|
||||
@ApiPropertyOptional({ description: '字段列表(提供则整体替换)', type: [TemplateFieldDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => TemplateFieldDto)
|
||||
fields?: TemplateFieldDto[];
|
||||
}
|
||||
|
||||
export class QueryTemplateDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '关键词' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
keyword?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '状态', enum: TemplateStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(TemplateStatus)
|
||||
status?: TemplateStatus;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Query } from '@nestjs/common';
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { RoleType } from '@artveris/shared';
|
||||
import { TemplateService } from './template.service';
|
||||
import { CreateTemplateDto, QueryTemplateDto, UpdateTemplateDto } from './dto/template.dto';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
|
||||
@ApiTags('溯源模板')
|
||||
@ApiBearerAuth()
|
||||
@Controller('templates')
|
||||
export class TemplateController {
|
||||
constructor(private readonly templateService: TemplateService) {}
|
||||
|
||||
@Get()
|
||||
@ApiOperation({ summary: '模板列表' })
|
||||
list(@Query() query: QueryTemplateDto) {
|
||||
return this.templateService.list(query);
|
||||
}
|
||||
|
||||
@Get('options')
|
||||
@ApiOperation({ summary: '启用模板(供建档选择)' })
|
||||
options() {
|
||||
return this.templateService.options();
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: '模板详情' })
|
||||
get(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.templateService.get(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '创建模板' })
|
||||
create(@Body() dto: CreateTemplateDto) {
|
||||
return this.templateService.create(dto);
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '更新模板' })
|
||||
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateTemplateDto) {
|
||||
return this.templateService.update(id, dto);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '删除模板' })
|
||||
remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.templateService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TemplateService } from './template.service';
|
||||
import { TemplateController } from './template.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [TemplateController],
|
||||
providers: [TemplateService],
|
||||
exports: [TemplateService],
|
||||
})
|
||||
export class TemplateModule {}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
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 { CreateTemplateDto, QueryTemplateDto, UpdateTemplateDto, TemplateFieldDto } from './dto/template.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TemplateService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
private fieldsCreate(fields: TemplateFieldDto[]) {
|
||||
return fields.map((f, i) => ({
|
||||
fieldKey: f.fieldKey,
|
||||
label: f.label,
|
||||
type: f.type,
|
||||
required: f.required ?? false,
|
||||
sortOrder: f.sortOrder ?? i,
|
||||
}));
|
||||
}
|
||||
|
||||
async create(dto: CreateTemplateDto) {
|
||||
return this.prisma.template.create({
|
||||
data: {
|
||||
name: dto.name,
|
||||
remark: dto.remark,
|
||||
fields: { create: this.fieldsCreate(dto.fields) },
|
||||
},
|
||||
include: { fields: { orderBy: { sortOrder: 'asc' } } },
|
||||
});
|
||||
}
|
||||
|
||||
async list(query: QueryTemplateDto) {
|
||||
const where: Prisma.TemplateWhereInput = { deletedAt: null };
|
||||
if (query.keyword) where.name = { contains: query.keyword };
|
||||
if (query.status) where.status = query.status;
|
||||
const [list, total] = await this.prisma.$transaction([
|
||||
this.prisma.template.findMany({
|
||||
where,
|
||||
include: { fields: { orderBy: { sortOrder: 'asc' } }, _count: { select: { artworks: true } } },
|
||||
orderBy: { id: 'desc' },
|
||||
skip: query.skip,
|
||||
take: query.take,
|
||||
}),
|
||||
this.prisma.template.count({ where }),
|
||||
]);
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
}
|
||||
|
||||
// 供建档表单选择的启用模板(含字段)
|
||||
async options() {
|
||||
return this.prisma.template.findMany({
|
||||
where: { deletedAt: null, status: TemplateStatus.ENABLED },
|
||||
include: { fields: { orderBy: { sortOrder: 'asc' } } },
|
||||
orderBy: { id: 'desc' },
|
||||
});
|
||||
}
|
||||
|
||||
async get(id: number) {
|
||||
const tpl = await this.prisma.template.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: { fields: { orderBy: { sortOrder: 'asc' } } },
|
||||
});
|
||||
if (!tpl) throw new BusinessException(ErrorCode.TEMPLATE_NOT_FOUND, '模板不存在', 404);
|
||||
return tpl;
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateTemplateDto) {
|
||||
await this.get(id);
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
if (dto.fields) {
|
||||
await tx.templateField.deleteMany({ where: { templateId: id } });
|
||||
await tx.templateField.createMany({
|
||||
data: this.fieldsCreate(dto.fields).map((f) => ({ ...f, templateId: id })),
|
||||
});
|
||||
}
|
||||
return tx.template.update({
|
||||
where: { id },
|
||||
data: { name: dto.name, remark: dto.remark, status: dto.status },
|
||||
include: { fields: { orderBy: { sortOrder: 'asc' } } },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
await this.get(id);
|
||||
const used = await this.prisma.artwork.count({ where: { templateId: id, deletedAt: null } });
|
||||
if (used > 0) {
|
||||
throw new BusinessException(ErrorCode.TEMPLATE_IN_USE, '模板已被作品使用,无法删除(可改为停用)');
|
||||
}
|
||||
await this.prisma.template.update({ where: { id }, data: { deletedAt: new Date() } });
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsArray,
|
||||
IsDateString,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { NodeType } from '@artveris/shared';
|
||||
import { MediaItemDto } from '../../artwork/dto/artwork.dto';
|
||||
|
||||
export class CreateNodeDto {
|
||||
@ApiProperty({ description: '节点类型', enum: NodeType })
|
||||
@IsEnum(NodeType)
|
||||
nodeType!: NodeType;
|
||||
|
||||
@ApiProperty({ description: '节点标题' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(80)
|
||||
title!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '发生时间' })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
occurredAt?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '地点' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
location?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '说明' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(2000)
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '图片/视频', type: [MediaItemDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => MediaItemDto)
|
||||
mediaFiles?: MediaItemDto[];
|
||||
|
||||
@ApiPropertyOptional({ description: '排序' })
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
export class UpdateNodeDto extends CreateNodeDto {}
|
||||
|
||||
export class ReorderNodeDto {
|
||||
@ApiProperty({ description: '按目标顺序排列的节点 ID 列表', type: [Number] })
|
||||
@IsArray()
|
||||
@IsInt({ each: true })
|
||||
ids!: number[];
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
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 { TraceNodeService } from './trace-node.service';
|
||||
import { CreateNodeDto, ReorderNodeDto, UpdateNodeDto } from './dto/trace-node.dto';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
|
||||
@ApiTags('溯源节点')
|
||||
@ApiBearerAuth()
|
||||
@Controller()
|
||||
export class TraceNodeController {
|
||||
constructor(private readonly nodeService: TraceNodeService) {}
|
||||
|
||||
@Get('artworks/:artworkId/nodes')
|
||||
@ApiOperation({ summary: '作品的溯源节点列表' })
|
||||
list(@Param('artworkId', ParseIntPipe) artworkId: number) {
|
||||
return this.nodeService.listByArtwork(artworkId);
|
||||
}
|
||||
|
||||
@Post('artworks/:artworkId/nodes')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '新增溯源节点' })
|
||||
create(@Param('artworkId', ParseIntPipe) artworkId: number, @Body() dto: CreateNodeDto) {
|
||||
return this.nodeService.create(artworkId, dto);
|
||||
}
|
||||
|
||||
@Put('artworks/:artworkId/nodes/reorder')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '调整节点顺序' })
|
||||
reorder(@Param('artworkId', ParseIntPipe) artworkId: number, @Body() dto: ReorderNodeDto) {
|
||||
return this.nodeService.reorder(artworkId, dto);
|
||||
}
|
||||
|
||||
@Put('nodes/:id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '更新溯源节点' })
|
||||
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateNodeDto) {
|
||||
return this.nodeService.update(id, dto);
|
||||
}
|
||||
|
||||
@Delete('nodes/:id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '删除溯源节点' })
|
||||
remove(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.nodeService.remove(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TraceNodeService } from './trace-node.service';
|
||||
import { TraceNodeController } from './trace-node.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [TraceNodeController],
|
||||
providers: [TraceNodeService],
|
||||
exports: [TraceNodeService],
|
||||
})
|
||||
export class TraceNodeModule {}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { ErrorCode } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { CreateNodeDto, ReorderNodeDto, UpdateNodeDto } from './dto/trace-node.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TraceNodeService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly storage: StorageService,
|
||||
) {}
|
||||
|
||||
private mapMedia(items: unknown) {
|
||||
if (!Array.isArray(items)) return [];
|
||||
return (items as Array<{ key: string }>)
|
||||
.filter((i) => i && i.key)
|
||||
.map((i) => ({ ...i, url: this.storage.getUrl(i.key) }));
|
||||
}
|
||||
|
||||
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 nodes = await this.prisma.traceNode.findMany({
|
||||
where: { artworkId },
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
});
|
||||
return nodes.map((n) => ({ ...n, mediaFiles: this.mapMedia(n.mediaFiles) }));
|
||||
}
|
||||
|
||||
async create(artworkId: number, dto: CreateNodeDto) {
|
||||
await this.ensureArtwork(artworkId);
|
||||
const count = await this.prisma.traceNode.count({ where: { artworkId } });
|
||||
const node = await this.prisma.traceNode.create({
|
||||
data: {
|
||||
artworkId,
|
||||
nodeType: dto.nodeType,
|
||||
title: dto.title,
|
||||
occurredAt: dto.occurredAt ? new Date(dto.occurredAt) : null,
|
||||
location: dto.location,
|
||||
description: dto.description,
|
||||
mediaFiles: (dto.mediaFiles ?? []) as unknown as Prisma.InputJsonValue,
|
||||
sortOrder: dto.sortOrder ?? count,
|
||||
},
|
||||
});
|
||||
return { ...node, mediaFiles: this.mapMedia(node.mediaFiles) };
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateNodeDto) {
|
||||
await this.ensureNode(id);
|
||||
const node = await this.prisma.traceNode.update({
|
||||
where: { id },
|
||||
data: {
|
||||
nodeType: dto.nodeType,
|
||||
title: dto.title,
|
||||
occurredAt: dto.occurredAt ? new Date(dto.occurredAt) : null,
|
||||
location: dto.location,
|
||||
description: dto.description,
|
||||
mediaFiles: (dto.mediaFiles ?? []) as unknown as Prisma.InputJsonValue,
|
||||
sortOrder: dto.sortOrder,
|
||||
},
|
||||
});
|
||||
return { ...node, mediaFiles: this.mapMedia(node.mediaFiles) };
|
||||
}
|
||||
|
||||
async remove(id: number) {
|
||||
await this.ensureNode(id);
|
||||
await this.prisma.traceNode.delete({ where: { id } });
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async reorder(artworkId: number, dto: ReorderNodeDto) {
|
||||
await this.ensureArtwork(artworkId);
|
||||
await this.prisma.$transaction(
|
||||
dto.ids.map((id, index) =>
|
||||
this.prisma.traceNode.updateMany({
|
||||
where: { id, artworkId },
|
||||
data: { sortOrder: index },
|
||||
}),
|
||||
),
|
||||
);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
private async ensureNode(id: number) {
|
||||
const n = await this.prisma.traceNode.findUnique({ where: { id } });
|
||||
if (!n) throw new BusinessException(ErrorCode.NOT_FOUND, '节点不存在', 404);
|
||||
return n;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user