refactor: 按甲方确认重构为一款多码(档案编号标识款、批次码、按款统计)
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,18 +0,0 @@
|
||||
-- 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;
|
||||
@@ -1,24 +0,0 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE `artwork` ADD COLUMN `audit_remark` VARCHAR(191) NULL,
|
||||
ADD COLUMN `audit_status` ENUM('PENDING', 'APPROVED', 'REJECTED') NOT NULL DEFAULT 'PENDING',
|
||||
ADD COLUMN `audited_at` DATETIME(3) NULL,
|
||||
ADD COLUMN `audited_by` INTEGER NULL;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE `query_log` ADD COLUMN `archive_no` VARCHAR(191) NULL,
|
||||
ADD COLUMN `batch_no` VARCHAR(191) NULL,
|
||||
ADD COLUMN `browser` VARCHAR(191) NULL,
|
||||
ADD COLUMN `code` VARCHAR(191) NULL,
|
||||
ADD COLUMN `first_activated_at` DATETIME(3) NULL,
|
||||
ADD COLUMN `os` VARCHAR(191) NULL,
|
||||
ADD COLUMN `query_count` INTEGER NULL,
|
||||
ADD COLUMN `sku` VARCHAR(191) NULL;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX `artwork_audit_status_idx` ON `artwork`(`audit_status`);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX `query_log_sku_idx` ON `query_log`(`sku`);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX `query_log_batch_no_idx` ON `query_log`(`batch_no`);
|
||||
+42
-8
@@ -47,16 +47,23 @@ CREATE TABLE `artwork` (
|
||||
`template_id` INTEGER NOT NULL,
|
||||
`title` VARCHAR(191) NOT NULL,
|
||||
`artist` VARCHAR(191) NULL,
|
||||
`archive_no` VARCHAR(191) NULL,
|
||||
`dynamic_fields` JSON NULL,
|
||||
`images` JSON NULL,
|
||||
`status` ENUM('DRAFT', 'ACTIVE', 'DISABLED') NOT NULL DEFAULT 'DRAFT',
|
||||
`audit_status` ENUM('PENDING', 'APPROVED', 'REJECTED') NOT NULL DEFAULT 'PENDING',
|
||||
`audit_remark` VARCHAR(191) NULL,
|
||||
`audited_by` INTEGER NULL,
|
||||
`audited_at` DATETIME(3) NULL,
|
||||
`created_by` INTEGER NULL,
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updated_at` DATETIME(3) NOT NULL,
|
||||
`deleted_at` DATETIME(3) NULL,
|
||||
|
||||
UNIQUE INDEX `artwork_archive_no_key`(`archive_no`),
|
||||
INDEX `artwork_template_id_idx`(`template_id`),
|
||||
INDEX `artwork_status_idx`(`status`),
|
||||
INDEX `artwork_audit_status_idx`(`audit_status`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
@@ -92,10 +99,21 @@ CREATE TABLE `certificate` (
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- 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;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE `batch` (
|
||||
`id` INTEGER NOT NULL AUTO_INCREMENT,
|
||||
`batch_no` VARCHAR(191) NOT NULL,
|
||||
`artwork_id` INTEGER NOT NULL,
|
||||
`quantity` INTEGER NOT NULL,
|
||||
`generated_count` INTEGER NOT NULL DEFAULT 0,
|
||||
`status` ENUM('PENDING', 'GENERATING', 'DONE', 'FAILED') NOT NULL DEFAULT 'PENDING',
|
||||
@@ -103,6 +121,7 @@ CREATE TABLE `batch` (
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
|
||||
UNIQUE INDEX `batch_batch_no_key`(`batch_no`),
|
||||
INDEX `batch_artwork_id_idx`(`artwork_id`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
@@ -111,14 +130,13 @@ CREATE TABLE `trace_code` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||
`code` VARCHAR(191) NOT NULL,
|
||||
`short_code` VARCHAR(191) NOT NULL,
|
||||
`artwork_id` INTEGER NULL,
|
||||
`batch_id` INTEGER NULL,
|
||||
`sku` VARCHAR(191) NULL,
|
||||
`archive_no` VARCHAR(191) NULL,
|
||||
`artwork_id` INTEGER NOT NULL,
|
||||
`batch_id` INTEGER NOT NULL,
|
||||
`group_id` INTEGER NULL,
|
||||
`out_time` DATETIME(3) NULL,
|
||||
`out_image` VARCHAR(191) NULL,
|
||||
`remark` VARCHAR(191) NULL,
|
||||
`status` ENUM('UNBOUND', 'INACTIVE', 'ACTIVE', 'DISABLED', 'ABNORMAL') NOT NULL DEFAULT 'UNBOUND',
|
||||
`status` ENUM('INACTIVE', 'ACTIVE', 'DISABLED', 'ABNORMAL') NOT NULL DEFAULT 'INACTIVE',
|
||||
`query_count` INTEGER NOT NULL DEFAULT 0,
|
||||
`first_activated_at` DATETIME(3) NULL,
|
||||
`last_queried_at` DATETIME(3) NULL,
|
||||
@@ -127,8 +145,9 @@ CREATE TABLE `trace_code` (
|
||||
|
||||
UNIQUE INDEX `trace_code_code_key`(`code`),
|
||||
UNIQUE INDEX `trace_code_short_code_key`(`short_code`),
|
||||
UNIQUE INDEX `trace_code_artwork_id_key`(`artwork_id`),
|
||||
INDEX `trace_code_artwork_id_idx`(`artwork_id`),
|
||||
INDEX `trace_code_batch_id_idx`(`batch_id`),
|
||||
INDEX `trace_code_group_id_idx`(`group_id`),
|
||||
INDEX `trace_code_status_idx`(`status`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
@@ -158,15 +177,24 @@ CREATE TABLE `query_log` (
|
||||
`trace_code_id` BIGINT NULL,
|
||||
`artwork_id` INTEGER NULL,
|
||||
`short_code` VARCHAR(191) NULL,
|
||||
`code` VARCHAR(191) NULL,
|
||||
`archive_no` VARCHAR(191) NULL,
|
||||
`batch_no` VARCHAR(191) NULL,
|
||||
`query_count` INTEGER NULL,
|
||||
`first_activated_at` DATETIME(3) NULL,
|
||||
`queried_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`query_result` ENUM('FIRST_ACTIVATE', 'REPEAT', 'INVALID', 'DISABLED', 'ABNORMAL') NOT NULL,
|
||||
`ip` VARCHAR(191) NULL,
|
||||
`region` VARCHAR(191) NULL,
|
||||
`user_agent` TEXT NULL,
|
||||
`device_type` VARCHAR(191) NULL,
|
||||
`browser` VARCHAR(191) NULL,
|
||||
`os` VARCHAR(191) NULL,
|
||||
|
||||
INDEX `query_log_trace_code_id_idx`(`trace_code_id`),
|
||||
INDEX `query_log_queried_at_idx`(`queried_at`),
|
||||
INDEX `query_log_archive_no_idx`(`archive_no`),
|
||||
INDEX `query_log_batch_no_idx`(`batch_no`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
@@ -215,10 +243,16 @@ ALTER TABLE `trace_node` ADD CONSTRAINT `trace_node_artwork_id_fkey` FOREIGN KEY
|
||||
ALTER TABLE `certificate` ADD CONSTRAINT `certificate_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
ALTER TABLE `batch` ADD CONSTRAINT `batch_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_batch_id_fkey` FOREIGN KEY (`batch_id`) REFERENCES `batch`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_batch_id_fkey` FOREIGN KEY (`batch_id`) REFERENCES `batch`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- 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;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE `blockchain_proof` ADD CONSTRAINT `blockchain_proof_trace_code_id_fkey` FOREIGN KEY (`trace_code_id`) REFERENCES `trace_code`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -68,7 +68,6 @@ enum BatchStatus {
|
||||
}
|
||||
|
||||
enum TraceCodeStatus {
|
||||
UNBOUND
|
||||
INACTIVE
|
||||
ACTIVE
|
||||
DISABLED
|
||||
@@ -155,6 +154,7 @@ model Artwork {
|
||||
templateId Int @map("template_id")
|
||||
title String
|
||||
artist String?
|
||||
archiveNo String? @unique @map("archive_no")
|
||||
dynamicFields Json? @map("dynamic_fields")
|
||||
images Json?
|
||||
status ArtworkStatus @default(DRAFT)
|
||||
@@ -171,7 +171,8 @@ model Artwork {
|
||||
creator SysUser? @relation(fields: [createdBy], references: [id])
|
||||
traceNodes TraceNode[]
|
||||
certificates Certificate[]
|
||||
traceCode TraceCode?
|
||||
batches Batch[]
|
||||
traceCodes TraceCode[]
|
||||
|
||||
@@index([templateId])
|
||||
@@index([status])
|
||||
@@ -227,14 +228,17 @@ model TraceCodeGroup {
|
||||
model Batch {
|
||||
id Int @id @default(autoincrement())
|
||||
batchNo String @unique @map("batch_no")
|
||||
artworkId Int @map("artwork_id")
|
||||
quantity Int
|
||||
generatedCount Int @default(0) @map("generated_count")
|
||||
status BatchStatus @default(PENDING)
|
||||
createdBy Int? @map("created_by")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
artwork Artwork @relation(fields: [artworkId], references: [id])
|
||||
traceCodes TraceCode[]
|
||||
|
||||
@@index([artworkId])
|
||||
@@map("batch")
|
||||
}
|
||||
|
||||
@@ -242,27 +246,26 @@ model TraceCode {
|
||||
id BigInt @id @default(autoincrement())
|
||||
code String @unique
|
||||
shortCode String @unique @map("short_code")
|
||||
artworkId Int? @unique @map("artwork_id")
|
||||
batchId Int? @map("batch_id")
|
||||
artworkId Int @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")
|
||||
outImage String? @map("out_image")
|
||||
remark String?
|
||||
status TraceCodeStatus @default(UNBOUND)
|
||||
status TraceCodeStatus @default(INACTIVE)
|
||||
queryCount Int @default(0) @map("query_count")
|
||||
firstActivatedAt DateTime? @map("first_activated_at")
|
||||
lastQueriedAt DateTime? @map("last_queried_at")
|
||||
url String?
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
artwork Artwork? @relation(fields: [artworkId], references: [id])
|
||||
batch Batch? @relation(fields: [batchId], references: [id])
|
||||
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([artworkId])
|
||||
@@index([batchId])
|
||||
@@index([groupId])
|
||||
@@index([status])
|
||||
@@ -295,7 +298,6 @@ model QueryLog {
|
||||
artworkId Int? @map("artwork_id")
|
||||
shortCode String? @map("short_code")
|
||||
code String?
|
||||
sku String?
|
||||
archiveNo String? @map("archive_no")
|
||||
batchNo String? @map("batch_no")
|
||||
queryCount Int? @map("query_count")
|
||||
@@ -313,7 +315,7 @@ model QueryLog {
|
||||
|
||||
@@index([traceCodeId])
|
||||
@@index([queriedAt])
|
||||
@@index([sku])
|
||||
@@index([archiveNo])
|
||||
@@index([batchNo])
|
||||
@@map("query_log")
|
||||
}
|
||||
|
||||
+72
-45
@@ -98,7 +98,10 @@ async function ensureSampleData(): Promise<void> {
|
||||
{ title: '影青刻花碗', artist: '陈一川', bg: '#2f6b5e', craft: '刻花 / 影青釉', material: '瓷石', size: '口径 18cm', year: '2024' },
|
||||
];
|
||||
|
||||
let codeSeq = 0;
|
||||
const base = (process.env.BASE_URL || 'http://localhost:3000').replace(/\/$/, '');
|
||||
const CODES_PER_ARTWORK = 3; // 每款示例生码数(演示一款多码)
|
||||
let artworkSeq = 0;
|
||||
let totalCodes = 0;
|
||||
for (const s of samples) {
|
||||
const imgKey = writeStorage(`seed/${shortId()}.jpg`, await placeholder(s.title, s.bg));
|
||||
const img2 = writeStorage(`seed/${shortId()}.jpg`, await placeholder('细节图', s.bg));
|
||||
@@ -127,6 +130,11 @@ async function ensureSampleData(): Promise<void> {
|
||||
},
|
||||
},
|
||||
});
|
||||
// 档案编号(款级,按 id 生成)
|
||||
await prisma.artwork.update({
|
||||
where: { id: artwork.id },
|
||||
data: { archiveNo: `ARTVERIS-${String(artwork.id).padStart(6, '0')}` },
|
||||
});
|
||||
|
||||
// 证书 + 水印
|
||||
const certOriginKey = writeStorage(`seed/${shortId()}.jpg`, await placeholder(`${s.title} 鉴定证书`, '#444c5a'));
|
||||
@@ -143,62 +151,81 @@ async function ensureSampleData(): Promise<void> {
|
||||
},
|
||||
});
|
||||
|
||||
// 追溯码(一物一码)
|
||||
const shortCode = shortId();
|
||||
const isActive = codeSeq < 2; // 前两件设为已激活并带查询记录
|
||||
const code = await prisma.traceCode.create({
|
||||
// 一款多码:建一个批次 + 多套独立编码
|
||||
const batch = await prisma.batch.create({
|
||||
data: {
|
||||
code: codeId(),
|
||||
shortCode,
|
||||
batchNo: `B-SEED-${String(artwork.id).padStart(4, '0')}`,
|
||||
artworkId: artwork.id,
|
||||
url: `${(process.env.BASE_URL || 'http://localhost:3000').replace(/\/$/, '')}/t/${shortCode}`,
|
||||
status: isActive ? 'ACTIVE' : 'INACTIVE',
|
||||
queryCount: isActive ? 3 + codeSeq * 2 : 0,
|
||||
firstActivatedAt: isActive ? new Date(Date.now() - 86400000) : null,
|
||||
lastQueriedAt: isActive ? new Date() : null,
|
||||
sku: `SKU-${1000 + codeSeq}`,
|
||||
archiveNo: `AW-${1000 + codeSeq}`,
|
||||
quantity: CODES_PER_ARTWORK,
|
||||
generatedCount: CODES_PER_ARTWORK,
|
||||
status: 'DONE',
|
||||
createdBy: admin?.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (isActive) {
|
||||
// 查询日志
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await prisma.queryLog.create({
|
||||
const artworkActive = artworkSeq < 2; // 前两款带激活码与查询记录
|
||||
for (let k = 0; k < CODES_PER_ARTWORK; k++) {
|
||||
const shortCode = shortId();
|
||||
const isActive = artworkActive && k < 2; // 该款前两套已激活
|
||||
const code = await prisma.traceCode.create({
|
||||
data: {
|
||||
code: codeId(),
|
||||
shortCode,
|
||||
artworkId: artwork.id,
|
||||
batchId: batch.id,
|
||||
url: `${base}/t/${shortCode}`,
|
||||
status: isActive ? 'ACTIVE' : 'INACTIVE',
|
||||
queryCount: isActive ? 3 + k : 0,
|
||||
firstActivatedAt: isActive ? new Date(Date.now() - 86400000) : null,
|
||||
lastQueriedAt: isActive ? new Date() : null,
|
||||
},
|
||||
});
|
||||
totalCodes++;
|
||||
|
||||
if (isActive) {
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await prisma.queryLog.create({
|
||||
data: {
|
||||
traceCodeId: code.id,
|
||||
artworkId: artwork.id,
|
||||
shortCode,
|
||||
code: code.code,
|
||||
archiveNo: `ARTVERIS-${String(artwork.id).padStart(6, '0')}`,
|
||||
batchNo: batch.batchNo,
|
||||
queryCount: 3 + k,
|
||||
firstActivatedAt: new Date(Date.now() - 86400000),
|
||||
queryResult: i === 0 ? 'FIRST_ACTIVATE' : 'REPEAT',
|
||||
ip: `120.0.0.${10 + i}`,
|
||||
region: '未知地区',
|
||||
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X)',
|
||||
deviceType: 'Mobile',
|
||||
browser: 'Safari',
|
||||
os: 'iOS',
|
||||
queriedAt: new Date(Date.now() - (3 - i) * 3600000),
|
||||
},
|
||||
});
|
||||
}
|
||||
const dataHash = '0x' + createHash('sha256').update(JSON.stringify({ c: code.code })).digest('hex');
|
||||
const txHash = '0x' + randomBytes(32).toString('hex');
|
||||
await prisma.blockchainProof.create({
|
||||
data: {
|
||||
traceCodeId: code.id,
|
||||
artworkId: artwork.id,
|
||||
shortCode,
|
||||
queryResult: i === 0 ? 'FIRST_ACTIVATE' : 'REPEAT',
|
||||
ip: `120.0.0.${10 + i}`,
|
||||
region: '未知地区',
|
||||
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X)',
|
||||
deviceType: 'Mobile',
|
||||
queriedAt: new Date(Date.now() - (3 - i) * 3600000),
|
||||
dataHash,
|
||||
txHash,
|
||||
blockHash: '0x' + createHash('sha256').update(txHash).digest('hex'),
|
||||
blockHeight: BigInt(8_500_000 + totalCodes),
|
||||
chainName: 'MockChain',
|
||||
explorerUrl: `https://mock-explorer.local/tx/${txHash}`,
|
||||
onchainAt: new Date(Date.now() - 86400000),
|
||||
status: 'ONCHAIN',
|
||||
rawResponse: { provider: 'mock-chain', code: 0, message: 'success' },
|
||||
},
|
||||
});
|
||||
}
|
||||
// 区块链存证
|
||||
const dataHash = '0x' + createHash('sha256').update(JSON.stringify({ t: s.title })).digest('hex');
|
||||
const txHash = '0x' + randomBytes(32).toString('hex');
|
||||
await prisma.blockchainProof.create({
|
||||
data: {
|
||||
traceCodeId: code.id,
|
||||
dataHash,
|
||||
txHash,
|
||||
blockHash: '0x' + createHash('sha256').update(txHash).digest('hex'),
|
||||
blockHeight: BigInt(8_500_000 + codeSeq),
|
||||
chainName: 'MockChain',
|
||||
explorerUrl: `https://mock-explorer.local/tx/${txHash}`,
|
||||
onchainAt: new Date(Date.now() - 86400000),
|
||||
status: 'ONCHAIN',
|
||||
rawResponse: { provider: 'mock-chain', code: 0, message: 'success' },
|
||||
},
|
||||
});
|
||||
}
|
||||
codeSeq++;
|
||||
artworkSeq++;
|
||||
}
|
||||
console.log(`已创建示例:模板 1、作品 ${samples.length}、证书与追溯码、查询日志与存证。`);
|
||||
console.log(`已创建示例:模板 1、作品 ${samples.length}(每款 ${CODES_PER_ARTWORK} 码,共 ${totalCodes} 码)、证书、查询日志与存证。`);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
|
||||
@@ -27,6 +27,11 @@ export class ArtworkService {
|
||||
.map((i) => ({ ...i, url: this.storage.getUrl(i.key) }));
|
||||
}
|
||||
|
||||
// 档案编号:款级唯一标识,按作品 id 生成,如 ARTVERIS-000001
|
||||
private buildArchiveNo(id: number): string {
|
||||
return `ARTVERIS-${String(id).padStart(6, '0')}`;
|
||||
}
|
||||
|
||||
async create(dto: CreateArtworkDto, userId: number) {
|
||||
const tpl = await this.prisma.template.findFirst({
|
||||
where: { id: dto.templateId, deletedAt: null },
|
||||
@@ -42,6 +47,11 @@ export class ArtworkService {
|
||||
createdBy: userId,
|
||||
},
|
||||
});
|
||||
// 创建后回填档案编号(需要自增 id)
|
||||
await this.prisma.artwork.update({
|
||||
where: { id: artwork.id },
|
||||
data: { archiveNo: this.buildArchiveNo(artwork.id) },
|
||||
});
|
||||
return this.get(artwork.id);
|
||||
}
|
||||
|
||||
@@ -51,6 +61,7 @@ export class ArtworkService {
|
||||
where.OR = [
|
||||
{ title: { contains: query.keyword } },
|
||||
{ artist: { contains: query.keyword } },
|
||||
{ archiveNo: { contains: query.keyword } },
|
||||
];
|
||||
}
|
||||
if (query.status) where.status = query.status;
|
||||
@@ -62,7 +73,7 @@ export class ArtworkService {
|
||||
where,
|
||||
include: {
|
||||
template: { select: { id: true, name: true } },
|
||||
traceCode: { select: { id: true, code: true, shortCode: true, status: true } },
|
||||
_count: { select: { traceCodes: true } },
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
skip: query.skip,
|
||||
@@ -70,9 +81,21 @@ export class ArtworkService {
|
||||
}),
|
||||
this.prisma.artwork.count({ where }),
|
||||
]);
|
||||
// 每款查询总次数 = 该款所有码 queryCount 之和(PRD 6.5:按款统计)
|
||||
const ids = rows.map((r) => r.id);
|
||||
const sums = ids.length
|
||||
? await this.prisma.traceCode.groupBy({
|
||||
by: ['artworkId'],
|
||||
where: { artworkId: { in: ids } },
|
||||
_sum: { queryCount: true },
|
||||
})
|
||||
: [];
|
||||
const sumMap = new Map(sums.map((s) => [s.artworkId, s._sum.queryCount ?? 0]));
|
||||
const list = rows.map((a) => ({
|
||||
...a,
|
||||
images: this.mapMedia(a.images),
|
||||
codeCount: a._count.traceCodes,
|
||||
queryTotal: sumMap.get(a.id) ?? 0,
|
||||
}));
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
}
|
||||
@@ -84,10 +107,16 @@ export class ArtworkService {
|
||||
template: { include: { fields: { orderBy: { sortOrder: 'asc' } } } },
|
||||
traceNodes: { orderBy: { sortOrder: 'asc' } },
|
||||
certificates: { orderBy: { id: 'asc' } },
|
||||
traceCode: { include: { proofs: { orderBy: { id: 'desc' } } } },
|
||||
batches: { orderBy: { id: 'desc' } },
|
||||
},
|
||||
});
|
||||
if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
|
||||
// 码统计:总数、已激活数、查询总次数(按款聚合)
|
||||
const [total, active, agg] = await this.prisma.$transaction([
|
||||
this.prisma.traceCode.count({ where: { artworkId: id } }),
|
||||
this.prisma.traceCode.count({ where: { artworkId: id, status: 'ACTIVE' } }),
|
||||
this.prisma.traceCode.aggregate({ where: { artworkId: id }, _sum: { queryCount: true } }),
|
||||
]);
|
||||
return {
|
||||
...a,
|
||||
images: this.mapMedia(a.images),
|
||||
@@ -97,6 +126,7 @@ export class ArtworkService {
|
||||
originUrl: c.originFileUrl ? this.storage.getUrl(c.originFileUrl) : null,
|
||||
watermarkUrl: c.watermarkFileUrl ? this.storage.getUrl(c.watermarkFileUrl) : null,
|
||||
})),
|
||||
codeStats: { total, active, queryTotal: agg._sum.queryCount ?? 0 },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -31,9 +31,8 @@ export class AttestationService {
|
||||
code: code.code,
|
||||
title: code.artwork.title,
|
||||
artist: code.artwork.artist,
|
||||
archiveNo: code.artwork.archiveNo,
|
||||
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),
|
||||
};
|
||||
|
||||
@@ -12,14 +12,14 @@ export class DashboardService {
|
||||
|
||||
const [
|
||||
totalArtworks,
|
||||
boundCodes,
|
||||
totalCodes,
|
||||
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(),
|
||||
this.prisma.traceCode.count({ where: { status: TraceCodeStatus.ACTIVE } }),
|
||||
this.prisma.queryLog.count(),
|
||||
this.prisma.queryLog.count({ where: { queriedAt: { gte: todayStart } } }),
|
||||
@@ -30,7 +30,7 @@ export class DashboardService {
|
||||
|
||||
return {
|
||||
totalArtworks,
|
||||
boundCodes,
|
||||
totalCodes,
|
||||
activatedCodes,
|
||||
totalQueries,
|
||||
todayQueries,
|
||||
@@ -58,19 +58,26 @@ export class DashboardService {
|
||||
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' },
|
||||
const grouped = await this.prisma.traceCode.groupBy({
|
||||
by: ['artworkId'],
|
||||
_sum: { queryCount: true },
|
||||
orderBy: { _sum: { 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,
|
||||
const ids = grouped.map((g) => g.artworkId);
|
||||
if (!ids.length) return [];
|
||||
const artworks = await this.prisma.artwork.findMany({
|
||||
where: { id: { in: ids } },
|
||||
select: { id: true, title: true, archiveNo: true },
|
||||
});
|
||||
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,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,18 +3,6 @@ import { Type } from 'class-transformer';
|
||||
import { IsDateString, IsInt, IsOptional, IsString, MaxLength, Min } 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()
|
||||
|
||||
@@ -136,8 +136,6 @@ export class ImportProcessor extends WorkerHost {
|
||||
await this.prisma.traceCode.update({
|
||||
where: { id: code.id },
|
||||
data: {
|
||||
sku: row.values.sku || undefined,
|
||||
archiveNo: row.values.archiveNo || undefined,
|
||||
outTime: outTime ?? undefined,
|
||||
outImage: row.values.outImage || undefined,
|
||||
remark: row.values.remark || undefined,
|
||||
|
||||
@@ -38,8 +38,6 @@ export class OutboundService {
|
||||
const updated = await 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,
|
||||
|
||||
@@ -8,7 +8,7 @@ import { GeoService } from '../geo/geo.service';
|
||||
import { REDIS_CLIENT } from '../redis/redis.module';
|
||||
import { parseUserAgent } from '../common/utils/ua.util';
|
||||
|
||||
type TraceCodeWithBatch = Prisma.TraceCodeGetPayload<{ include: { batch: true } }>;
|
||||
type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>;
|
||||
|
||||
export interface TraceContext {
|
||||
ip: string;
|
||||
@@ -55,9 +55,12 @@ export class PublicTraceService {
|
||||
return { status: 'INVALID' as const };
|
||||
}
|
||||
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { id }, include: { batch: true } });
|
||||
if (!code || !code.artworkId || code.status === TraceCodeStatus.UNBOUND) {
|
||||
await this.writeLog(id, null, shortCode, QueryResult.INVALID, ctx, code ?? undefined);
|
||||
const code = await this.prisma.traceCode.findUnique({
|
||||
where: { id },
|
||||
include: { batch: true, artwork: true },
|
||||
});
|
||||
if (!code) {
|
||||
await this.writeLog(id, null, shortCode, QueryResult.INVALID, ctx);
|
||||
return { status: 'INVALID' as const };
|
||||
}
|
||||
if (code.status === TraceCodeStatus.DISABLED) {
|
||||
@@ -129,6 +132,7 @@ export class PublicTraceService {
|
||||
artwork: {
|
||||
title: artwork.title,
|
||||
artist: artwork.artist,
|
||||
archiveNo: artwork.archiveNo,
|
||||
images: this.mapMedia(artwork.images),
|
||||
fields: this.buildFields(artwork.template.fields, artwork.dynamicFields),
|
||||
},
|
||||
@@ -189,7 +193,7 @@ export class PublicTraceService {
|
||||
shortCode: string,
|
||||
result: QueryResult,
|
||||
ctx: TraceContext,
|
||||
code?: Partial<TraceCodeWithBatch>,
|
||||
code?: Partial<TraceCodeWithRel>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const device = parseUserAgent(ctx.userAgent);
|
||||
@@ -199,8 +203,7 @@ export class PublicTraceService {
|
||||
artworkId: artworkId ?? undefined,
|
||||
shortCode,
|
||||
code: code?.code ?? undefined,
|
||||
sku: code?.sku ?? undefined,
|
||||
archiveNo: code?.archiveNo ?? undefined,
|
||||
archiveNo: code?.artwork?.archiveNo ?? undefined,
|
||||
batchNo: code?.batch?.batchNo ?? undefined,
|
||||
queryCount: code?.queryCount ?? undefined,
|
||||
firstActivatedAt: code?.firstActivatedAt ?? undefined,
|
||||
|
||||
@@ -13,10 +13,10 @@ class QueryLogQueryDto extends PaginationDto {
|
||||
@IsString()
|
||||
keyword?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'SKU' })
|
||||
@ApiPropertyOptional({ description: '档案编号' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
sku?: string;
|
||||
archiveNo?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '批次编号' })
|
||||
@IsOptional()
|
||||
@@ -53,11 +53,10 @@ export class QueryLogController {
|
||||
where.OR = [
|
||||
{ shortCode: { contains: query.keyword } },
|
||||
{ code: { contains: query.keyword } },
|
||||
{ sku: { contains: query.keyword } },
|
||||
{ archiveNo: { contains: query.keyword } },
|
||||
];
|
||||
}
|
||||
if (query.sku) where.sku = { contains: query.sku };
|
||||
if (query.archiveNo) where.archiveNo = { contains: query.archiveNo };
|
||||
if (query.batchNo) where.batchNo = { contains: query.batchNo };
|
||||
if (query.result) where.queryResult = query.result;
|
||||
if (query.startTime || query.endTime) {
|
||||
|
||||
@@ -17,6 +17,11 @@ import { TraceCodeStatus } from '@artveris/shared';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
|
||||
export class GenerateBatchDto {
|
||||
@ApiProperty({ description: '所属作品(款)ID' })
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
artworkId!: number;
|
||||
|
||||
@ApiProperty({ description: '生成数量', minimum: 1, maximum: 10000 })
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@@ -38,6 +43,12 @@ export class GenerateBatchDto {
|
||||
}
|
||||
|
||||
export class QueryTraceCodeDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '作品(款)ID' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
artworkId?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: '批次 ID' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@@ -105,13 +116,6 @@ export class BatchStatusDto {
|
||||
abnormal?: boolean;
|
||||
}
|
||||
|
||||
export class BindArtworkDto {
|
||||
@ApiProperty({ description: '艺术品 ID' })
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
artworkId!: number;
|
||||
}
|
||||
|
||||
export class QueryBatchDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '关键词(批次编号)' })
|
||||
@IsOptional()
|
||||
@@ -125,6 +129,12 @@ export class ExportTraceCodeDto {
|
||||
@IsIn(['xlsx', 'csv'])
|
||||
format?: 'xlsx' | 'csv';
|
||||
|
||||
@ApiPropertyOptional({ description: '作品(款)ID' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
artworkId?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: '分组 ID' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
|
||||
@@ -13,6 +13,7 @@ const codeId = customAlphabet(ALPHABET, 18);
|
||||
|
||||
interface GenJobData {
|
||||
batchId: number;
|
||||
artworkId: number;
|
||||
jobId: string;
|
||||
quantity: number;
|
||||
groupId?: number | null;
|
||||
@@ -31,7 +32,7 @@ export class GenCodeProcessor extends WorkerHost {
|
||||
}
|
||||
|
||||
async process(job: Job<GenJobData>): Promise<void> {
|
||||
const { batchId, jobId, quantity, groupId } = job.data;
|
||||
const { batchId, artworkId, 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 {
|
||||
return {
|
||||
code: codeId(),
|
||||
shortCode,
|
||||
artworkId,
|
||||
batchId,
|
||||
groupId: groupId ?? null,
|
||||
url: this.traceCode.buildTraceUrl(shortCode),
|
||||
|
||||
@@ -17,7 +17,6 @@ import { TraceCodeService } from './trace-code.service';
|
||||
import {
|
||||
BatchGroupDto,
|
||||
BatchStatusDto,
|
||||
BindArtworkDto,
|
||||
ExportTraceCodeDto,
|
||||
GenerateBatchDto,
|
||||
GroupDto,
|
||||
@@ -110,17 +109,4 @@ export class TraceCodeController {
|
||||
res.end(buf);
|
||||
}
|
||||
|
||||
@Put('trace-codes/:id/bind')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '绑定艺术品' })
|
||||
bind(@Param('id') id: string, @Body() dto: BindArtworkDto) {
|
||||
return this.service.bind(BigInt(id), dto.artworkId);
|
||||
}
|
||||
|
||||
@Put('trace-codes/:id/unbind')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '解绑艺术品' })
|
||||
unbind(@Param('id') id: string) {
|
||||
return this.service.unbind(BigInt(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Response } from 'express';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import * as QRCode from 'qrcode';
|
||||
import dayjs from 'dayjs';
|
||||
import { ErrorCode, JobType, QUEUE_NAMES, TraceCodeStatus } from '@artveris/shared';
|
||||
import { ArtworkStatus, ErrorCode, JobType, QUEUE_NAMES, TraceCodeStatus } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
@@ -38,20 +38,28 @@ export class TraceCodeService {
|
||||
}
|
||||
|
||||
async generateBatch(dto: GenerateBatchDto, userId: number) {
|
||||
// 必须指定作品(款):生码即归属该款(一款多码)
|
||||
const artwork = await this.prisma.artwork.findFirst({
|
||||
where: { id: dto.artworkId, deletedAt: null },
|
||||
});
|
||||
if (!artwork) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
|
||||
|
||||
const batchNo = dto.batchNo || `B${dayjs().format('YYYYMMDDHHmmss')}`;
|
||||
const exists = await this.prisma.batch.findUnique({ where: { batchNo } });
|
||||
if (exists) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '批次编号已存在');
|
||||
}
|
||||
const batch = await this.prisma.batch.create({
|
||||
data: { batchNo, quantity: dto.quantity, createdBy: userId },
|
||||
data: { batchNo, artworkId: dto.artworkId, quantity: dto.quantity, createdBy: userId },
|
||||
});
|
||||
const job = await this.jobs.create(JobType.GEN_CODE, dto.quantity, userId, {
|
||||
batchId: batch.id,
|
||||
artworkId: dto.artworkId,
|
||||
groupId: dto.groupId ?? null,
|
||||
});
|
||||
await this.genQueue.add('generate', {
|
||||
batchId: batch.id,
|
||||
artworkId: dto.artworkId,
|
||||
jobId: job.id,
|
||||
quantity: dto.quantity,
|
||||
groupId: dto.groupId ?? null,
|
||||
@@ -113,20 +121,16 @@ export class TraceCodeService {
|
||||
data: { status: TraceCodeStatus.DISABLED },
|
||||
});
|
||||
} else {
|
||||
// 启用:按是否已激活/已绑定恢复对应状态
|
||||
// 启用:已激活过的恢复为 ACTIVE,否则恢复为 INACTIVE
|
||||
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 } },
|
||||
where: { id: { in: ids }, firstActivatedAt: 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 };
|
||||
@@ -149,6 +153,7 @@ export class TraceCodeService {
|
||||
|
||||
async list(query: QueryTraceCodeDto) {
|
||||
const where: Prisma.TraceCodeWhereInput = {};
|
||||
if (query.artworkId) where.artworkId = query.artworkId;
|
||||
if (query.batchId) where.batchId = query.batchId;
|
||||
if (query.groupId) where.groupId = query.groupId;
|
||||
if (query.status) where.status = query.status;
|
||||
@@ -156,15 +161,16 @@ export class TraceCodeService {
|
||||
where.OR = [
|
||||
{ shortCode: { contains: query.keyword } },
|
||||
{ code: { contains: query.keyword } },
|
||||
{ sku: { contains: query.keyword } },
|
||||
{ archiveNo: { contains: query.keyword } },
|
||||
{ artwork: { archiveNo: { contains: query.keyword } } },
|
||||
{ artwork: { title: { contains: query.keyword } } },
|
||||
];
|
||||
}
|
||||
const [list, total] = await this.prisma.$transaction([
|
||||
this.prisma.traceCode.findMany({
|
||||
where,
|
||||
include: {
|
||||
artwork: { select: { id: true, title: true } },
|
||||
artwork: { select: { id: true, title: true, archiveNo: true } },
|
||||
batch: { select: { id: true, batchNo: true } },
|
||||
group: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { id: 'desc' },
|
||||
@@ -176,34 +182,6 @@ export class TraceCodeService {
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
}
|
||||
|
||||
async bind(id: bigint, artworkId: number) {
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { id } });
|
||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
||||
const artwork = await this.prisma.artwork.findFirst({ where: { id: artworkId, deletedAt: null } });
|
||||
if (!artwork) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
|
||||
|
||||
const bound = await this.prisma.traceCode.findUnique({ where: { artworkId } });
|
||||
if (bound && bound.id !== id) {
|
||||
throw new BusinessException(ErrorCode.TRACE_CODE_ALREADY_BOUND, '该艺术品已绑定其他追溯码');
|
||||
}
|
||||
|
||||
const next =
|
||||
code.status === TraceCodeStatus.UNBOUND ? TraceCodeStatus.INACTIVE : code.status;
|
||||
return this.prisma.traceCode.update({
|
||||
where: { id },
|
||||
data: { artworkId, status: next },
|
||||
});
|
||||
}
|
||||
|
||||
async unbind(id: bigint) {
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { id } });
|
||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
||||
return this.prisma.traceCode.update({
|
||||
where: { id },
|
||||
data: { artworkId: null, status: TraceCodeStatus.UNBOUND },
|
||||
});
|
||||
}
|
||||
|
||||
async getQrPng(id: bigint): Promise<Buffer> {
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { id } });
|
||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
||||
@@ -224,6 +202,7 @@ export class TraceCodeService {
|
||||
.map((s) => BigInt(s));
|
||||
where.id = { in: idList };
|
||||
} else {
|
||||
if (dto.artworkId) where.artworkId = dto.artworkId;
|
||||
if (dto.batchId) where.batchId = dto.batchId;
|
||||
if (dto.groupId) where.groupId = dto.groupId;
|
||||
if (dto.status) where.status = dto.status;
|
||||
@@ -231,21 +210,27 @@ export class TraceCodeService {
|
||||
where.OR = [
|
||||
{ shortCode: { contains: dto.keyword } },
|
||||
{ code: { contains: dto.keyword } },
|
||||
{ sku: { contains: dto.keyword } },
|
||||
{ archiveNo: { contains: dto.keyword } },
|
||||
{ artwork: { archiveNo: { contains: dto.keyword } } },
|
||||
{ artwork: { title: { contains: dto.keyword } } },
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
const codes = await this.prisma.traceCode.findMany({
|
||||
where,
|
||||
include: { batch: { select: { batchNo: true } }, group: { select: { name: true } } },
|
||||
include: {
|
||||
batch: { select: { batchNo: true } },
|
||||
group: { select: { name: true } },
|
||||
artwork: { select: { title: true, archiveNo: true } },
|
||||
},
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
|
||||
const wb = new ExcelJS.Workbook();
|
||||
const ws = wb.addWorksheet('追溯码');
|
||||
ws.columns = [
|
||||
{ header: '档案编号', key: 'archiveNo', width: 18 },
|
||||
{ header: '作品名称', key: 'title', width: 20 },
|
||||
{ header: '批次编号', key: 'batchNo', width: 22 },
|
||||
{ header: '分组', key: 'group', width: 14 },
|
||||
{ header: '追溯码', key: 'code', width: 24 },
|
||||
@@ -260,6 +245,8 @@ export class TraceCodeService {
|
||||
const url = c.url || this.buildTraceUrl(c.shortCode);
|
||||
const qr = await QRCode.toDataURL(url, { margin: 1, width: 200 });
|
||||
ws.addRow({
|
||||
archiveNo: c.artwork?.archiveNo ?? '',
|
||||
title: c.artwork?.title ?? '',
|
||||
batchNo: c.batch?.batchNo ?? '',
|
||||
group: c.group?.name ?? '',
|
||||
code: c.code,
|
||||
|
||||
Reference in New Issue
Block a user