325 lines
13 KiB
TypeScript
325 lines
13 KiB
TypeScript
import { PrismaClient, RoleType, AuditStatus } from '@prisma/client';
|
||
import * as bcrypt from 'bcryptjs';
|
||
import { existsSync, mkdirSync, writeFileSync } from 'fs';
|
||
import { dirname, join, resolve } from 'path';
|
||
import { customAlphabet } from 'nanoid';
|
||
import { randomBytes, randomInt, createHash } from 'crypto';
|
||
import sharp from 'sharp';
|
||
import { addWatermark } from '../src/certificate/watermark.util';
|
||
|
||
const prisma = new PrismaClient();
|
||
const storageDir = resolve(process.env.STORAGE_LOCAL_DIR || './storage');
|
||
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
||
const shortId = customAlphabet(ALPHABET, 10);
|
||
function buildShortCode(serialNo: number): string {
|
||
return `${randomInt(0, 1_000_000).toString().padStart(6, '0')}${serialNo.toString().padStart(6, '0')}`;
|
||
}
|
||
const watermarkText = process.env.WATERMARK_TEXT || '仅供溯源核验使用';
|
||
const DEFAULT_TEMPLATE_FIELDS = [
|
||
{ fieldKey: 'craft', label: '工艺', type: 'TEXT', required: true, sortOrder: 0 },
|
||
{ fieldKey: 'year', label: '创作年代 / 出品时间', type: 'TEXT', required: false, sortOrder: 1 },
|
||
{ fieldKey: 'size', label: '规格尺寸', type: 'TEXT', required: false, sortOrder: 2 },
|
||
{ fieldKey: 'material', label: '材质 / 媒介', type: 'TEXT', required: false, sortOrder: 3 },
|
||
{ fieldKey: 'certificationOrg', label: '认证机构', type: 'TEXT', required: false, sortOrder: 4 },
|
||
{ fieldKey: 'dataOwner', label: '数据权属', type: 'TEXT', required: false, sortOrder: 5 },
|
||
] as const;
|
||
|
||
function writeStorage(key: string, buf: Buffer): string {
|
||
const full = join(storageDir, key);
|
||
mkdirSync(dirname(full), { recursive: true });
|
||
writeFileSync(full, buf);
|
||
return key;
|
||
}
|
||
|
||
async function placeholder(text: string, bg: string, width = 900, height = 640): Promise<Buffer> {
|
||
const svg = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
|
||
<rect width="100%" height="100%" fill="${bg}"/>
|
||
<text x="50%" y="50%" font-family="Microsoft YaHei, sans-serif" font-size="56" fill="#ffffff" text-anchor="middle" dominant-baseline="middle">${text}</text>
|
||
</svg>`;
|
||
return sharp(Buffer.from(svg)).jpeg({ quality: 86 }).toBuffer();
|
||
}
|
||
|
||
async function ensureUsers(): Promise<void> {
|
||
const seedUsers = [
|
||
{
|
||
username: process.env.SEED_ADMIN_USERNAME || 'admin',
|
||
password: process.env.SEED_ADMIN_PASSWORD || 'Admin@12345',
|
||
realName: process.env.SEED_ADMIN_NAME || '超级管理员',
|
||
role: RoleType.SUPER_ADMIN,
|
||
},
|
||
{ username: 'operator', password: 'Operator@123', realName: '运营专员', role: RoleType.OPERATOR },
|
||
{ username: 'auditor', password: 'Auditor@123', realName: '审核专员', role: RoleType.AUDITOR },
|
||
{ username: 'viewer', password: 'Viewer@123', realName: '只读监管', role: RoleType.VIEWER },
|
||
];
|
||
for (const u of seedUsers) {
|
||
const exists = await prisma.sysUser.findUnique({ where: { username: u.username } });
|
||
if (!exists) {
|
||
await prisma.sysUser.create({
|
||
data: {
|
||
username: u.username,
|
||
passwordHash: await bcrypt.hash(u.password, 10),
|
||
realName: u.realName,
|
||
role: u.role,
|
||
},
|
||
});
|
||
console.log(`已创建用户:${u.username}(${u.role})`);
|
||
}
|
||
}
|
||
}
|
||
|
||
async function ensureSettings(): Promise<void> {
|
||
const defaults: Record<string, string> = {
|
||
appName: process.env.APP_NAME || '艺术品溯源平台',
|
||
appIconUrl: '',
|
||
logRetentionDays: process.env.LOG_RETENTION_DAYS || '365',
|
||
watermarkText,
|
||
filingInfo: '备案信息待补充',
|
||
};
|
||
for (const [key, value] of Object.entries(defaults)) {
|
||
await prisma.systemSetting.upsert({ where: { key }, update: {}, create: { key, value } });
|
||
}
|
||
}
|
||
|
||
async function ensureTemplateDefaultFields(templateId: number): Promise<void> {
|
||
const existing = await prisma.templateField.findMany({ where: { templateId } });
|
||
const byKey = new Map(existing.map((field) => [field.fieldKey, field]));
|
||
for (const field of DEFAULT_TEMPLATE_FIELDS) {
|
||
const current = byKey.get(field.fieldKey);
|
||
if (current) {
|
||
await prisma.templateField.update({
|
||
where: { id: current.id },
|
||
data: {
|
||
label: field.label,
|
||
type: field.type,
|
||
required: field.required,
|
||
sortOrder: field.sortOrder,
|
||
},
|
||
});
|
||
} else {
|
||
await prisma.templateField.create({
|
||
data: { ...field, templateId },
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
async function ensureSampleData(): Promise<void> {
|
||
const existing = await prisma.template.findFirst({ where: { name: '陶瓷溯源模板' } });
|
||
if (existing) {
|
||
await ensureTemplateDefaultFields(existing.id);
|
||
console.log('示例数据已存在,跳过。');
|
||
return;
|
||
}
|
||
|
||
const admin = await prisma.sysUser.findFirst({ where: { role: RoleType.SUPER_ADMIN } });
|
||
|
||
const template = await prisma.template.create({
|
||
data: {
|
||
name: '陶瓷溯源模板',
|
||
remark: '适用于陶瓷类艺术品',
|
||
fields: {
|
||
create: DEFAULT_TEMPLATE_FIELDS.map((field) => ({ ...field })),
|
||
},
|
||
},
|
||
});
|
||
|
||
const samples = [
|
||
{ title: '青花缠枝莲纹瓶', artist: '李明远', bg: '#2e5496', craft: '手工拉胚 / 釉下青花', material: '高岭土', size: '高 38cm', year: '2023' },
|
||
{ title: '霁红釉梅瓶', artist: '王守拙', bg: '#7a2e2e', craft: '高温铜红釉', material: '瓷土', size: '高 32cm', year: '2022' },
|
||
{ title: '影青刻花碗', artist: '陈一川', bg: '#2f6b5e', craft: '刻花 / 影青釉', material: '瓷石', size: '口径 18cm', year: '2024' },
|
||
];
|
||
|
||
const base = (process.env.BASE_URL || 'http://localhost:3000').replace(/\/$/, '');
|
||
const CODES_PER_ARTWORK = 3; // 每个示例档案下生成的追溯码数量
|
||
let artworkSeq = 0;
|
||
let totalCodes = 0;
|
||
// 为节点生成"带标题"的占位图片(演示:每节点多张、横向、按标题展示)
|
||
const nodeMedia = async (labels: string[], bg: string) => {
|
||
const arr: { key: string; name: string; type: string }[] = [];
|
||
for (const label of labels) {
|
||
const key = writeStorage(`seed/${shortId()}.jpg`, await placeholder(label, bg));
|
||
arr.push({ key, name: label, type: 'image' });
|
||
}
|
||
return arr;
|
||
};
|
||
|
||
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));
|
||
const showcaseImages = [
|
||
{
|
||
key: writeStorage(
|
||
`seed/${shortId()}.jpg`,
|
||
await placeholder(`${s.title} · 整体展示`, s.bg, 1200, 800),
|
||
),
|
||
name: '整体展示',
|
||
description: '从正面完整展示作品器型、比例与整体效果。',
|
||
type: 'image',
|
||
},
|
||
{
|
||
key: writeStorage(
|
||
`seed/${shortId()}.jpg`,
|
||
await placeholder(`${s.title} · 工艺细节`, s.bg, 800, 1200),
|
||
),
|
||
name: '工艺细节',
|
||
description: '近距离呈现作品纹样、釉色与手工制作细节。',
|
||
type: 'image',
|
||
},
|
||
{
|
||
key: writeStorage(
|
||
`seed/${shortId()}.jpg`,
|
||
await placeholder(`${s.title} · 多角度展示`, s.bg, 900, 1500),
|
||
),
|
||
name: '多角度展示',
|
||
description: '按原始比例展示作品局部与不同观察角度。',
|
||
type: 'image',
|
||
},
|
||
];
|
||
const createMedia = await nodeMedia(['设计稿', '选胚图'], s.bg);
|
||
const produceMedia = await nodeMedia(['手塑', '拉胚', '上釉', '烧制'], s.bg);
|
||
const storageMedia = await nodeMedia(['入库实况'], s.bg);
|
||
const outboundMedia = await nodeMedia(['出库实况'], s.bg);
|
||
const artwork = await prisma.artwork.create({
|
||
data: {
|
||
templateId: template.id,
|
||
title: s.title,
|
||
artist: s.artist,
|
||
status: 'ACTIVE',
|
||
auditStatus: AuditStatus.APPROVED,
|
||
auditedBy: admin?.id,
|
||
auditedAt: new Date(),
|
||
createdBy: admin?.id,
|
||
dynamicFields: { craft: s.craft, material: s.material, size: s.size, year: s.year },
|
||
images: [
|
||
{ key: imgKey, name: '主图' },
|
||
{ key: img2, name: '细节' },
|
||
],
|
||
showcaseImages,
|
||
traceNodes: {
|
||
create: [
|
||
{ nodeType: 'CREATE', title: '创作设计', location: '景德镇', description: '设计选胚,确定器型与纹样。', sortOrder: 0, mediaFiles: createMedia },
|
||
{ nodeType: 'PRODUCE', title: '制作烧制', location: '景德镇', description: '拉胚、上釉、高温烧制成型。', sortOrder: 1, mediaFiles: produceMedia },
|
||
{ nodeType: 'STORAGE', title: '入库托管', location: '艺术品仓储中心', description: '恒温恒湿仓储托管。', sortOrder: 2, mediaFiles: storageMedia },
|
||
{ nodeType: 'OUTBOUND', title: '出库流转', location: '艺术品仓储中心', description: '验真出库,交付藏家。', sortOrder: 3, mediaFiles: outboundMedia },
|
||
],
|
||
},
|
||
},
|
||
});
|
||
// 档案编号(款级,按 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'));
|
||
const wmBuf = await addWatermark(await placeholder(`${s.title} 鉴定证书`, '#444c5a'), watermarkText);
|
||
const wmKey = writeStorage(`seed/${shortId()}_wm.jpg`, wmBuf);
|
||
await prisma.certificate.create({
|
||
data: {
|
||
artworkId: artwork.id,
|
||
name: '权威鉴定证书',
|
||
issuer: '某艺术品鉴定中心',
|
||
type: 'CERT',
|
||
originFileUrl: certOriginKey,
|
||
watermarkFileUrl: wmKey,
|
||
},
|
||
});
|
||
|
||
// 一个艺术品档案下建一个批次,并生成多套独立追溯码。
|
||
const batch = await prisma.batch.create({
|
||
data: {
|
||
batchNo: `B-SEED-${String(artwork.id).padStart(4, '0')}`,
|
||
artworkId: artwork.id,
|
||
quantity: CODES_PER_ARTWORK,
|
||
generatedCount: CODES_PER_ARTWORK,
|
||
status: 'DONE',
|
||
createdBy: admin?.id,
|
||
},
|
||
});
|
||
|
||
const artworkActive = artworkSeq < 2; // 前两款带激活码与查询记录
|
||
for (let k = 0; k < CODES_PER_ARTWORK; k++) {
|
||
const serialNo = totalCodes + 1;
|
||
const shortCode = buildShortCode(serialNo);
|
||
const isActive = artworkActive && k < 2; // 该款前两套已激活
|
||
const code = await prisma.traceCode.create({
|
||
data: {
|
||
shortCode,
|
||
serialNo,
|
||
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,
|
||
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}`,
|
||
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({ shortCode })).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 + 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' },
|
||
},
|
||
});
|
||
}
|
||
}
|
||
artworkSeq++;
|
||
}
|
||
await prisma.traceCodeSequence.upsert({
|
||
where: { id: 1 },
|
||
update: { nextSeq: totalCodes + 1 },
|
||
create: { id: 1, nextSeq: totalCodes + 1 },
|
||
});
|
||
console.log(`已创建示例:模板 1、作品 ${samples.length}(每款 ${CODES_PER_ARTWORK} 码,共 ${totalCodes} 码)、证书、查询日志与存证。`);
|
||
}
|
||
|
||
async function main(): Promise<void> {
|
||
await ensureUsers();
|
||
await ensureSettings();
|
||
await ensureSampleData();
|
||
console.log('种子数据初始化完成。');
|
||
}
|
||
|
||
main()
|
||
.catch((e) => {
|
||
console.error(e);
|
||
process.exit(1);
|
||
})
|
||
.finally(() => {
|
||
void prisma.$disconnect();
|
||
});
|