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 { SettingsService } from '../settings/settings.service'; import { REDIS_CLIENT } from '../redis/redis.module'; import { parseUserAgent } from '../common/utils/ua.util'; import { buildTianheExplorerTxUrl } from '../blockchain/tianhe.provider'; type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>; type ArtworkWithRel = Prisma.ArtworkGetPayload<{ include: { template: { include: { fields: true } }; traceNodes: true; certificates: true; }; }>; export interface TraceContext { ip: string; userAgent?: string; } const MAP_TTL = 3600; // 短码→id 映射缓存 1 小时 const MISS_TTL = 60; // 无效码负缓存 60 秒,降低无效码刷库压力 const MISS_SENTINEL = '0'; // 负缓存哨兵值(真实 id 从 1 起,不会为 0) @Injectable() export class PublicTraceService { private readonly logger = new Logger(PublicTraceService.name); constructor( private readonly prisma: PrismaService, private readonly storage: StorageService, private readonly settings: SettingsService, @Inject(REDIS_CLIENT) private readonly redis: Redis, ) {} private mapMedia( items: unknown, ): Array<{ name?: string; type?: string; description?: string; url: string }> { if (!Array.isArray(items)) return []; return (items as Array<{ key: string; name?: string; type?: string; description?: string }>) .filter((i) => i && i.key) .map((i) => ({ name: i.name, type: i.type, description: i.description, 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; }>, outbound: { outTime: Date; images: Array<{ fileKey: string; fileName: string; mimeType: string; id: bigint; size: bigint; width: number; height: number; sortOrder: number }>; } | null, showOutboundTimeline: boolean, ) { const timeline = nodes.map((n) => ({ nodeType: n.nodeType, system: null as string | null, title: n.title as string | null, occurredAt: n.occurredAt as Date | null, location: n.location, description: n.description, media: this.mapMedia(n.mediaFiles), })); const outMedia = outbound?.images.map((image) => this.mapOutboundImage(image)) ?? []; if (showOutboundTimeline && outbound) { // 单件出库记录:不下发中文标题/说明,标记 system=OUTBOUND_RECORD 由 C 端按语言本地化 timeline.push({ nodeType: 'OUTBOUND', system: 'OUTBOUND_RECORD', title: null, occurredAt: outbound.outTime, location: null, description: null, media: outMedia, }); } return timeline; } private mapOutboundImage(image: { id: bigint; fileKey: string; fileName: string; mimeType: string; size: bigint; width: number; height: number; sortOrder: number; }) { return { id: image.id, key: image.fileKey, url: this.storage.getUrl(image.fileKey), name: image.fileName, type: 'image', mimeType: image.mimeType, size: image.size, width: image.width, height: image.height, sortOrder: image.sortOrder, }; } private async resolveId(shortCode: string): Promise { const cacheKey = `trace:map:${shortCode}`; const cached = await this.redis.get(cacheKey); if (cached === MISS_SENTINEL) return null; if (cached) return BigInt(cached); const code = await this.prisma.traceCode.findUnique({ where: { shortCode }, select: { id: true }, }); if (!code) { // 负缓存无效码,避免被脚本高频扫描时每次都落库 await this.redis.set(cacheKey, MISS_SENTINEL, 'EX', MISS_TTL); 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, outbound: { include: { images: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }], take: 20 }, _count: { select: { images: 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.ACTIVE || artwork.auditStatus !== AuditStatus.APPROVED ) { await this.writeLog(id, code.artworkId, shortCode, QueryResult.INVALID, ctx, code); return { status: 'INVALID' as const }; } // 激活 / 计数:用条件更新消除并发首次扫码的竞态。 // 只有真正把 INACTIVE 抢成 ACTIVE 的那一次请求 firstActivate=true(updateMany 返回 count=1), // 其余并发请求 count=0,退化为原子自增,避免 queryCount 被双双写成 1、firstActivatedAt 被覆盖。 const now = new Date(); let firstActivate = false; if (code.status === TraceCodeStatus.INACTIVE) { const claimed = await this.prisma.traceCode.updateMany({ where: { id, status: TraceCodeStatus.INACTIVE }, data: { status: TraceCodeStatus.ACTIVE, firstActivatedAt: now, queryCount: 1, lastQueriedAt: now, }, }); firstActivate = claimed.count > 0; } if (!firstActivate) { await this.prisma.traceCode.update({ where: { id }, data: { queryCount: { increment: 1 }, lastQueriedAt: now }, }); } // 回查最新值组装响应(首次激活时读到自身写入,重复查询读到自增后的值) const updated = await this.prisma.traceCode.findUniqueOrThrow({ where: { id } }); const proof = await this.prisma.blockchainProof.findUnique({ where: { traceCodeId: id } }); const result = firstActivate ? QueryResult.FIRST_ACTIVATE : QueryResult.REPEAT; await this.writeLog(id, artwork.id, shortCode, result, ctx, { ...code, ...updated }); const explorerUrl = await this.resolveExplorerUrl(proof); return { status: 'OK' as const, queriedAt: now, antiCounterfeit: { firstQuery: firstActivate, queryCount: updated.queryCount, firstActivatedAt: updated.firstActivatedAt, }, ...this.buildArtworkPayload(artwork, code, proof, explorerUrl), }; } // 后台预览:与 trace() 相同的数据组装,但零副作用——不激活、不计数、不写查询日志。 // state 决定防伪区块以「首次扫码」还是「重复访问」形态展示,antiCounterfeit 数值为演示占位/库中现值。 async preview(shortCode: string, state: 'inactive' | 'active') { if (!TRACE_CODE_PATTERN.test(shortCode)) return { status: 'INVALID' as const }; const id = await this.resolveId(shortCode); if (id === null) return { status: 'INVALID' as const }; const code = await this.prisma.traceCode.findUnique({ where: { id }, include: { batch: true, artwork: true, outbound: { include: { images: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }], take: 20 }, _count: { select: { images: true } }, }, }, }, }); if (!code) return { status: 'INVALID' as const }; if (code.status === TraceCodeStatus.DISABLED) return { status: 'DISABLED' as const }; if (code.status === TraceCodeStatus.ABNORMAL) 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.ACTIVE || artwork.auditStatus !== AuditStatus.APPROVED ) { return { status: 'INVALID' as const }; } const proof = await this.prisma.blockchainProof.findUnique({ where: { traceCodeId: id } }); const now = new Date(); const firstQuery = state === 'inactive'; const explorerUrl = await this.resolveExplorerUrl(proof); return { status: 'OK' as const, preview: true, queriedAt: now, antiCounterfeit: firstQuery ? { firstQuery: true, queryCount: 1, firstActivatedAt: now } : { firstQuery: false, queryCount: code.queryCount > 0 ? code.queryCount : 2, firstActivatedAt: code.firstActivatedAt ?? now, }, ...this.buildArtworkPayload(artwork, code, proof, explorerUrl), }; } // trace/preview 共用的作品展示数据(作品信息 / 时间线 / 证书 / 区块链存证) private buildArtworkPayload( artwork: ArtworkWithRel, code: { outbound?: { outTime: Date; remark: string | null; images: Array<{ id: bigint; fileKey: string; fileName: string; mimeType: string; size: bigint; width: number; height: number; sortOrder: number }>; _count: { images: number }; } | null; }, proof: { txHash: string | null; blockHash: string | null; blockHeight: bigint | null; chainName: string | null; onchainAt: Date | null; explorerUrl: string | null; contractAddress: string | null; status: string; failureReason: string | null; submittedAt: Date | null; } | null, explorerUrl: string | null, ) { return { artwork: { title: artwork.title, artist: artwork.artist, archiveNo: artwork.archiveNo, images: this.mapMedia(artwork.images), showcaseImages: this.mapMedia(artwork.showcaseImages), showOutboundTimeline: artwork.showOutboundTimeline, fields: this.buildFields(artwork.template.fields, artwork.dynamicFields), }, timeline: this.buildTimeline( artwork.traceNodes, code.outbound ?? null, artwork.showOutboundTimeline === true, ), outbound: code.outbound ? { outTime: code.outbound.outTime, remark: code.outbound.remark, images: { items: code.outbound.images.map((image) => this.mapOutboundImage(image)), total: code.outbound._count.images, page: 1, pageSize: 20, hasMore: code.outbound._count.images > code.outbound.images.length, }, } : null, 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 ? { status: proof.status, txHash: proof.txHash, blockHash: proof.blockHash, blockHeight: proof.blockHeight, chainName: proof.chainName, onchainAt: proof.onchainAt, explorerUrl, contractAddress: proof.contractAddress, submittedAt: proof.submittedAt, failureReason: this.publicFailureReason(proof.status, proof.failureReason), } : null, }; } private publicFailureReason(status: string, reason: string | null): string | null { if (status === ProofStatus.UNKNOWN) return '链上结果暂时无法确认,请稍后重试或联系平台管理员'; if (status === ProofStatus.FAILED) return reason ? '上链处理失败,请联系平台管理员' : '上链处理失败'; return null; } async outboundImages(shortCode: string, page: number, pageSize: number, previewAuthorized: boolean) { if (!TRACE_CODE_PATTERN.test(shortCode)) return { status: 'INVALID' as const }; const id = await this.resolveId(shortCode); if (id === null) return { status: 'INVALID' as const }; const code = await this.prisma.traceCode.findUnique({ where: { id }, select: { status: true, artwork: { select: { status: true, auditStatus: true, deletedAt: true } }, outbound: { select: { id: true } }, }, }); if ( !code || (!previewAuthorized && code.status !== TraceCodeStatus.ACTIVE) || code.status === TraceCodeStatus.DISABLED || code.status === TraceCodeStatus.ABNORMAL || code.artwork.deletedAt || code.artwork.status !== ArtworkStatus.ACTIVE || code.artwork.auditStatus !== AuditStatus.APPROVED ) { return { status: 'INVALID' as const }; } if (!code.outbound) return { items: [], total: 0, page, pageSize, hasMore: false }; const [items, total] = await this.prisma.$transaction([ this.prisma.outboundImage.findMany({ where: { outboundRecordId: code.outbound.id }, orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }], skip: (page - 1) * pageSize, take: pageSize, }), this.prisma.outboundImage.count({ where: { outboundRecordId: code.outbound.id } }), ]); return { items: items.map((image) => this.mapOutboundImage(image)), total, page, pageSize, hasMore: page * pageSize < total, }; } private async resolveExplorerUrl( proof: { txHash: string | null; chainName: string | null; explorerUrl: string | null } | null, ): Promise { const tianheProof = proof?.chainName === '天河链' || /tianhe|tichain/i.test(proof?.chainName || '') || /tianhecloud\.com/i.test(proof?.explorerUrl || ''); if (!proof?.txHash || !tianheProof) return proof?.explorerUrl ?? null; const settings = await this.settings.getAllRaw(); return buildTianheExplorerTxUrl(settings.tianheBaseUrl || '', proof.txHash, settings.tianheEnv); } private buildFields( fields: Array<{ fieldKey: string; label: string; type: string }>, dynamic: unknown, ) { const data = (dynamic as Record) || {}; 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, ): Promise { try { const device = parseUserAgent(ctx.userAgent); await this.prisma.queryLog.create({ data: { traceCodeId: traceCodeId ?? undefined, artworkId: artworkId ?? undefined, shortCode, 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}`); } } }