fix: 修正审查发现的出证重试、链上详情范围和手机保存证书问题

This commit is contained in:
Nixevol
2026-11-15 14:35:41 +08:00
parent d41c80a4b3
commit d1ade47864
26 changed files with 343 additions and 222 deletions
@@ -231,13 +231,6 @@ watch(
</script>
<style scoped>
.proof-link {
display: inline-flex;
align-items: center;
gap: 5px;
color: var(--brand);
text-decoration: none;
}
.unknown-alert {
margin-top: 12px;
}
-2
View File
@@ -690,8 +690,6 @@
"blockHeight": "Block Height",
"contract": "Contract Address",
"onchainAt": "On-chain Time",
"explorer": "Explorer",
"openExplorer": "Open Explorer",
"trigger": "Trigger On-chain",
"triggered": "On-chain task submitted",
"retry": "Retry On-chain",
-2
View File
@@ -690,8 +690,6 @@
"blockHeight": "区块高度",
"contract": "合约地址",
"onchainAt": "上链时间",
"explorer": "存证查询",
"openExplorer": "打开存证查询",
"trigger": "触发上链",
"triggered": "已提交上链任务",
"retry": "重新上链",
@@ -63,6 +63,32 @@ describe('Consumer certificate lifecycle', () => {
certificateNextCheck: null,
});
});
it('a connection reset during submit may have reached Tianhe, so it stays query-only', async () => {
const { service, row, prisma } = fixture();
const failure = new TypeError('fetch failed');
(failure as { cause?: unknown }).cause = Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' });
jest.spyOn(DepositProvider.prototype, 'submit').mockRejectedValue(failure);
await service.process(row);
expect(prisma.blockchainProof.updateMany.mock.calls[1][0].data.certificateState).toBe('WAITING');
});
it('re-applies with a new operation id only when the earlier request was never sent', async () => {
const { service, row, prisma } = fixture('FAILED');
row.certificateError = '暂时联系不上存证服务,证书没有生成。';
expect(await service.status('123456000001')).toMatchObject({ status: 'FAILED', retryable: true });
await service.request('123456000001');
const claim = prisma.blockchainProof.updateMany.mock.calls[0][0];
expect(claim.where).toEqual({ id: 1, certificateState: 'FAILED', certificateError: row.certificateError, status: 'ONCHAIN' });
expect(claim.data).toMatchObject({ certificateState: 'PENDING', certificateError: null, certificateAttempts: 0 });
expect(claim.data.certificateRequest.operateId).not.toBe('stable-op');
});
it('never re-applies after a rejection and does not return internal notes', async () => {
const { service, row, prisma } = fixture('FAILED');
row.certificateError = '存证提交被拒绝,请联系平台管理员';
const result = await service.request('123456000001');
expect(result).toMatchObject({ status: 'FAILED', retryable: false });
expect(JSON.stringify(result)).not.toContain('存证提交被拒绝');
expect(prisma.blockchainProof.updateMany).not.toHaveBeenCalled();
});
it('a submission timeout changes to query-only, preserving the exact operation id', async () => {
const { service, row, prisma } = fixture();
const submit = jest.spyOn(DepositProvider.prototype, 'submit').mockRejectedValue(new Error('timeout'));
@@ -19,8 +19,13 @@ interface CertificateRequest {
const ACTIVE_STATES = ['PENDING', 'SUBMITTING', 'WAITING', 'CHECKING'];
const MAX_CHECKS = 8;
// 这句话同时是“请求从未发出、可以重新申请”的标记,改动文字会让已有记录失去重试资格。
const UNREACHABLE_MESSAGE = '暂时联系不上存证服务,证书没有生成。';
/**
* 只认连接建立之前的失败,这时请求一定没有发出,重新申请不会重复扣费。
* 超时、连接被重置等情况下请求可能已经到达对方,不能算在内。
*/
function depositUnreachable(error: unknown) {
const texts: string[] = [];
let current: unknown = error;
@@ -30,7 +35,11 @@ function depositUnreachable(error: unknown) {
if (typeof code === 'string') texts.push(code);
current = (current as { cause?: unknown }).cause;
}
return /ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ECONNRESET/.test(texts.join(' '));
return /ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EHOSTUNREACH|ENETUNREACH|UND_ERR_CONNECT_TIMEOUT/.test(texts.join(' '));
}
function neverSent(proof: BlockchainProof) {
return proof.certificateState === 'FAILED' && !proof.certificateUrl && proof.certificateError === UNREACHABLE_MESSAGE;
}
@Injectable()
@@ -59,12 +68,12 @@ export class DepositCertificateService {
const certificate = request && proof.certificateState === 'READY'
? presentStoredCertificate(proof.certificateUrl, request.environment, request.address, request.text, await this.settings.get('certificateAuthorMode'), artist)
: null;
const status = proof.certificateState === 'READY' && !certificate ? 'FAILED' : proof.certificateState;
return {
status,
status: proof.certificateState === 'READY' && !certificate ? 'FAILED' : proof.certificateState,
generatedAt: proof.certificateGeneratedAt,
certificate: certificate && request ? { ...certificate, environment: request.environment } : certificate,
message: status === 'READY' ? null : proof.certificateError,
// 只告诉页面能否重新申请,内部处理说明不对外返回
retryable: neverSent(proof),
};
}
@@ -78,8 +87,8 @@ export class DepositCertificateService {
const { code, proof } = await this.eligible(shortCode);
if (proof.certificateState === 'READY') return this.view(proof, code.artwork.artist);
const settings = await this.settings.getAllRaw();
const retryUnreachable = proof.certificateState === 'FAILED' && !proof.certificateUrl && proof.certificateError === UNREACHABLE_MESSAGE;
if (proof.certificateState !== 'NONE' && !retryUnreachable) {
const retry = neverSent(proof);
if (proof.certificateState !== 'NONE' && !retry) {
// An uncertain submission is never submitted again. User action only resumes queries.
if (proof.certificateState === 'UNKNOWN' && (!proof.certificateNextCheck || proof.certificateNextCheck <= new Date())) {
await this.prisma.blockchainProof.updateMany({
@@ -119,10 +128,12 @@ export class DepositCertificateService {
// A single conditional write claims this item; concurrent callers cannot
// replace the winner's frozen evidence or operation id. No daily quota.
await this.prisma.blockchainProof.updateMany({
where: { id: proof.id, certificateState: retryUnreachable ? 'FAILED' : 'NONE', status: ProofStatus.ONCHAIN },
where: retry
? { id: proof.id, certificateState: 'FAILED', certificateError: UNREACHABLE_MESSAGE, status: ProofStatus.ONCHAIN }
: { id: proof.id, certificateState: 'NONE', status: ProofStatus.ONCHAIN },
data: {
certificateState: 'PENDING', certificateRequest: request as unknown as Prisma.InputJsonObject,
certificateError: null, certificateRequestedAt: now, certificateNextCheck: now,
certificateError: null, certificateAttempts: 0, certificateRequestedAt: now, certificateNextCheck: now,
},
});
return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }), code.artwork.artist);
@@ -1,18 +1,7 @@
import { certificateAuthorUrl, depositSignature, DepositProvider, DepositRejected, presentStoredCertificate, safeCertificateUrl } from './deposit.provider';
import { depositSignature, DepositProvider, DepositRejected, presentStoredCertificate, safeCertificateUrl } from './deposit.provider';
import { createHash } from 'crypto';
describe('V3 deposit protocol', () => {
it('sets only the author display name, preserves wallet and proof data, and falls back when the artist is missing', () => {
const original = 'https://test.tichain.tianhecloud.com/#/certificate?address=wallet&txHash=hash&digest=digest&depositContent=title';
const result = certificateAuthorUrl(original, 'ARTWORK_ARTIST', '黄志伟 & A');
const query = new URLSearchParams(new URL(result).hash.split('?')[1]);
expect(query.get('author')).toBe('黄志伟 & A');
expect(query.get('address')).toBe('wallet');
expect(query.get('txHash')).toBe('hash');
expect(query.get('digest')).toBe('digest');
expect(certificateAuthorUrl(result, 'WALLET')).toBe(original);
expect(certificateAuthorUrl(result, 'ARTWORK_ARTIST', '')).toBe(original);
});
afterEach(() => jest.restoreAllMocks());
it('signs parameters deterministically with the V3 prefix convention', () => {
expect(depositSignature('/v1/deposit/query', { operateId: 'x', address: 'y' }, {}, '1000', 'secret'))
@@ -20,7 +20,6 @@ export interface StoredCertificateView {
txHash: string;
author: string;
createdAt: string | null;
imageUrl?: string | null;
}
/** 公开页面只接收存证字段。天河链证书网址留在服务端,不进入浏览器。 */
@@ -50,16 +49,6 @@ export function safeCertificateUrl(value: unknown, environment: DepositEnvironme
export class DepositRejected extends Error {}
/** 官方证书页的显示参数;保留原address、digest和txHash,不改变存证身份。 */
export function certificateAuthorUrl(url: string, mode: string | null, artist?: string | null): string {
const parsed = new URL(url);
const params = new URLSearchParams(parsed.hash.slice('#/certificate?'.length));
if (mode === 'ARTWORK_ARTIST' && artist?.trim()) params.set('author', artist.trim());
else params.delete('author');
parsed.hash = '/certificate?' + params.toString();
return parsed.toString();
}
/** V3 uses signed headers and code=200, unlike the existing V2 provider. */
export class DepositProvider {
constructor(private readonly environment: DepositEnvironment, private readonly appId: string, private readonly appKey: string) {}
+46 -4
View File
@@ -1,5 +1,6 @@
import { parseChainDetail } from './chain-detail';
import { loadChainDetail, parseChainDetail, readStoredChainDetail } from './chain-detail';
const txHash = '0x' + 'a'.repeat(64);
const info = {
data: {
gasTxUsed: '3388899',
@@ -19,7 +20,8 @@ const receipt = {
describe('parseChainDetail', () => {
it('keeps gas, sender and logs and drops the raw input binary', () => {
const detail = parseChainDetail(info, receipt);
const detail = parseChainDetail(txHash, info, receipt);
expect(detail?.txHash).toBe(txHash);
expect(detail?.gasUsed).toBe('3388899');
expect(detail?.fromAddress).toBe('0x85aa7cdeba55cb08427018d066a26719b956ceff');
expect(detail?.logs).toHaveLength(1);
@@ -27,8 +29,48 @@ describe('parseChainDetail', () => {
expect(JSON.stringify(detail)).not.toContain('secret');
});
it('accepts numeric gas and token id from the explorer', () => {
const numeric = { data: { ...info.data, gasTxUsed: 66449, transactionDetail: [{ ...info.data.transactionDetail[0], tokenId: 4701 }] } };
const detail = parseChainDetail(txHash, numeric, receipt);
expect(detail?.gasUsed).toBe('66449');
expect(detail?.action?.tokenId).toBe('4701');
});
it('stays empty when gas, sender or logs are missing', () => {
expect(parseChainDetail({ data: { gasTxUsed: '', fromAddress: info.data.fromAddress } }, receipt)).toBeNull();
expect(parseChainDetail(info, { data: [] })).toBeNull();
expect(parseChainDetail(txHash, { data: { gasTxUsed: '', fromAddress: info.data.fromAddress } }, receipt)).toBeNull();
expect(parseChainDetail(txHash, info, { data: [] })).toBeNull();
});
});
describe('readStoredChainDetail', () => {
const stored = { chainDetail: parseChainDetail(txHash, info, receipt) };
it('returns the saved detail only for the transaction it was saved for', () => {
expect(readStoredChainDetail(stored, txHash)?.gasUsed).toBe('3388899');
expect(readStoredChainDetail(stored, '0x' + 'b'.repeat(64))).toBeNull();
expect(readStoredChainDetail(stored, null)).toBeNull();
});
it('ignores incomplete or missing snapshots', () => {
expect(readStoredChainDetail({ chainDetail: { txHash, gasUsed: '1', fromAddress: 'bad', logs: [] } }, txHash)).toBeNull();
expect(readStoredChainDetail({}, txHash)).toBeNull();
expect(readStoredChainDetail(null, txHash)).toBeNull();
});
});
describe('loadChainDetail', () => {
it('reads the transaction and its receipt from the explorer of the given environment', async () => {
const getter = jest.fn(async (url: string) => (url.includes('/receipt/info') ? receipt : info));
const detail = await loadChainDetail('production', txHash, null, getter);
expect(detail?.txHash).toBe(txHash);
expect(getter.mock.calls[0][0]).toBe(`https://explorer.tianhecloud.com/api/tichain-browser-new/transaction/info?txHash=${txHash}`);
expect(getter.mock.calls[1][0]).toBe(`https://explorer.tianhecloud.com/api/tichain-browser-new/receipt/info?hash=${txHash}&height=39944998`);
});
it('does not ask for a receipt when the block height is unknown', async () => {
const getter = jest.fn(async (_url: string) => ({ data: {} }));
expect(await loadChainDetail('test', txHash, null, getter)).toBeNull();
expect(getter).toHaveBeenCalledTimes(1);
expect(getter.mock.calls[0][0]).toContain('https://test.explorer.tianhecloud.com/');
});
});
+10 -5
View File
@@ -12,6 +12,8 @@ export interface ChainLogView {
}
export interface ChainDetail {
/** 这份详情属于哪笔交易;重新上链后旧详情不会被当成新交易的详情。 */
txHash: string;
gasUsed: string;
fromAddress: string;
toAddress: string;
@@ -27,19 +29,21 @@ export interface ChainDetail {
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
function text(value: unknown): string {
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
return typeof value === 'string' ? value.trim() : '';
}
export function readStoredChainDetail(raw: unknown): ChainDetail | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
export function readStoredChainDetail(raw: unknown, txHash: string | null | undefined): ChainDetail | null {
if (!txHash || !raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const detail = (raw as { chainDetail?: unknown }).chainDetail;
if (!detail || typeof detail !== 'object' || Array.isArray(detail)) return null;
const row = detail as ChainDetail;
if (row.txHash !== txHash) return null;
if (!row.gasUsed || !ADDRESS.test(row.fromAddress || '') || !Array.isArray(row.logs) || !row.logs.length) return null;
return row;
}
export function parseChainDetail(info: unknown, receipt: unknown): ChainDetail | null {
export function parseChainDetail(txHash: string, info: unknown, receipt: unknown): ChainDetail | null {
const data = info && typeof info === 'object' ? (info as { data?: unknown }).data : null;
if (!data || typeof data !== 'object') return null;
const row = data as Record<string, unknown>;
@@ -63,6 +67,7 @@ export function parseChainDetail(info: unknown, receipt: unknown): ChainDetail |
: {};
const action = Array.isArray(row.transactionDetail) ? row.transactionDetail[0] as Record<string, unknown> | undefined : undefined;
return {
txHash,
gasUsed,
fromAddress,
toAddress: text(row.toAddress),
@@ -87,7 +92,7 @@ export function parseChainDetail(info: unknown, receipt: unknown): ChainDetail |
};
}
export function explorerApiBase(environment: string): string {
function explorerApiBase(environment: string): string {
const host = environment === 'production' ? 'https://explorer.tianhecloud.com' : 'https://test.explorer.tianhecloud.com';
return `${host}/api/tichain-browser-new`;
}
@@ -99,7 +104,7 @@ export async function loadChainDetail(environment: string, txHash: string, block
const height = blockHeight || (infoData?.blockHeight == null ? '' : String(infoData.blockHeight));
if (!height) return null;
const receipt = await getter(`${base}/receipt/info?hash=${encodeURIComponent(txHash)}&height=${encodeURIComponent(height)}`);
return parseChainDetail(info, receipt);
return parseChainDetail(txHash, info, receipt);
}
async function defaultGet(url: string): Promise<unknown> {
@@ -121,6 +121,13 @@ describe('PublicTraceService draft visibility', () => {
await expect(service.outboundImages('482731000001', 1, 20, true)).resolves.toEqual({ status: 'INVALID' });
expect(prisma.outboundImage.findMany).not.toHaveBeenCalled();
});
it('does not look up chain detail for an item that is not publicly visible', async () => {
const { service, prisma } = createHarness();
await expect(service.captureChainDetail('482731000001')).resolves.toEqual({ complete: false, detail: null });
expect(prisma.blockchainProof.findUnique).not.toHaveBeenCalled();
});
});
describe('PublicTraceService outbound timeline visibility', () => {
@@ -423,7 +423,7 @@ export class PublicTraceService {
productId: mint?.productId ?? code.shortCode,
feature: mint?.feature ?? null,
mintTo: mint?.mintTo ?? null,
chainDetail: readStoredChainDetail(proof.rawResponse),
chainDetail: readStoredChainDetail(proof.rawResponse, proof.txHash),
submittedAt: proof.submittedAt,
failureReason: this.publicFailureReason(proof.status, proof.failureReason),
}
@@ -442,21 +442,42 @@ export class PublicTraceService {
}
private async captureChainDetailOnce(shortCode: string) {
if (!TRACE_CODE_PATTERN.test(shortCode)) return { complete: false, detail: null };
const code = await this.prisma.traceCode.findUnique({ where: { shortCode }, select: { id: true } });
if (!code) return { complete: false, detail: null };
const none = { complete: false, detail: null };
if (!TRACE_CODE_PATTERN.test(shortCode)) return none;
const code = await this.prisma.traceCode.findUnique({
where: { shortCode },
select: { id: true, status: true, artwork: { select: { status: true, auditStatus: true, deletedAt: true } } },
});
// 与公开溯源页同一可见范围:未激活、停用、未审核或已删除的实物不提供链上详情
if (
!code ||
code.status !== TraceCodeStatus.ACTIVE ||
code.artwork.deletedAt ||
code.artwork.status !== ArtworkStatus.ACTIVE ||
code.artwork.auditStatus !== AuditStatus.APPROVED
) {
return none;
}
const proof = await this.prisma.blockchainProof.findUnique({ where: { traceCodeId: code.id } });
const stored = readStoredChainDetail(proof?.rawResponse);
// 只在确认上链之后补存:确认任务此前还会改写 rawResponse,提前写入会互相覆盖
if (!proof?.txHash || proof.status !== ProofStatus.ONCHAIN || proof.chainName !== '天河链') return none;
const stored = readStoredChainDetail(proof.rawResponse, proof.txHash);
if (stored) return { complete: true, detail: stored };
if (!proof?.txHash || proof.chainName !== '天河链') return { complete: false, detail: null };
const environment = await this.settings.get('tianheEnv');
const detail = await loadChainDetail(environment || 'test', proof.txHash, proof.blockHeight == null ? null : proof.blockHeight.toString());
if (!detail) return { complete: false, detail: null };
const detail = await loadChainDetail(
environment || 'test',
proof.txHash,
proof.blockHeight == null ? null : proof.blockHeight.toString(),
).catch((error: unknown) => {
this.logger.warn(`链上详情暂时查询不到: ${(error as Error).message}`);
return null;
});
if (!detail) return none;
const current = proof.rawResponse && typeof proof.rawResponse === 'object' && !Array.isArray(proof.rawResponse)
? proof.rawResponse as Record<string, unknown>
: {};
await this.prisma.blockchainProof.update({
where: { id: proof.id },
await this.prisma.blockchainProof.updateMany({
where: { id: proof.id, txHash: proof.txHash, status: ProofStatus.ONCHAIN },
data: { rawResponse: { ...current, chainDetail: detail } as unknown as Prisma.InputJsonValue },
});
return { complete: true, detail };
+6 -1
View File
@@ -1,3 +1,8 @@
<template>
<router-view />
<!-- 保留溯源页:从存证详情或证书页返回时不重新查询,不会多记一次防伪查询次数 -->
<router-view v-slot="{ Component }">
<keep-alive include="Trace" :max="1">
<component :is="Component" />
</keep-alive>
</router-view>
</template>
+3 -2
View File
@@ -77,10 +77,11 @@ export interface TraceCertificateResult {
status: 'NONE' | 'PENDING' | 'SUBMITTING' | 'CHECKING' | 'WAITING' | 'READY' | 'UNKNOWN' | 'FAILED';
generatedAt: string | null;
certificate: TraceCertificateRecord | null;
message?: string | null;
/** 上次申请根本没有发出去,可以重新申请 */
retryable?: boolean;
}
export function requestTraceCertificate(shortCode: string): Promise<TraceCertificateResult> {
return instance.post(`/public/trace/${encodeURIComponent(shortCode)}/certificate`, {}, { timeout: 90_000 }) as unknown as Promise<TraceCertificateResult>;
return instance.post(`/public/trace/${encodeURIComponent(shortCode)}/certificate`, {}) as unknown as Promise<TraceCertificateResult>;
}
export function fetchTraceCertificate(shortCode: string): Promise<TraceCertificateResult> {
return instance.get(`/public/trace/${encodeURIComponent(shortCode)}/certificate`) as unknown as Promise<TraceCertificateResult>;
@@ -73,6 +73,7 @@
import { computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { ChainDetail } from '@/api';
import { writeProofCache } from './proofCache';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
@@ -115,8 +116,7 @@ const router = useRouter();
const canViewCertificate = computed(() => props.blockchain?.status === 'ONCHAIN' && Boolean(props.blockchain.txHash) && props.blockchain.chainName === '天河链');
function openProof() {
const key = `artveris.trace.proof.${props.preview ? 'preview.' : ''}${props.shortCode}`;
sessionStorage.setItem(key, JSON.stringify(props.blockchain || null));
writeProofCache(props.shortCode, props.preview === true, props.blockchain);
router.push({
name: props.preview ? 'trace-preview-proof' : 'trace-proof',
params: { code: props.shortCode },
@@ -71,33 +71,30 @@ const created = computed(() => {
onMounted(async () => {
const host = props.record.environment === 'test' ? 'https://test.explorer.tianhecloud.com' : 'https://explorer.tianhecloud.com';
// 按 4 倍像素生成,页面仍显示 88px,导出的大图里二维码才清晰
qrUrl.value = await QRCode.toDataURL(`${host}/#/tiChain/transDetail?hash=${props.record.txHash}`, {
width: 88,
width: 352,
margin: 0,
errorCorrectionLevel: 'H',
color: { dark: '#000000', light: '#ffffff' },
});
});
async function download() {
/** 把证书画成 3 倍大图。页面上的证书可能被缩小显示,所以用一份原尺寸的副本来画。 */
async function render(): Promise<HTMLCanvasElement> {
const target = sheet.value;
if (!target) return;
if (!target) throw new Error('certificate is not ready');
const host = document.createElement('div');
host.style.cssText = 'position:fixed;left:-10000px;top:0;width:508px;height:720px;';
const clone = target.cloneNode(true) as HTMLElement;
host.appendChild(clone);
host.appendChild(target.cloneNode(true));
document.body.appendChild(host);
try {
const { default: html2canvas } = await import('html2canvas');
const canvas = await html2canvas(clone, { scale: 3, backgroundColor: '#e0e0e0', useCORS: true });
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = `${Date.now()}.png`;
link.click();
return await html2canvas(host.firstElementChild as HTMLElement, { scale: 3, backgroundColor: '#e0e0e0' });
} finally {
host.remove();
}
}
defineExpose({ download });
defineExpose({ render });
</script>
@@ -1,9 +1,6 @@
<template>
<div class="tx-page">
<div class="tx-top">
<h3 v-if="showHeading">{{ t('chain.txTitle') }}</h3>
<div class="tx-hashbox">{{ txHash || '-' }}</div>
</div>
<div class="tx-hashbox">{{ txHash || '-' }}</div>
<section class="tx-card">
<div class="tx-tabs" role="tablist">
<button type="button" role="tab" :class="{ active: tab === 'info' }" :aria-selected="tab === 'info'" @click="tab = 'info'">{{ t('chain.txInfo') }}</button>
@@ -118,35 +115,30 @@
</div>
<div v-else class="tx-panel" role="tabpanel">
<p v-if="!detail?.logs?.length" class="tx-empty">{{ t('chain.txLogsEmpty') }}</p>
<template v-else>
<article v-for="(log, logIndex) in detail.logs" :key="logIndex" class="tx-log">
<div class="tx-row">
<span>Address</span>
<div class="tx-value"><span class="tx-addr">{{ log.address }}</span></div>
</div>
<div class="tx-row">
<span>Name</span>
<div class="tx-value"><b>{{ log.name }}</b></div>
</div>
<div class="tx-row">
<span>Topics</span>
<div class="tx-value">
<div v-for="(topic, index) in log.topics" :key="index" class="tx-topic">
<i>[{{ index }}]</i>
<span class="mono">{{ topic }}</span>
</div>
<article v-for="(log, logIndex) in detail?.logs || []" :key="logIndex" class="tx-log">
<div class="tx-row">
<span>Address</span>
<div class="tx-value"><span class="tx-addr">{{ log.address }}</span></div>
</div>
<div class="tx-row">
<span>Name</span>
<div class="tx-value"><b>{{ log.name }}</b></div>
</div>
<div class="tx-row">
<span>Topics</span>
<div class="tx-value">
<div v-for="(topic, index) in log.topics" :key="index" class="tx-topic">
<i>[{{ index }}]</i>
<span class="mono">{{ topic }}</span>
</div>
</div>
<div class="tx-row">
<span>Data</span>
<div class="tx-value"><b class="mono">{{ log.data || '0x' }}</b></div>
</div>
</article>
</template>
</div>
<div class="tx-row">
<span>Data</span>
<div class="tx-value"><b class="mono">{{ log.data || '0x' }}</b></div>
</div>
</article>
</div>
<button v-if="showClose" type="button" class="tx-back" @click="$emit('close')">{{ t('chain.txBack') }}</button>
</section>
</div>
</template>
@@ -167,7 +159,7 @@ const CopyIcon = defineComponent({
},
});
const props = withDefaults(defineProps<{
const props = defineProps<{
txHash?: string | null;
succeeded: boolean;
statusText: string;
@@ -180,10 +172,8 @@ const props = withDefaults(defineProps<{
feature?: string | null;
mintTo?: string | null;
detail?: ChainDetail | null;
showHeading?: boolean;
showClose?: boolean;
}>(), { showHeading: true, showClose: true });
defineEmits<{ (event: 'copy', value: string): void; (event: 'close'): void }>();
}>();
defineEmits<{ (event: 'copy', value: string): void }>();
const { t } = useI18n();
const tab = ref<'info' | 'logs'>('info');
const shownBlock = computed(() => props.detail?.blockHeight || props.blockHeight);
@@ -211,9 +201,7 @@ const inputs = computed(() => props.detail?.inputs?.length
<style scoped>
.tx-page { background: #f4f6fa; color: #1f2a37; border-radius: 12px; padding: 18px 18px 22px; }
.tx-top { display: flex; justify-content: space-between; gap: 16px; align-items: center; margin-bottom: 14px; }
.tx-top h3 { margin: 0; font-size: 18px; font-weight: 600; }
.tx-hashbox { max-width: 420px; flex: 1; border: 1px solid #e3e8f0; background: #fff; border-radius: 999px; padding: 7px 14px; color: #667085; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tx-hashbox { max-width: 420px; margin: 0 0 14px; border: 1px solid #e3e8f0; background: #fff; border-radius: 999px; padding: 7px 14px; color: #667085; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tx-card { background: #fff; border: 1px solid #e6ebf2; border-radius: 10px; padding: 8px 22px 22px; }
.tx-tabs { display: flex; gap: 22px; border-bottom: 1px solid #edf1f6; }
.tx-tabs button { border: 0; background: transparent; padding: 12px 0; color: #667085; font: inherit; cursor: pointer; }
@@ -235,14 +223,12 @@ th, td { border-bottom: 1px solid #f2f4f8; text-align: left; padding: 8px 6px; v
th { color: #667085; font-weight: 500; }
.tx-cell { word-break: break-all; white-space: pre-wrap; }
.tx-topic { display: flex; gap: 8px; align-items: flex-start; width: 100%; padding: 3px 0; }
.tx-topic i, .tx-topic em { color: #98a2b3; font-style: normal; flex: none; }
.tx-topic i { color: #98a2b3; font-style: normal; flex: none; }
.mono { font-family: Consolas, 'SFMono-Regular', monospace; word-break: break-all; }
.tx-back { margin-top: 18px; border: 0; background: #3b6cff; color: #fff; border-radius: 6px; padding: 8px 18px; font: inherit; cursor: pointer; }
.tx-empty { margin: 18px 0; color: #98a2b3; font-size: 14px; }
@media (max-width: 720px) {
.tx-page { padding: 12px; }
.tx-top, .tx-row { display: block; }
.tx-hashbox { max-width: none; margin-top: 10px; }
.tx-row { display: block; }
.tx-hashbox { max-width: none; }
.tx-row > span { display: block; margin-bottom: 6px; }
.tx-card { padding: 8px 12px 16px; }
}
+2 -2
View File
@@ -28,9 +28,9 @@ export function openTraceViewer(items: PublicMediaItem[], index: number): void {
export function safeTraceUrl(value?: string): string {
const url = traceMediaUrl(value);
if (!/^(https?:\/\/|\/)/i.test(url)) return '';
if (url.startsWith('/')) return url;
try {
if (/(^|\.)tianhecloud\.com$/i.test(new URL(url).hostname)) return '';
// 以当前站点为基准解析,“//域名/路径”这种写法也会按真实域名判断
if (/(^|\.)tianhecloud\.com$/i.test(new URL(url, window.location.origin).hostname)) return '';
} catch {
return '';
}
@@ -0,0 +1,24 @@
/**
* 溯源页把已拿到的区块链信息带给存证详情页,详情页不必为此再查一次溯源接口
* (每查一次都会计入防伪查询次数)。浏览器不允许使用存储时静默跳过,详情页会自行查询。
*/
function key(code: string, preview: boolean): string {
return `artveris.trace.proof.${preview ? 'preview.' : ''}${code}`;
}
export function writeProofCache(code: string, preview: boolean, value: unknown): void {
try {
sessionStorage.setItem(key(code, preview), JSON.stringify(value ?? null));
} catch {
// 存储不可用
}
}
export function readProofCache<T>(code: string, preview: boolean): T | null {
try {
const raw = sessionStorage.getItem(key(code, preview));
return raw ? (JSON.parse(raw) as T) : null;
} catch {
return null;
}
}
+4 -8
View File
@@ -59,8 +59,6 @@
"contract": "Contract",
"blockHeight": "Block Height",
"onchainAt": "On-chain Time",
"blockHash": "Block Hash",
"proofTitle": "Transaction",
"txTitle": "Transaction",
"txInfo": "Details",
"txLogs": "Logs",
@@ -80,7 +78,6 @@
"txBack": "Back",
"txGas": "Gas used",
"txSender": "Sender",
"txLogsEmpty": "",
"explorer": "View Proof",
"copy": "Copy",
"copied": "Copied",
@@ -90,16 +87,15 @@
"certificateRequestFailed": "Unable to request a certificate. Please try later or contact the platform.",
"certificateCheckAgain": "Check again",
"certificateFailed": "The attestation request was rejected. Please contact the platform.",
"certificateUnreachable": "The attestation service could not be reached, so no certificate was created. Please check again.",
"certificateUnavailable": "Unable to check the certificate. Please try again later.",
"certificateRetrieving": "Retrieving attestation details",
"certificateAcquiring": "Preparing your certificate",
"certificatePreparing": "Assembling your certificate",
"certificateDelayed": "This certificate is not ready yet, so there is no image. Certificates that are already generated open immediately. You can check again later.",
"certificateContent": "Attestation text",
"certificateDigest": "Digest",
"certificateAuthor": "Author",
"certificateTime": "Created",
"certificateDelayed": "Your certificate is still being prepared. Please check again later.",
"certificateDownload": "Download certificate",
"certificateDownloadFailed": "The certificate image could not be created. Please try again.",
"certificateSaveHint": "Press and hold to save",
"certificateChainId": "TiChain block ID",
"certificateChainIdTip": "This is the block transaction ID generated when the evidence was recorded. It can be used to look up the file hash on TiChain.",
"certificateDigestTitle": "SHA256 digest",
+5 -9
View File
@@ -59,8 +59,6 @@
"contract": "合约地址",
"blockHeight": "区块高度",
"onchainAt": "上链时间",
"blockHash": "区块哈希",
"proofTitle": "交易详情",
"txTitle": "交易详情",
"txInfo": "交易信息",
"txLogs": "日志",
@@ -80,7 +78,6 @@
"txBack": "返回",
"txGas": "Gas花费",
"txSender": "发送方",
"txLogsEmpty": "",
"explorer": "查看存证",
"copy": "复制",
"copied": "已复制",
@@ -89,17 +86,16 @@
"certificatePreview": "预览模式不生成证书。",
"certificateRequestFailed": "暂时无法生成证书,请稍后再试或联系平台。",
"certificateCheckAgain": "重新查询",
"certificateFailed": "暂时联系不上存证服务,证书没有生成。",
"certificateFailed": "存证申请未成功,请联系平台处理。",
"certificateUnreachable": "暂时联系不上存证服务,证书没有生成,请重新查询。",
"certificateUnavailable": "暂时无法查询证书,请稍后重试。",
"certificateRetrieving": "正在调取存证数据",
"certificateAcquiring": "获取存证证书",
"certificatePreparing": "正在整理存证证书",
"certificateDelayed": "这件证书还没有生成完成,所以暂时没有图片。已经生成过的证书会直接打开,也可以稍后再查。",
"certificateContent": "存证内容",
"certificateDigest": "摘要",
"certificateAuthor": "作者",
"certificateTime": "生成时间",
"certificateDelayed": "证书还在生成中,请稍后再查。",
"certificateDownload": "下载存证证书",
"certificateDownloadFailed": "证书图片没有生成成功,请再试一次。",
"certificateSaveHint": "请长按保存",
"certificateChainId": "天河链-区块链ID",
"certificateChainIdTip": "该字符串是证据上链过程中生成的区块交易ID值,通过此ID可以在天河链上查询到文件hash的上链信息。",
"certificateDigestTitle": "电子证据SHA256值",
+2
View File
@@ -2,6 +2,8 @@ import { createRouter, createWebHashHistory } from 'vue-router';
export default createRouter({
history: createWebHashHistory(),
// 进入新页面从顶部开始;返回时回到离开前的位置
scrollBehavior: (_to, _from, saved) => saved || { top: 0 },
routes: [
{ path: '/', component: () => import('@/views/Home.vue') },
{ path: '/trace/:code/proof', name: 'trace-proof', component: () => import('@/views/TraceProof.vue') },
+96 -56
View File
@@ -3,51 +3,56 @@
<header class="subpage-bar">
<button type="button" class="subpage-back" @click="back">{{ t('chain.txBack') }}</button>
<h1>{{ t('chain.certificateView') }}</h1>
<button v-if="certificateRecord" type="button" class="des-download" @click="certificateSheet?.download()">
<button v-if="certificateRecord" type="button" class="des-download" :disabled="saving" @click="save">
{{ t('chain.certificateDownload') }}
</button>
</header>
<div class="subpage-body">
<p v-if="preview" class="subpage-note">{{ t('chain.certificatePreview') }}</p>
<template v-else>
<p v-if="certificateError" class="subpage-note" role="alert">{{ certificateError }}</p>
<button v-if="certificateError && retryable" type="button" class="subpage-action" @click="load(true)">
<template v-else-if="certificateError">
<p class="subpage-note" role="alert">{{ certificateError }}</p>
<button v-if="retryable" type="button" class="subpage-action" @click="load(true)">
{{ t('chain.certificateCheckAgain') }}
</button>
<template v-else-if="certificateRecord">
<section class="prove-des">
<h2 class="des-title">
{{ t('chain.certificateChainId') }}
<button type="button" class="des-tip" :aria-label="t('chain.certificateChainId')" @click.stop="toggleTip('tx')">
<TipIcon />
<span class="des-pop" :class="{ open: tip === 'tx' }" role="tooltip">{{ t('chain.certificateChainIdTip') }}</span>
</button>
</h2>
<p class="des-hash">{{ certificateRecord.txHash }}</p>
<h2 class="des-title">
{{ t('chain.certificateDigestTitle') }}
<button type="button" class="des-tip" :aria-label="t('chain.certificateDigestTitle')" @click.stop="toggleTip('digest')">
<TipIcon />
<span class="des-pop" :class="{ open: tip === 'digest' }" role="tooltip">{{ t('chain.certificateDigestTip') }}</span>
</button>
</h2>
<p class="des-digest">{{ certificateRecord.digest }}</p>
</section>
<div ref="stage" class="cert-stage" :style="{ height: `${720 * scale}px` }">
<div class="cert-fit" :style="{ transform: `scale(${scale})` }">
<trace-certificate-sheet ref="certificateSheet" :record="certificateRecord" />
</div>
</template>
<template v-else-if="certificateRecord">
<p v-if="saveFailed" class="subpage-note" role="alert">{{ t('chain.certificateDownloadFailed') }}</p>
<section class="prove-des">
<h2 class="des-title">
{{ t('chain.certificateChainId') }}
<button type="button" class="des-tip" :aria-label="t('chain.certificateChainId')" @click.stop="toggleTip('tx')">
<TipIcon />
<span class="des-pop" :class="{ open: tip === 'tx' }" role="tooltip">{{ t('chain.certificateChainIdTip') }}</span>
</button>
</h2>
<p class="des-hash">{{ certificateRecord.txHash }}</p>
<h2 class="des-title">
{{ t('chain.certificateDigestTitle') }}
<button type="button" class="des-tip" :aria-label="t('chain.certificateDigestTitle')" @click.stop="toggleTip('digest')">
<TipIcon />
<span class="des-pop" :class="{ open: tip === 'digest' }" role="tooltip">{{ t('chain.certificateDigestTip') }}</span>
</button>
</h2>
<p class="des-digest">{{ certificateRecord.digest }}</p>
</section>
<div ref="stage" class="cert-stage" :style="{ height: `${720 * scale}px` }">
<div class="cert-fit" :style="{ transform: `scale(${scale})` }">
<trace-certificate-sheet ref="certificateSheet" :record="certificateRecord" />
</div>
</template>
<div v-else class="subpage-wait">
<div class="certificate-spinner" aria-hidden="true" />
<ol class="certificate-steps">
<li v-for="(key, index) in certificateSteps" :key="key" :class="{ current: certificatePhase === index, done: certificatePhase > index }">
<span aria-hidden="true">{{ certificatePhase > index ? '✓' : index + 1 }}</span>{{ t(key) }}
</li>
</ol>
</div>
</template>
<div v-else class="subpage-wait">
<div class="certificate-spinner" aria-hidden="true" />
<ol class="certificate-steps">
<li v-for="(key, index) in certificateSteps" :key="key" :class="{ current: certificatePhase === index, done: certificatePhase > index }">
<span aria-hidden="true">{{ certificatePhase > index ? '✓' : index + 1 }}</span>{{ t(key) }}
</li>
</ol>
</div>
</div>
<div v-if="savedImage" class="save-view" @click="savedImage = ''">
<img :src="savedImage" alt="" />
<p v-if="saveHint" class="save-hint"><span>{{ t('chain.certificateSaveHint') }}</span></p>
</div>
</div>
</template>
@@ -76,7 +81,7 @@ const code = String(route.params.code || '');
const certificateError = ref('');
const certificatePhase = ref(0);
const certificateRecord = ref<TraceCertificateRecord | null>(null);
const certificateSheet = ref<{ download: () => Promise<void> }>();
const certificateSheet = ref<{ render: () => Promise<HTMLCanvasElement> }>();
const retryable = ref(true);
const certificateSteps = ['chain.certificateRetrieving', 'chain.certificateAcquiring', 'chain.certificatePreparing'];
const certificatePollMs = 5000;
@@ -84,15 +89,18 @@ const certificateWaitMs = 60_000;
const stage = ref<HTMLElement>();
const scale = ref(1);
const tip = ref('');
const saving = ref(false);
const saveFailed = ref(false);
const savedImage = ref('');
const saveHint = ref(false);
let certificateTimer: ReturnType<typeof setTimeout> | undefined;
let hintTimer: ReturnType<typeof setTimeout> | undefined;
let certificateRun = 0;
let certificatePolls = 0;
let observer: ResizeObserver | undefined;
function back() {
const name = preview ? 'trace-preview' : 'trace';
if (window.history.state?.back) router.back();
else router.push({ name, params: { code }, query: route.query });
else router.replace({ name: preview ? 'trace-preview' : 'trace', params: { code }, query: route.query });
}
function failCertificate(messageKey: string, canRetry = true) {
certificateError.value = t(messageKey);
@@ -108,16 +116,17 @@ async function showCertificateResult(result: TraceCertificateResult, run: number
return;
}
if (result.status === 'FAILED') {
certificateError.value = result.message || t('chain.certificateFailed');
retryable.value = true;
return;
// 只有请求从未发出的失败才能重新申请,其余失败重试也不会有结果
return result.retryable
? failCertificate('chain.certificateUnreachable')
: failCertificate('chain.certificateFailed', false);
}
if (result.status === 'UNKNOWN') return failCertificate('chain.certificateDelayed');
if (result.status === 'NONE') return failCertificate('chain.certificateUnavailable');
certificatePhase.value = 1;
if (++certificatePolls > certificateWaitMs / certificatePollMs) return failCertificate('chain.certificateDelayed');
certificateTimer = setTimeout(async () => {
try { showCertificateResult(await fetchTraceCertificate(code), run); }
try { await showCertificateResult(await fetchTraceCertificate(code), run); }
catch { if (run === certificateRun) failCertificate('chain.certificateUnavailable'); }
}, certificatePollMs);
}
@@ -137,11 +146,37 @@ async function load(retry = false) {
certificatePhase.value = 1;
const result = retry || cached.status === 'NONE' || cached.status === 'UNKNOWN'
? await requestTraceCertificate(code) : cached;
showCertificateResult(result, run);
await showCertificateResult(result, run);
} catch {
if (run === certificateRun) failCertificate('chain.certificateRequestFailed');
}
}
async function save() {
if (saving.value || !certificateSheet.value) return;
saving.value = true;
saveFailed.value = false;
try {
const canvas = await certificateSheet.value.render();
// 与天河链证书页相同:手机上不能直接下载文件,改为显示图片由用户长按保存
if (document.body.clientWidth <= 768) {
savedImage.value = canvas.toDataURL('image/jpeg');
saveHint.value = true;
if (hintTimer) clearTimeout(hintTimer);
hintTimer = setTimeout(() => (saveHint.value = false), 2500);
return;
}
const link = document.createElement('a');
link.href = canvas.toDataURL('image/png');
link.download = `${Date.now()}.png`;
document.body.appendChild(link);
link.click();
link.remove();
} catch {
saveFailed.value = true;
} finally {
saving.value = false;
}
}
function toggleTip(name: string) {
if (window.matchMedia('(hover: hover) and (pointer: fine)').matches) return;
tip.value = tip.value === name ? '' : name;
@@ -152,26 +187,28 @@ function measure() {
}
onMounted(() => {
load();
observer = new ResizeObserver(measure);
observer.observe(document.documentElement);
window.addEventListener('resize', measure);
});
onUnmounted(() => {
certificateRun += 1;
if (certificateTimer) clearTimeout(certificateTimer);
observer?.disconnect();
if (hintTimer) clearTimeout(hintTimer);
window.removeEventListener('resize', measure);
});
</script>
<style scoped>
.subpage { max-width: 560px; margin: 0 auto; min-height: 100vh; background: var(--bg); }
.subpage-bar { position: sticky; top: 0; z-index: 8; display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 12px; background: var(--card-bg); border-bottom: 1px solid var(--border); flex-wrap: nowrap; }
.prove-des { margin: 4px 0 16px; text-align: left; color: #333; }
.subpage-bar { position: sticky; top: 0; z-index: 8; display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 12px; background: var(--card-bg); border-bottom: 1px solid var(--border); }
.subpage-bar h1 { flex: 1; min-width: 0; margin: 0; font-size: 16px; font-weight: 600; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.subpage-back, .subpage-action { border: 0; background: transparent; color: var(--brand-2); font: inherit; font-size: 14px; cursor: pointer; padding: 6px 0; }
.subpage-action { background: var(--brand); color: #fff; border-radius: 6px; padding: 8px 12px; }
.subpage-bar h1 { flex: 1; min-width: 0; margin: 0; font-size: 16px; font-weight: 600; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.des-title { display: flex; align-items: center; margin: 20px 0 12px; padding: 0 8px; border-left: 3px solid #2977f0; font-family: PingFang-SC-Bold, 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 14px; font-weight: 700; line-height: 20px; color: #333; letter-spacing: 0.14px; }
.subpage-body { padding: 12px 12px 28px; }
.subpage-note { margin: 12px 0; font-size: 14px; line-height: 1.6; }
.prove-des { margin: 4px 0 16px; text-align: left; }
.des-title { display: flex; align-items: center; margin: 20px 0 12px; padding: 0 8px; border-left: 3px solid #2977f0; font-family: PingFang-SC-Bold, 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 14px; font-weight: 700; line-height: 20px; color: var(--text); letter-spacing: 0.14px; }
.des-title:first-child { margin-top: 0; }
.des-tip { position: relative; display: inline-flex; margin-left: 4px; padding: 0; border: 0; background: transparent; color: #333; cursor: pointer; }
.des-tip { position: relative; display: inline-flex; margin-left: 4px; padding: 0; border: 0; background: transparent; color: inherit; cursor: pointer; }
.des-pop { display: none; position: absolute; left: calc(100% + 8px); top: 50%; z-index: 6; width: 200px; transform: translateY(-50%); box-sizing: border-box; padding: 12px; border: 1px solid #ebeef5; border-radius: 4px; background: #fff; color: #606266; font-family: PingFangSC-Regular, 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 14px; font-weight: 400; line-height: 1.4; letter-spacing: 0; text-align: left; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); }
.des-pop.open { display: block; }
@media (hover: hover) and (pointer: fine) {
@@ -179,16 +216,19 @@ onUnmounted(() => {
}
.des-hash, .des-digest { margin: 0 0 20px; font-family: PingFangSC-Regular, 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 14px; font-weight: 400; line-height: normal; letter-spacing: 0.14px; text-align: left; word-break: break-all; }
.des-hash { margin-bottom: 0; color: #2977f0; }
.des-digest { color: #666; word-break: break-word; }
.des-download { flex: none; min-width: 112px; height: 36px; padding: 6px 16px; border: 1px solid #2977f0; border-radius: 4px; background: #fff; color: #2977f0; font-family: PingFangSC-Regular, 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 14px; font-weight: 500; line-height: 14px; cursor: pointer; }
.des-digest { color: var(--muted); }
.des-download { flex: none; min-width: 112px; height: 36px; padding: 6px 16px; border: 1px solid #2977f0; border-radius: 4px; background: var(--card-bg); color: #2977f0; font-family: PingFangSC-Regular, 'PingFang SC', 'Microsoft YaHei', sans-serif; font-size: 14px; font-weight: 500; line-height: 14px; cursor: pointer; }
.des-download:hover { background: rgba(41, 119, 240, 0.06); }
.des-download:disabled { opacity: 0.6; cursor: default; }
@media (max-width: 420px) {
.des-pop { left: 0; top: calc(100% + 6px); transform: none; }
}
.subpage-body { padding: 12px 12px 28px; }
.subpage-note { margin: 12px 0; font-size: 14px; line-height: 1.6; }
.cert-stage { position: relative; width: 100%; margin: 0 auto; }
.cert-fit { position: absolute; left: 50%; top: 0; width: 508px; margin-left: -254px; transform-origin: top center; }
.save-view { position: fixed; inset: 0; z-index: 2048; display: flex; overflow: hidden; background: #303030; }
.save-view img { display: block; max-width: 100%; max-height: 100%; margin: auto; }
.save-hint { position: absolute; left: 0; bottom: 120px; width: 100%; margin: 0; text-align: center; pointer-events: none; }
.save-hint span { padding: 4px 8px; border-radius: 4px; background: rgba(90, 90, 90, 0.4); color: #fff; font-size: 20px; }
.subpage-wait { padding: 12px 4px 24px; }
.certificate-spinner { width: 28px; height: 28px; border: 3px solid var(--border); border-top-color: var(--brand); border-radius: 50%; margin: 0 auto 24px; animation: certificate-spin .8s linear infinite; }
.certificate-steps { list-style: none; padding: 0; margin: 0; display: grid; gap: 18px; font-size: 14px; }
+10 -20
View File
@@ -14,7 +14,7 @@
<trace-tx-detail
v-else
:tx-hash="blockchain?.txHash"
:succeeded="blockchain?.status === 'ONCHAIN'"
:succeeded="status === 'ONCHAIN'"
:status-text="t(`chain.statuses.${status}`)"
:block-height="blockchain?.blockHeight"
:contract-address="blockchain?.contractAddress"
@@ -25,10 +25,7 @@
:feature="blockchain?.feature"
:mint-to="blockchain?.mintTo"
:detail="blockchain?.chainDetail"
:show-heading="false"
:show-close="false"
@copy="copy"
@close="back"
/>
<transition name="toast">
<div v-if="toast" class="toast">{{ toast }}</div>
@@ -42,6 +39,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { fetchChainDetail, fetchTrace, fetchTracePreview, type ChainDetail } from '@/api';
import TraceTxDetail from '@/components/trace/TraceTxDetail.vue';
import { readProofCache, writeProofCache } from '@/components/trace/proofCache';
type ProofBlockchain = {
status?: string;
@@ -68,13 +66,9 @@ const blockchain = ref<ProofBlockchain | null>(null);
const toast = ref('');
const status = computed(() => blockchain.value?.status || 'ONCHAIN');
function storageKey() {
return `artveris.trace.proof.${preview ? 'preview.' : ''}${code}`;
}
function back() {
const name = preview ? 'trace-preview' : 'trace';
if (window.history.state?.back) router.back();
else router.push({ name, params: { code }, query: route.query });
else router.replace({ name: preview ? 'trace-preview' : 'trace', params: { code }, query: route.query });
}
async function copy(text?: string) {
if (!text) return;
@@ -92,10 +86,8 @@ async function copy(text?: string) {
setTimeout(() => (toast.value = ''), 1500);
}
onMounted(async () => {
const cached = sessionStorage.getItem(storageKey());
if (cached) {
try { blockchain.value = JSON.parse(cached) as ProofBlockchain; } catch { blockchain.value = null; }
}
// 从溯源页点进来时直接用它带过来的数据,不再请求一次溯源接口,避免多记一次查询
blockchain.value = readProofCache<ProofBlockchain>(code, preview);
if (!blockchain.value?.txHash) {
try {
const data = preview
@@ -117,22 +109,20 @@ onMounted(async () => {
if (result.complete && result.detail) blockchain.value = { ...blockchain.value, chainDetail: result.detail };
} catch { /* 查询不到时保留已有字段 */ }
}
sessionStorage.setItem(storageKey(), JSON.stringify(blockchain.value));
writeProofCache(code, preview, blockchain.value);
loading.value = false;
});
</script>
<style scoped>
.subpage { max-width: 960px; margin: 0 auto; min-height: 100vh; background: #f4f6fa; }
.subpage-bar { position: sticky; top: 0; z-index: 5; display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 12px; background: var(--card-bg); border-bottom: 1px solid var(--border); }
.subpage-bar { flex-wrap: wrap; }
/* 详情区固定用浅色版式,文字颜色也固定,深色模式下不会变成浅字配浅底 */
.subpage { max-width: 960px; margin: 0 auto; min-height: 100vh; background: #f4f6fa; color: #1f2a37; }
.subpage-bar { position: sticky; top: 0; z-index: 5; display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 8px 12px; background: var(--card-bg); border-bottom: 1px solid var(--border); color: var(--text); }
.subpage-bar h1 { flex: 1; min-width: 0; margin: 0; font-size: 16px; font-weight: 600; text-align: left; }
.subpage-back { border: 0; background: transparent; color: var(--brand-2); font: inherit; font-size: 14px; cursor: pointer; padding: 6px 0; }
.subpage-state { padding: 48px 16px; text-align: center; }
.subpage-state .muted { color: #667085; }
.spinner { width: 28px; height: 28px; border: 3px solid var(--border); border-top-color: var(--brand); border-radius: 50%; margin: 0 auto 12px; animation: spin .8s linear infinite; }
.toast { position: fixed; left: 50%; bottom: 28px; transform: translateX(-50%); background: #111827; color: #fff; border-radius: 999px; padding: 8px 14px; font-size: 13px; }
@media (max-width: 720px) {
.subpage { max-width: none; }
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
+1 -1
View File
@@ -213,7 +213,7 @@ flowchart LR
## 九、C 端与查验
- C 端溯源页区块链卡展示:链名、交易哈希、合约地址、区块高度、上链时间;tokenId 仍由后端保存,当前不对消费者展示;
- 「查看存证」打开站内存证详情,展示已保存的交易哈希、合约地址、区块高度、区块哈希和上链时间。公开溯源接口不返回天河链区块浏览器地址。
- 「查看存证」打开站内存证详情页,按交易详情版式展示交易哈希、状态、区块高度、Gas、发送方、交易动作、合约地址、接收方、时间、输入信息和日志。Gas、发送方和日志在确认上链后首次打开时从区块浏览器查到并存入本平台,之后只读本地。公开溯源接口不返回天河链区块浏览器地址。
- 数据哈希为平台内部计算并保留的结构化内容摘要,不随当前 publish 请求上链,也不是链上交易标识或消费者追溯码,不在 C 端展示。
## 十、生产上线检查单
+2 -2
View File
@@ -19,14 +19,14 @@ docker compose --env-file .deploy/local/.env -f docker/compose.local.yml stop
- 后台:<http://127.0.0.1:18080/admin/>
- 客户端:<http://127.0.0.1:18080/trace/>
- 超管账号:`admin`;本机生成的密码位于 `.deploy/local/credentials.json` 的 `admin` 字段。
- 超管账号:2026-11-15 重新导入线上数据后与线上后台账号相同;`.deploy/local/credentials.json` 里的 `admin` 字段是导入前的本机密码,已不再有效。
- Compose 密码:`.deploy/local/.env`。
- 应用配置:`.deploy/local/config/.env`。
- 上传、备份、临时文件:`.deploy/local/storage`、`backups`、`tmp`。
- MySQL 数据卷:`artveris-local_mysql`;Redis 数据卷:`artveris-local_redis`。
- MySQL 库名:`artveris_test`,数据库和 Redis 不开放宿主机端口。
上述 `.deploy` 配置与秘密均被 Git 忽略,不应提交。当前环境已按用户要求导入生产业务数据与媒体作为测试数据;天河链凭据重新配置为专用测试环境,运行配置独立于线上。
上述 `.deploy` 配置与秘密均被 Git 忽略,不应提交。当前环境已按用户要求导入 2026-11-15 的线上数据库与媒体,备份在 `.deploy/local/backup-20261115/`。系统设置随数据库一起导入,天河链环境和凭据与线上相同。
本地使用独立的 `docker/Dockerfile.dev`。API 开发容器内由 `docker/dev.mjs` 管理共享包 TypeScript watch、Nest watch、admin/client Vite 四个进程;Nginx 按 `/admin/`、`/trace/`、`/api` 路由到相应进程,并代理热更新 WebSocket。共享包、API 和前后台源码挂载到容器,Linux 依赖保存在镜像内,不使用 Windows 的 node_modules。
+9 -4
View File
@@ -8,7 +8,11 @@
扫码页区块链模块底部左侧为“查看存证”、右侧靠右为“查看证书”,均不显示箭头。仅明确 ONCHAIN 且有交易哈希的天河链实物显示证书按钮,未上链或处理中均不显示。仅已激活、正常、已审核通过的实物可申请。普通页面打开、刷新与证书状态 GET 都不会提交存证;后台预览模式按钮禁用,不产生付费副作用。
「查看存证」和「查看证书」都进入本平台独立页面,不使用弹窗,手机上按屏幕宽度缩放,证书内部排版不改。证书页顶部右侧是下载按钮。区块链编号和 SHA256 放在证书图片上方,说明用悬停提示;哈希只显示文字,不跳转到天河链。证书页文案依次为“正在调取存证数据”“获取存证证书”“正在整理存证证书”。先读取已保存的证书字段,已生成的马上显示。没有时才 POST 申请,并继续查询 1 分钟;仍未完成就停止转圈并提示稍后再查。提交在收到任何响应前就连接失败时,记为未生成并可以重试;请求发出后超时则只查询原操作号,避免重复付费。证书按天河链证书页的版式在浏览器中绘制,下载也由浏览器生成 PNG。之后只读本地。交易详情里的 Gas、发送方和日志在第一次查到前留空,查全后写入本地,之后不再请求天河链。离开页面只停止当前等待,后台已提交任务继续完成。再次进入直接读取数据库已有记录,不重复生成。公开接口不返回天河链网址,客户页面也不能跳转到天河链。
「查看存证」和「查看证书」都进入本平台独立页面,不使用弹窗,手机上按屏幕宽度缩放,证书内部排版不改。证书页顶部右侧是下载按钮。区块链编号和 SHA256 放在证书图片上方,说明用悬停提示;哈希只显示文字,不跳转到天河链。证书页文案依次为“正在调取存证数据”“获取存证证书”“正在整理存证证书”。先读取已保存的证书字段,已生成的马上显示。没有时才 POST 申请,并继续查询 1 分钟;仍未完成就停止转圈并提示稍后再查。证书按天河链证书页的版式在浏览器中绘制,图片也由浏览器生成:电脑上点击下载保存 PNG;手机上与天河链证书页相同,显示生成的图片并提示长按保存。之后只读本地。离开页面只停止当前等待,后台已提交任务继续完成。再次进入直接读取数据库已有记录,不重复生成。公开接口不返回天河链网址,客户页面也不能跳转到天河链。
交易详情里的 Gas、发送方和日志在第一次查到前留空,查全后连同交易哈希一起写入本地,之后不再请求天河链;重新上链后旧详情不会套用到新交易。链上详情只对已激活、正常、审核通过且已确认上链的实物提供,范围与溯源页一致。
从存证详情或证书页返回溯源页时不重新查询,不会多记一次防伪查询次数,并回到离开前的位置。直接打开这两个页面的地址时仍会查询一次溯源信息。
新证书首次点击时按系统设置 `certificateTextTemplate` 渲染并冻结正文,默认 `{{作品名称}} {{版本}}`,例如“十二生肖莲花手工杯 一个装”。设置入口为“系统设置 → 区块链 → 证书文本模板”,帮助按钮点击后才弹出字段说明。支持 `{{作品名称}}`、`{{版本}}`、`{{追溯码}}`、`{{档案编号}}`、`{{作者}}`,可自由排序、重复使用并插入普通文本或换行。版本按作品模板中显示名为“版本”的字段取值,当前数据键为 `size`,不能硬编码成 `version`。
@@ -26,14 +30,15 @@
NONE -> PENDING -> SUBMITTING -> WAITING -> CHECKING -> READY
| |
+-> WAITING +-> WAITING / UNKNOWN
+-> FAILED(明确拒绝)
+-> FAILED(明确拒绝,或连接没有建立)
```
- 首次申请使用数据库单条条件更新与单件凭据唯一约束,避免并发创建多份存证。并发请求不能覆盖已保存的证据快照或操作编号。
- 请求快照包含固定 `operateId`、环境、App ID、钱包地址和原文,不含密钥。
- 定时 Worker 每 5 秒检查已持久化任务,使用数据库租约和 CAS 防止多个进程同时处理同一条;不会扫描未申请的实物生成证书。
- 提交前先写 `SUBMITTING`。超时、连接中断、崩溃恢复时一律仅查询原操作,不创建新编号、不重新提交;查询一轮最多 8 次,未就绪进入 `UNKNOWN`,消费者稍后可点击继续查询。
- 远端明确拒绝进入 `FAILED`,需平台排查,不允许消费者无限重提。
- 提交前先写 `SUBMITTING`。超时、连接被重置、崩溃恢复时请求可能已经到达天河链,一律仅查询原操作,不创建新编号、不重新提交;查询一轮最多 8 次,未就绪进入 `UNKNOWN`,消费者稍后可点击继续查询。
- 连接还没有建立就失败(拒绝连接、域名解析失败、网络不可达、连接超时)时请求一定没有发出,进入 `FAILED` 并标记可重新申请;消费者再次点击会换新的操作编号重新提交,不会重复扣费。
- 远端明确拒绝进入 `FAILED`,需平台排查,不允许消费者无限重提。公开接口只返回能否重新申请,不返回内部处理说明。
- 凭据、钱包或环境变更会暂停当前任务,不会把测试操作切到正式环境执行。
- 官方链接仅允许对应环境天河链证书页;校验钱包、哈希、文本摘要后保存,并正确编码文本中的 URL 特殊字符。
- 数据备份包含证书状态、请求快照和 URL。恢复进行中的证书时转入 `UNKNOWN`,避免备份前后不确定的外部副作用被再次提交。