feat: 支持配置证书文本模板和作者显示方式
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
import { DEFAULT_CERTIFICATE_TEXT_TEMPLATE, renderCertificateText, validateCertificateTextTemplate } from '@artveris/shared';
|
||||
|
||||
const values = { '作品名称': '十二生肖莲花手工杯', '版本': '一个装', '追溯码': '295708006702', '档案编号': 'ARTVERIS-000005', '作者': '黄志伟' };
|
||||
describe('证书文本模板', () => {
|
||||
it('默认作品名称加版本', () => {
|
||||
expect(renderCertificateText(DEFAULT_CERTIFICATE_TEXT_TEMPLATE, values)).toBe('十二生肖莲花手工杯 一个装');
|
||||
});
|
||||
it('支持自定义次序、普通文字、重复字段和真实换行', () => {
|
||||
expect(renderCertificateText('{{版本}}:{{作品名称}}\n{{追溯码}} {{ 作者 }} {{档案编号}} {{版本}}', values))
|
||||
.toBe('一个装:十二生肖莲花手工杯\n295708006702 黄志伟 ARTVERIS-000005 一个装');
|
||||
});
|
||||
it('缺少字段显示为空且字段值不进行二次模板替换', () => {
|
||||
expect(renderCertificateText(DEFAULT_CERTIFICATE_TEXT_TEMPLATE, { ...values, '版本': '' })).toBe(values.作品名称);
|
||||
expect(renderCertificateText('{{作品名称}}', { ...values, '作品名称': '{{作者}}' })).toBe('{{作者}}');
|
||||
});
|
||||
it('拒绝空值、超长、未知字段、错误花括号和表达式', () => {
|
||||
for (const template of ['', ' ', 'a'.repeat(501), '{{不存在}}', '{作品名称}', '{{作品名称', '{{作品名称.toUpperCase()}}']) {
|
||||
expect(validateCertificateTextTemplate(template)).not.toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,7 @@ function fixture(state = 'PENDING') {
|
||||
updateMany: jest.fn().mockResolvedValue({ count: 1 }),
|
||||
findUniqueOrThrow: jest.fn().mockResolvedValue(row),
|
||||
},
|
||||
traceCode: { findUnique: jest.fn().mockResolvedValue({ shortCode: '123456000001', status: 'ACTIVE', artwork: { status: 'ACTIVE', auditStatus: 'APPROVED' }, proofs: [row] }) },
|
||||
traceCode: { findUnique: jest.fn().mockResolvedValue({ shortCode: '123456000001', status: 'ACTIVE', artwork: { title: '测试作品', archiveNo: 'ARTVERIS-000001', status: 'ACTIVE', auditStatus: 'APPROVED' }, proofs: [row] }) },
|
||||
$transaction: jest.fn(),
|
||||
};
|
||||
const config = { getAllRaw: jest.fn().mockResolvedValue(settings), get: jest.fn().mockResolvedValue('true') };
|
||||
@@ -105,15 +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 () => {
|
||||
it('defaults to title and version using the template label rather than assuming a version key', async () => {
|
||||
const { service, prisma, row } = fixture('NONE');
|
||||
prisma.traceCode.findUnique.mockResolvedValue({
|
||||
shortCode: '295708006702', status: 'ACTIVE',
|
||||
artwork: { title: '风生水起莲花生肖青蛙手工茶器', status: 'ACTIVE', auditStatus: 'APPROVED' },
|
||||
artwork: { title: '十二生肖莲花手工杯', status: 'ACTIVE', auditStatus: 'APPROVED', dynamicFields: { size: '一个装' }, template: { fields: [{ label: '版本', fieldKey: 'size' }] } },
|
||||
proofs: [row],
|
||||
} as any);
|
||||
await service.request('295708006702');
|
||||
expect(prisma.blockchainProof.updateMany.mock.calls[0][0].data.certificateRequest.text)
|
||||
.toBe('风生水起莲花生肖青蛙手工茶器\n295708006702');
|
||||
.toBe('十二生肖莲花手工杯 一个装');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,11 +2,11 @@ import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Interval } from '@nestjs/schedule';
|
||||
import { ArtworkStatus, AuditStatus, BlockchainProof, Prisma, ProofStatus, TraceCodeStatus } from '@prisma/client';
|
||||
import { randomBytes, randomUUID } from 'crypto';
|
||||
import { ErrorCode, TRACE_CODE_PATTERN } from '@artveris/shared';
|
||||
import { DEFAULT_CERTIFICATE_TEXT_TEMPLATE, ErrorCode, renderCertificateText, TRACE_CODE_PATTERN } from '@artveris/shared';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { DepositEnvironment, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider';
|
||||
import { certificateAuthorUrl, DepositEnvironment, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider';
|
||||
|
||||
interface CertificateRequest {
|
||||
version: 1;
|
||||
@@ -30,7 +30,7 @@ export class DepositCertificateService {
|
||||
private async eligible(shortCode: string) {
|
||||
if (!TRACE_CODE_PATTERN.test(shortCode)) throw new BusinessException(ErrorCode.NOT_FOUND, '追溯码不可用', 404);
|
||||
const code = await this.prisma.traceCode.findUnique({
|
||||
where: { shortCode }, include: { artwork: true, proofs: true },
|
||||
where: { shortCode }, include: { artwork: { include: { template: { include: { fields: true } } } }, proofs: true },
|
||||
});
|
||||
const proof = code?.proofs[0];
|
||||
if (!code || code.status !== TraceCodeStatus.ACTIVE || code.artwork.deletedAt ||
|
||||
@@ -41,25 +41,26 @@ export class DepositCertificateService {
|
||||
return { code, proof };
|
||||
}
|
||||
|
||||
private view(proof: BlockchainProof) {
|
||||
private async view(proof: BlockchainProof, artist?: string | null) {
|
||||
const request = proof.certificateRequest as unknown as CertificateRequest | null;
|
||||
const url = request && proof.certificateState === 'READY'
|
||||
? safeCertificateUrl(proof.certificateUrl, request.environment, request.address) : null;
|
||||
return {
|
||||
status: proof.certificateState === 'READY' && !url ? 'FAILED' : proof.certificateState,
|
||||
url, generatedAt: proof.certificateGeneratedAt,
|
||||
url: url ? certificateAuthorUrl(url, await this.settings.get('certificateAuthorMode'), artist) : null,
|
||||
generatedAt: proof.certificateGeneratedAt,
|
||||
};
|
||||
}
|
||||
|
||||
/** No remote calls, writes, activation, or query-count changes. */
|
||||
async status(shortCode: string) {
|
||||
const { proof } = await this.eligible(shortCode);
|
||||
return this.view(proof);
|
||||
const { code, proof } = await this.eligible(shortCode);
|
||||
return this.view(proof, code.artwork.artist);
|
||||
}
|
||||
|
||||
async request(shortCode: string) {
|
||||
const { code, proof } = await this.eligible(shortCode);
|
||||
if (proof.certificateState === 'READY') return this.view(proof);
|
||||
if (proof.certificateState === 'READY') return this.view(proof, code.artwork.artist);
|
||||
const settings = await this.settings.getAllRaw();
|
||||
if (proof.certificateState !== 'NONE') {
|
||||
// An uncertain submission is never submitted again. User action only resumes queries.
|
||||
@@ -69,7 +70,7 @@ export class DepositCertificateService {
|
||||
data: { certificateState: 'WAITING', certificateAttempts: 0, certificateNextCheck: new Date() },
|
||||
});
|
||||
}
|
||||
return this.view((await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } })));
|
||||
return this.view((await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } })), code.artwork.artist);
|
||||
}
|
||||
const environment = settings.tianheEnv as DepositEnvironment;
|
||||
if (settings.blockchainDriver !== 'tianhe' || !['test', 'production'].includes(environment) ||
|
||||
@@ -77,11 +78,26 @@ export class DepositCertificateService {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '平台存证配置尚未就绪');
|
||||
}
|
||||
const now = new Date();
|
||||
// “版本”是作品模板的动态字段;按显示名查键,不能假定数据库键叫version。
|
||||
const versionField = code.artwork.template?.fields.find(field => field.label.trim() === '版本');
|
||||
const dynamic = code.artwork.dynamicFields as Record<string, unknown> | null;
|
||||
const versionValue = versionField ? dynamic?.[versionField.fieldKey] : undefined;
|
||||
let text: string;
|
||||
try {
|
||||
text = renderCertificateText(settings.certificateTextTemplate ?? DEFAULT_CERTIFICATE_TEXT_TEMPLATE, {
|
||||
'作品名称': code.artwork.title,
|
||||
'版本': typeof versionValue === 'string' || typeof versionValue === 'number' ? String(versionValue) : '',
|
||||
'追溯码': code.shortCode,
|
||||
'档案编号': code.artwork.archiveNo || '',
|
||||
'作者': code.artwork.artist || '',
|
||||
});
|
||||
} catch { throw new BusinessException(ErrorCode.BAD_REQUEST, '证书文本模板配置无效,请联系平台管理员'); }
|
||||
if (!text || text.length > 2000) throw new BusinessException(ErrorCode.BAD_REQUEST, '证书文本为空或过长,请检查模板及作品字段');
|
||||
const request: CertificateRequest = {
|
||||
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}\n${code.shortCode}`,
|
||||
// 冻结首次申请时渲染出的文本,模板变化不会改变已提交或已生成证书。
|
||||
text,
|
||||
};
|
||||
// A single conditional write claims this item; concurrent callers cannot
|
||||
// replace the winner's frozen evidence or operation id. No daily quota.
|
||||
@@ -92,7 +108,7 @@ export class DepositCertificateService {
|
||||
certificateRequestedAt: now, certificateNextCheck: now,
|
||||
},
|
||||
});
|
||||
return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }));
|
||||
return this.view(await this.prisma.blockchainProof.findUniqueOrThrow({ where: { id: proof.id } }), code.artwork.artist);
|
||||
}
|
||||
|
||||
/** Persistent DB-backed work: only explicit requests enter PENDING. Restart-safe. */
|
||||
|
||||
@@ -1,7 +1,18 @@
|
||||
import { depositSignature, DepositProvider, DepositRejected, safeCertificateUrl } from './deposit.provider';
|
||||
import { certificateAuthorUrl, depositSignature, DepositProvider, DepositRejected, 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'))
|
||||
|
||||
@@ -29,6 +29,16 @@ 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) {}
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { SettingsService } from './settings.service';
|
||||
|
||||
describe('SettingsService.update', () => {
|
||||
it('rejects invalid certificate templates before any settings are persisted', async () => {
|
||||
const prisma = { $transaction: jest.fn() };
|
||||
const service = new SettingsService(prisma as any, {} as any);
|
||||
await expect(service.updateAtomic({ certificateTextTemplate: '{{错误字段}}' })).rejects.toThrow();
|
||||
expect(prisma.$transaction).not.toHaveBeenCalled();
|
||||
});
|
||||
it('uses the explicit development URL for links and displayed settings after importing production data', async () => {
|
||||
const prisma = { systemSetting: {
|
||||
findMany: jest.fn().mockResolvedValue([{ key: 'clientBaseUrl', value: 'https://art.qclh.xyz/trace' }]),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
|
||||
import { DEFAULT_CERTIFICATE_TEXT_TEMPLATE, validateCertificateTextTemplate } from '@artveris/shared';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
@@ -29,6 +30,8 @@ const EDITABLE_KEYS = [
|
||||
'storageMigrationFingerprint',
|
||||
'storageMigrationCopied',
|
||||
'blockchainDriver',
|
||||
'certificateTextTemplate',
|
||||
'certificateAuthorMode',
|
||||
'tianheEnv',
|
||||
'tianheBaseUrl',
|
||||
'tianheAppId',
|
||||
@@ -89,6 +92,8 @@ export class SettingsService {
|
||||
ossAccessKeySecret: this.config.get<string>('storage.oss.accessKeySecret') || '',
|
||||
settingsEncryptionKey: this.config.get<string>('settingsEncryptionKey') || '',
|
||||
blockchainDriver: this.config.get<string>('blockchain.driver') || 'mock',
|
||||
certificateTextTemplate: DEFAULT_CERTIFICATE_TEXT_TEMPLATE,
|
||||
certificateAuthorMode: 'WALLET',
|
||||
tianheEnv: 'test',
|
||||
tianheBaseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com',
|
||||
tianheAppId: this.config.get<string>('blockchain.tianhe.appId') || '',
|
||||
@@ -146,6 +151,12 @@ export class SettingsService {
|
||||
}
|
||||
|
||||
async updateAtomic(values: Record<string, string>): Promise<void> {
|
||||
if (values.certificateAuthorMode !== undefined && !['WALLET', 'ARTWORK_ARTIST'].includes(values.certificateAuthorMode)) {
|
||||
throw new BadRequestException('证书作者显示方式无效');
|
||||
}
|
||||
if (values.certificateTextTemplate !== undefined && validateCertificateTextTemplate(values.certificateTextTemplate)) {
|
||||
throw new BadRequestException('证书文本模板不能为空,最多500字符,支持:作品名称、版本、追溯码、档案编号、作者,字段使用双花括号');
|
||||
}
|
||||
const updates: Array<{ key: string; value: string }> = [];
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (!EDITABLE_KEYS.includes(key)) continue;
|
||||
|
||||
Reference in New Issue
Block a user