feat: 实现批量生码、二维码导出与公开溯源激活计数
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Request, Response } from 'express';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Public } from '../common/decorators/public.decorator';
|
||||
import { extractIp } from '../common/utils/ua.util';
|
||||
import { PublicTraceService } from './public-trace.service';
|
||||
|
||||
@ApiTags('公开溯源')
|
||||
@Controller()
|
||||
export class PublicTraceController {
|
||||
constructor(
|
||||
private readonly service: PublicTraceService,
|
||||
private readonly config: ConfigService,
|
||||
) {}
|
||||
|
||||
@Public()
|
||||
@Get('public/trace/:shortCode')
|
||||
@ApiOperation({ summary: 'C 端溯源查询(匿名)' })
|
||||
trace(@Param('shortCode') shortCode: string, @Req() req: Request) {
|
||||
const ip = extractIp(req.headers as Record<string, unknown>, req.ip);
|
||||
const userAgent = req.headers['user-agent'];
|
||||
return this.service.trace(shortCode, { ip, userAgent });
|
||||
}
|
||||
|
||||
// 短链跳转:扫码打开 /t/:shortCode -> 重定向到 C 端溯源页(不在 /api 前缀下)
|
||||
@Public()
|
||||
@Get('t/:shortCode')
|
||||
redirect(@Param('shortCode') shortCode: string, @Res() res: Response) {
|
||||
const template =
|
||||
this.config.get<string>('traceUrlTemplate') ||
|
||||
'http://localhost:5174/#/pages/trace/index?code={code}';
|
||||
res.redirect(302, template.replace('{code}', encodeURIComponent(shortCode)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PublicTraceService } from './public-trace.service';
|
||||
import { PublicTraceController } from './public-trace.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [PublicTraceController],
|
||||
providers: [PublicTraceService],
|
||||
exports: [PublicTraceService],
|
||||
})
|
||||
export class PublicTraceModule {}
|
||||
@@ -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}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user