feat: 接入天河链存证接口
This commit is contained in:
@@ -45,7 +45,12 @@ export class AttestationService {
|
||||
};
|
||||
const dataHash = this.blockchain.hashData(summary);
|
||||
const proof = await this.prisma.blockchainProof.create({
|
||||
data: { traceCodeId, dataHash, status: ProofStatus.PENDING },
|
||||
data: {
|
||||
traceCodeId,
|
||||
dataHash,
|
||||
status: ProofStatus.PENDING,
|
||||
rawResponse: { requestMeta: summary },
|
||||
},
|
||||
});
|
||||
await this.queue.add('onchain', { proofId: proof.id });
|
||||
return proof;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { BullModule } from '@nestjs/bullmq';
|
||||
import { QUEUE_NAMES } from '@artveris/shared';
|
||||
import { SettingsModule } from '../settings/settings.module';
|
||||
import { BlockchainService } from './blockchain.service';
|
||||
import { AttestationService } from './attestation.service';
|
||||
import { BlockchainController } from './blockchain.controller';
|
||||
@@ -8,7 +9,7 @@ import { OnchainProcessor } from './onchain.processor';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.ONCHAIN })],
|
||||
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.ONCHAIN }), SettingsModule],
|
||||
controllers: [BlockchainController],
|
||||
providers: [BlockchainService, AttestationService, OnchainProcessor],
|
||||
exports: [BlockchainService, AttestationService],
|
||||
|
||||
@@ -1,25 +1,29 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { BlockchainService } from './blockchain.service';
|
||||
|
||||
function makeService(): BlockchainService {
|
||||
const config = {
|
||||
get: (key: string) => (key === 'blockchain.driver' ? 'mock' : undefined),
|
||||
} as unknown as ConfigService;
|
||||
return new BlockchainService(config);
|
||||
const settings = {
|
||||
getAll: async () => ({ blockchainDriver: 'mock' }),
|
||||
} as unknown as SettingsService;
|
||||
return new BlockchainService(config, settings);
|
||||
}
|
||||
|
||||
describe('BlockchainService.hashData', () => {
|
||||
const svc = makeService();
|
||||
|
||||
it('相同输入产生相同哈希', () => {
|
||||
const a = svc.hashData({ title: '青花瓷', n: 1 });
|
||||
const b = svc.hashData({ title: '青花瓷', n: 1 });
|
||||
const a = svc.hashData({ title: '青花瓶', n: 1 });
|
||||
const b = svc.hashData({ title: '青花瓶', n: 1 });
|
||||
expect(a).toBe(b);
|
||||
expect(a).toMatch(/^0x[0-9a-f]{64}$/);
|
||||
});
|
||||
|
||||
it('不同输入产生不同哈希', () => {
|
||||
const a = svc.hashData({ title: '青花瓷' });
|
||||
const a = svc.hashData({ title: '青花瓶' });
|
||||
const b = svc.hashData({ title: '霁红釉' });
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
|
||||
@@ -1,36 +1,52 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createHash } from 'crypto';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
|
||||
import { MockProvider } from './mock.provider';
|
||||
import { TianheProvider } from './tianhe.provider';
|
||||
|
||||
const TIANHE_TEST_URL = 'https://test.api.tichain.tianhecloud.com';
|
||||
const TIANHE_PRODUCTION_URL = 'https://api.tichain.tianhecloud.com';
|
||||
|
||||
@Injectable()
|
||||
export class BlockchainService {
|
||||
private readonly logger = new Logger(BlockchainService.name);
|
||||
private readonly provider: AttestationProvider;
|
||||
|
||||
constructor(private readonly config: ConfigService) {
|
||||
const driver = this.config.get<string>('blockchain.driver');
|
||||
if (driver === 'tianhe') {
|
||||
this.provider = new TianheProvider({
|
||||
baseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || '',
|
||||
appId: this.config.get<string>('blockchain.tianhe.appId') || '',
|
||||
appKey: this.config.get<string>('blockchain.tianhe.appKey') || '',
|
||||
});
|
||||
} else {
|
||||
this.provider = new MockProvider();
|
||||
}
|
||||
this.logger.log(`区块链存证驱动:${this.provider.name}`);
|
||||
}
|
||||
constructor(
|
||||
private readonly config: ConfigService,
|
||||
private readonly settings: SettingsService,
|
||||
) {}
|
||||
|
||||
// 计算任意业务数据的稳定摘要哈希
|
||||
hashData(data: unknown): string {
|
||||
const json = JSON.stringify(data);
|
||||
return '0x' + createHash('sha256').update(json).digest('hex');
|
||||
return '0x' + createHash('sha256').update(JSON.stringify(data)).digest('hex');
|
||||
}
|
||||
|
||||
attest(payload: AttestPayload): Promise<AttestResult> {
|
||||
return this.provider.attest(payload);
|
||||
async attest(payload: AttestPayload): Promise<AttestResult> {
|
||||
const provider = await this.buildProvider();
|
||||
this.logger.log(`区块链存证驱动:${provider.name}`);
|
||||
return provider.attest(payload);
|
||||
}
|
||||
|
||||
private async buildProvider(): Promise<AttestationProvider> {
|
||||
const settings = await this.settings.getAll();
|
||||
const driver = (settings.blockchainDriver || this.config.get<string>('blockchain.driver') || 'mock') as 'mock' | 'tianhe';
|
||||
if (driver !== 'tianhe') return new MockProvider();
|
||||
|
||||
const env = settings.tianheEnv || 'test';
|
||||
const configuredBaseUrl =
|
||||
env === 'test'
|
||||
? TIANHE_TEST_URL
|
||||
: env === 'production'
|
||||
? TIANHE_PRODUCTION_URL
|
||||
: settings.tianheBaseUrl || this.config.get<string>('blockchain.tianhe.baseUrl') || TIANHE_TEST_URL;
|
||||
|
||||
return new TianheProvider({
|
||||
baseUrl: configuredBaseUrl,
|
||||
appId: settings.tianheAppId || this.config.get<string>('blockchain.tianhe.appId') || '',
|
||||
appKey: settings.tianheAppKey || this.config.get<string>('blockchain.tianhe.appKey') || '',
|
||||
userId: settings.tianheUserId || this.config.get<string>('blockchain.tianhe.userId') || '',
|
||||
userKey: settings.tianheUserKey || this.config.get<string>('blockchain.tianhe.userKey') || '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
export interface AttestPayload {
|
||||
// 业务数据摘要(对作品/证书/出库/节点等关键数据计算的哈希)
|
||||
dataHash: string;
|
||||
// 附带的可读元信息(仅用于存证记录,可选)
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface AttestResult {
|
||||
dataHash: string;
|
||||
txHash: string;
|
||||
blockHash: string;
|
||||
blockHeight: number;
|
||||
blockHash?: string | null;
|
||||
blockHeight?: number | null;
|
||||
chainName: string;
|
||||
explorerUrl: string;
|
||||
explorerUrl?: string | null;
|
||||
onchainAt: Date;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,12 @@ interface OnchainJobData {
|
||||
proofId: number;
|
||||
}
|
||||
|
||||
function requestMeta(raw: unknown): Record<string, unknown> | undefined {
|
||||
if (!raw || typeof raw !== 'object') return undefined;
|
||||
const meta = (raw as Record<string, unknown>).requestMeta;
|
||||
return meta && typeof meta === 'object' ? (meta as Record<string, unknown>) : undefined;
|
||||
}
|
||||
|
||||
@Processor(QUEUE_NAMES.ONCHAIN)
|
||||
export class OnchainProcessor extends WorkerHost {
|
||||
private readonly logger = new Logger(OnchainProcessor.name);
|
||||
@@ -25,27 +31,38 @@ export class OnchainProcessor extends WorkerHost {
|
||||
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
|
||||
if (!proof) return;
|
||||
try {
|
||||
const result = await this.blockchain.attest({ dataHash: proof.dataHash });
|
||||
const result = await this.blockchain.attest({
|
||||
dataHash: proof.dataHash,
|
||||
meta: requestMeta(proof.rawResponse),
|
||||
});
|
||||
await this.prisma.blockchainProof.update({
|
||||
where: { id: proofId },
|
||||
data: {
|
||||
status: ProofStatus.ONCHAIN,
|
||||
txHash: result.txHash,
|
||||
blockHash: result.blockHash,
|
||||
blockHeight: BigInt(result.blockHeight),
|
||||
blockHash: result.blockHash || null,
|
||||
blockHeight: result.blockHeight !== null && result.blockHeight !== undefined ? BigInt(result.blockHeight) : null,
|
||||
chainName: result.chainName,
|
||||
explorerUrl: result.explorerUrl,
|
||||
explorerUrl: result.explorerUrl || null,
|
||||
onchainAt: result.onchainAt,
|
||||
rawResponse: result.raw as object,
|
||||
},
|
||||
});
|
||||
this.logger.log(`存证 ${proofId} 上链成功`);
|
||||
} catch (e) {
|
||||
const message = (e as Error).message;
|
||||
await this.prisma.blockchainProof.update({
|
||||
where: { id: proofId },
|
||||
data: { status: ProofStatus.FAILED },
|
||||
data: {
|
||||
status: ProofStatus.FAILED,
|
||||
rawResponse: {
|
||||
...(proof.rawResponse && typeof proof.rawResponse === 'object' ? (proof.rawResponse as object) : {}),
|
||||
error: message,
|
||||
failedAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
});
|
||||
this.logger.error(`存证 ${proofId} 上链失败: ${(e as Error).message}`);
|
||||
this.logger.error(`存证 ${proofId} 上链失败: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +1,123 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
|
||||
|
||||
export interface TianheOptions {
|
||||
baseUrl: string;
|
||||
appId: string;
|
||||
appKey: string;
|
||||
userId: string;
|
||||
userKey: string;
|
||||
}
|
||||
|
||||
function required(value: string | undefined, label: string): string {
|
||||
const v = (value || '').trim();
|
||||
if (!v) throw new Error(`天河链配置缺少 ${label}`);
|
||||
return v;
|
||||
}
|
||||
|
||||
function pickString(source: unknown, keys: string[]): string | null {
|
||||
if (!source || typeof source !== 'object') return null;
|
||||
const obj = source as Record<string, unknown>;
|
||||
for (const key of keys) {
|
||||
const value = obj[key];
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
if (typeof value === 'number') return String(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function pickNumber(source: unknown, keys: string[]): number | null {
|
||||
if (!source || typeof source !== 'object') return null;
|
||||
const obj = source as Record<string, unknown>;
|
||||
for (const key of keys) {
|
||||
const value = obj[key];
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
||||
if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function responseData(raw: unknown): Record<string, unknown> {
|
||||
if (!raw || typeof raw !== 'object') return {};
|
||||
const obj = raw as Record<string, unknown>;
|
||||
const data = obj.data;
|
||||
return data && typeof data === 'object' ? { ...obj, ...(data as Record<string, unknown>) } : obj;
|
||||
}
|
||||
|
||||
// 天河链存证适配器(接入细节待确认,预留对接)。
|
||||
// 已知:纯存证接口 POST /api/v2/nfr/upload,appId/appKey 直接鉴权;
|
||||
// 待确认:完整返回字段、存证查询链接、是否需注册托管钱包等。
|
||||
// 确认后在 attest() 内补全真实请求与字段映射即可,对上层 BlockchainService 透明。
|
||||
export class TianheProvider implements AttestationProvider {
|
||||
readonly name = 'tianhe';
|
||||
private readonly logger = new Logger(TianheProvider.name);
|
||||
|
||||
constructor(private readonly opts: TianheOptions) {}
|
||||
|
||||
async attest(_payload: AttestPayload): Promise<AttestResult> {
|
||||
if (!this.opts.appId || !this.opts.appKey || !this.opts.baseUrl) {
|
||||
throw new Error('天河链未配置(TIANHE_APP_ID/APP_KEY/BASE_URL),请在 .env 配置后再启用 BLOCKCHAIN_DRIVER=tianhe');
|
||||
async attest(payload: AttestPayload): Promise<AttestResult> {
|
||||
const baseUrl = required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
|
||||
const userDto = {
|
||||
appId: required(this.opts.appId, 'App ID'),
|
||||
appKey: required(this.opts.appKey, 'App Key'),
|
||||
userId: required(this.opts.userId, 'User ID'),
|
||||
userKey: required(this.opts.userKey, 'User Key'),
|
||||
};
|
||||
const meta = {
|
||||
dataHash: payload.dataHash,
|
||||
...(payload.meta || {}),
|
||||
generatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const form = new FormData();
|
||||
form.append('userDto', JSON.stringify(userDto));
|
||||
form.append(
|
||||
'file',
|
||||
new Blob([JSON.stringify(meta, null, 2)], { type: 'application/json' }),
|
||||
`artveris-proof-${payload.dataHash.replace(/^0x/, '').slice(0, 16)}.json`,
|
||||
);
|
||||
|
||||
const res = await fetch(`${baseUrl}/api/v2/nfr/upload`, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
});
|
||||
const text = await res.text();
|
||||
let raw: Record<string, unknown> = { text };
|
||||
try {
|
||||
raw = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
raw = { text };
|
||||
}
|
||||
// TODO: 待天河链接入细节确认后实现真实存证请求与返回字段映射。
|
||||
this.logger.warn('天河链真实接入尚未实现,请先使用 BLOCKCHAIN_DRIVER=mock');
|
||||
throw new Error('天河链真实接入待确认,请暂用 BLOCKCHAIN_DRIVER=mock');
|
||||
if (!res.ok) {
|
||||
throw new Error(`天河链存证请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
|
||||
}
|
||||
|
||||
const code = pickString(raw, ['code', 'statusCode', 'errCode']);
|
||||
const success = code === null || code === '0' || code.toLowerCase() === 'success' || code === '200';
|
||||
if (!success) {
|
||||
const msg = pickString(raw, ['message', 'msg', 'error']) || '接口返回失败';
|
||||
throw new Error(`天河链存证失败:${msg}`);
|
||||
}
|
||||
|
||||
const data = responseData(raw);
|
||||
const txHash =
|
||||
pickString(data, [
|
||||
'txHash',
|
||||
'transactionHash',
|
||||
'hash',
|
||||
'proofHash',
|
||||
'certHash',
|
||||
'attestationHash',
|
||||
'chainHash',
|
||||
]) || payload.dataHash;
|
||||
const explorerUrl = pickString(data, ['url', 'link', 'proofUrl', 'viewUrl', 'certUrl', 'explorerUrl', 'uri']);
|
||||
const blockHash = pickString(data, ['blockHash']);
|
||||
const blockHeight = pickNumber(data, ['blockHeight', 'height']);
|
||||
const onchainAtText = pickString(data, ['onchainAt', 'chainTime', 'createdAt', 'time']);
|
||||
const onchainAt = onchainAtText ? new Date(onchainAtText) : new Date();
|
||||
|
||||
return {
|
||||
dataHash: payload.dataHash,
|
||||
txHash,
|
||||
blockHash,
|
||||
blockHeight,
|
||||
chainName: '天河链',
|
||||
explorerUrl,
|
||||
onchainAt: Number.isNaN(onchainAt.getTime()) ? new Date() : onchainAt,
|
||||
raw: { requestMeta: meta, response: raw },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ export interface AppConfig {
|
||||
};
|
||||
blockchain: {
|
||||
driver: 'mock' | 'tianhe';
|
||||
tianhe: { baseUrl: string; appId: string; appKey: string };
|
||||
tianhe: { baseUrl: string; appId: string; appKey: string; userId: string; userKey: string };
|
||||
};
|
||||
seedAdmin: { username: string; password: string; name: string };
|
||||
logRetentionDays: number;
|
||||
@@ -68,9 +68,11 @@ export default (): AppConfig => {
|
||||
blockchain: {
|
||||
driver: (process.env.BLOCKCHAIN_DRIVER as 'mock' | 'tianhe') || 'mock',
|
||||
tianhe: {
|
||||
baseUrl: process.env.TIANHE_BASE_URL || '',
|
||||
baseUrl: process.env.TIANHE_BASE_URL || 'https://test.api.tichain.tianhecloud.com',
|
||||
appId: process.env.TIANHE_APP_ID || '',
|
||||
appKey: process.env.TIANHE_APP_KEY || '',
|
||||
userId: process.env.TIANHE_USER_ID || '',
|
||||
userKey: process.env.TIANHE_USER_KEY || '',
|
||||
},
|
||||
},
|
||||
seedAdmin: {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsArray, IsDateString, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
|
||||
import { IsArray, IsDateString, IsOptional, IsString, MaxLength } from 'class-validator';
|
||||
|
||||
export class OutboundDto {
|
||||
@ApiPropertyOptional({ description: '出库时间' })
|
||||
@@ -19,24 +18,6 @@ export class OutboundDto {
|
||||
@IsString({ each: true })
|
||||
outImageKeys?: string[];
|
||||
|
||||
@ApiPropertyOptional({ description: '上链哈希值(填写则记录上链结果)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
txHash?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '上链时间' })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
onchainAt?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '区块高度' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
blockHeight?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: '备注' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
|
||||
@@ -115,7 +115,6 @@ export class ImportPreviewProcessor extends WorkerHost {
|
||||
status: 'INVALID',
|
||||
shortCode: values.shortCode || null,
|
||||
batchNo: values.batchNo || null,
|
||||
txHash: values.txHash || null,
|
||||
remark: values.remark || null,
|
||||
reason: '',
|
||||
preview: values,
|
||||
@@ -133,13 +132,6 @@ export class ImportPreviewProcessor extends WorkerHost {
|
||||
}
|
||||
const outTime = parseDate(values.outTime);
|
||||
if (outTime === null) throw new Error('出库时间格式不正确');
|
||||
const onchainAt = parseDate(values.onchainAt);
|
||||
if (onchainAt === null) throw new Error('上链时间格式不正确');
|
||||
let blockHeight: bigint | null = null;
|
||||
if (values.blockHeight) {
|
||||
if (!/^\d+$/.test(values.blockHeight)) throw new Error('区块高度应为整数');
|
||||
blockHeight = BigInt(values.blockHeight);
|
||||
}
|
||||
|
||||
const imagePaths = (values.outImages || '')
|
||||
.split(';')
|
||||
@@ -161,8 +153,6 @@ export class ImportPreviewProcessor extends WorkerHost {
|
||||
Object.assign(result, {
|
||||
status: 'VALID',
|
||||
outTime,
|
||||
onchainAt,
|
||||
blockHeight,
|
||||
outImagePaths: imagePaths,
|
||||
outImageKeys: imageItems,
|
||||
preview: { ...values, images: imageItems },
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import { createHash } from 'crypto';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import { JobStatus, ProofStatus, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { JobStatus, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { JobsService } from '../jobs/jobs.service';
|
||||
@@ -55,27 +54,6 @@ export class ImportProcessor extends WorkerHost {
|
||||
remark: row.remark || undefined,
|
||||
},
|
||||
});
|
||||
|
||||
if (row.txHash) {
|
||||
const dup = await this.prisma.blockchainProof.findFirst({
|
||||
where: { traceCodeId: code.id, txHash: row.txHash },
|
||||
});
|
||||
if (!dup) {
|
||||
const dataHash = '0x' + createHash('sha256').update(`${code.code}:${row.txHash}`).digest('hex');
|
||||
await this.prisma.blockchainProof.create({
|
||||
data: {
|
||||
traceCodeId: code.id,
|
||||
dataHash,
|
||||
txHash: row.txHash,
|
||||
blockHeight: row.blockHeight ?? null,
|
||||
chainName: '手工登记',
|
||||
onchainAt: row.onchainAt ?? new Date(),
|
||||
status: ProofStatus.ONCHAIN,
|
||||
rawResponse: { source: 'import' },
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
await this.prisma.outboundImportRow.update({ where: { id: row.id }, data: { status: 'IMPORTED', reason: null } });
|
||||
success++;
|
||||
} catch (e) {
|
||||
@@ -116,7 +94,6 @@ export class ImportProcessor extends WorkerHost {
|
||||
{ header: '批次编号', key: 'batchNo', width: 22 },
|
||||
{ header: '出库时间', key: 'outTime', width: 22 },
|
||||
{ header: '图片数量', key: 'imageCount', width: 10 },
|
||||
{ header: '上链哈希', key: 'txHash', width: 30 },
|
||||
{ header: '处理状态', key: 'status', width: 14 },
|
||||
{ header: '原因', key: 'reason', width: 40 },
|
||||
];
|
||||
@@ -128,7 +105,6 @@ export class ImportProcessor extends WorkerHost {
|
||||
batchNo: row.batchNo || '',
|
||||
outTime: row.outTime?.toISOString() || '',
|
||||
imageCount: jsonArray(row.outImageKeys).length,
|
||||
txHash: row.txHash || '',
|
||||
status: row.status,
|
||||
reason: row.reason || '',
|
||||
});
|
||||
|
||||
@@ -2,18 +2,11 @@ import { Injectable } from '@nestjs/common';
|
||||
import { InjectQueue } from '@nestjs/bullmq';
|
||||
import { Queue } from 'bullmq';
|
||||
import { Response } from 'express';
|
||||
import { createHash } from 'crypto';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import AdmZip from 'adm-zip';
|
||||
import sharp from 'sharp';
|
||||
import { Prisma, RoleType } from '@prisma/client';
|
||||
import {
|
||||
ErrorCode,
|
||||
JobType,
|
||||
OUTBOUND_IMPORT_COLUMNS,
|
||||
ProofStatus,
|
||||
QUEUE_NAMES,
|
||||
} from '@artveris/shared';
|
||||
import { ErrorCode, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { JobsService } from '../jobs/jobs.service';
|
||||
@@ -50,42 +43,10 @@ export class OutboundService {
|
||||
: Prisma.JsonNull;
|
||||
}
|
||||
if ('remark' in dto) data.remark = dto.remark || null;
|
||||
const updated = await this.prisma.traceCode.update({
|
||||
return this.prisma.traceCode.update({
|
||||
where: { id: traceCodeId },
|
||||
data,
|
||||
});
|
||||
if (dto.txHash) {
|
||||
await this.recordProof(traceCodeId, code.code, {
|
||||
txHash: dto.txHash,
|
||||
onchainAt: dto.onchainAt ? new Date(dto.onchainAt) : new Date(),
|
||||
blockHeight: dto.blockHeight,
|
||||
});
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
private async recordProof(
|
||||
traceCodeId: bigint,
|
||||
code: string,
|
||||
p: { txHash: string; onchainAt: Date; blockHeight?: number },
|
||||
) {
|
||||
const dup = await this.prisma.blockchainProof.findFirst({
|
||||
where: { traceCodeId, txHash: p.txHash },
|
||||
});
|
||||
if (dup) return;
|
||||
const dataHash = '0x' + createHash('sha256').update(`${code}:${p.txHash}`).digest('hex');
|
||||
await this.prisma.blockchainProof.create({
|
||||
data: {
|
||||
traceCodeId,
|
||||
dataHash,
|
||||
txHash: p.txHash,
|
||||
blockHeight: p.blockHeight !== undefined ? BigInt(p.blockHeight) : null,
|
||||
chainName: '手工登记',
|
||||
onchainAt: p.onchainAt,
|
||||
status: ProofStatus.ONCHAIN,
|
||||
rawResponse: { source: 'manual' },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async generateTemplate(res: Response): Promise<void> {
|
||||
@@ -94,23 +55,17 @@ export class OutboundService {
|
||||
ws.columns = OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: c.key === 'outImages' ? 36 : 22 }));
|
||||
ws.getRow(1).font = { bold: true };
|
||||
ws.addRow({
|
||||
shortCode: '请替换为真实追溯码1',
|
||||
shortCode: '请替换为真实追溯码',
|
||||
batchNo: 'B20260704001',
|
||||
outTime: '2026-07-04 10:00',
|
||||
outImages: 'images/out-001.jpg',
|
||||
txHash: '0xabc123',
|
||||
onchainAt: '2026-07-04 10:30',
|
||||
blockHeight: '8500001',
|
||||
remark: '单图示例',
|
||||
});
|
||||
ws.addRow({
|
||||
shortCode: '请替换为真实追溯码2',
|
||||
shortCode: '请替换为真实追溯码',
|
||||
batchNo: 'B20260704001',
|
||||
outTime: '2026-07-04 11:00',
|
||||
outImages: 'images/out-002.png;images/out-003.jpg',
|
||||
txHash: '',
|
||||
onchainAt: '',
|
||||
blockHeight: '',
|
||||
remark: '多图示例',
|
||||
});
|
||||
|
||||
@@ -127,17 +82,21 @@ export class OutboundService {
|
||||
|
||||
const zip = new AdmZip();
|
||||
zip.addFile('outbound-import-template.xlsx', Buffer.from(await wb.xlsx.writeBuffer()));
|
||||
zip.addFile('说明.txt', Buffer.from(
|
||||
[
|
||||
'出库批量导入说明',
|
||||
'',
|
||||
'1. ZIP 根目录必须包含一个 xlsx 文件和 images 文件夹。',
|
||||
'2. 出库实况图路径填写 images/xxx.jpg,多张图片使用英文分号 ; 分隔。',
|
||||
'3. 不允许使用绝对路径、..、反斜杠或 images 目录之外的路径。',
|
||||
'4. 上传 ZIP 后系统会先预览校验,确认无误后才正式导入。',
|
||||
].join('\r\n'),
|
||||
'utf8',
|
||||
));
|
||||
zip.addFile(
|
||||
'说明.txt',
|
||||
Buffer.from(
|
||||
[
|
||||
'出库批量导入说明',
|
||||
'',
|
||||
'1. ZIP 根目录必须包含一个 xlsx 文件和 images 文件夹。',
|
||||
'2. 出库实况图路径填写 images/xxx.jpg,多张图片使用英文分号 ; 分隔。',
|
||||
'3. 不允许使用绝对路径、..、反斜杠或 images 目录之外的路径。',
|
||||
'4. 上传 ZIP 后系统会先预览校验,确认无误后才正式导入。',
|
||||
'5. 链上哈希、存证链接和上链时间由天河链接口返回后自动写入,不在导入模板中手工填写。',
|
||||
].join('\r\n'),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
zip.addFile('images/out-001.jpg', await this.sampleImage('#13a8a8'));
|
||||
zip.addFile('images/out-002.png', await this.sampleImage('#3b82f6', 'png'));
|
||||
zip.addFile('images/out-003.jpg', await this.sampleImage('#f59e0b'));
|
||||
@@ -182,7 +141,6 @@ export class OutboundService {
|
||||
return { sessionId: session.id, jobId: job.id };
|
||||
}
|
||||
|
||||
// 兼容旧入口:上传后只做预览,不直接入库。
|
||||
startImport(file: Express.Multer.File, userId: number) {
|
||||
return this.startPreview(file, userId);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,13 @@ const EDITABLE_KEYS = [
|
||||
'backupSchedule',
|
||||
'backupRetentionDays',
|
||||
'backupRetentionCount',
|
||||
'blockchainDriver',
|
||||
'tianheEnv',
|
||||
'tianheBaseUrl',
|
||||
'tianheAppId',
|
||||
'tianheAppKey',
|
||||
'tianheUserId',
|
||||
'tianheUserKey',
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
@@ -37,6 +44,13 @@ export class SettingsService {
|
||||
backupSchedule: 'daily',
|
||||
backupRetentionDays: '30',
|
||||
backupRetentionCount: '10',
|
||||
blockchainDriver: this.config.get<string>('blockchain.driver') || 'mock',
|
||||
tianheEnv: 'test',
|
||||
tianheBaseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com',
|
||||
tianheAppId: this.config.get<string>('blockchain.tianhe.appId') || '',
|
||||
tianheAppKey: this.config.get<string>('blockchain.tianhe.appKey') || '',
|
||||
tianheUserId: this.config.get<string>('blockchain.tianhe.userId') || '',
|
||||
tianheUserKey: this.config.get<string>('blockchain.tianhe.userKey') || '',
|
||||
};
|
||||
for (const r of rows) {
|
||||
map[r.key] = r.key === 'appName' && r.value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : r.value;
|
||||
|
||||
Reference in New Issue
Block a user