feat: 接入天河链存证接口
This commit is contained in:
@@ -52,6 +52,8 @@ BLOCKCHAIN_DRIVER=mock
|
|||||||
TIANHE_BASE_URL=https://test.api.tichain.tianhecloud.com
|
TIANHE_BASE_URL=https://test.api.tichain.tianhecloud.com
|
||||||
TIANHE_APP_ID=
|
TIANHE_APP_ID=
|
||||||
TIANHE_APP_KEY=
|
TIANHE_APP_KEY=
|
||||||
|
TIANHE_USER_ID=
|
||||||
|
TIANHE_USER_KEY=
|
||||||
|
|
||||||
# ===== 查询日志默认保留天数(后台可改) =====
|
# ===== 查询日志默认保留天数(后台可改) =====
|
||||||
LOG_RETENTION_DAYS=365
|
LOG_RETENTION_DAYS=365
|
||||||
|
|||||||
@@ -9,10 +9,10 @@
|
|||||||
## A. 未实现 → 已全部实现
|
## A. 未实现 → 已全部实现
|
||||||
|
|
||||||
### A1. 出库与上链导入(§6.4)★
|
### A1. 出库与上链导入(§6.4)★
|
||||||
- [x] 批量导入字段补齐:短码、SKU、档案编号、**批次编号、出库实况图、上链哈希值、上链时间、区块高度**、备注(`packages/shared/src/constants.ts`)。
|
- [x] 批量导入字段补齐:追溯码、批次编号、出库实况图、备注(`packages/shared/src/constants.ts`);链上哈希、存证链接、上链时间改由区块链接口返回后自动写入,不再允许导入或手工填写。
|
||||||
- [x] 后台「单条录入」界面:`Outbound.vue` 新增「单条录入」标签页(搜索追溯码 + 填写各字段)。
|
- [x] 后台单件出库登记已内聚到追溯码管理行操作(填写出库时间、出库实况图、备注,可保存后触发上链)。
|
||||||
- [x] 「出库实况图」上传控件:单条录入页含图片上传;导入支持实况图 key/URL 列。
|
- [x] 「出库实况图」上传控件:单条录入页含图片上传;导入支持实况图 key/URL 列。
|
||||||
- [x] 导入按字段记录上链结果:填写上链哈希则写入一条 ONCHAIN 存证(`import.processor.ts`、`outbound.service.ts`)。
|
- [x] 上链结果记录改为 provider 回写:触发上链后由天河链/Mock provider 返回哈希、存证链接、上链时间并写入 `BlockchainProof`。
|
||||||
|
|
||||||
### A2. 审核员审批流(§10.1)
|
### A2. 审核员审批流(§10.1)
|
||||||
- [x] 新增艺术品审核流:`Artwork.auditStatus`(PENDING/APPROVED/REJECTED)+ `auditRemark/auditedBy/auditedAt`;`POST /artworks/:id/audit`(AUDITOR);运营编辑后自动回到 PENDING;后台新增「内容审核」页(审核员/超管可见)。公开溯源仅展示 APPROVED 作品。
|
- [x] 新增艺术品审核流:`Artwork.auditStatus`(PENDING/APPROVED/REJECTED)+ `auditRemark/auditedBy/auditedAt`;`POST /artworks/:id/audit`(AUDITOR);运营编辑后自动回到 PENDING;后台新增「内容审核」页(审核员/超管可见)。公开溯源仅展示 APPROVED 作品。
|
||||||
@@ -42,7 +42,7 @@
|
|||||||
### B2. 后端 / 数据模型
|
### B2. 后端 / 数据模型
|
||||||
- [x] §6.5 `QueryLog` 补字段:code、sku、archiveNo、batchNo、queryCount 快照、firstActivatedAt、browser、os。
|
- [x] §6.5 `QueryLog` 补字段:code、sku、archiveNo、batchNo、queryCount 快照、firstActivatedAt、browser、os。
|
||||||
- [x] ★§6.5 日志检索支持 SKU/批次/真实 code(`query-log.controller.ts`)。
|
- [x] ★§6.5 日志检索支持 SKU/批次/真实 code(`query-log.controller.ts`)。
|
||||||
- [x] §6.4 出库导入校验文件类型(xlsx)+ 字段格式(日期合法性、区块高度整数)。
|
- [x] §6.4 出库导入校验 ZIP/xlsx、图片路径与出库时间格式;上链字段不再从导入文件读取。
|
||||||
- [x] §7 `/upload` 限制为 OPERATOR+(只读监管员上传返回 403,已实测)。
|
- [x] §7 `/upload` 限制为 OPERATOR+(只读监管员上传返回 403,已实测)。
|
||||||
- [x] §5.5 新增把码批量置「异常 ABNORMAL」的运营接口(`batch/status` 的 `abnormal` 选项)。
|
- [x] §5.5 新增把码批量置「异常 ABNORMAL」的运营接口(`batch/status` 的 `abnormal` 选项)。
|
||||||
|
|
||||||
@@ -72,7 +72,7 @@
|
|||||||
## E. QA 加固轮(2026-06-29,安全审查 + Bugbot 复审后修复)
|
## E. QA 加固轮(2026-06-29,安全审查 + Bugbot 复审后修复)
|
||||||
|
|
||||||
经独立的「安全审查」与「Bugbot」子代理审查变更,修复以下问题并复测通过:
|
经独立的「安全审查」与「Bugbot」子代理审查变更,修复以下问题并复测通过:
|
||||||
- [x] 上链存证去重:单条录入与导入对「同码同 txHash」不再重复写入存证(`outbound.service.ts`、`import.processor.ts`)。
|
- [x] 上链存证去重与流程收敛:单条录入和导入不再手工写入 txHash,统一通过 `POST /trace-codes/:id/onchain` 创建存证任务。
|
||||||
- [x] 导入批次编号核对:填写「批次编号」则强制校验与该码实际批次一致,不符则该行失败并给出原因。
|
- [x] 导入批次编号核对:填写「批次编号」则强制校验与该码实际批次一致,不符则该行失败并给出原因。
|
||||||
- [x] 导入 Excel 单元格解析加固:兼容日期型单元格(Date)、富文本、公式结果、超链接、数字,避免日期型单元格误判为非法。
|
- [x] 导入 Excel 单元格解析加固:兼容日期型单元格(Date)、富文本、公式结果、超链接、数字,避免日期型单元格误判为非法。
|
||||||
- [x] 动态 IMAGE/FILE 字段 URL 解析:公开接口 `buildFields` 将存储 key 转为可访问 URL(兼容存 key 或存绝对 URL 两种情况),避免 C 端 404。
|
- [x] 动态 IMAGE/FILE 字段 URL 解析:公开接口 `buildFields` 将存储 key 转为可访问 URL(兼容存 key 或存绝对 URL 两种情况),避免 C 端 404。
|
||||||
@@ -80,6 +80,6 @@
|
|||||||
|
|
||||||
判定为「按当前 PRD 范围可接受、不修改」的项:
|
判定为「按当前 PRD 范围可接受、不修改」的项:
|
||||||
- 迁移未回填存量作品为 APPROVED(Bugbot high):仅在升级「已有生产数据」库时影响;本项目无线上数据、可重建,且已 `db:reset` 重新种子(示例作品 APPROVED);编辑已应用迁移会破坏 Prisma 校验,故不改。
|
- 迁移未回填存量作品为 APPROVED(Bugbot high):仅在升级「已有生产数据」库时影响;本项目无线上数据、可重建,且已 `db:reset` 重新种子(示例作品 APPROVED);编辑已应用迁移会破坏 Prisma 校验,故不改。
|
||||||
- 手工登记上链未做链上校验(安全 medium):PRD §6.4 在 mock/手工阶段即允许「记录上链结果」并展示,真实链上校验属后续天河链对接;已保留 `chainName=手工登记` 标识并去重。
|
- 手工登记上链未做链上校验(已废弃):天河链接入后不再允许后台手工填写链上哈希,链上结果统一由 provider 返回并保存原始响应。
|
||||||
|
|
||||||
验证:4 包构建通过、后端 9 单测通过、导入边界/去重/动态字段 Node 用例通过、浏览器回归 5/5 通过(含动态图片字段缩略图+查看器、审核通过闭环、运营六页面、模板排序/停用、监管员只读)。系统状态:纯净种子。
|
验证:4 包构建通过、后端 9 单测通过、导入边界/去重/动态字段 Node 用例通过、浏览器回归 5/5 通过(含动态图片字段缩略图+查看器、审核通过闭环、运营六页面、模板排序/停用、监管员只读)。系统状态:纯净种子。
|
||||||
|
|||||||
@@ -197,3 +197,5 @@
|
|||||||
- 开发脚本约定:`python scripts/dev.py` 会启动 `nest start --watch`,API 运行时不要手动或脚本化删除 `apps/api/dist`;如遇缺模块或半残 `dist`,停止当前 dev 进程后重新运行 `python scripts/dev.py`。
|
- 开发脚本约定:`python scripts/dev.py` 会启动 `nest start --watch`,API 运行时不要手动或脚本化删除 `apps/api/dist`;如遇缺模块或半残 `dist`,停止当前 dev 进程后重新运行 `python scripts/dev.py`。
|
||||||
- 客户端:当前 `Trace.vue` 依赖 `openMediaViewer.ts` + PhotoSwipe,不再使用旧 `MediaViewer.vue`;顶部语言菜单和追溯码复制是用户当前未提交改动的一部分,后续若继续修改客户端,需保护这些改动。
|
- 客户端:当前 `Trace.vue` 依赖 `openMediaViewer.ts` + PhotoSwipe,不再使用旧 `MediaViewer.vue`;顶部语言菜单和追溯码复制是用户当前未提交改动的一部分,后续若继续修改客户端,需保护这些改动。
|
||||||
- 文案残留:`apps/client/src/locales/*` 仍保留 `privacy.note`,但当前页面不显示底部隐私说明;若按合规要求恢复,需要在 `Trace.vue` 重新渲染对应文案。
|
- 文案残留:`apps/client/src/locales/*` 仍保留 `privacy.note`,但当前页面不显示底部隐私说明;若按合规要求恢复,需要在 `Trace.vue` 重新渲染对应文案。
|
||||||
|
|
||||||
|
- 天河链测试存证接入(2026-07-06):根据语雀/Apifox 文档,当前平台先接 `POST /api/v2/nfr/upload` 数字商品元数据上链存储接口,默认测试域名 `https://test.api.tichain.tianhecloud.com`,正式域名 `https://api.tichain.tianhecloud.com`。系统设置新增区块链存证卡片,可切换 `mock/tianhe`、测试/正式/自定义环境,并配置 `appId/appKey/userId/userKey`;`BlockchainService` 每次上链动态读取系统设置并以 `.env` 兜底,无需重启即可切换。`AttestationService` 创建 proof 时保存本次作品/追溯码/批次/出库摘要到 `rawResponse.requestMeta`,`OnchainProcessor` 调 provider 时上传该 JSON 元数据文件,成功后保存天河链返回的哈希、存证链接、上链时间和原始响应,失败时保留错误信息。出库 ZIP 模板和导入流程不再包含“上链哈希/上链时间/区块高度”列,避免绕过链上接口手工登记。
|
||||||
|
|||||||
@@ -157,24 +157,9 @@
|
|||||||
<n-form-item :label="t('pages.outbound.outImage')">
|
<n-form-item :label="t('pages.outbound.outImage')">
|
||||||
<media-upload v-model="outImages" type="image" :max="8" />
|
<media-upload v-model="outImages" type="image" :max="8" />
|
||||||
</n-form-item>
|
</n-form-item>
|
||||||
<n-divider style="margin: 4px 0 14px">{{ t('pages.outbound.onchainSection') }}</n-divider>
|
<n-alert type="info" :bordered="false" class="onchain-tip">
|
||||||
<n-grid :cols="2" :x-gap="16">
|
{{ t('pages.outbound.onchainAutoTip') }}
|
||||||
<n-form-item-gi span="2" :label="t('pages.blockchain.txHash')">
|
</n-alert>
|
||||||
<n-input v-model:value="outboundForm.txHash" :placeholder="t('pages.outbound.txHashTip')" />
|
|
||||||
</n-form-item-gi>
|
|
||||||
<n-form-item-gi :label="t('pages.blockchain.onchainAt')">
|
|
||||||
<n-date-picker v-model:formatted-value="outboundForm.onchainAt" value-format="yyyy-MM-dd HH:mm" type="datetime" clearable style="width: 100%" />
|
|
||||||
</n-form-item-gi>
|
|
||||||
<n-form-item-gi span="2">
|
|
||||||
<n-collapse>
|
|
||||||
<n-collapse-item :title="t('pages.outbound.moreOnchainInfo')" name="more-onchain">
|
|
||||||
<n-form-item :label="t('pages.blockchain.blockHeight')">
|
|
||||||
<n-input-number v-model:value="outboundForm.blockHeight" :min="0" style="width: 100%" />
|
|
||||||
</n-form-item>
|
|
||||||
</n-collapse-item>
|
|
||||||
</n-collapse>
|
|
||||||
</n-form-item-gi>
|
|
||||||
</n-grid>
|
|
||||||
</n-form>
|
</n-form>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<div style="text-align: right">
|
<div style="text-align: right">
|
||||||
@@ -293,9 +278,6 @@ const outImages = ref<any[]>([]);
|
|||||||
const outboundForm = reactive<any>({
|
const outboundForm = reactive<any>({
|
||||||
outTime: null,
|
outTime: null,
|
||||||
remark: '',
|
remark: '',
|
||||||
txHash: '',
|
|
||||||
onchainAt: null,
|
|
||||||
blockHeight: null,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const columns = computed<DataTableColumns<any>>(() => {
|
const columns = computed<DataTableColumns<any>>(() => {
|
||||||
@@ -721,12 +703,6 @@ function formatDateTime(value?: string | Date | null) {
|
|||||||
return value ? dayjs(value).format('YYYY-MM-DD HH:mm') : null;
|
return value ? dayjs(value).format('YYYY-MM-DD HH:mm') : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toNumber(value: unknown) {
|
|
||||||
if (value === null || value === undefined || value === '') return null;
|
|
||||||
const n = Number(value);
|
|
||||||
return Number.isFinite(n) ? n : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function fileName(key: string) {
|
function fileName(key: string) {
|
||||||
return key.split('/').pop() || key;
|
return key.split('/').pop() || key;
|
||||||
}
|
}
|
||||||
@@ -743,12 +719,8 @@ function getOutImages(row: any) {
|
|||||||
|
|
||||||
function openOutboundModal(row: any) {
|
function openOutboundModal(row: any) {
|
||||||
outboundTarget.value = row;
|
outboundTarget.value = row;
|
||||||
const latestProof = row.latestProof;
|
|
||||||
outboundForm.outTime = formatDateTime(row.outTime);
|
outboundForm.outTime = formatDateTime(row.outTime);
|
||||||
outboundForm.remark = row.remark || '';
|
outboundForm.remark = row.remark || '';
|
||||||
outboundForm.txHash = latestProof?.txHash || '';
|
|
||||||
outboundForm.onchainAt = formatDateTime(latestProof?.onchainAt);
|
|
||||||
outboundForm.blockHeight = toNumber(latestProof?.blockHeight);
|
|
||||||
outImages.value = getOutImages(row);
|
outImages.value = getOutImages(row);
|
||||||
outboundModal.value = true;
|
outboundModal.value = true;
|
||||||
}
|
}
|
||||||
@@ -765,9 +737,6 @@ async function saveOutbound(triggerOnchain: boolean) {
|
|||||||
outTime: outboundForm.outTime ? dayjs(outboundForm.outTime).toISOString() : null,
|
outTime: outboundForm.outTime ? dayjs(outboundForm.outTime).toISOString() : null,
|
||||||
outImageKey: outImages.value[0]?.key ?? null,
|
outImageKey: outImages.value[0]?.key ?? null,
|
||||||
outImageKeys: outImages.value.map((item) => item.key).filter(Boolean),
|
outImageKeys: outImages.value.map((item) => item.key).filter(Boolean),
|
||||||
txHash: outboundForm.txHash || undefined,
|
|
||||||
onchainAt: outboundForm.onchainAt ? dayjs(outboundForm.onchainAt).toISOString() : undefined,
|
|
||||||
blockHeight: outboundForm.blockHeight ?? undefined,
|
|
||||||
remark: outboundForm.remark || null,
|
remark: outboundForm.remark || null,
|
||||||
});
|
});
|
||||||
if (triggerOnchain) {
|
if (triggerOnchain) {
|
||||||
@@ -932,6 +901,9 @@ onUnmounted(() => {
|
|||||||
.mr8 {
|
.mr8 {
|
||||||
margin-right: 8px;
|
margin-right: 8px;
|
||||||
}
|
}
|
||||||
|
.onchain-tip {
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
@media (max-width: 720px) {
|
@media (max-width: 720px) {
|
||||||
.toolbar-control,
|
.toolbar-control,
|
||||||
.toolbar-control.wide,
|
.toolbar-control.wide,
|
||||||
|
|||||||
@@ -152,7 +152,10 @@
|
|||||||
"3014": "Batch not found",
|
"3014": "Batch not found",
|
||||||
"3015": "Artwork file has business data and cannot be deleted"
|
"3015": "Artwork file has business data and cannot be deleted"
|
||||||
},
|
},
|
||||||
"lang": { "zh": "Simplified Chinese", "en": "English" }
|
"lang": {
|
||||||
|
"zh": "Simplified Chinese",
|
||||||
|
"en": "English"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"menu": {
|
"menu": {
|
||||||
"dashboard": "Dashboard",
|
"dashboard": "Dashboard",
|
||||||
@@ -354,8 +357,8 @@
|
|||||||
"import": "Batch Import",
|
"import": "Batch Import",
|
||||||
"outTime": "Outbound Time",
|
"outTime": "Outbound Time",
|
||||||
"outImage": "Outbound Photo",
|
"outImage": "Outbound Photo",
|
||||||
"onchainSection": "On-chain info (optional; filling a hash records the result)",
|
"onchainSection": "On-chain Info",
|
||||||
"txHashTip": "Paste the on-chain transaction/attestation hash",
|
"txHashTip": "Written automatically from the blockchain API response",
|
||||||
"moreOnchainInfo": "More On-chain Info",
|
"moreOnchainInfo": "More On-chain Info",
|
||||||
"saveRecord": "Save Record",
|
"saveRecord": "Save Record",
|
||||||
"saveAndTriggerOnchain": "Save & Trigger On-chain",
|
"saveAndTriggerOnchain": "Save & Trigger On-chain",
|
||||||
@@ -365,7 +368,7 @@
|
|||||||
"successCount": "Success",
|
"successCount": "Success",
|
||||||
"failCount": "Failed",
|
"failCount": "Failed",
|
||||||
"downloadResult": "Download Details",
|
"downloadResult": "Download Details",
|
||||||
"tip": "Download the template first, fill it in and upload (xlsx). Includes outbound photo, on-chain hash/time/block height.",
|
"tip": "Download the template ZIP, fill it in, and upload. On-chain results are recorded automatically from the blockchain API response.",
|
||||||
"downloadZipTemplate": "Download Template ZIP",
|
"downloadZipTemplate": "Download Template ZIP",
|
||||||
"uploadZipPreview": "Upload & Preview",
|
"uploadZipPreview": "Upload & Preview",
|
||||||
"totalRows": "Rows",
|
"totalRows": "Rows",
|
||||||
@@ -390,7 +393,8 @@
|
|||||||
"IMPORTED": "Imported",
|
"IMPORTED": "Imported",
|
||||||
"FAILED": "Failed",
|
"FAILED": "Failed",
|
||||||
"EXPIRED": "Expired"
|
"EXPIRED": "Expired"
|
||||||
}
|
},
|
||||||
|
"onchainAutoTip": "On-chain hash, attestation link, and on-chain time are written automatically from the configured blockchain API response."
|
||||||
},
|
},
|
||||||
"blockchain": {
|
"blockchain": {
|
||||||
"title": "Blockchain Attestation",
|
"title": "Blockchain Attestation",
|
||||||
@@ -441,7 +445,20 @@
|
|||||||
"scheduleOff": "Off",
|
"scheduleOff": "Off",
|
||||||
"scheduleDaily": "Daily",
|
"scheduleDaily": "Daily",
|
||||||
"scheduleWeekly": "Weekly",
|
"scheduleWeekly": "Weekly",
|
||||||
"saved": "Settings saved"
|
"saved": "Settings saved",
|
||||||
|
"blockchainSettings": "Blockchain Attestation",
|
||||||
|
"blockchainDriver": "Attestation Driver",
|
||||||
|
"blockchainDriverMock": "Mock",
|
||||||
|
"blockchainDriverTianhe": "Tianhe Chain",
|
||||||
|
"tianheEnv": "Tianhe Environment",
|
||||||
|
"tianheEnvTest": "Test",
|
||||||
|
"tianheEnvProduction": "Production",
|
||||||
|
"tianheEnvCustom": "Custom",
|
||||||
|
"tianheBaseUrl": "API URL",
|
||||||
|
"tianheAppId": "App ID",
|
||||||
|
"tianheAppKey": "App Key",
|
||||||
|
"tianheUserId": "User ID",
|
||||||
|
"tianheUserKey": "User Key"
|
||||||
},
|
},
|
||||||
"profile": {
|
"profile": {
|
||||||
"title": "Personal Info",
|
"title": "Personal Info",
|
||||||
|
|||||||
@@ -152,7 +152,10 @@
|
|||||||
"3014": "批次不存在",
|
"3014": "批次不存在",
|
||||||
"3015": "艺术品档案已有业务数据,无法删除"
|
"3015": "艺术品档案已有业务数据,无法删除"
|
||||||
},
|
},
|
||||||
"lang": { "zh": "简体中文", "en": "English" }
|
"lang": {
|
||||||
|
"zh": "简体中文",
|
||||||
|
"en": "English"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"menu": {
|
"menu": {
|
||||||
"dashboard": "数据看板",
|
"dashboard": "数据看板",
|
||||||
@@ -354,8 +357,8 @@
|
|||||||
"import": "批量导入",
|
"import": "批量导入",
|
||||||
"outTime": "出库时间",
|
"outTime": "出库时间",
|
||||||
"outImage": "出库实况图",
|
"outImage": "出库实况图",
|
||||||
"onchainSection": "上链信息(选填,填写哈希即登记上链结果)",
|
"onchainSection": "上链信息",
|
||||||
"txHashTip": "粘贴链上交易/存证哈希",
|
"txHashTip": "由区块链接口返回后自动写入",
|
||||||
"moreOnchainInfo": "更多上链信息",
|
"moreOnchainInfo": "更多上链信息",
|
||||||
"saveRecord": "保存登记",
|
"saveRecord": "保存登记",
|
||||||
"saveAndTriggerOnchain": "保存并触发上链",
|
"saveAndTriggerOnchain": "保存并触发上链",
|
||||||
@@ -365,7 +368,7 @@
|
|||||||
"successCount": "成功",
|
"successCount": "成功",
|
||||||
"failCount": "失败",
|
"failCount": "失败",
|
||||||
"downloadResult": "下载结果明细",
|
"downloadResult": "下载结果明细",
|
||||||
"tip": "请先下载模板,按模板填写后上传(支持 xlsx)。模板含出库实况图、上链哈希/时间/区块高度等字段。",
|
"tip": "下载模板 ZIP 后按说明填写并上传;链上结果由区块链接口返回后自动记录。",
|
||||||
"downloadZipTemplate": "下载模板包",
|
"downloadZipTemplate": "下载模板包",
|
||||||
"uploadZipPreview": "上传并预览",
|
"uploadZipPreview": "上传并预览",
|
||||||
"totalRows": "总行数",
|
"totalRows": "总行数",
|
||||||
@@ -390,7 +393,8 @@
|
|||||||
"IMPORTED": "已导入",
|
"IMPORTED": "已导入",
|
||||||
"FAILED": "失败",
|
"FAILED": "失败",
|
||||||
"EXPIRED": "已过期"
|
"EXPIRED": "已过期"
|
||||||
}
|
},
|
||||||
|
"onchainAutoTip": "链上哈希、存证链接、上链时间由当前配置的区块链接口返回后自动写入。"
|
||||||
},
|
},
|
||||||
"blockchain": {
|
"blockchain": {
|
||||||
"title": "区块链存证",
|
"title": "区块链存证",
|
||||||
@@ -441,7 +445,20 @@
|
|||||||
"scheduleOff": "关闭",
|
"scheduleOff": "关闭",
|
||||||
"scheduleDaily": "每天",
|
"scheduleDaily": "每天",
|
||||||
"scheduleWeekly": "每周",
|
"scheduleWeekly": "每周",
|
||||||
"saved": "设置已保存"
|
"saved": "设置已保存",
|
||||||
|
"blockchainSettings": "区块链存证",
|
||||||
|
"blockchainDriver": "存证驱动",
|
||||||
|
"blockchainDriverMock": "模拟存证",
|
||||||
|
"blockchainDriverTianhe": "天河链",
|
||||||
|
"tianheEnv": "天河链环境",
|
||||||
|
"tianheEnvTest": "测试环境",
|
||||||
|
"tianheEnvProduction": "正式环境",
|
||||||
|
"tianheEnvCustom": "自定义",
|
||||||
|
"tianheBaseUrl": "接口地址",
|
||||||
|
"tianheAppId": "App ID",
|
||||||
|
"tianheAppKey": "App Key",
|
||||||
|
"tianheUserId": "User ID",
|
||||||
|
"tianheUserKey": "User Key"
|
||||||
},
|
},
|
||||||
"profile": {
|
"profile": {
|
||||||
"title": "个人信息",
|
"title": "个人信息",
|
||||||
|
|||||||
@@ -125,7 +125,6 @@ const columns = computed<DataTableColumns<any>>(() => [
|
|||||||
align: 'center',
|
align: 'center',
|
||||||
render: (row) => renderImages(row),
|
render: (row) => renderImages(row),
|
||||||
},
|
},
|
||||||
{ title: t('pages.blockchain.txHash'), key: 'txHash', minWidth: 260, ellipsis: { tooltip: true } },
|
|
||||||
{ title: t('common.label.remark'), key: 'remark', minWidth: 220, ellipsis: { tooltip: true } },
|
{ title: t('common.label.remark'), key: 'remark', minWidth: 220, ellipsis: { tooltip: true } },
|
||||||
{
|
{
|
||||||
title: t('pages.outbound.errorReason'),
|
title: t('pages.outbound.errorReason'),
|
||||||
|
|||||||
@@ -64,6 +64,45 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="settings-card">
|
||||||
|
<div class="card-title">{{ t('pages.settings.blockchainSettings') }}</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<n-form-item :label="t('pages.settings.blockchainDriver')">
|
||||||
|
<n-select v-model:value="form.blockchainDriver" :options="blockchainDriverOptions" class="select-control" />
|
||||||
|
</n-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<n-form-item :label="t('pages.settings.tianheEnv')">
|
||||||
|
<n-select v-model:value="form.tianheEnv" :options="tianheEnvOptions" class="select-control" @update:value="onTianheEnvChange" />
|
||||||
|
</n-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<n-form-item :label="t('pages.settings.tianheBaseUrl')">
|
||||||
|
<n-input v-model:value="form.tianheBaseUrl" class="url-control" :disabled="form.tianheEnv !== 'custom'" />
|
||||||
|
</n-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<n-form-item :label="t('pages.settings.tianheAppId')">
|
||||||
|
<n-input v-model:value="form.tianheAppId" class="text-control" />
|
||||||
|
</n-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<n-form-item :label="t('pages.settings.tianheAppKey')">
|
||||||
|
<n-input v-model:value="form.tianheAppKey" type="password" show-password-on="click" class="text-control" />
|
||||||
|
</n-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<n-form-item :label="t('pages.settings.tianheUserId')">
|
||||||
|
<n-input v-model:value="form.tianheUserId" class="text-control" />
|
||||||
|
</n-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="setting-row">
|
||||||
|
<n-form-item :label="t('pages.settings.tianheUserKey')">
|
||||||
|
<n-input v-model:value="form.tianheUserKey" type="password" show-password-on="click" class="text-control" />
|
||||||
|
</n-form-item>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="settings-card">
|
<section class="settings-card">
|
||||||
<div class="card-title">{{ t('pages.settings.backupPolicy') }}</div>
|
<div class="card-title">{{ t('pages.settings.backupPolicy') }}</div>
|
||||||
<div class="setting-row">
|
<div class="setting-row">
|
||||||
@@ -105,6 +144,17 @@ import { DEFAULT_APP_ICON_URL, resolveAppIcon, setFavicon } from '@/utils/appIco
|
|||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const saving = ref(false);
|
const saving = ref(false);
|
||||||
|
const TIANHE_TEST_URL = 'https://test.api.tichain.tianhecloud.com';
|
||||||
|
const TIANHE_PRODUCTION_URL = 'https://api.tichain.tianhecloud.com';
|
||||||
|
const blockchainDriverOptions = computed(() => [
|
||||||
|
{ label: t('pages.settings.blockchainDriverMock'), value: 'mock' },
|
||||||
|
{ label: t('pages.settings.blockchainDriverTianhe'), value: 'tianhe' },
|
||||||
|
]);
|
||||||
|
const tianheEnvOptions = computed(() => [
|
||||||
|
{ label: t('pages.settings.tianheEnvTest'), value: 'test' },
|
||||||
|
{ label: t('pages.settings.tianheEnvProduction'), value: 'production' },
|
||||||
|
{ label: t('pages.settings.tianheEnvCustom'), value: 'custom' },
|
||||||
|
]);
|
||||||
const backupScheduleOptions = computed(() => [
|
const backupScheduleOptions = computed(() => [
|
||||||
{ label: t('pages.settings.scheduleOff'), value: 'off' },
|
{ label: t('pages.settings.scheduleOff'), value: 'off' },
|
||||||
{ label: t('pages.settings.scheduleDaily'), value: 'daily' },
|
{ label: t('pages.settings.scheduleDaily'), value: 'daily' },
|
||||||
@@ -129,6 +179,13 @@ const form = reactive({
|
|||||||
backupSchedule: 'daily',
|
backupSchedule: 'daily',
|
||||||
backupRetentionDays: 30,
|
backupRetentionDays: 30,
|
||||||
backupRetentionCount: 10,
|
backupRetentionCount: 10,
|
||||||
|
blockchainDriver: 'mock',
|
||||||
|
tianheEnv: 'test',
|
||||||
|
tianheBaseUrl: TIANHE_TEST_URL,
|
||||||
|
tianheAppId: '',
|
||||||
|
tianheAppKey: '',
|
||||||
|
tianheUserId: '',
|
||||||
|
tianheUserKey: '',
|
||||||
});
|
});
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
@@ -145,6 +202,18 @@ async function load() {
|
|||||||
form.backupSchedule = s.backupSchedule || 'daily';
|
form.backupSchedule = s.backupSchedule || 'daily';
|
||||||
form.backupRetentionDays = Number(s.backupRetentionDays || 30);
|
form.backupRetentionDays = Number(s.backupRetentionDays || 30);
|
||||||
form.backupRetentionCount = Number(s.backupRetentionCount || 10);
|
form.backupRetentionCount = Number(s.backupRetentionCount || 10);
|
||||||
|
form.blockchainDriver = s.blockchainDriver || 'mock';
|
||||||
|
form.tianheEnv = s.tianheEnv || 'test';
|
||||||
|
form.tianheBaseUrl = s.tianheBaseUrl || TIANHE_TEST_URL;
|
||||||
|
form.tianheAppId = s.tianheAppId || '';
|
||||||
|
form.tianheAppKey = s.tianheAppKey || '';
|
||||||
|
form.tianheUserId = s.tianheUserId || '';
|
||||||
|
form.tianheUserKey = s.tianheUserKey || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function onTianheEnvChange(value: string) {
|
||||||
|
if (value === 'test') form.tianheBaseUrl = TIANHE_TEST_URL;
|
||||||
|
if (value === 'production') form.tianheBaseUrl = TIANHE_PRODUCTION_URL;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function save() {
|
async function save() {
|
||||||
@@ -163,6 +232,13 @@ async function save() {
|
|||||||
backupSchedule: form.backupSchedule,
|
backupSchedule: form.backupSchedule,
|
||||||
backupRetentionDays: String(form.backupRetentionDays),
|
backupRetentionDays: String(form.backupRetentionDays),
|
||||||
backupRetentionCount: String(form.backupRetentionCount),
|
backupRetentionCount: String(form.backupRetentionCount),
|
||||||
|
blockchainDriver: form.blockchainDriver,
|
||||||
|
tianheEnv: form.tianheEnv,
|
||||||
|
tianheBaseUrl: form.tianheBaseUrl,
|
||||||
|
tianheAppId: form.tianheAppId,
|
||||||
|
tianheAppKey: form.tianheAppKey,
|
||||||
|
tianheUserId: form.tianheUserId,
|
||||||
|
tianheUserKey: form.tianheUserKey,
|
||||||
});
|
});
|
||||||
setFavicon(appIconUrl);
|
setFavicon(appIconUrl);
|
||||||
window.dispatchEvent(new CustomEvent('artveris-settings-updated'));
|
window.dispatchEvent(new CustomEvent('artveris-settings-updated'));
|
||||||
@@ -287,6 +363,9 @@ const currentIconUrl = computed(() => resolveAppIcon(form.appIconFiles[0]?.url |
|
|||||||
.text-control {
|
.text-control {
|
||||||
width: 180px;
|
width: 180px;
|
||||||
}
|
}
|
||||||
|
.url-control {
|
||||||
|
width: 220px;
|
||||||
|
}
|
||||||
.number-control {
|
.number-control {
|
||||||
width: 128px;
|
width: 128px;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,7 +45,12 @@ export class AttestationService {
|
|||||||
};
|
};
|
||||||
const dataHash = this.blockchain.hashData(summary);
|
const dataHash = this.blockchain.hashData(summary);
|
||||||
const proof = await this.prisma.blockchainProof.create({
|
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 });
|
await this.queue.add('onchain', { proofId: proof.id });
|
||||||
return proof;
|
return proof;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
import { Global, Module } from '@nestjs/common';
|
||||||
import { BullModule } from '@nestjs/bullmq';
|
import { BullModule } from '@nestjs/bullmq';
|
||||||
import { QUEUE_NAMES } from '@artveris/shared';
|
import { QUEUE_NAMES } from '@artveris/shared';
|
||||||
|
import { SettingsModule } from '../settings/settings.module';
|
||||||
import { BlockchainService } from './blockchain.service';
|
import { BlockchainService } from './blockchain.service';
|
||||||
import { AttestationService } from './attestation.service';
|
import { AttestationService } from './attestation.service';
|
||||||
import { BlockchainController } from './blockchain.controller';
|
import { BlockchainController } from './blockchain.controller';
|
||||||
@@ -8,7 +9,7 @@ import { OnchainProcessor } from './onchain.processor';
|
|||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.ONCHAIN })],
|
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.ONCHAIN }), SettingsModule],
|
||||||
controllers: [BlockchainController],
|
controllers: [BlockchainController],
|
||||||
providers: [BlockchainService, AttestationService, OnchainProcessor],
|
providers: [BlockchainService, AttestationService, OnchainProcessor],
|
||||||
exports: [BlockchainService, AttestationService],
|
exports: [BlockchainService, AttestationService],
|
||||||
|
|||||||
@@ -1,25 +1,29 @@
|
|||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { SettingsService } from '../settings/settings.service';
|
||||||
import { BlockchainService } from './blockchain.service';
|
import { BlockchainService } from './blockchain.service';
|
||||||
|
|
||||||
function makeService(): BlockchainService {
|
function makeService(): BlockchainService {
|
||||||
const config = {
|
const config = {
|
||||||
get: (key: string) => (key === 'blockchain.driver' ? 'mock' : undefined),
|
get: (key: string) => (key === 'blockchain.driver' ? 'mock' : undefined),
|
||||||
} as unknown as ConfigService;
|
} 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', () => {
|
describe('BlockchainService.hashData', () => {
|
||||||
const svc = makeService();
|
const svc = makeService();
|
||||||
|
|
||||||
it('相同输入产生相同哈希', () => {
|
it('相同输入产生相同哈希', () => {
|
||||||
const a = svc.hashData({ title: '青花瓷', n: 1 });
|
const a = svc.hashData({ title: '青花瓶', n: 1 });
|
||||||
const b = svc.hashData({ title: '青花瓷', n: 1 });
|
const b = svc.hashData({ title: '青花瓶', n: 1 });
|
||||||
expect(a).toBe(b);
|
expect(a).toBe(b);
|
||||||
expect(a).toMatch(/^0x[0-9a-f]{64}$/);
|
expect(a).toMatch(/^0x[0-9a-f]{64}$/);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('不同输入产生不同哈希', () => {
|
it('不同输入产生不同哈希', () => {
|
||||||
const a = svc.hashData({ title: '青花瓷' });
|
const a = svc.hashData({ title: '青花瓶' });
|
||||||
const b = svc.hashData({ title: '霁红釉' });
|
const b = svc.hashData({ title: '霁红釉' });
|
||||||
expect(a).not.toBe(b);
|
expect(a).not.toBe(b);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,36 +1,52 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { createHash } from 'crypto';
|
import { createHash } from 'crypto';
|
||||||
|
import { SettingsService } from '../settings/settings.service';
|
||||||
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
|
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
|
||||||
import { MockProvider } from './mock.provider';
|
import { MockProvider } from './mock.provider';
|
||||||
import { TianheProvider } from './tianhe.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()
|
@Injectable()
|
||||||
export class BlockchainService {
|
export class BlockchainService {
|
||||||
private readonly logger = new Logger(BlockchainService.name);
|
private readonly logger = new Logger(BlockchainService.name);
|
||||||
private readonly provider: AttestationProvider;
|
|
||||||
|
|
||||||
constructor(private readonly config: ConfigService) {
|
constructor(
|
||||||
const driver = this.config.get<string>('blockchain.driver');
|
private readonly config: ConfigService,
|
||||||
if (driver === 'tianhe') {
|
private readonly settings: SettingsService,
|
||||||
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}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 计算任意业务数据的稳定摘要哈希
|
|
||||||
hashData(data: unknown): string {
|
hashData(data: unknown): string {
|
||||||
const json = JSON.stringify(data);
|
return '0x' + createHash('sha256').update(JSON.stringify(data)).digest('hex');
|
||||||
return '0x' + createHash('sha256').update(json).digest('hex');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
attest(payload: AttestPayload): Promise<AttestResult> {
|
async attest(payload: AttestPayload): Promise<AttestResult> {
|
||||||
return this.provider.attest(payload);
|
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 {
|
export interface AttestPayload {
|
||||||
// 业务数据摘要(对作品/证书/出库/节点等关键数据计算的哈希)
|
|
||||||
dataHash: string;
|
dataHash: string;
|
||||||
// 附带的可读元信息(仅用于存证记录,可选)
|
|
||||||
meta?: Record<string, unknown>;
|
meta?: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AttestResult {
|
export interface AttestResult {
|
||||||
dataHash: string;
|
dataHash: string;
|
||||||
txHash: string;
|
txHash: string;
|
||||||
blockHash: string;
|
blockHash?: string | null;
|
||||||
blockHeight: number;
|
blockHeight?: number | null;
|
||||||
chainName: string;
|
chainName: string;
|
||||||
explorerUrl: string;
|
explorerUrl?: string | null;
|
||||||
onchainAt: Date;
|
onchainAt: Date;
|
||||||
raw: Record<string, unknown>;
|
raw: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,12 @@ interface OnchainJobData {
|
|||||||
proofId: number;
|
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)
|
@Processor(QUEUE_NAMES.ONCHAIN)
|
||||||
export class OnchainProcessor extends WorkerHost {
|
export class OnchainProcessor extends WorkerHost {
|
||||||
private readonly logger = new Logger(OnchainProcessor.name);
|
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 } });
|
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
|
||||||
if (!proof) return;
|
if (!proof) return;
|
||||||
try {
|
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({
|
await this.prisma.blockchainProof.update({
|
||||||
where: { id: proofId },
|
where: { id: proofId },
|
||||||
data: {
|
data: {
|
||||||
status: ProofStatus.ONCHAIN,
|
status: ProofStatus.ONCHAIN,
|
||||||
txHash: result.txHash,
|
txHash: result.txHash,
|
||||||
blockHash: result.blockHash,
|
blockHash: result.blockHash || null,
|
||||||
blockHeight: BigInt(result.blockHeight),
|
blockHeight: result.blockHeight !== null && result.blockHeight !== undefined ? BigInt(result.blockHeight) : null,
|
||||||
chainName: result.chainName,
|
chainName: result.chainName,
|
||||||
explorerUrl: result.explorerUrl,
|
explorerUrl: result.explorerUrl || null,
|
||||||
onchainAt: result.onchainAt,
|
onchainAt: result.onchainAt,
|
||||||
rawResponse: result.raw as object,
|
rawResponse: result.raw as object,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
this.logger.log(`存证 ${proofId} 上链成功`);
|
this.logger.log(`存证 ${proofId} 上链成功`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
const message = (e as Error).message;
|
||||||
await this.prisma.blockchainProof.update({
|
await this.prisma.blockchainProof.update({
|
||||||
where: { id: proofId },
|
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';
|
import { AttestPayload, AttestResult, AttestationProvider } from './blockchain.types';
|
||||||
|
|
||||||
export interface TianheOptions {
|
export interface TianheOptions {
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
appId: string;
|
appId: string;
|
||||||
appKey: 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 {
|
export class TianheProvider implements AttestationProvider {
|
||||||
readonly name = 'tianhe';
|
readonly name = 'tianhe';
|
||||||
private readonly logger = new Logger(TianheProvider.name);
|
|
||||||
|
|
||||||
constructor(private readonly opts: TianheOptions) {}
|
constructor(private readonly opts: TianheOptions) {}
|
||||||
|
|
||||||
async attest(_payload: AttestPayload): Promise<AttestResult> {
|
async attest(payload: AttestPayload): Promise<AttestResult> {
|
||||||
if (!this.opts.appId || !this.opts.appKey || !this.opts.baseUrl) {
|
const baseUrl = required(this.opts.baseUrl, 'Base URL').replace(/\/+$/, '');
|
||||||
throw new Error('天河链未配置(TIANHE_APP_ID/APP_KEY/BASE_URL),请在 .env 配置后再启用 BLOCKCHAIN_DRIVER=tianhe');
|
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: 待天河链接入细节确认后实现真实存证请求与返回字段映射。
|
if (!res.ok) {
|
||||||
this.logger.warn('天河链真实接入尚未实现,请先使用 BLOCKCHAIN_DRIVER=mock');
|
throw new Error(`天河链存证请求失败:HTTP ${res.status} ${text.slice(0, 200)}`);
|
||||||
throw new Error('天河链真实接入待确认,请暂用 BLOCKCHAIN_DRIVER=mock');
|
}
|
||||||
|
|
||||||
|
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: {
|
blockchain: {
|
||||||
driver: 'mock' | 'tianhe';
|
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 };
|
seedAdmin: { username: string; password: string; name: string };
|
||||||
logRetentionDays: number;
|
logRetentionDays: number;
|
||||||
@@ -68,9 +68,11 @@ export default (): AppConfig => {
|
|||||||
blockchain: {
|
blockchain: {
|
||||||
driver: (process.env.BLOCKCHAIN_DRIVER as 'mock' | 'tianhe') || 'mock',
|
driver: (process.env.BLOCKCHAIN_DRIVER as 'mock' | 'tianhe') || 'mock',
|
||||||
tianhe: {
|
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 || '',
|
appId: process.env.TIANHE_APP_ID || '',
|
||||||
appKey: process.env.TIANHE_APP_KEY || '',
|
appKey: process.env.TIANHE_APP_KEY || '',
|
||||||
|
userId: process.env.TIANHE_USER_ID || '',
|
||||||
|
userKey: process.env.TIANHE_USER_KEY || '',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
seedAdmin: {
|
seedAdmin: {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
import { Type } from 'class-transformer';
|
import { IsArray, IsDateString, IsOptional, IsString, MaxLength } from 'class-validator';
|
||||||
import { IsArray, IsDateString, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
|
|
||||||
|
|
||||||
export class OutboundDto {
|
export class OutboundDto {
|
||||||
@ApiPropertyOptional({ description: '出库时间' })
|
@ApiPropertyOptional({ description: '出库时间' })
|
||||||
@@ -19,24 +18,6 @@ export class OutboundDto {
|
|||||||
@IsString({ each: true })
|
@IsString({ each: true })
|
||||||
outImageKeys?: string[];
|
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: '备注' })
|
@ApiPropertyOptional({ description: '备注' })
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
|
|||||||
@@ -115,7 +115,6 @@ export class ImportPreviewProcessor extends WorkerHost {
|
|||||||
status: 'INVALID',
|
status: 'INVALID',
|
||||||
shortCode: values.shortCode || null,
|
shortCode: values.shortCode || null,
|
||||||
batchNo: values.batchNo || null,
|
batchNo: values.batchNo || null,
|
||||||
txHash: values.txHash || null,
|
|
||||||
remark: values.remark || null,
|
remark: values.remark || null,
|
||||||
reason: '',
|
reason: '',
|
||||||
preview: values,
|
preview: values,
|
||||||
@@ -133,13 +132,6 @@ export class ImportPreviewProcessor extends WorkerHost {
|
|||||||
}
|
}
|
||||||
const outTime = parseDate(values.outTime);
|
const outTime = parseDate(values.outTime);
|
||||||
if (outTime === null) throw new Error('出库时间格式不正确');
|
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 || '')
|
const imagePaths = (values.outImages || '')
|
||||||
.split(';')
|
.split(';')
|
||||||
@@ -161,8 +153,6 @@ export class ImportPreviewProcessor extends WorkerHost {
|
|||||||
Object.assign(result, {
|
Object.assign(result, {
|
||||||
status: 'VALID',
|
status: 'VALID',
|
||||||
outTime,
|
outTime,
|
||||||
onchainAt,
|
|
||||||
blockHeight,
|
|
||||||
outImagePaths: imagePaths,
|
outImagePaths: imagePaths,
|
||||||
outImageKeys: imageItems,
|
outImageKeys: imageItems,
|
||||||
preview: { ...values, images: imageItems },
|
preview: { ...values, images: imageItems },
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||||
import { Logger } from '@nestjs/common';
|
import { Logger } from '@nestjs/common';
|
||||||
import { Job } from 'bullmq';
|
import { Job } from 'bullmq';
|
||||||
import { createHash } from 'crypto';
|
|
||||||
import * as ExcelJS from 'exceljs';
|
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 { PrismaService } from '../prisma/prisma.service';
|
||||||
import { StorageService } from '../storage/storage.service';
|
import { StorageService } from '../storage/storage.service';
|
||||||
import { JobsService } from '../jobs/jobs.service';
|
import { JobsService } from '../jobs/jobs.service';
|
||||||
@@ -55,27 +54,6 @@ export class ImportProcessor extends WorkerHost {
|
|||||||
remark: row.remark || undefined,
|
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 } });
|
await this.prisma.outboundImportRow.update({ where: { id: row.id }, data: { status: 'IMPORTED', reason: null } });
|
||||||
success++;
|
success++;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -116,7 +94,6 @@ export class ImportProcessor extends WorkerHost {
|
|||||||
{ header: '批次编号', key: 'batchNo', width: 22 },
|
{ header: '批次编号', key: 'batchNo', width: 22 },
|
||||||
{ header: '出库时间', key: 'outTime', width: 22 },
|
{ header: '出库时间', key: 'outTime', width: 22 },
|
||||||
{ header: '图片数量', key: 'imageCount', width: 10 },
|
{ header: '图片数量', key: 'imageCount', width: 10 },
|
||||||
{ header: '上链哈希', key: 'txHash', width: 30 },
|
|
||||||
{ header: '处理状态', key: 'status', width: 14 },
|
{ header: '处理状态', key: 'status', width: 14 },
|
||||||
{ header: '原因', key: 'reason', width: 40 },
|
{ header: '原因', key: 'reason', width: 40 },
|
||||||
];
|
];
|
||||||
@@ -128,7 +105,6 @@ export class ImportProcessor extends WorkerHost {
|
|||||||
batchNo: row.batchNo || '',
|
batchNo: row.batchNo || '',
|
||||||
outTime: row.outTime?.toISOString() || '',
|
outTime: row.outTime?.toISOString() || '',
|
||||||
imageCount: jsonArray(row.outImageKeys).length,
|
imageCount: jsonArray(row.outImageKeys).length,
|
||||||
txHash: row.txHash || '',
|
|
||||||
status: row.status,
|
status: row.status,
|
||||||
reason: row.reason || '',
|
reason: row.reason || '',
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,18 +2,11 @@ import { Injectable } from '@nestjs/common';
|
|||||||
import { InjectQueue } from '@nestjs/bullmq';
|
import { InjectQueue } from '@nestjs/bullmq';
|
||||||
import { Queue } from 'bullmq';
|
import { Queue } from 'bullmq';
|
||||||
import { Response } from 'express';
|
import { Response } from 'express';
|
||||||
import { createHash } from 'crypto';
|
|
||||||
import * as ExcelJS from 'exceljs';
|
import * as ExcelJS from 'exceljs';
|
||||||
import AdmZip from 'adm-zip';
|
import AdmZip from 'adm-zip';
|
||||||
import sharp from 'sharp';
|
import sharp from 'sharp';
|
||||||
import { Prisma, RoleType } from '@prisma/client';
|
import { Prisma, RoleType } from '@prisma/client';
|
||||||
import {
|
import { ErrorCode, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
|
||||||
ErrorCode,
|
|
||||||
JobType,
|
|
||||||
OUTBOUND_IMPORT_COLUMNS,
|
|
||||||
ProofStatus,
|
|
||||||
QUEUE_NAMES,
|
|
||||||
} from '@artveris/shared';
|
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { StorageService } from '../storage/storage.service';
|
import { StorageService } from '../storage/storage.service';
|
||||||
import { JobsService } from '../jobs/jobs.service';
|
import { JobsService } from '../jobs/jobs.service';
|
||||||
@@ -50,42 +43,10 @@ export class OutboundService {
|
|||||||
: Prisma.JsonNull;
|
: Prisma.JsonNull;
|
||||||
}
|
}
|
||||||
if ('remark' in dto) data.remark = dto.remark || null;
|
if ('remark' in dto) data.remark = dto.remark || null;
|
||||||
const updated = await this.prisma.traceCode.update({
|
return this.prisma.traceCode.update({
|
||||||
where: { id: traceCodeId },
|
where: { id: traceCodeId },
|
||||||
data,
|
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> {
|
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.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.getRow(1).font = { bold: true };
|
||||||
ws.addRow({
|
ws.addRow({
|
||||||
shortCode: '请替换为真实追溯码1',
|
shortCode: '请替换为真实追溯码',
|
||||||
batchNo: 'B20260704001',
|
batchNo: 'B20260704001',
|
||||||
outTime: '2026-07-04 10:00',
|
outTime: '2026-07-04 10:00',
|
||||||
outImages: 'images/out-001.jpg',
|
outImages: 'images/out-001.jpg',
|
||||||
txHash: '0xabc123',
|
|
||||||
onchainAt: '2026-07-04 10:30',
|
|
||||||
blockHeight: '8500001',
|
|
||||||
remark: '单图示例',
|
remark: '单图示例',
|
||||||
});
|
});
|
||||||
ws.addRow({
|
ws.addRow({
|
||||||
shortCode: '请替换为真实追溯码2',
|
shortCode: '请替换为真实追溯码',
|
||||||
batchNo: 'B20260704001',
|
batchNo: 'B20260704001',
|
||||||
outTime: '2026-07-04 11:00',
|
outTime: '2026-07-04 11:00',
|
||||||
outImages: 'images/out-002.png;images/out-003.jpg',
|
outImages: 'images/out-002.png;images/out-003.jpg',
|
||||||
txHash: '',
|
|
||||||
onchainAt: '',
|
|
||||||
blockHeight: '',
|
|
||||||
remark: '多图示例',
|
remark: '多图示例',
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -127,17 +82,21 @@ export class OutboundService {
|
|||||||
|
|
||||||
const zip = new AdmZip();
|
const zip = new AdmZip();
|
||||||
zip.addFile('outbound-import-template.xlsx', Buffer.from(await wb.xlsx.writeBuffer()));
|
zip.addFile('outbound-import-template.xlsx', Buffer.from(await wb.xlsx.writeBuffer()));
|
||||||
zip.addFile('说明.txt', Buffer.from(
|
zip.addFile(
|
||||||
[
|
'说明.txt',
|
||||||
'出库批量导入说明',
|
Buffer.from(
|
||||||
'',
|
[
|
||||||
'1. ZIP 根目录必须包含一个 xlsx 文件和 images 文件夹。',
|
'出库批量导入说明',
|
||||||
'2. 出库实况图路径填写 images/xxx.jpg,多张图片使用英文分号 ; 分隔。',
|
'',
|
||||||
'3. 不允许使用绝对路径、..、反斜杠或 images 目录之外的路径。',
|
'1. ZIP 根目录必须包含一个 xlsx 文件和 images 文件夹。',
|
||||||
'4. 上传 ZIP 后系统会先预览校验,确认无误后才正式导入。',
|
'2. 出库实况图路径填写 images/xxx.jpg,多张图片使用英文分号 ; 分隔。',
|
||||||
].join('\r\n'),
|
'3. 不允许使用绝对路径、..、反斜杠或 images 目录之外的路径。',
|
||||||
'utf8',
|
'4. 上传 ZIP 后系统会先预览校验,确认无误后才正式导入。',
|
||||||
));
|
'5. 链上哈希、存证链接和上链时间由天河链接口返回后自动写入,不在导入模板中手工填写。',
|
||||||
|
].join('\r\n'),
|
||||||
|
'utf8',
|
||||||
|
),
|
||||||
|
);
|
||||||
zip.addFile('images/out-001.jpg', await this.sampleImage('#13a8a8'));
|
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-002.png', await this.sampleImage('#3b82f6', 'png'));
|
||||||
zip.addFile('images/out-003.jpg', await this.sampleImage('#f59e0b'));
|
zip.addFile('images/out-003.jpg', await this.sampleImage('#f59e0b'));
|
||||||
@@ -182,7 +141,6 @@ export class OutboundService {
|
|||||||
return { sessionId: session.id, jobId: job.id };
|
return { sessionId: session.id, jobId: job.id };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 兼容旧入口:上传后只做预览,不直接入库。
|
|
||||||
startImport(file: Express.Multer.File, userId: number) {
|
startImport(file: Express.Multer.File, userId: number) {
|
||||||
return this.startPreview(file, userId);
|
return this.startPreview(file, userId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,13 @@ const EDITABLE_KEYS = [
|
|||||||
'backupSchedule',
|
'backupSchedule',
|
||||||
'backupRetentionDays',
|
'backupRetentionDays',
|
||||||
'backupRetentionCount',
|
'backupRetentionCount',
|
||||||
|
'blockchainDriver',
|
||||||
|
'tianheEnv',
|
||||||
|
'tianheBaseUrl',
|
||||||
|
'tianheAppId',
|
||||||
|
'tianheAppKey',
|
||||||
|
'tianheUserId',
|
||||||
|
'tianheUserKey',
|
||||||
];
|
];
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -37,6 +44,13 @@ export class SettingsService {
|
|||||||
backupSchedule: 'daily',
|
backupSchedule: 'daily',
|
||||||
backupRetentionDays: '30',
|
backupRetentionDays: '30',
|
||||||
backupRetentionCount: '10',
|
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) {
|
for (const r of rows) {
|
||||||
map[r.key] = r.key === 'appName' && r.value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : r.value;
|
map[r.key] = r.key === 'appName' && r.value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : r.value;
|
||||||
|
|||||||
@@ -86,6 +86,8 @@ services:
|
|||||||
TIANHE_BASE_URL: ${TIANHE_BASE_URL:-}
|
TIANHE_BASE_URL: ${TIANHE_BASE_URL:-}
|
||||||
TIANHE_APP_ID: ${TIANHE_APP_ID:-}
|
TIANHE_APP_ID: ${TIANHE_APP_ID:-}
|
||||||
TIANHE_APP_KEY: ${TIANHE_APP_KEY:-}
|
TIANHE_APP_KEY: ${TIANHE_APP_KEY:-}
|
||||||
|
TIANHE_USER_ID: ${TIANHE_USER_ID:-}
|
||||||
|
TIANHE_USER_KEY: ${TIANHE_USER_KEY:-}
|
||||||
OSS_ENDPOINT: ${OSS_ENDPOINT:-}
|
OSS_ENDPOINT: ${OSS_ENDPOINT:-}
|
||||||
OSS_REGION: ${OSS_REGION:-}
|
OSS_REGION: ${OSS_REGION:-}
|
||||||
OSS_BUCKET: ${OSS_BUCKET:-}
|
OSS_BUCKET: ${OSS_BUCKET:-}
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
// 全局常量。
|
|
||||||
|
|
||||||
export const QUEUE_NAMES = {
|
export const QUEUE_NAMES = {
|
||||||
GEN_CODE: 'gen-code',
|
GEN_CODE: 'gen-code',
|
||||||
IMPORT_OUTBOUND: 'import-outbound',
|
IMPORT_OUTBOUND: 'import-outbound',
|
||||||
@@ -10,18 +8,15 @@ export const QUEUE_NAMES = {
|
|||||||
RESTORE: 'restore',
|
RESTORE: 'restore',
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
// 公开随机短码长度(Base62)
|
|
||||||
export const SHORT_CODE_LENGTH = 10;
|
export const SHORT_CODE_LENGTH = 10;
|
||||||
|
|
||||||
// 上传限制
|
export const MAX_IMAGE_SIZE = 10 * 1024 * 1024;
|
||||||
export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB
|
export const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
|
||||||
export const MAX_VIDEO_SIZE = 100 * 1024 * 1024; // 100MB
|
export const MAX_FILE_SIZE = 20 * 1024 * 1024;
|
||||||
export const MAX_FILE_SIZE = 20 * 1024 * 1024; // 20MB
|
|
||||||
export const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/svg+xml'];
|
export const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/svg+xml'];
|
||||||
export const ALLOWED_VIDEO_TYPES = ['video/mp4', 'video/webm', 'video/quicktime'];
|
export const ALLOWED_VIDEO_TYPES = ['video/mp4', 'video/webm', 'video/quicktime'];
|
||||||
export const ALLOWED_DOC_TYPES = ['application/pdf', 'image/jpeg', 'image/png'];
|
export const ALLOWED_DOC_TYPES = ['application/pdf', 'image/jpeg', 'image/png'];
|
||||||
|
|
||||||
// 出库导入模板列定义(导入解析与模板下载共用,保证表头一致)
|
|
||||||
export interface ImportColumn {
|
export interface ImportColumn {
|
||||||
key: string;
|
key: string;
|
||||||
header: string;
|
header: string;
|
||||||
@@ -30,14 +25,40 @@ export interface ImportColumn {
|
|||||||
example: string;
|
example: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 出库导入按"每套追溯码"逐行填写(追溯码定位到具体一套),档案编号是款级、由系统自动生成,无需导入。
|
|
||||||
export const OUTBOUND_IMPORT_COLUMNS: ImportColumn[] = [
|
export const OUTBOUND_IMPORT_COLUMNS: ImportColumn[] = [
|
||||||
{ key: 'shortCode', header: '追溯码', required: true, note: '必填,生码导出文件中的追溯码(定位到具体一套)', example: 'a8K3pQ9x2M' },
|
{
|
||||||
{ key: 'batchNo', header: '批次编号', required: false, note: '选填,仅作核对,与该码实际批次不符则该行失败', example: 'B20240601' },
|
key: 'shortCode',
|
||||||
{ key: 'outTime', header: '出库时间', required: false, note: '选填,格式 YYYY-MM-DD HH:mm', example: '2024-06-01 10:00' },
|
header: '追溯码',
|
||||||
{ key: 'outImages', header: '出库实况图路径', required: false, note: '选填,ZIP 内 images 目录下的图片路径,多张用 ; 分隔,如 images/out-001.jpg;images/out-002.png', example: 'images/out-001.jpg;images/out-002.png' },
|
required: true,
|
||||||
{ key: 'txHash', header: '上链哈希值', required: false, note: '选填,链上交易/存证哈希,填写则记录上链结果', example: '0xabc123...' },
|
note: '必填,生码导出文件中的追溯码,定位到具体一件作品。',
|
||||||
{ key: 'onchainAt', header: '上链时间', required: false, note: '选填,格式 YYYY-MM-DD HH:mm', example: '2024-06-02 09:30' },
|
example: 'a8K3pQ9x2M',
|
||||||
{ key: 'blockHeight', header: '区块高度', required: false, note: '选填,整数', example: '8500001' },
|
},
|
||||||
{ key: 'remark', header: '备注', required: false, note: '选填', example: '' },
|
{
|
||||||
|
key: 'batchNo',
|
||||||
|
header: '批次编号',
|
||||||
|
required: false,
|
||||||
|
note: '选填,仅作核对;与该码实际批次不符则该行失败。',
|
||||||
|
example: 'B20240601',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'outTime',
|
||||||
|
header: '出库时间',
|
||||||
|
required: false,
|
||||||
|
note: '选填,格式 YYYY-MM-DD HH:mm。',
|
||||||
|
example: '2024-06-01 10:00',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'outImages',
|
||||||
|
header: '出库实况图路径',
|
||||||
|
required: false,
|
||||||
|
note: '选填,ZIP 内 images 目录下的图片路径,多张用 ; 分隔,如 images/out-001.jpg;images/out-002.png。',
|
||||||
|
example: 'images/out-001.jpg;images/out-002.png',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'remark',
|
||||||
|
header: '备注',
|
||||||
|
required: false,
|
||||||
|
note: '选填。',
|
||||||
|
example: '',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -132,6 +132,8 @@ def build_env(cfg: dict) -> dict[str, str]:
|
|||||||
"TIANHE_BASE_URL": bc["tianhe"]["base_url"],
|
"TIANHE_BASE_URL": bc["tianhe"]["base_url"],
|
||||||
"TIANHE_APP_ID": bc["tianhe"]["app_id"],
|
"TIANHE_APP_ID": bc["tianhe"]["app_id"],
|
||||||
"TIANHE_APP_KEY": bc["tianhe"]["app_key"],
|
"TIANHE_APP_KEY": bc["tianhe"]["app_key"],
|
||||||
|
"TIANHE_USER_ID": bc["tianhe"].get("user_id", ""),
|
||||||
|
"TIANHE_USER_KEY": bc["tianhe"].get("user_key", ""),
|
||||||
"LOG_RETENTION_DAYS": str(cfg["log"]["retention_days"]),
|
"LOG_RETENTION_DAYS": str(cfg["log"]["retention_days"]),
|
||||||
"WATERMARK_TEXT": cfg["watermark"]["text"],
|
"WATERMARK_TEXT": cfg["watermark"]["text"],
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,6 +49,8 @@ blockchain:
|
|||||||
base_url: "https://test.api.tichain.tianhecloud.com"
|
base_url: "https://test.api.tichain.tianhecloud.com"
|
||||||
app_id: ""
|
app_id: ""
|
||||||
app_key: ""
|
app_key: ""
|
||||||
|
user_id: ""
|
||||||
|
user_key: ""
|
||||||
|
|
||||||
log:
|
log:
|
||||||
retention_days: 365 # 查询日志默认保留天数(后台可改)
|
retention_days: 365 # 查询日志默认保留天数(后台可改)
|
||||||
|
|||||||
@@ -381,6 +381,8 @@ def write_env_file(path: Path, cfg: DeployConfig, image_tag: str) -> None:
|
|||||||
"TIANHE_BASE_URL": "",
|
"TIANHE_BASE_URL": "",
|
||||||
"TIANHE_APP_ID": "",
|
"TIANHE_APP_ID": "",
|
||||||
"TIANHE_APP_KEY": "",
|
"TIANHE_APP_KEY": "",
|
||||||
|
"TIANHE_USER_ID": "",
|
||||||
|
"TIANHE_USER_KEY": "",
|
||||||
"LOG_RETENTION_DAYS": "365",
|
"LOG_RETENTION_DAYS": "365",
|
||||||
"WATERMARK_TEXT": "仅供溯源核验使用",
|
"WATERMARK_TEXT": "仅供溯源核验使用",
|
||||||
"BACKUP_DIR": "/app/apps/api/backups",
|
"BACKUP_DIR": "/app/apps/api/backups",
|
||||||
@@ -513,6 +515,8 @@ services:
|
|||||||
TIANHE_BASE_URL: ${TIANHE_BASE_URL}
|
TIANHE_BASE_URL: ${TIANHE_BASE_URL}
|
||||||
TIANHE_APP_ID: ${TIANHE_APP_ID}
|
TIANHE_APP_ID: ${TIANHE_APP_ID}
|
||||||
TIANHE_APP_KEY: ${TIANHE_APP_KEY}
|
TIANHE_APP_KEY: ${TIANHE_APP_KEY}
|
||||||
|
TIANHE_USER_ID: ${TIANHE_USER_ID}
|
||||||
|
TIANHE_USER_KEY: ${TIANHE_USER_KEY}
|
||||||
GEO_DRIVER: mock
|
GEO_DRIVER: mock
|
||||||
volumes:
|
volumes:
|
||||||
- artveris_storage:/app/apps/api/storage
|
- artveris_storage:/app/apps/api/storage
|
||||||
|
|||||||
Reference in New Issue
Block a user