feat: 追溯码新增分组管理与批量分组/启停接口
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `trace_code` ADD COLUMN `group_id` INTEGER NULL;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `trace_code_group` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`name` VARCHAR(191) NOT NULL,
|
||||
`remark` VARCHAR(191) NULL,
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX `trace_code_group_id_idx` ON `trace_code`(`group_id`);
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_group_id_fkey` FOREIGN KEY (`group_id`) REFERENCES `trace_code_group`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -202,6 +202,17 @@ model Certificate {
|
||||
@@map("certificate")
|
||||
}
|
||||
|
||||
model TraceCodeGroup {
|
||||
id Int @id @default(autoincrement())
|
||||
name String
|
||||
remark String?
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
traceCodes TraceCode[]
|
||||
|
||||
@@map("trace_code_group")
|
||||
}
|
||||
|
||||
model Batch {
|
||||
id Int @id @default(autoincrement())
|
||||
batchNo String @unique @map("batch_no")
|
||||
@@ -222,6 +233,7 @@ model TraceCode {
|
||||
shortCode String @unique @map("short_code")
|
||||
artworkId Int? @unique @map("artwork_id")
|
||||
batchId Int? @map("batch_id")
|
||||
groupId Int? @map("group_id")
|
||||
sku String?
|
||||
archiveNo String? @map("archive_no")
|
||||
outTime DateTime? @map("out_time")
|
||||
@@ -236,10 +248,12 @@ model TraceCode {
|
||||
|
||||
artwork Artwork? @relation(fields: [artworkId], references: [id])
|
||||
batch Batch? @relation(fields: [batchId], references: [id])
|
||||
group TraceCodeGroup? @relation(fields: [groupId], references: [id])
|
||||
proofs BlockchainProof[]
|
||||
queryLogs QueryLog[]
|
||||
|
||||
@@index([batchId])
|
||||
@@index([groupId])
|
||||
@@index([status])
|
||||
@@map("trace_code")
|
||||
}
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsEnum, IsInt, IsOptional, IsString, Max, MaxLength, Min } from 'class-validator';
|
||||
import {
|
||||
ArrayNotEmpty,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
MaxLength,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { TraceCodeStatus } from '@artveris/shared';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
|
||||
@@ -17,6 +28,12 @@ export class GenerateBatchDto {
|
||||
@IsString()
|
||||
@MaxLength(50)
|
||||
batchNo?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '分组 ID' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
groupId?: number;
|
||||
}
|
||||
|
||||
export class QueryTraceCodeDto extends PaginationDto {
|
||||
@@ -31,12 +48,57 @@ export class QueryTraceCodeDto extends PaginationDto {
|
||||
@IsEnum(TraceCodeStatus)
|
||||
status?: TraceCodeStatus;
|
||||
|
||||
@ApiPropertyOptional({ description: '分组 ID' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
groupId?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: '关键词(短码/追溯码/SKU/档案号)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
keyword?: string;
|
||||
}
|
||||
|
||||
export class GroupDto {
|
||||
@ApiProperty({ description: '分组名称' })
|
||||
@IsString()
|
||||
@MaxLength(50)
|
||||
name!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '备注' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
export class BatchGroupDto {
|
||||
@ApiProperty({ description: '追溯码 ID 列表', type: [String] })
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsString({ each: true })
|
||||
ids!: string[];
|
||||
|
||||
@ApiPropertyOptional({ description: '目标分组 ID(null 表示移出分组)' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
groupId?: number | null;
|
||||
}
|
||||
|
||||
export class BatchStatusDto {
|
||||
@ApiProperty({ description: '追溯码 ID 列表', type: [String] })
|
||||
@IsArray()
|
||||
@ArrayNotEmpty()
|
||||
@IsString({ each: true })
|
||||
ids!: string[];
|
||||
|
||||
@ApiProperty({ description: 'true 停用,false 启用' })
|
||||
@IsBoolean()
|
||||
disabled!: boolean;
|
||||
}
|
||||
|
||||
export class BindArtworkDto {
|
||||
@ApiProperty({ description: '艺术品 ID' })
|
||||
@Type(() => Number)
|
||||
|
||||
@@ -15,6 +15,7 @@ interface GenJobData {
|
||||
batchId: number;
|
||||
jobId: string;
|
||||
quantity: number;
|
||||
groupId?: number | null;
|
||||
}
|
||||
|
||||
@Processor(QUEUE_NAMES.GEN_CODE)
|
||||
@@ -30,7 +31,7 @@ export class GenCodeProcessor extends WorkerHost {
|
||||
}
|
||||
|
||||
async process(job: Job<GenJobData>): Promise<void> {
|
||||
const { batchId, jobId, quantity } = job.data;
|
||||
const { batchId, jobId, quantity, groupId } = job.data;
|
||||
await this.jobs.start(jobId);
|
||||
await this.prisma.batch.update({ where: { id: batchId }, data: { status: BatchStatus.GENERATING } });
|
||||
|
||||
@@ -45,6 +46,7 @@ export class GenCodeProcessor extends WorkerHost {
|
||||
code: codeId(),
|
||||
shortCode,
|
||||
batchId,
|
||||
groupId: groupId ?? null,
|
||||
url: this.traceCode.buildTraceUrl(shortCode),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
@@ -13,8 +15,11 @@ import { Response } from 'express';
|
||||
import { RoleType } from '@artveris/shared';
|
||||
import { TraceCodeService } from './trace-code.service';
|
||||
import {
|
||||
BatchGroupDto,
|
||||
BatchStatusDto,
|
||||
BindArtworkDto,
|
||||
GenerateBatchDto,
|
||||
GroupDto,
|
||||
QueryBatchDto,
|
||||
QueryTraceCodeDto,
|
||||
} from './dto/trace-code.dto';
|
||||
@@ -41,6 +46,47 @@ export class TraceCodeController {
|
||||
return this.service.listBatches(query);
|
||||
}
|
||||
|
||||
@Get('trace-code-groups')
|
||||
@ApiOperation({ summary: '分组列表' })
|
||||
groups() {
|
||||
return this.service.listGroups();
|
||||
}
|
||||
|
||||
@Post('trace-code-groups')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '创建分组' })
|
||||
createGroup(@Body() dto: GroupDto) {
|
||||
return this.service.createGroup(dto);
|
||||
}
|
||||
|
||||
@Put('trace-code-groups/:id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '更新分组' })
|
||||
updateGroup(@Param('id', ParseIntPipe) id: number, @Body() dto: GroupDto) {
|
||||
return this.service.updateGroup(id, dto);
|
||||
}
|
||||
|
||||
@Delete('trace-code-groups/:id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '删除分组' })
|
||||
removeGroup(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.service.removeGroup(id);
|
||||
}
|
||||
|
||||
@Put('trace-codes/batch/group')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '批量设置分组' })
|
||||
batchGroup(@Body() dto: BatchGroupDto) {
|
||||
return this.service.batchSetGroup(dto);
|
||||
}
|
||||
|
||||
@Put('trace-codes/batch/status')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '批量启用/停用' })
|
||||
batchStatus(@Body() dto: BatchStatusDto) {
|
||||
return this.service.batchSetStatus(dto);
|
||||
}
|
||||
|
||||
@Get('trace-codes')
|
||||
@ApiOperation({ summary: '追溯码列表' })
|
||||
list(@Query() query: QueryTraceCodeDto) {
|
||||
|
||||
@@ -12,7 +12,14 @@ import { PrismaService } from '../prisma/prisma.service';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
import { JobsService } from '../jobs/jobs.service';
|
||||
import { GenerateBatchDto, QueryBatchDto, QueryTraceCodeDto } from './dto/trace-code.dto';
|
||||
import {
|
||||
BatchGroupDto,
|
||||
BatchStatusDto,
|
||||
GenerateBatchDto,
|
||||
GroupDto,
|
||||
QueryBatchDto,
|
||||
QueryTraceCodeDto,
|
||||
} from './dto/trace-code.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TraceCodeService {
|
||||
@@ -40,15 +47,84 @@ export class TraceCodeService {
|
||||
});
|
||||
const job = await this.jobs.create(JobType.GEN_CODE, dto.quantity, userId, {
|
||||
batchId: batch.id,
|
||||
groupId: dto.groupId ?? null,
|
||||
});
|
||||
await this.genQueue.add('generate', {
|
||||
batchId: batch.id,
|
||||
jobId: job.id,
|
||||
quantity: dto.quantity,
|
||||
groupId: dto.groupId ?? null,
|
||||
});
|
||||
return { batchId: batch.id, batchNo, jobId: job.id, quantity: dto.quantity };
|
||||
}
|
||||
|
||||
// ===== 分组管理 =====
|
||||
listGroups() {
|
||||
return this.prisma.traceCodeGroup.findMany({
|
||||
orderBy: { id: 'desc' },
|
||||
include: { _count: { select: { traceCodes: true } } },
|
||||
});
|
||||
}
|
||||
|
||||
createGroup(dto: GroupDto) {
|
||||
return this.prisma.traceCodeGroup.create({ data: { name: dto.name, remark: dto.remark } });
|
||||
}
|
||||
|
||||
async updateGroup(id: number, dto: GroupDto) {
|
||||
await this.ensureGroup(id);
|
||||
return this.prisma.traceCodeGroup.update({ where: { id }, data: { name: dto.name, remark: dto.remark } });
|
||||
}
|
||||
|
||||
async removeGroup(id: number) {
|
||||
await this.ensureGroup(id);
|
||||
await this.prisma.traceCode.updateMany({ where: { groupId: id }, data: { groupId: null } });
|
||||
await this.prisma.traceCodeGroup.delete({ where: { id } });
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
private async ensureGroup(id: number) {
|
||||
const g = await this.prisma.traceCodeGroup.findUnique({ where: { id } });
|
||||
if (!g) throw new BusinessException(ErrorCode.NOT_FOUND, '分组不存在', 404);
|
||||
return g;
|
||||
}
|
||||
|
||||
// ===== 批量操作 =====
|
||||
async batchSetGroup(dto: BatchGroupDto) {
|
||||
const ids = dto.ids.map((i) => BigInt(i));
|
||||
await this.prisma.traceCode.updateMany({
|
||||
where: { id: { in: ids } },
|
||||
data: { groupId: dto.groupId ?? null },
|
||||
});
|
||||
return { success: true, count: ids.length };
|
||||
}
|
||||
|
||||
async batchSetStatus(dto: BatchStatusDto) {
|
||||
const ids = dto.ids.map((i) => BigInt(i));
|
||||
if (dto.disabled) {
|
||||
await this.prisma.traceCode.updateMany({
|
||||
where: { id: { in: ids } },
|
||||
data: { status: TraceCodeStatus.DISABLED },
|
||||
});
|
||||
} else {
|
||||
// 启用:按是否已激活/已绑定恢复对应状态
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.traceCode.updateMany({
|
||||
where: { id: { in: ids }, firstActivatedAt: { not: null } },
|
||||
data: { status: TraceCodeStatus.ACTIVE },
|
||||
}),
|
||||
this.prisma.traceCode.updateMany({
|
||||
where: { id: { in: ids }, firstActivatedAt: null, artworkId: { not: null } },
|
||||
data: { status: TraceCodeStatus.INACTIVE },
|
||||
}),
|
||||
this.prisma.traceCode.updateMany({
|
||||
where: { id: { in: ids }, firstActivatedAt: null, artworkId: null },
|
||||
data: { status: TraceCodeStatus.UNBOUND },
|
||||
}),
|
||||
]);
|
||||
}
|
||||
return { success: true, count: ids.length };
|
||||
}
|
||||
|
||||
async listBatches(query: QueryBatchDto) {
|
||||
const where: Prisma.BatchWhereInput = {};
|
||||
if (query.keyword) where.batchNo = { contains: query.keyword };
|
||||
@@ -67,6 +143,7 @@ export class TraceCodeService {
|
||||
async list(query: QueryTraceCodeDto) {
|
||||
const where: Prisma.TraceCodeWhereInput = {};
|
||||
if (query.batchId) where.batchId = query.batchId;
|
||||
if (query.groupId) where.groupId = query.groupId;
|
||||
if (query.status) where.status = query.status;
|
||||
if (query.keyword) {
|
||||
where.OR = [
|
||||
@@ -79,7 +156,10 @@ export class TraceCodeService {
|
||||
const [list, total] = await this.prisma.$transaction([
|
||||
this.prisma.traceCode.findMany({
|
||||
where,
|
||||
include: { artwork: { select: { id: true, title: true } } },
|
||||
include: {
|
||||
artwork: { select: { id: true, title: true } },
|
||||
group: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
skip: query.skip,
|
||||
take: query.take,
|
||||
|
||||
Reference in New Issue
Block a user