Files
Artveris/apps/api/src/public-trace/public-trace.service.ts
T

263 lines
8.8 KiB
TypeScript

import { Inject, Injectable, Logger } from '@nestjs/common';
import type Redis from 'ioredis';
import { Prisma } from '@prisma/client';
import { ArtworkStatus, AuditStatus, QueryResult, ProofStatus, TRACE_CODE_PATTERN, TraceCodeStatus } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { REDIS_CLIENT } from '../redis/redis.module';
import { parseUserAgent } from '../common/utils/ua.util';
type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>;
export interface TraceContext {
ip: string;
userAgent?: string;
}
const MAP_TTL = 3600; // 短码→id 映射缓存 1 小时
const OUTBOUND_TRACE_TITLE = '本件出库记录';
const OUTBOUND_TRACE_DESC = '该追溯码对应实物的出库实况记录。';
@Injectable()
export class PublicTraceService {
private readonly logger = new Logger(PublicTraceService.name);
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
@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 buildTimeline(
nodes: Array<{
nodeType: string;
title: string;
occurredAt: Date | null;
location: string | null;
description: string | null;
mediaFiles: unknown;
}>,
code: { outTime?: Date | null; outImage?: string | null; outImages?: unknown },
) {
const timeline = nodes.map((n) => ({
nodeType: n.nodeType,
title: n.title,
occurredAt: n.occurredAt,
location: n.location,
description: n.description,
media: this.mapMedia(n.mediaFiles),
}));
const outMedia = Array.isArray(code.outImages)
? (code.outImages as Array<{ key?: string; name?: string; type?: string }>)
.map((item) => (typeof item === 'string' ? { key: item } : item))
.filter((item) => item?.key)
.map((item) => ({ name: item.name || '出库实况图', type: item.type || 'image', url: this.storage.getUrl(item.key as string) }))
: code.outImage
? [{ name: '出库实况图', type: 'image', url: this.storage.getUrl(code.outImage) }]
: [];
if (code.outTime || outMedia.length) {
timeline.push({
nodeType: 'OUTBOUND',
title: OUTBOUND_TRACE_TITLE,
occurredAt: code.outTime ?? null,
location: null,
description: OUTBOUND_TRACE_DESC,
media: outMedia,
});
}
return timeline;
}
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) {
if (!TRACE_CODE_PATTERN.test(shortCode)) {
await this.writeLog(null, null, shortCode, QueryResult.INVALID, ctx);
return { status: 'INVALID' as const };
}
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 },
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) {
await this.writeLog(id, code.artworkId, shortCode, QueryResult.DISABLED, ctx, code);
return { status: 'DISABLED' as const };
}
if (code.status === TraceCodeStatus.ABNORMAL) {
await this.writeLog(id, code.artworkId, shortCode, QueryResult.ABNORMAL, ctx, code);
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 ||
artwork.auditStatus !== AuditStatus.APPROVED
) {
await this.writeLog(id, code.artworkId, shortCode, QueryResult.INVALID, ctx, code);
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, { ...code, ...updated });
return {
status: 'OK' as const,
code: code.code,
queriedAt: now,
antiCounterfeit: {
firstQuery: firstActivate,
queryCount: updated.queryCount,
firstActivatedAt: updated.firstActivatedAt,
},
artwork: {
title: artwork.title,
artist: artwork.artist,
archiveNo: artwork.archiveNo,
images: this.mapMedia(artwork.images),
fields: this.buildFields(artwork.template.fields, artwork.dynamicFields),
},
timeline: this.buildTimeline(artwork.traceNodes, code),
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) => {
let value = data[f.fieldKey];
// 图片/文件字段:若存的是存储 key(非绝对/Data URL),转为可访问 URL,避免 C 端 404
if (
(f.type === 'IMAGE' || f.type === 'FILE') &&
typeof value === 'string' &&
value &&
!/^(https?:|data:|\/)/i.test(value)
) {
value = this.storage.getUrl(value);
}
return { label: f.label, type: f.type, value };
})
.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,
code?: Partial<TraceCodeWithRel>,
): Promise<void> {
try {
const device = parseUserAgent(ctx.userAgent);
await this.prisma.queryLog.create({
data: {
traceCodeId: traceCodeId ?? undefined,
artworkId: artworkId ?? undefined,
shortCode,
code: code?.code ?? undefined,
archiveNo: code?.artwork?.archiveNo ?? undefined,
batchNo: code?.batch?.batchNo ?? undefined,
queryCount: code?.queryCount ?? undefined,
firstActivatedAt: code?.firstActivatedAt ?? undefined,
queryResult: result,
ip: ctx.ip,
userAgent: ctx.userAgent,
deviceType: device.deviceType,
browser: device.browser,
os: device.os,
},
});
} catch (e) {
this.logger.warn(`查询日志写入失败: ${(e as Error).message}`);
}
}
}