feat: 实现批量生码、二维码导出与公开溯源激活计数

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-28 16:12:50 +08:00
co-authored by Cursor
parent b4108d7434
commit 63c0488ff7
11 changed files with 652 additions and 0 deletions
@@ -0,0 +1,189 @@
import { Inject, Injectable, Logger } from '@nestjs/common';
import type Redis from 'ioredis';
import { ArtworkStatus, QueryResult, ProofStatus, TraceCodeStatus } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { GeoService } from '../geo/geo.service';
import { REDIS_CLIENT } from '../redis/redis.module';
import { parseUserAgent } from '../common/utils/ua.util';
export interface TraceContext {
ip: string;
userAgent?: string;
}
const MAP_TTL = 3600; // 短码→id 映射缓存 1 小时
@Injectable()
export class PublicTraceService {
private readonly logger = new Logger(PublicTraceService.name);
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly geo: GeoService,
@Inject(REDIS_CLIENT) private readonly redis: Redis,
) {}
private mapMedia(items: unknown) {
if (!Array.isArray(items)) return [];
return (items as Array<{ key: string; name?: string; type?: string }>)
.filter((i) => i && i.key)
.map((i) => ({ name: i.name, type: i.type, url: this.storage.getUrl(i.key) }));
}
private async resolveId(shortCode: string): Promise<bigint | null> {
const cacheKey = `trace:map:${shortCode}`;
const cached = await this.redis.get(cacheKey);
if (cached) return BigInt(cached);
const code = await this.prisma.traceCode.findUnique({
where: { shortCode },
select: { id: true },
});
if (!code) return null;
await this.redis.set(cacheKey, code.id.toString(), 'EX', MAP_TTL);
return code.id;
}
async trace(shortCode: string, ctx: TraceContext) {
const id = await this.resolveId(shortCode);
if (id === null) {
await this.writeLog(null, null, shortCode, QueryResult.INVALID, ctx);
return { status: 'INVALID' as const };
}
const code = await this.prisma.traceCode.findUnique({ where: { id } });
if (!code || !code.artworkId || code.status === TraceCodeStatus.UNBOUND) {
await this.writeLog(id, null, shortCode, QueryResult.INVALID, ctx);
return { status: 'INVALID' as const };
}
if (code.status === TraceCodeStatus.DISABLED) {
await this.writeLog(id, code.artworkId, shortCode, QueryResult.DISABLED, ctx);
return { status: 'DISABLED' as const };
}
if (code.status === TraceCodeStatus.ABNORMAL) {
await this.writeLog(id, code.artworkId, shortCode, QueryResult.ABNORMAL, ctx);
return { status: 'ABNORMAL' as const };
}
const artwork = await this.prisma.artwork.findFirst({
where: { id: code.artworkId, deletedAt: null },
include: {
template: { include: { fields: { orderBy: { sortOrder: 'asc' } } } },
traceNodes: { orderBy: { sortOrder: 'asc' } },
certificates: { orderBy: { id: 'asc' } },
},
});
if (!artwork || artwork.status === ArtworkStatus.DISABLED) {
await this.writeLog(id, code.artworkId, shortCode, QueryResult.INVALID, ctx);
return { status: 'INVALID' as const };
}
// 激活 / 计数
const now = new Date();
let firstActivate = false;
let updated;
if (code.status === TraceCodeStatus.INACTIVE) {
updated = await this.prisma.traceCode.update({
where: { id },
data: {
status: TraceCodeStatus.ACTIVE,
firstActivatedAt: now,
queryCount: 1,
lastQueriedAt: now,
},
});
firstActivate = true;
} else {
updated = await this.prisma.traceCode.update({
where: { id },
data: { queryCount: { increment: 1 }, lastQueriedAt: now },
});
}
const proof = await this.prisma.blockchainProof.findFirst({
where: { traceCodeId: id, status: ProofStatus.ONCHAIN },
orderBy: { id: 'desc' },
});
const result = firstActivate ? QueryResult.FIRST_ACTIVATE : QueryResult.REPEAT;
await this.writeLog(id, artwork.id, shortCode, result, ctx);
return {
status: 'OK' as const,
antiCounterfeit: {
firstQuery: firstActivate,
queryCount: updated.queryCount,
firstActivatedAt: updated.firstActivatedAt,
},
artwork: {
title: artwork.title,
artist: artwork.artist,
images: this.mapMedia(artwork.images),
fields: this.buildFields(artwork.template.fields, artwork.dynamicFields),
},
timeline: artwork.traceNodes.map((n) => ({
nodeType: n.nodeType,
title: n.title,
occurredAt: n.occurredAt,
location: n.location,
description: n.description,
media: this.mapMedia(n.mediaFiles),
})),
certificates: artwork.certificates.map((c) => ({
name: c.name,
issuer: c.issuer,
issuedAt: c.issuedAt,
type: c.type,
url: c.watermarkFileUrl ? this.storage.getUrl(c.watermarkFileUrl) : null,
})),
blockchain: proof
? {
txHash: proof.txHash,
dataHash: proof.dataHash,
blockHash: proof.blockHash,
blockHeight: proof.blockHeight,
chainName: proof.chainName,
onchainAt: proof.onchainAt,
explorerUrl: proof.explorerUrl,
}
: null,
};
}
private buildFields(
fields: Array<{ fieldKey: string; label: string; type: string }>,
dynamic: unknown,
) {
const data = (dynamic as Record<string, unknown>) || {};
return fields
.map((f) => ({ label: f.label, type: f.type, value: data[f.fieldKey] }))
.filter((f) => f.value !== undefined && f.value !== null && f.value !== '');
}
private async writeLog(
traceCodeId: bigint | null,
artworkId: number | null,
shortCode: string,
result: QueryResult,
ctx: TraceContext,
): Promise<void> {
try {
const device = parseUserAgent(ctx.userAgent);
await this.prisma.queryLog.create({
data: {
traceCodeId: traceCodeId ?? undefined,
artworkId: artworkId ?? undefined,
shortCode,
queryResult: result,
ip: ctx.ip,
region: this.geo.resolveRegion(ctx.ip),
userAgent: ctx.userAgent,
deviceType: device.deviceType,
},
});
} catch (e) {
this.logger.warn(`查询日志写入失败: ${(e as Error).message}`);
}
}
}