feat: 优化消费者出证进度弹窗和证书文本

This commit is contained in:
Nixevol
2026-09-20 02:14:39 +08:00
parent c4864992e8
commit c5c0168e4c
9 changed files with 123 additions and 136 deletions
@@ -105,4 +105,15 @@ describe('Consumer certificate lifecycle', () => {
expect(row.certificateRequest).toBe(saved);
expect(writes).toBe(1);
});
it('freezes only the artwork title and physical trace code, separated by a newline', async () => {
const { service, prisma, row } = fixture('NONE');
prisma.traceCode.findUnique.mockResolvedValue({
shortCode: '295708006702', status: 'ACTIVE',
artwork: { title: '风生水起莲花生肖青蛙手工茶器', status: 'ACTIVE', auditStatus: 'APPROVED' },
proofs: [row],
} as any);
await service.request('295708006702');
expect(prisma.blockchainProof.updateMany.mock.calls[0][0].data.certificateRequest.text)
.toBe('风生水起莲花生肖青蛙手工茶器\n295708006702');
});
});
@@ -81,14 +81,7 @@ export class DepositCertificateService {
version: 1, environment, appId: settings.tianheAppId, address: settings.tianheWalletAddress,
operateId: `avc${randomBytes(8).toString('hex')}`,
// The official TEXT certificate prints this verbatim; use readable labels.
text: [
`作品:${code.artwork.title}`,
`作者:${code.artwork.artist || '未填写'}`,
`档案编号:${code.artwork.archiveNo}`,
`实物追溯码:${code.shortCode}`,
`数字身份交易:${proof.txHash}`,
`证据记录时间:${now.toISOString()}`,
].join(';'),
text: `${code.artwork.title}\n${code.shortCode}`,
};
// A single conditional write claims this item; concurrent callers cannot
// replace the winner's frozen evidence or operation id. No daily quota.
@@ -31,7 +31,7 @@ describe('V3 deposit protocol', () => {
await expect(new DepositProvider('test', 'app', 'key').submit('addr', 'op', 'test')).rejects.toBeInstanceOf(DepositRejected);
});
it('binds the returned certificate to the exact frozen evidence and preserves reserved characters', async () => {
const text = '作品:A&B + 100% #茶器';
const text = 'A&B + 100% #茶器\n295708006702';
const digest = createHash('sha256').update(text).digest('hex');
const value = 'https://test.tichain.tianhecloud.com/#/certificate?depositContent=broken&type=TEXT&address=addr&txHash=0x' + 'a'.repeat(64) + '&digest=' + digest;
jest.spyOn(global, 'fetch').mockResolvedValue({ ok: true, json: async () => ({ code: 200, success: true, data: value }) } as any);
@@ -65,23 +65,37 @@
target="_blank"
rel="noopener noreferrer"
>
{{ t('chain.explorer') }} →
{{ t('chain.explorer') }}
</a>
<button v-if="canViewCertificate" class="chain-link certificate-link" :disabled="opening || preview" @click="viewCertificate">
{{ t(opening ? 'chain.certificateOpening' : 'chain.certificateView') }} →
<button ref="certificateButton" v-if="canViewCertificate" class="chain-link certificate-link" :disabled="opening || preview" @click="viewCertificate">
{{ t('chain.certificateView') }}
</button>
</div>
<p v-if="preview && canViewCertificate" class="muted chain-status-note">{{ t('chain.certificatePreview') }}</p>
<p v-if="certificateError" role="alert" class="chain-status-note">{{ certificateError }}</p>
</template>
<div v-else class="chain-empty muted">{{ t('chain.notOnchain') }}</div>
</section>
<Teleport to="body">
<dialog ref="certificateDialog" class="certificate-dialog" aria-labelledby="certificate-dialog-title" @cancel.prevent="closeCertificateDialog">
<button class="certificate-close" :aria-label="t('viewer.close')" @click="closeCertificateDialog">×</button>
<h3 id="certificate-dialog-title">{{ t('chain.certificateView') }}</h3>
<div v-if="!certificateError" class="certificate-spinner" aria-hidden="true" />
<div aria-live="polite">
<p v-if="certificateError" role="alert">{{ certificateError }}</p>
<ol v-else 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>
<button v-if="certificateError && retryable" class="certificate-retry" @click="viewCertificate">{{ t('chain.certificateCheckAgain') }}</button>
</dialog>
</Teleport>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';
import { fetchTraceCertificate, requestTraceCertificate } from '@/api';
import { computed, onUnmounted, ref, watch } from 'vue';
import { fetchTraceCertificate, requestTraceCertificate, type TraceCertificateResult } from '@/api';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import { safeTraceUrl } from './media';
@@ -114,33 +128,76 @@ const props = defineProps<{
}>();
defineEmits<{ (event: 'copy', value: string): void }>();
const { t } = useI18n();
const router = useRouter();
const opening = ref(false);
const certificateError = ref('');
const canViewCertificate = computed(() => status.value === 'ONCHAIN' && props.blockchain?.chainName === '天河链');
const canViewCertificate = computed(() => props.blockchain?.status === 'ONCHAIN' && Boolean(props.blockchain.txHash) && props.blockchain.chainName === '天河链');
const certificateDialog = ref<HTMLDialogElement>();
const certificateButton = ref<HTMLButtonElement>();
const certificatePhase = ref(0);
const retryable = ref(true);
const certificateSteps = ['chain.certificateRetrieving', 'chain.certificateAcquiring', 'chain.certificateRedirecting'];
let certificateTimer: ReturnType<typeof setTimeout> | undefined;
let certificateRun = 0;
let certificatePolls = 0;
function stopCertificateWait() {
certificateRun++;
if (certificateTimer) clearTimeout(certificateTimer);
opening.value = false;
}
function closeCertificateDialog() {
stopCertificateWait();
certificateDialog.value?.close();
certificateButton.value?.focus();
}
function failCertificate(messageKey: string, canRetry = true) {
certificateError.value = t(messageKey);
retryable.value = canRetry;
opening.value = false;
}
function showCertificateResult(result: TraceCertificateResult, run: number, code: string) {
if (run !== certificateRun) return;
if (result.status === 'READY' && result.url) {
certificatePhase.value = 2;
certificateTimer = setTimeout(() => {
if (run === certificateRun) window.location.assign(result.url!);
}, 350);
return;
}
if (result.status === 'FAILED') return 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 >= 60) return failCertificate('chain.certificateDelayed');
certificateTimer = setTimeout(async () => {
try { showCertificateResult(await fetchTraceCertificate(code), run, code); }
catch { if (run === certificateRun) failCertificate('chain.certificateUnavailable'); }
}, 5000);
}
async function viewCertificate() {
if (opening.value || props.preview) return;
if (opening.value || props.preview || !canViewCertificate.value) return;
stopCertificateWait();
const run = certificateRun;
const code = props.shortCode;
certificateError.value = '';
const href = router.resolve({ path: `/certificate/${props.shortCode}` }).href;
// Open while the click gesture is active. The waiting page never starts a deposit itself.
const popup = window.open(href, '_blank');
if (popup) popup.opener = null;
certificatePhase.value = 0;
certificatePolls = 0;
if (!certificateDialog.value?.open) certificateDialog.value?.showModal();
opening.value = true;
try {
const cached = await fetchTraceCertificate(props.shortCode);
const cached = await fetchTraceCertificate(code);
if (run !== certificateRun) return;
certificatePhase.value = 1;
const result = cached.status === 'NONE' || cached.status === 'UNKNOWN'
? await requestTraceCertificate(props.shortCode) : cached;
if (!popup) {
await router.push(`/certificate/${props.shortCode}`);
} else if (result.status === 'READY' && result.url) {
popup.location.replace(result.url);
}
? await requestTraceCertificate(code) : cached;
showCertificateResult(result, run, code);
} catch {
if (popup && !popup.closed) popup.close();
certificateError.value = t('chain.certificateRequestFailed');
} finally { opening.value = false; }
if (run === certificateRun) failCertificate('chain.certificateRequestFailed');
}
}
watch(() => props.shortCode, closeCertificateDialog);
onUnmounted(stopCertificateWait);
const status = computed<ProofStatus>(() => {
const value = props.blockchain?.status as ProofStatus | undefined;
@@ -253,6 +310,19 @@ function formatTime(value: string) {
padding: 8px 0;
}
.chain-actions { display: flex; align-items: center; gap: 24px; flex-wrap: wrap; }
.certificate-link { padding: 0; border: 0; background: none; cursor: pointer; font-family: inherit; }
.certificate-link { margin-left: auto; padding: 0; border: 0; background: none; cursor: pointer; font-family: inherit; }
.certificate-link:disabled { opacity: .55; cursor: default; }
.certificate-dialog { width: min(360px, calc(100vw - 40px)); box-sizing: border-box; padding: 28px; border: 1px solid var(--border); border-radius: 16px; background: var(--card-bg); color: var(--text); box-shadow: 0 16px 60px #0003; }
.certificate-dialog::backdrop { background: #0007; }
.certificate-dialog h3 { margin: 0 0 22px; font-size: 18px; }
.certificate-close { position: absolute; top: 9px; right: 12px; border: 0; background: transparent; color: var(--muted); font-size: 25px; cursor: pointer; }
.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; }
.certificate-steps li { display: flex; gap: 12px; align-items: center; color: var(--muted); }
.certificate-steps li span { border: 1px solid var(--border); border-radius: 50%; width: 24px; height: 24px; display: grid; place-items: center; flex-shrink: 0; }
.certificate-steps li.current { color: var(--text); font-weight: 600; }
.certificate-steps li.done { color: var(--brand); }
.certificate-retry { border: 0; background: var(--brand); color: white; padding: 9px 18px; border-radius: 6px; cursor: pointer; font: inherit; }
@keyframes certificate-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .certificate-spinner { animation: none; } }
</style>
+5 -9
View File
@@ -64,19 +64,15 @@
"copied": "Copied",
"notOnchain": "This artwork has not been recorded on-chain yet.",
"certificateView": "View certificate",
"certificateOpening": "Opening…",
"certificatePreview": "Certificates cannot be generated in preview mode.",
"certificateRequestFailed": "Unable to request a certificate. Please try later or contact the platform.",
"certificateGenerating": "Your certificate is being prepared. The TiChain certificate page will open when it is ready.",
"certificateShared": "One certificate is generated for this physical item and reused on future visits.",
"certificateOpen": "Open certificate",
"certificateCheckAgain": "Check again",
"certificateBack": "Back",
"certificateReady": "Your certificate is ready.",
"certificateFailed": "The attestation request was rejected. Please contact the platform.",
"certificateUnknown": "The result is not yet confirmed. Check again later; the attestation will not be submitted again.",
"certificateNotRequested": "No certificate has been requested. Select View certificate on the item trace page.",
"certificateUnavailable": "Unable to check the certificate. Please try again later."
"certificateUnavailable": "Unable to check the certificate. Please try again later.",
"certificateRetrieving": "Retrieving attestation details",
"certificateAcquiring": "Preparing your certificate",
"certificateRedirecting": "Opening your certificate",
"certificateDelayed": "Your certificate is not ready yet. Please try again later."
},
"field": {
"viewFile": "View file"
+5 -9
View File
@@ -64,19 +64,15 @@
"copied": "已复制",
"notOnchain": "该作品暂未上链存证。",
"certificateView": "查看证书",
"certificateOpening": "正在打开…",
"certificatePreview": "预览模式不生成证书。",
"certificateRequestFailed": "暂时无法生成证书,请稍后再试或联系平台。",
"certificateGenerating": "证书生成中,请稍候。完成后将自动打开天河链证书页面。",
"certificateShared": "同一件实物仅生成一次,之后直接查看已有证书。",
"certificateOpen": "打开证书",
"certificateCheckAgain": "重新查询",
"certificateBack": "返回",
"certificateReady": "证书已就绪。",
"certificateFailed": "存证申请未成功,请联系平台处理。",
"certificateUnknown": "结果暂未确认。稍后可重新查询,系统不会重复提交存证。",
"certificateNotRequested": "尚未申请证书,请从该实物溯源页点击“查看证书”。",
"certificateUnavailable": "暂时无法查询证书,请稍后重试。"
"certificateUnavailable": "暂时无法查询证书,请稍后重试。",
"certificateRetrieving": "正在调取存证数据",
"certificateAcquiring": "获取存证证书",
"certificateRedirecting": "正在打开存证证书",
"certificateDelayed": "证书暂未就绪,请稍后再试。"
},
"field": {
"viewFile": "查看文件"
-1
View File
@@ -5,7 +5,6 @@ export default createRouter({
routes: [
{ path: '/', component: () => import('@/views/Home.vue') },
{ path: '/trace/:code', component: () => import('@/views/Trace.vue') },
{ path: '/certificate/:code', component: () => import('@/views/Certificate.vue') },
// 后台预览模式:复用 Trace.vue,凭 ?token= 时间令牌访问,不激活/不计数
{ path: '/trace/preview/:code', component: () => import('@/views/Trace.vue') },
{ path: '/:pathMatch(.*)*', redirect: '/' },
-79
View File
@@ -1,79 +0,0 @@
<template>
<main class="certificate-page">
<section class="card certificate-card" aria-live="polite">
<h1>{{ t('chain.certificateView') }}</h1>
<p>{{ t(message) }}</p>
<p class="muted">{{ t('chain.certificateShared') }}</p>
<a v-if="url" class="action" :href="url" rel="noopener noreferrer">{{ t('chain.certificateOpen') }} →</a>
<button v-else-if="retryable" class="action" :disabled="busy" @click="resume">{{ t('chain.certificateCheckAgain') }}</button>
<button class="back" @click="router.back()">{{ t('chain.certificateBack') }}</button>
</section>
</main>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { fetchTraceCertificate, requestTraceCertificate } from '@/api';
const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const message = ref('chain.certificateGenerating');
const retryable = ref(false);
const busy = ref(false);
const url = ref('');
let timer: ReturnType<typeof setTimeout> | undefined;
let stopped = false;
let polls = 0;
async function poll() {
if (stopped) return;
try {
const result = await fetchTraceCertificate(String(route.params.code));
if (stopped) return;
if (result.status === 'READY' && result.url) {
url.value = result.url;
message.value = 'chain.certificateReady';
window.location.replace(result.url);
return;
}
if (result.status === 'FAILED') { message.value = 'chain.certificateFailed'; return; }
if (result.status === 'UNKNOWN') {
message.value = 'chain.certificateUnknown'; retryable.value = true; return;
}
// A GET or link preview must never generate a certificate.
if (result.status === 'NONE' && polls >= 5) { message.value = 'chain.certificateNotRequested'; return; }
if (++polls >= 60) { message.value = 'chain.certificateUnknown'; retryable.value = true; return; }
timer = setTimeout(poll, 5000);
} catch {
if (!stopped) { message.value = 'chain.certificateUnavailable'; retryable.value = true; }
}
}
async function resume() {
if (busy.value) return;
busy.value = true;
try {
// Do not create a new request from this waiting page, even when opened directly.
const state = await fetchTraceCertificate(String(route.params.code));
if (state.status === 'NONE') { message.value = 'chain.certificateNotRequested'; retryable.value = false; return; }
if (state.status === 'UNKNOWN') await requestTraceCertificate(String(route.params.code));
polls = 0; retryable.value = false; message.value = 'chain.certificateGenerating';
await poll();
} catch { message.value = 'chain.certificateRequestFailed'; }
finally { busy.value = false; }
}
onMounted(poll);
onUnmounted(() => { stopped = true; if (timer) clearTimeout(timer); });
</script>
<style scoped>
.certificate-page { max-width: 600px; margin: 8vh auto; padding: 20px; }
.certificate-card { padding: 28px; text-align: center; line-height: 1.7; }
h1 { font-size: 23px; }
.action, .back { display: block; margin: 20px auto 0; padding: 10px 18px; border-radius: 8px; font: inherit; cursor: pointer; }
.action { color: white; background: var(--brand); border: none; text-decoration: none; }
.back { background: transparent; border: 1px solid var(--border); color: var(--muted); }
</style>