fix: 统一追溯码并修正天河链存证跳转

This commit is contained in:
Nixevol
2026-07-13 07:06:43 +08:00
parent 61d813a096
commit 09b9887a30
21 changed files with 79 additions and 98 deletions
@@ -0,0 +1,3 @@
-- 12 位 short_code 已是唯一业务追溯码,移除历史遗留的第二套完整编码。
ALTER TABLE `query_log` DROP COLUMN `code`;
ALTER TABLE `trace_code` DROP INDEX `trace_code_code_key`, DROP COLUMN `code`;
-2
View File
@@ -307,7 +307,6 @@ model Batch {
model TraceCode {
id BigInt @id @default(autoincrement())
code String @unique
shortCode String @unique @map("short_code")
artworkId Int @map("artwork_id")
batchId Int @map("batch_id")
@@ -370,7 +369,6 @@ model QueryLog {
traceCodeId BigInt? @map("trace_code_id")
artworkId Int? @map("artwork_id")
shortCode String? @map("short_code")
code String?
archiveNo String? @map("archive_no")
batchNo String? @map("batch_no")
queryCount Int? @map("query_count")
+1 -4
View File
@@ -11,7 +11,6 @@ const prisma = new PrismaClient();
const storageDir = resolve(process.env.STORAGE_LOCAL_DIR || './storage');
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const shortId = customAlphabet(ALPHABET, 10);
const codeId = customAlphabet(ALPHABET, 18);
// 公开短码须为 12 位纯数字(与 TRACE_CODE_PATTERN=/^\d{12}$/ 一致),否则 C 端公开溯源会判 INVALID
const numericId = customAlphabet('0123456789', 12);
function uniqueShortCode(used: Set<string>): string {
@@ -221,7 +220,6 @@ async function ensureSampleData(): Promise<void> {
const isActive = artworkActive && k < 2; // 该款前两套已激活
const code = await prisma.traceCode.create({
data: {
code: codeId(),
shortCode,
artworkId: artwork.id,
batchId: batch.id,
@@ -241,7 +239,6 @@ async function ensureSampleData(): Promise<void> {
traceCodeId: code.id,
artworkId: artwork.id,
shortCode,
code: code.code,
archiveNo: `ARTVERIS-${String(artwork.id).padStart(6, '0')}`,
batchNo: batch.batchNo,
queryCount: 3 + k,
@@ -256,7 +253,7 @@ async function ensureSampleData(): Promise<void> {
},
});
}
const dataHash = '0x' + createHash('sha256').update(JSON.stringify({ c: code.code })).digest('hex');
const dataHash = '0x' + createHash('sha256').update(JSON.stringify({ shortCode })).digest('hex');
const txHash = '0x' + randomBytes(32).toString('hex');
await prisma.blockchainProof.create({
data: {
+8 -1
View File
@@ -343,7 +343,14 @@ export class BackupService {
await (tx as any)[model].deleteMany();
}
for (const model of MODELS) {
const rows = Array.isArray(db[model]) ? db[model].map(reviveRow) : [];
const rows = Array.isArray(db[model])
? db[model].map((row: unknown) => {
const revived = reviveRow(row as Record<string, any>) as Record<string, unknown>;
// 兼容移除第二套完整编码前生成的历史备份。
if (model === 'traceCode' || model === 'queryLog') delete revived.code;
return revived;
})
: [];
if (rows.length) await (tx as any)[model].createMany({ data: rows });
}
}, { timeout: 120000 });
@@ -60,7 +60,6 @@ export class AttestationService {
const summary = {
shortCode: code.shortCode,
code: code.code,
title: code.artwork.title,
artist: code.artwork.artist,
archiveNo: code.artwork.archiveNo,
@@ -22,7 +22,7 @@ function mockHttpsRequestOnce(responseJson: unknown, statusCode = 200) {
// 放在 jest.mock 之后导入,确保 provider 拿到被 mock 的 https
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { TianheProvider } = require('./tianhe.provider') as typeof import('./tianhe.provider');
const { TianheProvider, buildTianheExplorerTxUrl } = require('./tianhe.provider') as typeof import('./tianhe.provider');
describe('TianheProvider', () => {
const provider = new TianheProvider({
@@ -37,6 +37,16 @@ describe('TianheProvider', () => {
jest.restoreAllMocks();
});
it('按天河环境生成 DApp 浏览器交易详情地址', () => {
const txHash = '0xabc/123';
expect(buildTianheExplorerTxUrl('https://test.api.tichain.tianhecloud.com', txHash)).toBe(
'https://test.explorer.tianhecloud.com/#/tiChain/transDetail?hash=0xabc%2F123',
);
expect(
buildTianheExplorerTxUrl('https://custom-api.example.com', txHash, 'production'),
).toBe('https://explorer.tianhecloud.com/#/tiChain/transDetail?hash=0xabc%2F123');
});
it('按天河链 upload 文档映射交易哈希、存证链接和文件哈希', async () => {
const response = {
code: 0,
+11 -9
View File
@@ -71,6 +71,15 @@ function redactSecrets(obj: Record<string, unknown>): Record<string, unknown> {
return masked;
}
export function buildTianheExplorerTxUrl(baseUrl: string, txHash: string, environment?: string): string {
const testEnvironment =
environment === 'test' || (environment !== 'production' && baseUrl.toLowerCase().includes('test.'));
const explorerBase = testEnvironment
? 'https://test.explorer.tianhecloud.com'
: 'https://explorer.tianhecloud.com';
return `${explorerBase}/#/tiChain/transDetail?hash=${encodeURIComponent(txHash)}`;
}
export class TianheProvider implements AttestationProvider {
readonly name = 'tianhe';
private readonly logger = new Logger('TianheAPI');
@@ -89,16 +98,9 @@ export class TianheProvider implements AttestationProvider {
return required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
}
// 天河区块浏览器域名:测试 test.explorer.tianhecloud.com / 生产 explorer.tianhecloud.com(由 API base 是否含 test. 判定)
private explorerBase(): string {
return this.baseUrl().includes('test.')
? 'https://test.explorer.tianhecloud.com'
: 'https://explorer.tianhecloud.com';
}
// 交易详情页:客户凭 mint 交易哈希可查看状态/区块高度/追溯码(productId)/存证链接(feature),比裸 UDFS JSON 规范
// DApp 浏览器交易详情页使用 mint 交易哈希,不使用 API 地址或本地 dataHash。
explorerTxUrl(txHash: string): string {
return `${this.explorerBase()}/#/tiChain/transDetail?hash=${encodeURIComponent(txHash)}`;
return buildTianheExplorerTxUrl(this.baseUrl(), txHash);
}
private credentials() {
@@ -4,8 +4,10 @@ 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<{
@@ -32,6 +34,7 @@ export class PublicTraceService {
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly settings: SettingsService,
@Inject(REDIS_CLIENT) private readonly redis: Redis,
) {}
@@ -183,17 +186,17 @@ export class PublicTraceService {
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,
code: code.code,
queriedAt: now,
antiCounterfeit: {
firstQuery: firstActivate,
queryCount: updated.queryCount,
firstActivatedAt: updated.firstActivatedAt,
},
...this.buildArtworkPayload(artwork, code, proof),
...this.buildArtworkPayload(artwork, code, proof, explorerUrl),
};
}
@@ -235,10 +238,10 @@ export class PublicTraceService {
const now = new Date();
const firstQuery = state === 'inactive';
const explorerUrl = await this.resolveExplorerUrl(proof);
return {
status: 'OK' as const,
preview: true,
code: code.code,
queriedAt: now,
antiCounterfeit: firstQuery
? { firstQuery: true, queryCount: 1, firstActivatedAt: now }
@@ -247,7 +250,7 @@ export class PublicTraceService {
queryCount: code.queryCount > 0 ? code.queryCount : 2,
firstActivatedAt: code.firstActivatedAt ?? now,
},
...this.buildArtworkPayload(artwork, code, proof),
...this.buildArtworkPayload(artwork, code, proof, explorerUrl),
};
}
@@ -266,6 +269,7 @@ export class PublicTraceService {
tokenId: bigint | null;
contractAddress: string | null;
} | null,
explorerUrl: string | null,
) {
return {
artwork: {
@@ -291,7 +295,7 @@ export class PublicTraceService {
blockHeight: proof.blockHeight,
chainName: proof.chainName,
onchainAt: proof.onchainAt,
explorerUrl: proof.explorerUrl,
explorerUrl,
tokenId: proof.tokenId,
contractAddress: proof.contractAddress,
}
@@ -299,6 +303,18 @@ export class PublicTraceService {
};
}
private async resolveExplorerUrl(
proof: { txHash: string | null; chainName: string | null; explorerUrl: string | null } | null,
): Promise<string | null> {
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,
@@ -336,7 +352,6 @@ export class PublicTraceService {
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,
@@ -9,7 +9,7 @@ import { PaginationDto } from '../common/dto/pagination.dto';
import { buildOrderBy } from '../common/utils/sort.util';
class QueryLogQueryDto extends PaginationDto {
@ApiPropertyOptional({ description: '关键词(追溯码 / 完整编码 / 档案编号)' })
@ApiPropertyOptional({ description: '关键词(追溯码 / 档案编号)' })
@IsOptional()
@IsString()
keyword?: string;
@@ -53,7 +53,6 @@ export class QueryLogController {
if (query.keyword) {
where.OR = [
{ shortCode: { contains: query.keyword } },
{ code: { contains: query.keyword } },
{ archiveNo: { contains: query.keyword } },
];
}
@@ -71,7 +71,7 @@ export class QueryTraceCodeDto extends PaginationDto {
@IsInt()
groupId?: number;
@ApiPropertyOptional({ description: '关键词(追溯码/完整编码/档案号/作品名称)' })
@ApiPropertyOptional({ description: '关键词(追溯码/档案号/作品名称)' })
@IsOptional()
@IsString()
keyword?: string;
@@ -1,16 +1,12 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import { customAlphabet } from 'nanoid';
import { BatchStatus, JobStatus, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { JobsService } from '../jobs/jobs.service';
import { TraceCodeService } from './trace-code.service';
import { TraceCodeGeneratorService } from './trace-code-generator.service';
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const codeId = customAlphabet(ALPHABET, 18);
interface GenJobData {
batchId: number;
artworkId: number;
@@ -45,7 +41,6 @@ export class GenCodeProcessor extends WorkerHost {
const shortCodes = await this.generator.generate(n);
const rows = shortCodes.map((shortCode) => {
return {
code: codeId(),
shortCode,
artworkId,
batchId,
@@ -409,7 +409,6 @@ export class TraceCodeService {
and.push({
OR: [
{ shortCode: { contains: query.keyword } },
{ code: { contains: query.keyword } },
{ url: { contains: query.keyword } },
{ remark: { contains: query.keyword } },
{ artwork: { archiveNo: { contains: query.keyword } } },
@@ -508,7 +507,6 @@ export class TraceCodeService {
{ header: '批次编号', key: 'batchNo', width: 22 },
{ header: '分组', key: 'group', width: 14 },
{ header: '追溯码', key: 'shortCode', width: 16 },
{ header: '完整编码', key: 'code', width: 24 },
{ header: '链接', key: 'url', width: 40 },
{ header: '二维码', key: 'qr', width: 18 },
{ header: '生成时间', key: 'createdAt', width: 22 },
@@ -525,7 +523,6 @@ export class TraceCodeService {
title: c.artwork?.title ?? '',
batchNo: c.batch?.batchNo ?? '',
group: c.group?.name ?? '',
code: c.code,
shortCode: c.shortCode,
url: { text: url, hyperlink: url },
qr: '',
@@ -540,7 +537,7 @@ export class TraceCodeService {
qrImages.push({ name: `images/${c.shortCode}.png`, buffer: qr });
const imageId = wb.addImage({ buffer: qr as unknown as ExcelJS.Buffer, extension: 'png' });
ws.addImage(imageId, {
tl: { col: 7.15, row: row.number - 0.9 },
tl: { col: 6.15, row: row.number - 0.9 },
ext: { width: 84, height: 84 },
});
}