Merge branch 'dev/tianhe-no-metadata-upload'

This commit is contained in:
Nixevol
2026-07-13 01:30:14 +08:00
30 changed files with 1821 additions and 631 deletions
+89 -107
View File
@@ -1,86 +1,70 @@
# artveris · 艺术品可信溯源与认证系统
# Artveris · 艺术品可信溯源与认证平台
基于"一物一码、首次激活、多次查询"的艺术品全生命周期溯源与认证平台。包含面向消费者的移动溯源页、面向运营的管理后台,以及支持批量生码、出库导入、区块链存证(Mock 可切换真实)、查询风控等能力。
Artveris 是一套面向艺术品行业的全生命周期溯源与认证系统,围绕"一物一码、首次激活、多次查询"构建。平台为每件实物艺术品生成唯一追溯码与二维码,消费者扫码即可查看作品档案、溯源时间线、认证证书与区块链存证;运营方通过管理后台完成建档、审核、生码、出库登记与上链存证的完整闭环。
## 一、技术栈
## 核心能力
- 后端:Node.js + NestJS + Prisma + MySQL 8 + Redis + BullMQ
- 后台:Vue3 + Vite + Naive UI + Pinia + vue-i18n + ECharts
- 客户端:Vue3 + Vite(移动优先响应式溯源页,中英双语)
- 全栈 TypeScript,pnpm monorepo
- 图片处理 sharp、二维码 qrcode、导入导出 exceljs、ZIP 模板/备份 adm-zip
- **一物一码**:档案 → 批次 → 追溯码三层模型,一款作品可分批生产多件,每件实物独立编码、独立凭证。
- **首扫激活防伪**:追溯码首次被扫描时自动激活并留痕,重复查询计数提示,异常状态(停用/异常)明确警示。
- **区块链存证**:接入天河链,每件商品出库后可铸造为链上数字商品(NFT),消费者可凭交易哈希在区块浏览器独立查验;也可使用内置模拟驱动在无链环境下完整体验流程。
- **内容审核流**:档案修改走修订快照与审核,超管直改、运营提审,历史版本可追溯。
- **批量作业**:批量生码、二维码打包导出(xlsx + 图片)、出库 ZIP 批量导入(先预览校验后入库)。
- **预览模式**:后台可在不激活、不计数的前提下预览任意追溯码的消费者页面,预览链接由时效令牌保护,过期自动失效。
- **备份恢复**:手动/定时备份,备份包可下载、上传预校验后恢复,跨重装迁移。
- **国际化**:后台与消费者端均支持中英双语。
## 二、目录结构
## 系统组成
```
artveris/
├─ apps/
│ ├─ api/ # NestJS 后端(REST API + BullMQ 处理器)
│ ├─ admin/ # 运营管理后台(Vue3 + Naive UI)
│ └─ client/ # 客户端溯源页(Vue3 响应式)
│ ├─ api/ # NestJS 后端(REST API + BullMQ 异步任务)
│ ├─ admin/ # 运营管理后台(Vue3 + Naive UI)
│ └─ client/ # 消费者溯源页(Vue3,移动优先)
├─ packages/
│ └─ shared/ # 共享枚举/错误码/响应类型/常量
├─ docker/ # 生产镜像构建:Dockerfile.api + entrypoint.sh
├─ docs/ # PRD 与技术方案
└─ aidocs/ # 项目记忆与开发记录
│ └─ shared/ # 共享枚举/错误码/类型/常量
├─ docker/ # 生产镜像构建
├─ scripts/ # 开发/构建/部署脚本(Python)
├─ docs/ # 产品与技术文档
└─ aidocs/ # 开发过程记录
```
## 三、本地开发(已验证)
技术栈:全栈 TypeScript + pnpm monorepo。后端 NestJS + Prisma + MySQL 8 + Redis + BullMQ;前端 Vue3 + Vite + Naive UI + Pinia + vue-i18n + ECharts;图片处理 sharp,二维码 qrcode,表格 exceljs。
前置:Node ≥ 20;本机 **MySQL 8 与 Redis**(开发脚本直接连接本机服务,不使用 Docker;连不上不阻塞,仅告警并继续启动);脚本方式另需 Python 3.9+。pnpm 若未安装,脚本会通过 Node 自带的 corepack 自动激活项目声明的版本。
生产形态为**单服务同端口托管三端**:后台 `/admin`、消费者页 `/trace`、接口 `/api`、短链跳转 `/t/:code`、本地上传资源 `/uploads`,前置 Nginx 反代一个端口即可。
### 方式一:一键脚本(推荐)
## 快速开始(本地开发)
唯一运行配置来源是仓库根目录的 `.env`。`scripts/config.yaml` 只提供三端端口 + 安装向导的 MySQL/Redis 预填充,脚本**不再自动生成 `.env`**:
前置要求:Node ≥ 20,本机 MySQL 8 与 Redis,Python 3.9+(仅开发脚本使用)。pnpm 未安装时脚本会经 corepack 自动激活。
### 一键脚本(推荐)
```bash
python -m venv .venv # 首次:创建 Python 虚拟环境
.\.venv\Scripts\activate # 激活虚拟环境
python -m venv .venv
.\.venv\Scripts\activate # Windows;macOS/Linux 为 source .venv/bin/activate
python -m pip install -r scripts/requirements.txt
python scripts/dev.py --install # 首次:装依赖 + 启动三端
python scripts/dev.py # 日常启动(先激活 .venv)
python scripts/dev.py --install # 首次:安装依赖 + 启动三端
python scripts/dev.py # 日常启动
```
启动契约与生产一致:
- **全新检出(无 `.env`)**:自动进入安装向导,浏览器打开 `http://localhost:5173` 按页面提示填写 MySQL/Redis 与管理员账号,提交后自动建库、迁移、初始化并写入根 `.env`,随后转入正常开发模式。
- **已有 `.env`**:直接构建共享包、同步数据库并启动三端。加 `--no-seed` 跳过种子数据,`--stop` 停止全部进程。
- **没有 `.env`(全新检出)**:`dev.py` 自动进入安装向导(API 安装模式 + admin,不连库)。在 `http://localhost:5173` 填写本机 MySQL/Redis 与管理员账号并提交,向导会建库、迁移建表、初始化并写入根 `.env`,随后 API 退出。
- **已有 `.env`(安装向导或手动写入)**:`dev.py` 正常开发——构建 shared、prisma generate,探测 DB 可连则迁移+种子,再同时启动三端;`--no-seed` 跳过种子。
- `--install-mode`:强制安装向导调试(写临时 `apps/api/.env.install-dev`,不污染根 `.env`)。
若 PowerShell 阻止激活虚拟环境,先执行 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass`。更多细节见 `scripts/README.md`。
旧版脚本自动生成的 `.env`(首行含「由 scripts/config.yaml 自动生成」)会被 `dev.py` 检测到并删除,转入安装向导重新配置。
如果 PowerShell 阻止激活 `.venv`,可先执行:
```powershell
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
```
详见 `scripts/README.md`。
### 方式二:手动命令
### 手动命令
```bash
# 1. 安装依赖
pnpm install
# 2. 确保本机已安装并启动 MySQL 8 与 Redis,且已创建业务库(或账号有建库权限)
# 连接信息与根 .env 的 DATABASE_URL / REDIS_* 一致
# 3. 构建共享包
pnpm build:shared
# 4. 初始化数据库 + 种子数据
pnpm --filter @artveris/api prisma:migrate
pnpm --filter @artveris/api seed
# 或一键重置+种子: pnpm --filter @artveris/api db:reset
# 5. 分别启动三端
pnpm dev:api # 后端 http://localhost:3000 (文档 /api/docs)
pnpm dev:api # 后端 http://localhost:3000 (Swagger 文档 /api/docs)
pnpm dev:admin # 后台 http://localhost:5173
pnpm dev:client # 客户端 http://localhost:5174
```
### 默认账号(种子)
### 默认账号(种子数据)
| 角色 | 用户名 | 密码 |
| --- | --- | --- |
@@ -89,83 +73,81 @@ pnpm dev:client # 客户端 http://localhost:5174
| 审核员 | auditor | Auditor@123 |
| 只读监管 | viewer | Viewer@123 |
### 体验扫码溯源
### 体验流程
后台从「艺术品档案」进入某个档案的「数据管理」可查看/生成该档案下的批次与追溯码;客户端访问 `http://localhost:5174/#/trace/<短码>` 即可查看溯源详情(首次访问自动激活)。短链 `http://localhost:3000/t/<短码>` 会 302 跳转到客户端页面。
1. 后台「溯源模板」建模板 →「艺术品档案」建档并通过审核;
2. 档案的「数据管理」中生成批次与追溯码;
3. 追溯码列表点击码值可进入预览页(不激活);「登记出库」填写出库信息后可「保存并触发上链」;
4. 消费者端访问追溯码链接(列表中可复制)即可查看溯源详情,首次访问自动激活。
### 出库导入与备份
## 配置
- 出库批量导入使用 ZIP:根目录包含 1 个 xlsx 和 `images/` 文件夹,xlsx 中出库实况图路径填写 `images/xxx.jpg`,多张用英文分号分隔。后台会先预览校验,确认后才正式入库。
- 超管可在后台「系统设置 → 备份与恢复」手动创建、下载、删除备份包,也可在同页配置定时备份与保留策略。备份包保存在服务器本地非公开目录,不放入 `/uploads`。
运行配置集中在根目录 `.env`(示例见 `.env.example`),关键项:
## 四、环境变量(.env)
- `DATABASE_URL` / `REDIS_*`:数据库与缓存连接;
- `JWT_SECRET` / `JWT_EXPIRES_IN`:登录令牌;
- `STORAGE_DRIVER=local|oss` 与 `OSS_*` / `CDN_BASE_URL`:文件存储(本地磁盘或 S3 兼容对象存储);
- `BLOCKCHAIN_DRIVER=mock|tianhe` 与 `TIANHE_*`:区块链驱动。
所有配置集中在根目录 `.env`(示例见 `.env.example`),关键项:
平台名称、客户端地址、日志保留、备份策略、存储方式、区块链凭据等均可在后台「系统设置」在线修改,设置页的值优先于 `.env`。
- `APP_NAME` 平台显示名(甲方品牌名待定,改此一处即可;后台「系统设置」亦可在线修改)。
- `DATABASE_URL` / `REDIS_*` 数据库与缓存连接。
- `JWT_SECRET` / `JWT_EXPIRES_IN` 登录令牌。
- 文件存储:`STORAGE_DRIVER=local|oss`、`CDN_BASE_URL`、`OSS_*`。
- 备份目录:可选 `BACKUP_DIR` 指定服务器本地非公开备份目录。
- 区块链:`BLOCKCHAIN_DRIVER=mock|tianhe`、`TIANHE_*`。
上传媒体按 `{模板ID}/{档案编号}/` 目录归档,出库实况图存放于 `{模板ID}/{档案编号}/{追溯码}/`,文件名带业务语义与时间戳,便于直接浏览与迁移。
## 五、Mock 与可切换接入
## 区块链存证
为方便后续对接真实服务,以下能力均以 env 驱动的适配器实现,**默认走本地/Mock,切换真实服务无需改业务代码**:
- 默认 `mock` 驱动返回拟真数据,无需任何外部依赖即可演示完整上链流程;
- 切换天河链:后台「系统设置 → 区块链存证」选择天河链、填写 AppID/AppKey 并注册平台托管钱包即可,无需改代码;
- 每件商品上链即铸造一个链上数字商品(productId = 追溯码),交易确认后回填 tokenId 与区块高度,消费者可跳转区块浏览器查验;
- 集成细节、接口清单、流程与时序图见 [docs/天河链集成说明.md](docs/天河链集成说明.md)。
- **对象存储 / CDN**:默认本地磁盘(`/uploads` 静态访问)。要上云:设 `STORAGE_DRIVER=oss` 并填 `OSS_ENDPOINT/REGION/BUCKET/ACCESS_KEY_*`(S3 兼容,支持阿里云 OSS S3 端点 / MinIO);设 `CDN_BASE_URL` 启用 CDN。
- **区块链存证**:默认 `mock`(返回拟真交易哈希/区块高度/存证链接)。要接天河链:实现 `apps/api/src/blockchain/tianhe.provider.ts` 的 `attest()`(接口细节待确认),并设 `BLOCKCHAIN_DRIVER=tianhe` + `TIANHE_*`。
## 生产部署
## 六、生产部署
### 单服务 + 安装向导(推荐)
### 推荐方式:单服务 + 首次安装向导
```bash
python scripts/build.py # 生成发布包(.release/),含 server.cjs 与 PM2 配置
python scripts/build.py --upgrade # 生成升级包,只替换代码、保留 .env/storage/backups
```
系统本质是**一个 Node 服务同端口托管三端**:后台 `/admin`、客户端 `/trace`、接口 `/api`、短链 `/t/:code`、本地资源 `/uploads`。生产只需部署这一个服务(如宝塔/1Panel 的 Node/PM2 项目,或 systemd),域名与 HTTPS 由前置 Nginx/宝塔/1Panel 反代到该服务的监听端口即可。
部署后首次访问 `/admin` 自动进入安装向导,填写对外访问地址、MySQL/Redis 与管理员账号即完成初始化。持久层约定:`.env`、`storage/`(上传)、`backups/`(备份)与数据库在升级中永不覆盖。
首次启动访问后台 `/admin`,系统检测到未安装会**自动进入安装向导**,只需填写:
### Docker / 远程部署(可选)
- **对外访问地址**:一个域名即可,三端共用;客户端自动位于 `/trace`,后台 `/admin`,接口 `/api`。
- **服务监听端口**:默认 3000,由反代指向该端口。
- **MySQL**:主机/端口/库名/账号/密码。库不存在时会自动创建(`CREATE DATABASE`)并建表、初始化超管与基础设置;若业务账号无建库权限,可另填“建库管理员账号”。
- **Redis**:主机/端口/密码(默认 `127.0.0.1:6379`)。
- **管理员**与**存储方式**(本地/OSS)。
```bash
python scripts/build_docker.py # 构建离线 Docker 包(含镜像与 compose,目标机免联网)
python scripts/remote.py # SSH 一键远程部署/升级
```
提交后系统自动完成建库、迁移建表、数据初始化,并把配置写入运行目录下的单一 `.env`(带中文注释)后重启进入正式系统。发布包由 `python scripts/build.py` 生成(输出到 `.release/`):默认「全新包」含 `server.cjs`、`ecosystem.config.cjs` 与安装手册;加 `--upgrade` 生成「升级包」,自带 `upgrade.sh`/`upgrade.ps1`,只替换代码、保留服务器上的 `.env`、`storage/`、`backups/`。
容器入口默认监听 `127.0.0.1:18080`,由外层面板(宝塔/1Panel)反代域名与 HTTPS;数据落在宿主机 `data/` 目录。
> 统一持久化约定:`.env`(配置+密钥+溯源码盐)、`storage/`(上传)、`backups/`(备份)、数据库 是持久层,升级永不覆盖;代码/镜像是可替换层。配置只有一个文件——运行目录下的 `.env`。
### 可选:Docker / SSH 自动化
以下为**可选的自动化部署工具**,与核心系统解耦,仅在需要容器化或一键远程部署时使用。统一为「单域名单端口 + Nginx 反代到 API 容器」模型(API 仍单端口托管三端),且**与单服务部署一样走首次安装向导**:Docker 包只配置基础设施(MySQL/Redis/网络/镜像),不预置 `DATABASE_URL`、不自动创建管理员。配置数据落在宿主机 bind-mount 目录 `data/{config,storage,backups,mysql,redis}`,其中 `data/config/.env` 由安装向导写入:
- `python scripts/build_docker.py`:构建完整**离线 Docker 包**(API/MySQL/Redis/Nginx 镜像 + `docker-compose.yml` + `load.sh`/`up.sh`),输出 `dist/artveris-docker-*.tar.gz`;目标机只需 Docker,无需联网拉镜像,解压后 `sh up.sh` 即部署。容器首次启动进入安装向导(MySQL/Redis 连接信息已预填充为容器内 `mysql`/`redis`),在页面设置管理员账号密码后提交即完成。`up.sh [upgrade|fresh|clean]`:升级不覆盖已有 `.env` 与 `data/`(含 config),清理才删数据。
- `python scripts/remote.py`:SSH 一键远程部署——复用 build_docker 产包上传并执行 `up.sh`;交互选择「升级 / 全新 / 清理重装」,升级保留服务器 `.env` 与 `data/`。
容器入口默认监听 `127.0.0.1:18080`,由外层 1Panel/宝塔反代域名 + HTTPS;MySQL/Redis 只在容器专属网络内暴露,不占用宿主机端口。构建镜像的 Dockerfile 为 `docker/Dockerfile.api`(`docker/entrypoint.sh` 直接启动服务,建库/迁移/建超管由安装向导完成)。
## 七、命令速查
## 命令速查
| 命令 | 说明 |
| --- | --- |
| `python scripts/dev.py` | 本地开发一键启动(连本机 MySQL/Redis) |
| `pnpm build:shared` | 构建共享包 |
| `pnpm dev:api / dev:admin / dev:client` | 启动三端开发 |
| `pnpm build` | 构建全部 |
| `python scripts/build.py` | 构建非 Docker 发布包(宝塔/1Panel) |
| `python scripts/build_docker.py` | 构建离线 Docker 包 |
| `python scripts/remote.py` | SSH 远程 Docker 部署 |
| `pnpm --filter @artveris/api db:reset` | 重置数据库并种子化 |
| `python scripts/dev.py` | 本地开发一键启动 |
| `pnpm build` | 构建全部包 |
| `pnpm --filter @artveris/api test` | 后端单元测试 |
| `pnpm --filter @artveris/api db:reset` | 重置数据库并写入种子 |
| `python scripts/build.py` | 构建发布包 |
| `python scripts/build_docker.py` | 构建离线 Docker 包 |
## 八、安全与合规
## 文档索引
- 后台四角色(超管/运营/审核/只读监管)RBAC;C 端匿名访问。
- 后台关键写操作、导入、导出、上传、备份与恢复会记录操作日志;操作日志仅超管可见,保留周期后台可配。
- 查询日志按需完整记录 IP/设备,仅后台可见,用户端不展示;保留周期后台可配。
- 天河链等密钥仅存服务端 env,不下发前端。
| 文档 | 内容 |
| --- | --- |
| [docs/PRD-艺术品可信溯源与认证系统.md](docs/PRD-艺术品可信溯源与认证系统.md) | 产品需求 |
| [docs/技术方案-艺术品可信溯源与认证系统.md](docs/技术方案-艺术品可信溯源与认证系统.md) | 技术方案 |
| [docs/天河链集成说明.md](docs/天河链集成说明.md) | 区块链集成:关系/流程/时序/状态机图与接口说明 |
| [docs/项目交接文档.md](docs/项目交接文档.md) | 已定稿决策、边界与维护须知(新维护者必读) |
| [scripts/README.md](scripts/README.md) | 开发与部署脚本说明 |
## 九、许可协议
## 安全与合规
本项目为商业闭源软件,采用 [PolyForm Strict License 1.0.0](./LICENSE),版权归 Nixevol 所有。
- 后台四角色 RBAC(超管/运营/审核/只读监管),消费者端匿名访问;
- 关键写操作、密钥揭示与复制、导入导出、备份恢复均记录操作日志,仅超管可见;
- 查询日志记录访问 IP 与设备用于防伪风控,仅后台可见;
- 链上钱包凭据仅存服务端,前端默认掩码展示,揭示需二次确认并留痕。
未经作者书面授权,禁止分发、修改 / 二次开发,或用于任何商业用途;商业授权与合作请联系作者。详见根目录 `LICENSE`。
## 许可协议
本项目为商业闭源软件,采用 [PolyForm Strict License 1.0.0](./LICENSE),版权归 Nixevol 所有。未经书面授权,禁止分发、修改或用于任何商业用途。
+13
View File
@@ -250,6 +250,17 @@
- 出库/上链防重复(2026-07-10):按「一物一码只能出库一次、已上链不可再上」补齐幂等校验。① 出库:`outbound.service.updateSingle`(单件)、`import-preview.processor`(导入预览)、`import.processor`(导入提交,防预览→提交竞态)三处均对 `code.outTime` 已存在拒绝「该追溯码已登记出库,不可重复出库」。② 上链:`attestation.service.trigger` 新增查重——存在 ONCHAIN/CONFIRMING/PENDING 的 proof 即拒绝(已上链→「不可重复上链」,处理中→「请稍候」);仅 FAILED 可通过独立 `retry` 接口重试(retry 原地更新既有 proof、不走 trigger,不受影响)。实测重复上链/重复出库均返回 400 拒绝。
- 天河链确认节奏调整(2026-07-10):`onchain.processor` 确认查询改为「提交完立即查 1 次 → 未到 10s → 再 30s」共 3 次自动尝试,之后停等手动重新确认(原为 30s/60s 两次)。用延迟数组 `AUTO_CONFIRM_DELAYS_MS=[0,10_000,30_000]`、`MAX_AUTO_CONFIRM_ATTEMPTS=数组长度`,第 attempt 次延迟取 `[attempt-1]`。实测:提交同秒即查到 mint 已进块(status 0x0、blockHeight、tokenId),直接 ONCHAIN。
- 天河链方案 B 落地(存证+发行+轮换,2026-07-10,dev/refine):按甲方决策「其余全做、媒体待定」实现。① 数据模型:`blockchain_proof` 加 `token_id`/`contract_address`(迁移 `20260710110000_add_proof_token_fields`);schema 补 `@db.VarChar` 注解消除历史 drift(operation_log.path 512 / outbound_import_session.file_key 512 / backup_record.file_path 1024)。② `TianheProvider` 新增 `publish`(接口2,operateId≤20,name≤42,author≤120,feature≤500)与 `updateUserKey`(接口7)。③ `BlockchainService.attestWithTianhe`:upload 存证→publish 铸 1 NFT(productId=追溯码、feature=存证链接)→ 主 txHash 切为 mint 交易、confirmationRequired=true 走接口9确认→ONCHAIN;合约地址存 `tianheContractAddress`、已发行最大 tokenId 存 `tianheMaxTokenId`(指定合约时作 baseTokenId,队列串行无争用);缺 product 时退化纯存证。`confirmTransaction` 确认成功回填 tokenId、更新 maxTokenId。④ `rotateTianheUserKey`:生成新随机 key→接口7链上改→持久化→接口8校验地址,`/settings/tianhe/identity/rotate` + 设置页「轮换密钥」(二次确认+回显强提示)。⑤ C 端:public-trace + Trace.vue 区块链卡增 tokenId/合约地址展示(i18n chain.tokenId/chain.contract)。⑥ 实测(测试环境):追溯码 412680781069 走通 upload→publish(合约 0xc96ae8a4... tokenId=0)→确认(区块高度 5820347)→ONCHAIN,C 端展示数字藏品编号 0/合约地址/区块高度;轮换 UserKey 成功(钱包地址不变),新 key 回填测试文档。验证:4 包构建 + 27 单测通过。**唯一待定:媒体上链层级 L1/L2/L3 待甲方确认「链上放什么」,当前维持 JSON 存证。**
- 首版定稿与交接(2026-07-13):五项收尾。① 艺术品档案列表「追溯码数量」列改为可点击链接(NButton text type=primary),点击进入该档案追溯码管理页 `/artworks/:id/trace-codes`。② 新增 `docs/天河链集成说明.md`——以代码现状(仅发行、无元数据上链)为准的正式集成文档,含实体关系图/业务流程图/上链时序图/存证状态机/身份生命周期图(mermaid)+ 接口清单(用 1/2/3/7/9,不用 upload/transfer/burn 及原因)+ 发行参数约束 + 实测接口行为 + 生产上线检查单。③ 重写产品化 `README.md`(去过程性字样,产品简介/系统组成/快速开始/配置/区块链/部署/命令速查/文档索引/许可)。④ 新增 `docs/项目交接文档.md`——面向新维护者(人+AI)的记忆继承入口:全部已拍板决策清单(天河链定稿/密钥安全/出库上链三不变量/审核流/C端/预览/媒体存储/权限/部署)、已知取舍与坑 10 条、关键代码地图、运维要点、AI 记忆继承指引与冲突裁决规则(代码现状 > 交接文档 > project_context > docs 旧表述)。⑤ 所有分支合并入 master 并删除 dev/refine、dev/tianhe-no-metadata-upload(仅本地,未推送远程),master 为首版终版。
- 追溯码客户端预览功能(2026-07-12,分支 `dev/tianhe-no-metadata-upload`):后台可预览 C 端页面且**零副作用**(不激活/不计数/不写查询日志)。① 令牌:`common/utils/preview-token.util.ts` 类 TOTP——HMAC-SHA256(jwt.secret, `preview:窗口号`) 取 16 hex,周期 10 分钟,校验接受当前+上一窗口(实际有效 10~20 分钟),无状态不落库,`timingSafeEqual` 防时序;外泄地址最长 2 窗口失效。② 后端:`GET /trace-codes/preview-token`(登录态)返回 `{token, clientBase, periodMs}`;`GET public/trace/:shortCode/preview?token&state`(@Public+限流)校验失败返回 `{status:'PREVIEW_EXPIRED'}`,成功走 `PublicTraceService.preview(state)`——与 trace() 共用 `buildArtworkPayload`(作品/时间线/证书/链上),但无任何 update/writeLog;`state=inactive` 时 antiCounterfeit 演示为首次扫码,`active` 用库中现值(0 时占位 2)。③ C 端:路由 `/trace/preview/:code` 复用 Trace.vue;`isPreview` 按路径判定,预览条(sticky 橙色)含「未激活/已激活」切换(切换重新请求),PREVIEW_EXPIRED 显示「预览链接已过期请回后台重开」。④ 后台:`traceCodeApi.previewToken`;TraceCodePanel 令牌缓存 8 分钟;**点追溯码=进预览页**(hover 提示「点击进入预览页(不激活、不计入查询次数)」;先同步 window.open('about:blank') 再异步填 URL 防弹窗拦截);**点链接列=弹确认框**告知直接访问会激活/计数,按钮[取消][访问预览页面][访问实际页面]。⑤ 预览 URL 仅点击时临时拼接不进行数据,导出仍只含真实短链。验证:5 项令牌单测 + API 实测(preview 前后 queryCount=0/INACTIVE 不变、查询日志 0 条、坏令牌拒绝、双状态正确)+ 全量构建 + 32 单测通过。
- 追溯码列表列重排+关联跳转(2026-07-12,分支 `dev/tianhe-no-metadata-upload`,两页共用 `TraceCodePanel` 同时生效):列顺序改为 追溯码→名称→档案编号→批次编号→分组→出库状态→上链状态→出库时间→激活状态→查询次数→激活时间→链接→创建时间→操作;名称/档案编号仅全局页显示(`fixedArtworkId` 时隐藏,档案内为同一作品)。关联:追溯码列渲染为 `<a target=_blank href=r.url>` 点击开 C 端溯源页;名称/档案编号渲染为 `.cell-link` 点击 `goArtwork(id)` → `router.push({name:'artwork-detail'})`。`status` 列标题改用 `pages.traceCode.activationStatus`(激活状态),`firstActivatedAt` 标签改为「激活时间」,新增 `openTrace` i18n。追溯码列 `fixed:'left'`、操作列 `fixed:'right'`。浏览器双页实测通过。
- 媒体存储层级改为人类可读目录(2026-07-13):原为 `YYYY/MM/DD/{hash16}-{nanoid}{ext}` 按上传日期混存、文件名不可辨认。新层级 **`{模板ID}/{档案编号}/`**:作品图 `作品图_{YYYYMMDDHHmmss}_{序号}.ext`、节点图 `节点-{标题}_...`、证书 `证书-{名称}_...`(水印件沿用 derivedKey 同目录 `_wm` 后缀);出库实况图再下一级 **`{模板ID}/{档案编号}/{追溯码}/出库实况_{时间戳}_{序号}.ext`**。实现=「上传仍进通用日期目录,实体保存时归位(move)」:① `StorageService` 增 `sanitizeSegment`(清洗非法字符)/`moveKey`(读→写→删,失败保留原 key 不断业务)/`relocateMedia`(批量归位+改写 url+返回 oldKey→newKey 映射,跳过已在目录内/http/data:);② `artwork.service.relocateArtworkMedia`:create 事务后归位(档案编号事务内才生成)并回写初始 revision afterSnapshot;update 开头先归位既有媒体(顺带渐进迁移历史存量)→ keyMap 改写 DTO → 再归位 DTO 新上传,快照/`applySnapshot` 的证书按 originKey reconcile 因两侧同步改写不受影响;③ `outbound.updateSingle` 与 `import.processor` 在写 outImages 前归位(include artwork 取 templateId/archiveNo)。已知取舍:历史 revision 快照仍持旧 key,其文件被迁移后历史审核详情预览会 404(业务数据不受影响)。构建+32 单测通过。
- AppKey 揭示改为明文(2026-07-13):用户原话「APPKey点击眼睛后显示442******de7 而不是完整的key」实为**吐槽**(点眼睛只看到掩码、看不到完整 key),前两轮误读成"要求只显示掩码"。改正:`POST /settings/tianhe/app-key/reveal`(超管+操作日志)改回返回明文 `appKey`;前端确认框文案改为「将显示完整 App Key 并记入操作日志」,确认后输入框回填明文(type=text 完整可见),收起眼睛时若未编辑则恢复服务端掩码(明文不留输入框);`update()` 的 `isMaskedSecret` 跳过逻辑保证掩码值保存不会覆盖真实 key。教训:**用户描述现象时"显示X而不是Y"大概率是抱怨现状X、想要Y,拿不准先确认**。
- 追溯码链接直连客户端地址(2026-07-13):用户设置了「客户端地址」但列表/二维码仍生成 `/t/` 短链(仅取 origin 拼 `/t/`,丢了路径且必须经后端跳转)。改为 `buildDynamicShortLink = ${clientBaseUrl}/#/trace/${shortCode}`(完整含路径,列表/详情/二维码/导出四处共用,动态生成换地址自动跟随);删除无人引用的 `buildTraceUrl/buildShortLink/shortLinkOrigin` 与 ConfigService 注入。`GET /t/:shortCode` 跳转端点保留,兼容历史已打印二维码。API 构建+32 单测通过。
- 系统设置页排版返工(2026-07-12,分支 `dev/tianhe-no-metadata-upload`):上一版分页布局被用户否掉(全竖排、控件不自适应、卡片标题与 tab 重复、区块链两卡没有真正左右排、AppKey 掩码被窄输入框截断)。重做要点:① 各 tab 去掉与 tab 同名的内层卡片标题,直接放 `n-form label-placement="left" :label-width="150" :show-feedback="false"`(标题左、控件右、`max-width:720px` 内自适应拉伸);② 备份 tab=顶部横排 inline 表单(定时备份/保留天数/数量)+ 分割线 + `BackupRestorePanel` flex 填满剩余高度(tab-pane 加 `pane-flex` 关外层滚动),表格自适应宽度;③ 区块链 tab=`chain-grid`(`grid-template-columns:repeat(auto-fit,minmax(430px,1fr))`)两卡真左右并排:左卡「接口配置」(新 i18n 键 `chainApiConfig`,避免与 tab 名重复)、右卡「链上身份」按钮在卡头右侧;④ AppKey 输入框拉宽后揭示的掩码 `442******de7` 完整可见(实测);⑤ 补 `watch(route.query.tab)` 支持浏览器前进/后退与手改地址栏同步切 tab。浏览器逐 tab 截图实测通过(URL 跟随、确认框、掩码、备份表格填充)。教训:**转包 UI 布局任务必须附截图级验收标准,否则容易做成"能编译但难看"**。
- 追溯码列表锚点样式与状态列点击(2026-07-12,分支 `dev/tianhe-no-metadata-upload`):① 修复名称/档案编号锚点样式不生效——表格单元格由 `n-data-table` 子组件渲染、不带本组件 scope 属性,`.cell-link` 须用 `:deep()` 才命中,改为 `:deep(.cell-link)`。② 出库状态、上链状态两列渲染包一层 `.cell-click`(cursor:pointer + hover 提亮),点击调 `openOutboundModal(row)` 进「出库上链」详情弹窗。③ 只读角色(`!auth.canWrite`)从状态列点开弹窗时隐藏保存/触发按钮(footer `v-if="!targetOnchain && auth.canWrite"`)。admin 构建通过。
- 出库/上链弹窗 UI 打磨(2026-07-10,分支 `dev/tianhe-no-metadata-upload`):① 出库时间加红星必填标识(`n-form-item-gi :required="!outboundReadonly"`);② 修复「关闭」按钮显示字面量——`common.action` 原缺 `close` 键,已补中英;③「区块链存证」详情用 `n-descriptions` 的 `label-style` 设 `whiteSpace:nowrap + verticalAlign:middle`,标题不再折行、垂直居中;④ 除「上链状态」外每项(数据哈希/交易哈希/tokenId/合约/区块高度/上链时间/存证查询)加复制按钮(`CopyOutline` + `navigator.clipboard`,`copyValue` 提示 `common.msg.copied/copyFailed`)。浏览器实测通过。
- 出库/上链一致性强化(2026-07-10,分支 `dev/tianhe-no-metadata-upload`):按甲方口径补三条不变量。① 确认中即已上链:前端 `rowIsOnchain` 由仅认 ONCHAIN 改为认 `ONCHAIN/CONFIRMING/PENDING`(这些状态菜单均显示「上链信息」、不给再触发;仅 FAILED 显示「上链」可重试),与后端 `attestation.trigger` 早有的防重复拦截对齐(天河 publish 一返回 mint 哈希即已广播上链、必进块,除非明确失败,故确认中不可重复上链);`targetProof` 回退用 `latestAnyProof` 使确认中也能展示上链信息。② 出库时间必填默认此刻:弹窗未出库时默认 `dayjs()` 此刻、前端空值拦截、后端 `outbound.updateSingle` 强制 `outTime` 非空。③ 上链必先出库:后端 `attestation.trigger` 增 `isOutbound(code)` 校验,未出库拒绝「请先登记出库再上链」,杜绝「已上链未登记」不一致(防直连 API 绕过)。注:这些为通用改进,暂随本分支;方案二合并时一并进 dev/refine,若方案二被否再单独回植。
- 天河链去掉元数据上链存证、改为仅发行(2026-07-10,分支 `dev/tianhe-no-metadata-upload`,待甲方展示确认后再合并):甲方定「不上传元数据、作品详情/媒体存我方 OSS」。上链链路由「upload 存证 + publish 发行」精简为「仅 publish 发行」,每件省一次上链调用(按次计费更省)。改动:① `AttestPayload.product` 增 `feature`;② `attestation.service` 注入 `StorageService`,`product.feature=作品主图公开URL`(天河 feature 语义=作品媒体地址,正是甲方放 OSS 的图,藏品/交易详情页可展示);③ `onchain.processor.productInfo` 透传 feature;④ `blockchain.service.attestWithTianhe` 删除 `provider.attest(upload)` 调用,直接 publish(feature),raw 去掉 upload 痕迹。`TianheProvider.attest`(upload) 方法保留(AttestationProvider 接口所需 + 便于甲方后续加回,仅需在 attestWithTianhe 恢复两步调用)。dataHash 仍本地计算并展示(作品数据指纹,非天河链上存证)。构建+11 单测通过。分支未合并。
- C端「查看存证」改跳天河区块浏览器交易详情页(2026-07-10):原 `explorerUrl` 存的是 upload 返回的 UDFS 裸 JSON 链接(打开只有文本,不规范)。实测天河浏览器 URL 规则后改为跳交易详情页 `https://{test.}explorer.tianhecloud.com/#/tiChain/transDetail?hash=<mintTxHash>`(显示状态/区块高度/发行动作/合约/productId=追溯码/feature=存证链接,规范完整)。实现:`TianheProvider.explorerTxUrl()` 按 API base 是否含 `test.` 自动切测试/生产浏览器域名;`blockchain.service.attestWithTianhe` 的 `explorerUrl` 改用它,UDFS 链接保留在 `raw.attestUrl`(浏览器 feature 字段也含)。确认流程不覆盖 explorerUrl。C 端/后台经 `public-trace`、trace-code 列表自动跟随。仅对新上链记录生效,旧记录重上链即更新。藏品详情页 `nfrDetail?nfrId=&contractAddress=` 因不传媒体会显示「未获取到媒体内容」故不选它。API 构建+11 单测通过。
- 天河链范围甲方定稿(2026-07-10 微信):① 范围=三步接入的第①②步+第③步「首发」——链上注册→部署合约→铸造链上商品→首发,**首发=铸造到平台钱包(publish 已覆盖,无需额外接口)**;不做第③步 NFT 二级交易(transfer 转让 / burn 合并·销毁)。甲方「不做 NFT」= 不做二级交易,铸造/发行照做,**方案B(存证+发行)保留不动**。② **媒体不上链**:图片/视频全部只存我方服务器/OSS,天河只放存证 JSON;L1/L2/L3 媒体上链全部不做(原「媒体缺口/待甲方确认」项关闭);副作用已知接受:哈希锁结构化溯源信息、不锁媒体本体。③ **不做删除功能**:上链不可删(区块链本质),现状符合(删除不触链、已上链受限删除)。④ **计费=按每次调用上链接口计费**(非按容量),每件=upload+publish 两次调用,是否每件都上链为纯运营决策。结论:代码无需改动,仅锁定决策到 `aidocs/天河链对接分析与建议.md` §七/§八。
- 出库上链菜单按状态动态化(2026-07-10):`TraceCodePanel` 行操作菜单「登记出库/上链」改名「出库上链」并按状态切换:未登记=「出库上链」(弹窗可编辑,按钮 保存登记 / 保存并触发上链);已登记未上链=「上链」(弹窗回填已登记出库时间/备注/实况图且只读,按钮仅「触发上链」,saveOutbound 跳过 updateSingle 只调 onchain,避免撞出库幂等);已登记已上链=「上链信息」(只读回填 + 追加区块链信息 n-descriptions:上链状态/dataHash/txHash/tokenId/合约/区块高度/上链时间/存证链接,底部仅「关闭」,隐藏所有保存按钮)。状态判定 `rowIsOutbound`(outTime 或 outImages)、`rowIsOnchain`(latestProof=ONCHAIN);只读态用 `outboundReadonly` 驱动表单与新增的 `MediaUpload :disabled`(禁上传/删除、保留预览)。i18n 新增 traceCode.triggerOnchainOnly/onchainInfo、blockchain.status/tokenId/contract。admin 构建通过。
@@ -297,6 +308,8 @@
- vite dev 访问体验(2026-07-09):① admin/client 的 base 分别为 `/admin/`、`/trace/`,dev 下直接访问 `/admin`(无尾斜杠)或根 `/` 时 vite 只提示 "did you mean /admin/" 不跳转——两个 `vite.config.ts` 各加 `redirectToBase` 插件(`configureServer` 中间件),把 `/` 与不带尾斜杠的 base 302 到带尾斜杠的 base(保留 query)。② admin 代理 `/api` 增加 `configure` 错误处理 `onProxyError`:安装完成自动切换、API 重启的空档里前端仍在轮询 `/api/install/status`,连接被拒时返回 503 让前端静默重试,避免大段 `ECONNREFUSED` 堆栈。(生产单端口由 API `mountSpa` 托管 `/admin`→index,无此问题。)
- 本地 dev 进程管理:`--stop` + 安装后自动切换(2026-07-09,明确不引入 PM2):本地 dev 仍是「前台阻塞 + Job Object/控制台事件整树清理」模型,PM2 仅用于生产(build.py 的 `ecosystem.config.cjs`)。新增两点 PM2 式体验:① `python scripts/dev.py --stop`:复用 `kill_project_servers(ports)` 一键停掉 api/admin/client 后退出,零新依赖。② 安装完成自动切正式模式:无 `.env` 进入安装向导后,`dev.py` 用 `wait_for_install_env(ENV_FILE, api_proc)` 持续监听根 `.env` 出现——因后端在迁移+建超管全部成功后**最后一步**才写 `.env`,失败尝试与填写过程都不写,故「文件出现且非空」是安全的完成信号,**天然避开安装中重启**;一旦检测到即 `stop_proc_tree` 安装 API + `free_port(3000)`,保留 admin vite 不断连,以正式模式重启 `dev:api`+`dev:client`(不再迁移/种子,避免覆盖向导设置的管理员),随后 `p.wait()` 阻塞,Ctrl+C 仍整树清理。`--install-mode` 调试模式写临时 `.env.install-dev`、不自动切换(保留手动重run)。前端 `submit()` 相应简化为:成功后统一 `pollUntilReady()`(等 `installed && !needsDevRestart`)就绪跳后台,超时兜底提示 `doneLocalDev`。`dev.py` 导入补 `free_port`/`stop_proc_tree`。验证:api/admin build 通过、`py_compile` 通过。
- 系统设置页分页重构 + 区块链存证卡安全排版(2026-07-12):`Settings.vue` 改为 5 个 `n-tab-pane`(platform 平台 / logs 仅日志保留天数 / blockchain 区块链存证 / storage 存储 / backup 备份策略+备份列表,logs 与 backup 拆成独立 tab)。URL 跟随 tab:`onTabChange` 用 `router.replace({query:{...,tab}})`,进入页读 `route.query.tab` 初始化,`TAB_NAMES=['platform','logs','blockchain','storage','backup']` 非法回落 platform。布局去居中:`.tab-body` 去 `display:flex`、`.tab-stack` `margin:0`、去掉 tabs nav 的 `justify-content:center`,内容顶部左对齐 + `max-width`(stack-narrow 560/stack-wide 1080)。区块链 tab 改 `n-grid cols="1 900:2"` 两卡左右并排:左卡=驱动/环境/接口地址/AppID/AppKey,右卡=链上身份(钱包地址/UserID/UserKey + 重新确认身份/手动录入/轮换密钥按钮,mock 驱动时右卡显示 `tianheIdentityMockHint`)。安全:AppKey 眼睛揭示走 `POST /settings/tianhe/app-key/reveal`(`maskSecretPublic` 只回 `442******de7` 掩码,永不回明文)+ 二次确认;UserKey 复制走有审计的 `POST /settings/tianhe/identity/reveal`(OperationLogInterceptor 留痕)+ 二次确认;揭示/复制均为 `@vicons/ionicons5` 图标按钮(quaternary circle)。后端接口/掩码工具此前已具备,本次仅前端重构 + 新增 i18n 键(tabLogs/tabBackup/tianheIdentityMockHint,删除 tabLogsBackup)。浏览器 MCP 未连通,以 `pnpm --filter @artveris/admin build` 通过为准。
### apps/client(Vue3+Vite 移动优先溯源页)
- 入口 `views/Trace.vue`(顶部媒体无缝轮播、防伪横幅、动态字段、时间轴节点媒体默认收缩、水印证书、区块链卡、i18n、暗色变量)+ `Home.vue`;`composables/openMediaViewer.ts`(PhotoSwipe,已弃用旧 MediaViewer.vue);hash 路由 `/trace/:code`,短链 `/t/{code}` 由 API 302。
+2
View File
@@ -85,6 +85,7 @@ export const traceCodeApi = {
qrBlob: (id: string) => download(`/trace-codes/${id}/qrcode`),
onchain: (id: string) => post(`/trace-codes/${id}/onchain`, {}),
confirmProof: (id: number) => post(`/blockchain-proofs/${id}/confirm`, {}),
previewToken: () => get<{ token: string; clientBase: string; periodMs: number }>('/trace-codes/preview-token'),
// 分组
groups: (params?: object) => get<any[]>('/trace-code-groups', params),
createGroup: (data: { name: string; remark?: string }) => post('/trace-code-groups', data),
@@ -138,6 +139,7 @@ export const settingsApi = {
tianheVerify: (data: { userId: string; userKey: string }) =>
post<{ userId: string; address: string }>('/settings/tianhe/verify', data),
tianheIdentity: () => get<{ userId: string; address: string; userKeyMasked: string }>('/settings/tianhe/identity'),
tianheRevealAppKey: () => post<{ appKey: string }>('/settings/tianhe/app-key/reveal', {}),
tianheReveal: () => post<{ userId: string; userKey: string; address: string }>('/settings/tianhe/identity/reveal', {}),
tianheRotate: () => post<{ userId: string; userKey: string; address: string }>('/settings/tianhe/identity/rotate', {}),
};
+257 -55
View File
@@ -147,7 +147,7 @@
<n-modal v-model:show="outboundModal" preset="card" :title="outboundModalTitle" style="width: 620px">
<n-form :model="outboundForm" label-placement="top">
<n-grid :cols="2" :x-gap="16">
<n-form-item-gi :label="t('pages.outbound.outTime')">
<n-form-item-gi :label="t('pages.outbound.outTime')" :required="!outboundReadonly">
<n-date-picker v-if="!outboundReadonly" v-model:formatted-value="outboundForm.outTime" value-format="yyyy-MM-dd HH:mm" type="datetime" clearable style="width: 100%" />
<n-text v-else>{{ outboundForm.outTime || '-' }}</n-text>
</n-form-item-gi>
@@ -163,30 +163,51 @@
<template v-if="targetOnchain && targetProof">
<n-divider style="margin: 4px 0 12px">{{ t('pages.blockchain.title') }}</n-divider>
<n-descriptions :column="1" label-placement="left" size="small" bordered>
<n-descriptions
:column="1"
label-placement="left"
size="small"
bordered
:label-style="{ whiteSpace: 'nowrap', verticalAlign: 'middle' }"
:content-style="{ verticalAlign: 'middle' }"
>
<n-descriptions-item :label="t('pages.blockchain.status')">
<n-tag size="small" :type="proofStatusType(targetProof)">{{ proofStatusText(targetProof) }}</n-tag>
</n-descriptions-item>
<n-descriptions-item v-if="targetProof.dataHash" :label="t('pages.blockchain.dataHash')">
<span class="onchain-mono">{{ targetProof.dataHash }}</span>
<span class="onchain-val"><span class="onchain-mono">{{ targetProof.dataHash }}</span>
<n-button quaternary circle size="tiny" :title="t('common.action.copy')" @click="copyValue(targetProof.dataHash)"><template #icon><n-icon :component="CopyOutline" /></template></n-button>
</span>
</n-descriptions-item>
<n-descriptions-item v-if="targetProof.txHash" :label="t('pages.blockchain.txHash')">
<span class="onchain-mono">{{ targetProof.txHash }}</span>
<span class="onchain-val"><span class="onchain-mono">{{ targetProof.txHash }}</span>
<n-button quaternary circle size="tiny" :title="t('common.action.copy')" @click="copyValue(targetProof.txHash)"><template #icon><n-icon :component="CopyOutline" /></template></n-button>
</span>
</n-descriptions-item>
<n-descriptions-item v-if="targetProof.tokenId" :label="t('pages.blockchain.tokenId')">
<span class="onchain-mono">{{ targetProof.tokenId }}</span>
<n-descriptions-item v-if="targetProof.tokenId !== null && targetProof.tokenId !== undefined" :label="t('pages.blockchain.tokenId')">
<span class="onchain-val"><span class="onchain-mono">{{ targetProof.tokenId }}</span>
<n-button quaternary circle size="tiny" :title="t('common.action.copy')" @click="copyValue(targetProof.tokenId)"><template #icon><n-icon :component="CopyOutline" /></template></n-button>
</span>
</n-descriptions-item>
<n-descriptions-item v-if="targetProof.contractAddress" :label="t('pages.blockchain.contract')">
<span class="onchain-mono">{{ targetProof.contractAddress }}</span>
<span class="onchain-val"><span class="onchain-mono">{{ targetProof.contractAddress }}</span>
<n-button quaternary circle size="tiny" :title="t('common.action.copy')" @click="copyValue(targetProof.contractAddress)"><template #icon><n-icon :component="CopyOutline" /></template></n-button>
</span>
</n-descriptions-item>
<n-descriptions-item v-if="targetProof.blockHeight" :label="t('pages.blockchain.blockHeight')">
{{ targetProof.blockHeight }}
<span class="onchain-val"><span>{{ targetProof.blockHeight }}</span>
<n-button quaternary circle size="tiny" :title="t('common.action.copy')" @click="copyValue(targetProof.blockHeight)"><template #icon><n-icon :component="CopyOutline" /></template></n-button>
</span>
</n-descriptions-item>
<n-descriptions-item v-if="targetProof.onchainAt" :label="t('pages.blockchain.onchainAt')">
{{ fmt(targetProof.onchainAt) }}
<span class="onchain-val"><span>{{ fmt(targetProof.onchainAt) }}</span>
<n-button quaternary circle size="tiny" :title="t('common.action.copy')" @click="copyValue(fmt(targetProof.onchainAt))"><template #icon><n-icon :component="CopyOutline" /></template></n-button>
</span>
</n-descriptions-item>
<n-descriptions-item v-if="targetProof.explorerUrl" :label="t('pages.blockchain.explorer')">
<a :href="targetProof.explorerUrl" target="_blank" rel="noopener" style="color: var(--brand)">{{ targetProof.explorerUrl }}</a>
<span class="onchain-val"><a :href="targetProof.explorerUrl" target="_blank" rel="noopener" class="onchain-mono" style="color: var(--brand)">{{ targetProof.explorerUrl }}</a>
<n-button quaternary circle size="tiny" :title="t('common.action.copy')" @click="copyValue(targetProof.explorerUrl)"><template #icon><n-icon :component="CopyOutline" /></template></n-button>
</span>
</n-descriptions-item>
</n-descriptions>
</template>
@@ -200,7 +221,8 @@
<n-button class="mr8" @click="outboundModal = false">
{{ targetOnchain ? t('common.action.close') : t('common.action.cancel') }}
</n-button>
<template v-if="!targetOnchain">
<!-- 只读角色(无写权限)从状态列点开时仅可查看,隐藏保存/触发按钮 -->
<template v-if="!targetOnchain && auth.canWrite">
<n-button v-if="!targetOutbound" class="mr8" :loading="outboundSaving" @click="saveOutbound(false)">{{ t('pages.outbound.saveRecord') }}</n-button>
<n-button type="primary" :loading="outboundTriggering" @click="saveOutbound(true)">
{{ targetOutbound ? t('pages.blockchain.trigger') : t('pages.outbound.saveAndTriggerOnchain') }}
@@ -214,10 +236,10 @@
<script setup lang="ts">
import { computed, h, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { NButton, NDropdown, NIcon, NTag, NText, type DataTableColumns, type DropdownOption } from 'naive-ui';
import { SearchOutline, AddOutline, DownloadOutline, QrCodeOutline, FolderOutline, OpenOutline, EllipsisHorizontalOutline, FilterOutline } from '@vicons/ionicons5';
import { SearchOutline, AddOutline, DownloadOutline, QrCodeOutline, FolderOutline, OpenOutline, EllipsisHorizontalOutline, FilterOutline, CopyOutline } from '@vicons/ionicons5';
import dayjs from 'dayjs';
import { TraceCodeStatus } from '@artveris/shared';
import { traceCodeApi, jobApi, artworkApi, outboundApi } from '@/api';
@@ -239,6 +261,7 @@ const emit = defineEmits<{
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const auth = useAuthStore();
const fixedArtworkId = computed(() => props.artworkId || null);
@@ -326,7 +349,9 @@ function rowIsOutbound(row: any) {
return Boolean(row.outTime || getOutImages(row).length);
}
function rowIsOnchain(row: any) {
return Boolean(row?.latestProof);
// 已提交上链即视为已上链:ONCHAIN(已确认)/CONFIRMING(确认中)/PENDING(待处理) 均不允许重复上链,仅 FAILED 可重试
const s = row?.latestAnyProof?.status;
return s === 'ONCHAIN' || s === 'CONFIRMING' || s === 'PENDING';
}
function outboundMenuLabel(row: any) {
if (rowIsOnchain(row)) return t('pages.traceCode.onchainInfo');
@@ -336,12 +361,56 @@ function outboundMenuLabel(row: any) {
const targetOutbound = computed(() => rowIsOutbound(outboundTarget.value));
const targetOnchain = computed(() => rowIsOnchain(outboundTarget.value));
const outboundReadonly = computed(() => targetOutbound.value || targetOnchain.value);
const targetProof = computed<any>(() => outboundTarget.value?.latestProof ?? null);
const targetProof = computed<any>(() => outboundTarget.value?.latestProof ?? outboundTarget.value?.latestAnyProof ?? null);
const outboundModalTitle = computed(() => outboundMenuLabel(outboundTarget.value));
const columns = computed<DataTableColumns<any>>(() => {
const base: DataTableColumns<any> = [
const cols: DataTableColumns<any> = [
{ type: 'selection' },
// 追溯码:点击进入预览页(不激活、不计数)
{
title: () => t('pages.traceCode.shortCode'),
key: 'shortCode',
width: 140,
align: 'center',
fixed: 'left',
render: (r) =>
h(
'a',
{ class: 'cell-link', title: t('pages.traceCode.previewHint'), onClick: () => openPreview(r) },
r.shortCode,
),
},
];
// 名称 + 档案编号:点击跳到艺术品档案详情;档案内页(固定 artworkId)为同一作品,无需展示
if (!fixedArtworkId.value) {
cols.push(
{
title: () => t('pages.artwork.title'),
key: 'artwork',
minWidth: 180,
ellipsis: { tooltip: true },
render: (r) =>
r.artwork
? h('a', { class: 'cell-link', onClick: () => goArtwork(r.artwork.id) }, r.artwork.title || '-')
: '-',
},
{
title: () => t('pages.artwork.archiveNo'),
key: 'archiveNo',
width: 140,
align: 'center',
render: (r) =>
r.artwork?.archiveNo
? h('a', { class: 'cell-link', onClick: () => goArtwork(r.artwork.id) }, r.artwork.archiveNo)
: '-',
},
);
}
cols.push(
// 批次编号
{
title: () => renderFilterTitle(t('pages.traceCode.batchNo'), query.batchId, batchOptions.value, (value) => setHeaderFilter('batchId', value)),
key: 'batch',
@@ -349,6 +418,15 @@ const columns = computed<DataTableColumns<any>>(() => {
align: 'center',
render: (r) => r.batch?.batchNo || '-',
},
// 分组
{
title: () => renderFilterTitle(t('pages.traceCode.group'), query.groupId, groupFilterOptions.value, (value) => setHeaderFilter('groupId', value)),
key: 'group',
width: 110,
align: 'center',
render: (r) => r.group?.name || h(NText, { depth: 3 }, { default: () => t('pages.traceCode.noGroup') }),
},
// 出库状态:点击打开该行「出库上链」详情弹窗(弹窗按状态自动呈现登记/上链/只读信息形态)
{
title: () =>
renderFilterTitle(t('pages.traceCode.outboundStatus'), query.outboundStatus, outboundStatusOptions.value, (value) =>
@@ -358,51 +436,71 @@ const columns = computed<DataTableColumns<any>>(() => {
width: 124,
align: 'center',
render: (r) =>
r.outTime || getOutImages(r).length
? h(NTag, { size: 'small', type: 'success' }, { default: () => t('pages.traceCode.outRegistered') })
: h(NText, { depth: 3 }, { default: () => t('pages.traceCode.notOutbound') }),
h(
'span',
{ class: 'cell-click', title: outboundMenuLabel(r), onClick: () => openOutboundModal(r) },
[
r.outTime || getOutImages(r).length
? h(NTag, { size: 'small', type: 'success' }, { default: () => t('pages.traceCode.outRegistered') })
: h(NText, { depth: 3 }, { default: () => t('pages.traceCode.notOutbound') }),
],
),
},
{ title: () => t('pages.outbound.outTime'), key: 'outTime', width: 150, align: 'center', render: (r) => fmt(r.outTime), ...sortProps('outTime') },
// 上链状态:同上,点击进详情弹窗
{
title: () => t('pages.traceCode.onchainStatus'),
key: 'onchainStatus',
width: 112,
align: 'center',
render: (r) =>
r.latestAnyProof
? h(NTag, { size: 'small', type: proofStatusType(r.latestAnyProof) }, { default: () => proofStatusText(r.latestAnyProof) })
: h(NText, { depth: 3 }, { default: () => t('pages.traceCode.noOnchain') }),
},
{ title: () => t('pages.traceCode.shortCode'), key: 'shortCode', width: 120, align: 'center', ellipsis: { tooltip: true } },
{ title: () => t('common.label.createdAt'), key: 'createdAt', width: 150, align: 'center', render: (r) => fmt(r.createdAt), ...sortProps('createdAt') },
{
title: () => t('pages.traceCode.url'),
key: 'url',
minWidth: 420,
ellipsis: { tooltip: true },
render: (r) =>
h(
'a',
{ href: r.url, target: '_blank', rel: 'noopener', style: 'color: var(--brand); text-decoration: none' },
[r.url, h(NIcon, { component: OpenOutline, style: 'vertical-align:-2px;margin-left:4px' })],
'span',
{ class: 'cell-click', title: outboundMenuLabel(r), onClick: () => openOutboundModal(r) },
[
r.latestAnyProof
? h(NTag, { size: 'small', type: proofStatusType(r.latestAnyProof) }, { default: () => proofStatusText(r.latestAnyProof) })
: h(NText, { depth: 3 }, { default: () => t('pages.traceCode.noOnchain') }),
],
),
},
// 出库时间
{ title: () => t('pages.outbound.outTime'), key: 'outTime', width: 150, align: 'center', render: (r) => fmt(r.outTime), ...sortProps('outTime') },
// 激活状态
{
title: () => renderFilterTitle(t('pages.traceCode.group'), query.groupId, groupFilterOptions.value, (value) => setHeaderFilter('groupId', value)),
key: 'group',
width: 110,
align: 'center',
render: (r) => r.group?.name || h(NText, { depth: 3 }, { default: () => t('pages.traceCode.noGroup') }),
},
{
title: () => renderFilterTitle(t('common.label.status'), query.status, statusOptions, (value) => setHeaderFilter('status', value)),
title: () => renderFilterTitle(t('pages.traceCode.activationStatus'), query.status, statusOptions, (value) => setHeaderFilter('status', value)),
key: 'status',
width: 108,
align: 'center',
render: (r) => h(NTag, { size: 'small', type: statusType(r.status) }, { default: () => t(`common.status.${r.status}`) }),
},
// 查询次数
{ title: () => t('pages.traceCode.queryCount'), key: 'queryCount', width: 100, align: 'center' },
// 激活时间
{ title: () => t('pages.traceCode.firstActivatedAt'), key: 'firstActivatedAt', width: 150, align: 'center', render: (r) => fmt(r.firstActivatedAt), ...sortProps('firstActivatedAt') },
// 链接:拦截直跳,先告知「直接访问会激活/计数」,再让用户选预览或实际访问
{
title: () => t('pages.traceCode.url'),
key: 'url',
minWidth: 360,
ellipsis: { tooltip: true },
render: (r) =>
h(
'a',
{
href: r.url,
style: 'color: var(--brand); text-decoration: none',
title: t('pages.traceCode.visitWarnTitle'),
onClick: (e: MouseEvent) => {
e.preventDefault();
confirmVisitReal(r);
},
},
[r.url, h(NIcon, { component: OpenOutline, style: 'vertical-align:-2px;margin-left:4px' })],
),
},
// 创建时间
{ title: () => t('common.label.createdAt'), key: 'createdAt', width: 150, align: 'center', render: (r) => fmt(r.createdAt), ...sortProps('createdAt') },
// 操作
{
title: () => t('common.label.operation'),
key: 'ops',
@@ -428,19 +526,77 @@ const columns = computed<DataTableColumns<any>>(() => {
: null,
]),
},
];
if (!fixedArtworkId.value) {
base.splice(
4,
0,
{ title: () => t('pages.artwork.archiveNo'), key: 'archiveNo', width: 130, align: 'center', render: (r) => r.artwork?.archiveNo || '-' },
{ title: () => t('pages.artwork.title'), key: 'artwork', minWidth: 180, ellipsis: { tooltip: true }, render: (r) => r.artwork?.title || '-' },
);
}
return base;
);
return cols;
});
function goArtwork(id?: number) {
if (!id) return;
router.push({ name: 'artwork-detail', params: { id: String(id) } });
}
// 预览令牌缓存:令牌自取用起至少 10 分钟有效(当前+上一窗口),缓存 8 分钟内复用,过期自动重取。
// 预览 URL 仅在点击时临时拼接,不进入行数据,因此导出永远只含真实短链。
let previewCache: { token: string; clientBase: string; fetchedAt: number } | null = null;
async function getPreviewInfo() {
if (!previewCache || Date.now() - previewCache.fetchedAt > 8 * 60_000) {
const res = await traceCodeApi.previewToken();
previewCache = { token: res.token, clientBase: res.clientBase, fetchedAt: Date.now() };
}
return previewCache;
}
// 先同步开空白窗口再异步填充地址,避免 await 后 window.open 被浏览器拦截
function openPreview(row: any) {
const win = window.open('about:blank', '_blank');
getPreviewInfo()
.then((info) => {
const url = `${info.clientBase}/#/trace/preview/${encodeURIComponent(row.shortCode)}?token=${info.token}&state=inactive`;
if (win) win.location.href = url;
else window.open(url, '_blank');
})
.catch(() => {
win?.close();
message.error(t('pages.traceCode.previewOpenFailed'));
});
}
// 点「链接」列:告知直接访问会激活/计数,提供预览与实际两个入口
function confirmVisitReal(row: any) {
const d = dialog.warning({
title: t('pages.traceCode.visitWarnTitle'),
content: t('pages.traceCode.visitWarnContent'),
action: () =>
h('div', { style: 'display:flex;gap:8px;justify-content:flex-end' }, [
h(NButton, { size: 'small', onClick: () => d.destroy() }, { default: () => t('common.action.cancel') }),
h(
NButton,
{
size: 'small',
type: 'primary',
onClick: () => {
d.destroy();
openPreview(row);
},
},
{ default: () => t('pages.traceCode.visitPreview') },
),
h(
NButton,
{
size: 'small',
type: 'warning',
onClick: () => {
d.destroy();
window.open(row.url, '_blank');
},
},
{ default: () => t('pages.traceCode.visitReal') },
),
]),
});
}
type HeaderFilterField = 'batchId' | 'groupId' | 'status' | 'outboundStatus';
type HeaderFilterValue = string | number | null;
type HeaderFilterOption = { label: string; value: string | number };
@@ -817,9 +973,21 @@ function getOutImages(row: any) {
);
}
async function copyValue(value: unknown) {
const text = value === null || value === undefined ? '' : String(value);
if (!text) return;
try {
await navigator.clipboard.writeText(text);
message.success(t('common.msg.copied'));
} catch {
message.error(t('common.msg.copyFailed'));
}
}
function openOutboundModal(row: any) {
outboundTarget.value = row;
outboundForm.outTime = formatDateTime(row.outTime);
// 出库时间必填:未出库时默认此刻;已出库时回显既有时间(只读)
outboundForm.outTime = row.outTime ? formatDateTime(row.outTime) : dayjs().format('YYYY-MM-DD HH:mm');
outboundForm.remark = row.remark || '';
outImages.value = getOutImages(row);
outboundModal.value = true;
@@ -827,6 +995,10 @@ function openOutboundModal(row: any) {
async function saveOutbound(triggerOnchain: boolean) {
if (!outboundTarget.value) return;
if (!outboundReadonly.value && !outboundForm.outTime) {
message.warning(t('pages.outbound.outTimeRequired'));
return;
}
if (triggerOnchain) {
outboundTriggering.value = true;
} else {
@@ -1006,11 +1178,41 @@ onUnmounted(() => {
.onchain-tip {
margin-top: 4px;
}
/* 表格单元格由 n-data-table 子组件渲染,不带本组件 scope 属性,必须用 :deep() 才能命中 */
:deep(.cell-link) {
color: var(--brand);
cursor: pointer;
text-decoration: none;
}
:deep(.cell-link:hover) {
text-decoration: underline;
}
/* 状态列可点击:悬停轻微提亮提示可点 */
:deep(.cell-click) {
cursor: pointer;
display: inline-flex;
align-items: center;
}
:deep(.cell-click:hover) {
opacity: 0.75;
}
.onchain-mono {
font-family: 'JetBrains Mono', Consolas, monospace;
font-size: 12px;
word-break: break-all;
}
.onchain-val {
display: flex;
align-items: center;
gap: 6px;
}
.onchain-val > :first-child {
flex: 1;
min-width: 0;
}
.onchain-val .n-button {
flex: 0 0 auto;
}
@media (max-width: 720px) {
.toolbar-control,
.toolbar-control.wide,
+25 -2
View File
@@ -23,6 +23,7 @@
"unbind": "Unbind",
"retry": "Retry",
"copy": "Copy",
"close": "Close",
"onchain": "On-chain",
"qrcode": "QR Code",
"manage": "Manage",
@@ -116,6 +117,7 @@
"created": "Created",
"updated": "Updated",
"copied": "Copied",
"copyFailed": "Copy failed",
"operationSuccess": "Success",
"loginExpired": "Session expired, please log in again",
"networkError": "Network error, please try again",
@@ -381,7 +383,15 @@
"url": "Link",
"keywordPlaceholder": "Trace code / link / archive no. / name / artist / batch / group / note",
"queryCount": "Queries",
"firstActivatedAt": "First Activated",
"firstActivatedAt": "Activated At",
"activationStatus": "Activation",
"openTrace": "Open trace page",
"previewHint": "Click to open preview (no activation, no query counting)",
"previewOpenFailed": "Failed to open preview, please retry",
"visitWarnTitle": "Visit Notice",
"visitWarnContent": "Visiting the real trace link will activate the code and increase its query count. To just check the page, use the preview page (no activation, no counting).",
"visitPreview": "Open Preview Page",
"visitReal": "Open Real Page",
"exportBatch": "Export Batch",
"exportCurrent": "Current filter",
"bindArtwork": "Link Artwork File",
@@ -466,7 +476,8 @@
"FAILED": "Failed",
"EXPIRED": "Expired"
},
"onchainAutoTip": "On-chain hash, attestation link, and on-chain time are written automatically from the configured blockchain API response."
"onchainAutoTip": "On-chain hash, attestation link, and on-chain time are written automatically from the configured blockchain API response.",
"outTimeRequired": "Outbound time is required"
},
"blockchain": {
"title": "Blockchain Attestation",
@@ -505,6 +516,12 @@
"platformInfo": "Platform Settings",
"logAndDisplay": "Log Settings",
"backupPolicy": "Backup Policy",
"tabPlatform": "Platform",
"tabLogs": "Logs",
"tabBlockchain": "Blockchain",
"tabStorage": "Storage",
"tabBackup": "Backup",
"backupList": "Backup List",
"appName": "Platform Name",
"appIcon": "System Icon",
"logRetentionDays": "Query Log Days",
@@ -541,6 +558,7 @@
"scheduleWeekly": "Weekly",
"saved": "Settings saved",
"blockchainSettings": "Blockchain Attestation",
"chainApiConfig": "API Configuration",
"blockchainDriver": "Attestation Driver",
"blockchainDriverMock": "Mock",
"blockchainDriverTianhe": "Tianhe Chain",
@@ -552,6 +570,7 @@
"tianheAppId": "App ID",
"tianheAppKey": "App Key",
"tianheIdentity": "On-chain Identity (Platform Custodial Wallet)",
"tianheIdentityMockHint": "The current attestation driver is mock. Switch to Tianhe chain and save to manage the platform custodial wallet identity here.",
"tianheWalletAddress": "Wallet Address",
"tianheNotRegistered": "Not registered",
"tianheRegister": "Register Identity",
@@ -567,6 +586,10 @@
"tianheRevealConfirmContent": "The User Key is the sole credential for the platform custodial wallet. Revealing it will be recorded in the operation log. Make sure your environment is secure before continuing.",
"tianheCopy": "Copy",
"tianheCopied": "User Key copied",
"tianheCopyConfirmTitle": "Copy User Key",
"tianheCopyConfirmContent": "Copying writes the full User Key to the clipboard and will be recorded in the operation log. Make sure your environment is secure before continuing.",
"tianheAppKeyRevealTitle": "View App Key",
"tianheAppKeyRevealContent": "This will display the full App Key and be recorded in the operation log. Make sure your environment is secure before continuing.",
"tianheIdentityHint": "The User Key is the only credential to open the platform custodial wallet. TiChain does not store it and it cannot be recovered. Keep the User ID and User Key offline; after reinstalling or migrating, use Manual Entry to continue with the same on-chain identity.",
"tianheRegisterDone": "On-chain identity registered",
"tianheSaveKeyWarning": "Save these credentials offline immediately (losing them means you cannot attest with the same identity again): User ID: {userId}; User Key: {userKey}",
+25 -2
View File
@@ -23,6 +23,7 @@
"unbind": "解绑",
"retry": "重试",
"copy": "复制",
"close": "关闭",
"onchain": "上链存证",
"qrcode": "二维码",
"manage": "管理",
@@ -116,6 +117,7 @@
"created": "创建成功",
"updated": "更新成功",
"copied": "已复制",
"copyFailed": "复制失败",
"operationSuccess": "操作成功",
"loginExpired": "登录已过期,请重新登录",
"networkError": "网络异常,请稍后再试",
@@ -381,7 +383,15 @@
"url": "链接",
"keywordPlaceholder": "追溯码 / 链接 / 档案编号 / 名称 / 艺术家 / 批次 / 分组 / 备注",
"queryCount": "查询次数",
"firstActivatedAt": "首次激活时间",
"firstActivatedAt": "激活时间",
"activationStatus": "激活状态",
"openTrace": "打开溯源页",
"previewHint": "点击进入预览页(不激活、不计入查询次数)",
"previewOpenFailed": "预览页打开失败,请重试",
"visitWarnTitle": "访问提示",
"visitWarnContent": "直接访问追溯码链接会激活该码并增加查询次数。如仅需查看页面效果,请使用预览页面(不激活、不计入查询次数)。",
"visitPreview": "访问预览页面",
"visitReal": "访问实际页面",
"exportBatch": "导出本批",
"exportCurrent": "当前筛选",
"bindArtwork": "关联作品档案",
@@ -466,7 +476,8 @@
"FAILED": "失败",
"EXPIRED": "已过期"
},
"onchainAutoTip": "链上哈希、存证链接、上链时间由当前配置的区块链接口返回后自动写入。"
"onchainAutoTip": "链上哈希、存证链接、上链时间由当前配置的区块链接口返回后自动写入。",
"outTimeRequired": "出库时间不能为空"
},
"blockchain": {
"title": "区块链存证",
@@ -505,6 +516,12 @@
"platformInfo": "平台设置",
"logAndDisplay": "日志设置",
"backupPolicy": "备份策略",
"tabPlatform": "平台设置",
"tabLogs": "日志设置",
"tabBlockchain": "区块链存证",
"tabStorage": "存储配置",
"tabBackup": "备份",
"backupList": "备份列表",
"appName": "平台名称",
"appIcon": "系统图标",
"logRetentionDays": "查询日志保留天数",
@@ -541,6 +558,7 @@
"scheduleWeekly": "每周",
"saved": "设置已保存",
"blockchainSettings": "区块链存证",
"chainApiConfig": "接口配置",
"blockchainDriver": "存证驱动",
"blockchainDriverMock": "模拟存证",
"blockchainDriverTianhe": "天河链",
@@ -552,6 +570,7 @@
"tianheAppId": "App ID",
"tianheAppKey": "App Key",
"tianheIdentity": "链上身份(平台托管钱包)",
"tianheIdentityMockHint": "当前存证驱动为模拟存证,切换为天河链并保存后可在此管理平台托管钱包身份。",
"tianheWalletAddress": "钱包地址",
"tianheNotRegistered": "未注册",
"tianheRegister": "注册链上身份",
@@ -567,6 +586,10 @@
"tianheRevealConfirmContent": "User Key 是平台托管钱包的唯一凭据,揭示操作将被记入操作日志。请确认当前环境安全后再继续。",
"tianheCopy": "复制",
"tianheCopied": "User Key 已复制",
"tianheCopyConfirmTitle": "复制 User Key",
"tianheCopyConfirmContent": "复制会将完整 User Key 写入剪贴板,该操作将记入操作日志。请确认当前环境安全后再继续。",
"tianheAppKeyRevealTitle": "查看 App Key",
"tianheAppKeyRevealContent": "该操作将显示完整 App Key 并记入操作日志,请确认当前环境安全后再继续。",
"tianheIdentityHint": "User Key 是打开平台托管钱包的唯一凭据,天河链不留存、无法找回。请务必离线保存 User ID 与 User Key;重装或迁移系统后可通过「手动录入」继续使用同一链上身份。",
"tianheRegisterDone": "链上身份注册成功",
"tianheSaveKeyWarning": "请立即离线保存以下凭据(丢失将无法继续以同一身份存证):User ID:{userId};User Key:{userKey}",
+12 -1
View File
@@ -102,7 +102,18 @@ const columns: DataTableColumns<any> = [
{ title: () => t('pages.artwork.title'), key: 'title', minWidth: 220, ellipsis: { tooltip: true } },
{ title: () => t('pages.artwork.artist'), key: 'artist', minWidth: 130, ellipsis: { tooltip: true }, render: (r) => r.artist || '-' },
{ title: () => t('pages.artwork.template'), key: 'template', minWidth: 150, ellipsis: { tooltip: true }, render: (r) => r.template?.name || '-' },
{ title: () => t('pages.artwork.codeCount'), key: 'codeCount', width: 100, align: 'center', render: (r) => r.codeCount ?? 0 },
{
title: () => t('pages.artwork.codeCount'),
key: 'codeCount',
width: 100,
align: 'center',
render: (r) =>
h(
NButton,
{ text: true, type: 'primary', title: t('pages.artwork.dataManage'), onClick: () => router.push(`/artworks/${r.id}/trace-codes`) },
{ default: () => String(r.codeCount ?? 0) },
),
},
{ title: () => t('pages.artwork.queryTotal'), key: 'queryTotal', width: 100, align: 'center', render: (r) => r.queryTotal ?? 0 },
{
title: () => renderTableFilterTitle(t('common.label.status'), query.status, statusOptions, (value) => setFilter('status', value)),
+416 -397
View File
@@ -1,257 +1,266 @@
<template>
<div class="page settings-page">
<div class="settings-shell">
<div class="settings-content">
<n-form class="settings-form" label-placement="top">
<div class="settings-save">
<n-button type="primary" :loading="saving" @click="save">{{ t('common.action.save') }}</n-button>
</div>
<n-tabs class="settings-tabs" type="line" :value="activeTab" @update:value="onTabChange">
<template #suffix>
<n-button v-if="activeTab !== 'storage'" type="primary" size="small" :loading="saving" @click="save">
{{ t('common.action.save') }}
</n-button>
</template>
<div class="settings-card-grid">
<section class="settings-card platform-card">
<div class="card-title">{{ t('pages.settings.platformInfo') }}</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.appName')">
<n-input v-model:value="form.appName" class="text-control" />
</n-form-item>
</div>
<div class="setting-row icon-row">
<div class="setting-label">{{ t('pages.settings.appIcon') }}</div>
<div class="icon-setting">
<div class="icon-preview-wrap">
<img class="icon-preview" :src="currentIconUrl" alt="" />
</div>
<media-upload v-model="form.appIconFiles" type="image" :max="1" class="icon-upload" />
<n-tab-pane name="platform" :tab="t('pages.settings.tabPlatform')">
<div class="pane">
<n-form class="settings-form" label-placement="left" label-align="left" :label-width="150" :show-feedback="false">
<n-form-item :label="t('pages.settings.appName')">
<n-input v-model:value="form.appName" />
</n-form-item>
<n-form-item :label="t('pages.settings.appIcon')">
<div class="icon-setting">
<div class="icon-preview-wrap">
<img class="icon-preview" :src="currentIconUrl" alt="" />
</div>
<media-upload v-model="form.appIconFiles" type="image" :max="1" class="icon-upload" />
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.watermarkText')">
<n-input v-model:value="form.watermarkText" class="text-control" />
</n-form-item>
<n-form-item :label="t('pages.settings.watermarkText')">
<n-input v-model:value="form.watermarkText" />
</n-form-item>
<n-form-item :label="t('pages.settings.filingInfo')">
<n-input v-model:value="form.filingInfo" />
</n-form-item>
<n-form-item :label="t('pages.settings.carouselInterval')">
<n-input-number
v-model:value="form.carouselInterval"
:min="0"
:max="30"
:step="0.5"
:precision="1"
button-placement="both"
class="number-control"
/>
</n-form-item>
<n-form-item :label="t('pages.settings.clientBaseUrl')">
<n-input v-model:value="form.clientBaseUrl" />
</n-form-item>
</n-form>
</div>
</n-tab-pane>
<n-tab-pane name="logs" :tab="t('pages.settings.tabLogs')">
<div class="pane">
<n-form class="settings-form" label-placement="left" label-align="left" :label-width="150" :show-feedback="false">
<n-form-item :label="t('pages.settings.logRetentionDays')">
<n-input-number v-model:value="form.logRetentionDays" :min="1" button-placement="both" class="number-control" />
</n-form-item>
<n-form-item :label="t('pages.settings.operationLogRetentionDays')">
<n-input-number v-model:value="form.operationLogRetentionDays" :min="1" button-placement="both" class="number-control" />
</n-form-item>
</n-form>
</div>
</n-tab-pane>
<n-tab-pane name="backup" :tab="t('pages.settings.tabBackup')" class="pane-flex">
<div class="pane pane-column">
<n-form
class="backup-policy-form"
label-placement="left"
label-align="left"
:show-feedback="false"
inline
>
<n-form-item :label="t('pages.settings.backupSchedule')">
<n-select v-model:value="backupScheduleValue" :options="backupScheduleOptions" class="select-control" />
</n-form-item>
<n-form-item :label="t('pages.settings.backupRetentionDays')">
<n-input-number v-model:value="form.backupRetentionDays" :min="1" button-placement="both" class="number-control" />
</n-form-item>
<n-form-item :label="t('pages.settings.backupRetentionCount')">
<n-input-number v-model:value="form.backupRetentionCount" :min="1" button-placement="both" class="number-control" />
</n-form-item>
</n-form>
<n-divider class="pane-divider" />
<div class="backup-fill">
<backup-restore-panel />
</div>
</div>
</n-tab-pane>
<n-tab-pane name="blockchain" :tab="t('pages.settings.tabBlockchain')">
<div class="pane pane-full">
<div class="chain-grid">
<section class="chain-card">
<div class="chain-card-title">{{ t('pages.settings.chainApiConfig') }}</div>
<n-form class="chain-form" label-placement="left" label-align="left" :label-width="120" :show-feedback="false">
<n-form-item :label="t('pages.settings.blockchainDriver')">
<n-select v-model:value="form.blockchainDriver" :options="blockchainDriverOptions" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.filingInfo')">
<n-input v-model:value="form.filingInfo" class="text-control" />
<n-form-item :label="t('pages.settings.tianheEnv')">
<n-select v-model:value="form.tianheEnv" :options="tianheEnvOptions" @update:value="onTianheEnvChange" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.carouselInterval')">
<n-input-number
v-model:value="form.carouselInterval"
:min="0"
:max="30"
:step="0.5"
:precision="1"
button-placement="both"
class="number-control"
/>
<n-form-item :label="t('pages.settings.tianheBaseUrl')">
<n-input v-model:value="form.tianheBaseUrl" :disabled="form.tianheEnv !== 'custom'" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.clientBaseUrl')">
<n-input v-model:value="form.clientBaseUrl" class="url-control" />
<n-form-item :label="t('pages.settings.tianheAppId')">
<n-input v-model:value="form.tianheAppId" />
</n-form-item>
</div>
<n-form-item :label="t('pages.settings.tianheAppKey')">
<div class="secret-field">
<n-input v-model:value="form.tianheAppKey" :type="appKeyRevealed ? 'text' : 'password'" class="secret-input" />
<n-button
quaternary
circle
size="small"
:title="appKeyRevealed ? t('pages.settings.tianheHide') : t('pages.settings.tianheReveal')"
@click="toggleAppKeyReveal"
>
<template #icon>
<n-icon :component="appKeyRevealed ? EyeOffOutline : EyeOutline" />
</template>
</n-button>
</div>
</n-form-item>
</n-form>
</section>
<div class="settings-side-stack">
<section class="settings-card">
<div class="card-title">{{ t('pages.settings.logAndDisplay') }}</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.logRetentionDays')">
<n-input-number v-model:value="form.logRetentionDays" :min="1" button-placement="both" class="number-control" />
</n-form-item>
<section class="chain-card">
<div class="chain-card-title">
<span>{{ t('pages.settings.tianheIdentity') }}</span>
<div v-if="form.blockchainDriver === 'tianhe'" class="card-actions">
<n-button size="small" :loading="registeringIdentity" @click="registerIdentity">
{{ identity.address ? t('pages.settings.tianheReRegister') : t('pages.settings.tianheRegister') }}
</n-button>
<n-button size="small" @click="manualEntryVisible = true">{{ t('pages.settings.tianheManualEntry') }}</n-button>
<n-button v-if="identity.userKeyMasked" size="small" :loading="rotatingIdentity" @click="rotateUserKey">
{{ t('pages.settings.tianheRotate') }}
</n-button>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.operationLogRetentionDays')">
<n-input-number v-model:value="form.operationLogRetentionDays" :min="1" button-placement="both" class="number-control" />
</n-form-item>
</div>
</section>
<section class="settings-card">
<div class="card-title">{{ t('pages.settings.backupPolicy') }}</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.backupSchedule')">
<n-select v-model:value="backupScheduleValue" :options="backupScheduleOptions" class="select-control" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.backupRetentionDays')">
<n-input-number v-model:value="form.backupRetentionDays" :min="1" button-placement="both" class="number-control" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.backupRetentionCount')">
<n-input-number v-model:value="form.backupRetentionCount" :min="1" button-placement="both" class="number-control" />
</n-form-item>
</div>
</section>
</div>
<section class="settings-card blockchain-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>
<template v-if="form.blockchainDriver === 'tianhe'">
<div class="setting-row identity-head">
<span class="identity-title">{{ t('pages.settings.tianheIdentity') }}</span>
<div class="card-actions">
<n-button size="small" :loading="registeringIdentity" @click="registerIdentity">
{{ identity.address ? t('pages.settings.tianheReRegister') : t('pages.settings.tianheRegister') }}
</n-button>
<n-button size="small" @click="manualEntryVisible = true">{{ t('pages.settings.tianheManualEntry') }}</n-button>
<n-button v-if="identity.userKeyMasked" size="small" :loading="rotatingIdentity" @click="rotateUserKey">{{ t('pages.settings.tianheRotate') }}</n-button>
</div>
</div>
<div class="setting-row">
<n-form class="chain-form" label-placement="left" label-align="left" :label-width="120" :show-feedback="false">
<n-form-item :label="t('pages.settings.tianheWalletAddress')">
<span class="identity-value mono">{{ identity.address || t('pages.settings.tianheNotRegistered') }}</span>
</n-form-item>
</div>
<div class="setting-row">
<n-form-item label="User ID">
<span class="identity-value mono">{{ identity.userId || '-' }}</span>
</n-form-item>
</div>
<div class="setting-row">
<n-form-item label="User Key">
<div class="identity-key">
<span class="identity-value mono">{{ identityKeyDisplay }}</span>
<n-button v-if="identity.userKeyMasked" size="tiny" quaternary @click="revealUserKey">
{{ revealKey ? t('pages.settings.tianheHide') : t('pages.settings.tianheReveal') }}
<n-button
v-if="identity.userKeyMasked"
quaternary
circle
size="small"
:title="revealKey ? t('pages.settings.tianheHide') : t('pages.settings.tianheReveal')"
@click="revealUserKey"
>
<template #icon>
<n-icon :component="revealKey ? EyeOffOutline : EyeOutline" />
</template>
</n-button>
<n-button
v-if="identity.userKeyMasked"
quaternary
circle
size="small"
:title="t('pages.settings.tianheCopy')"
@click="copyUserKey"
>
<template #icon>
<n-icon :component="CopyOutline" />
</template>
</n-button>
<n-button v-if="identity.userKeyMasked" size="tiny" quaternary @click="copyUserKey">{{ t('pages.settings.tianheCopy') }}</n-button>
</div>
</n-form-item>
</div>
</n-form>
<p class="identity-hint">{{ t('pages.settings.tianheIdentityHint') }}</p>
</template>
</section>
<n-modal
v-model:show="manualEntryVisible"
preset="dialog"
:title="t('pages.settings.tianheManualEntry')"
:positive-text="t('pages.settings.tianheVerifySave')"
:negative-text="t('common.action.cancel')"
:loading="verifyingIdentity"
@positive-click="verifyIdentity"
>
<p class="identity-hint">{{ t('pages.settings.tianheManualHint') }}</p>
<n-form-item label="User ID">
<n-input v-model:value="manualEntry.userId" :placeholder="t('pages.settings.tianheManualUserIdPh')" />
</n-form-item>
<n-form-item label="User Key">
<n-input v-model:value="manualEntry.userKey" type="password" show-password-on="click" :placeholder="t('pages.settings.tianheManualUserKeyPh')" />
</n-form-item>
</n-modal>
<section class="settings-card storage-card">
<div class="card-title">
<span class="card-title-text">
{{ t('pages.settings.storageSettings') }}
<n-popover trigger="hover" placement="bottom-start" :style="{ maxWidth: '340px' }">
<template #trigger>
<n-icon class="hint-icon" :component="HelpCircleOutline" />
</template>
<span class="hint-popover">{{ t('pages.settings.storageHint') }}</span>
</n-popover>
</span>
<div class="card-actions">
<n-button size="small" :loading="testingStorage" @click="testStorage">{{ t('pages.settings.testStorage') }}</n-button>
<n-button size="small" :loading="migratingStorage" @click="migrateStorage">{{ t('pages.settings.migrateStorage') }}</n-button>
<n-button size="small" type="primary" :loading="confirmingStorage" @click="confirmStorage">{{ t('pages.settings.confirmStorage') }}</n-button>
</div>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.storageDriver')">
<n-select v-model:value="form.storageDriver" :options="storageDriverOptions" class="select-control" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.storageLocalDir')">
<n-input v-model:value="form.storageLocalDir" class="url-control" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.cdnBaseUrl')">
<n-input v-model:value="form.cdnBaseUrl" class="url-control" />
</n-form-item>
</div>
<template v-if="form.storageDriver === 'oss'">
<div class="setting-row">
<n-form-item :label="t('pages.settings.ossEndpoint')">
<n-input v-model:value="form.ossEndpoint" class="url-control" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.ossRegion')">
<n-input v-model:value="form.ossRegion" class="text-control" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.ossBucket')">
<n-input v-model:value="form.ossBucket" class="text-control" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.ossAccessKeyId')">
<n-input v-model:value="form.ossAccessKeyId" class="text-control" />
</n-form-item>
</div>
<div class="setting-row">
<n-form-item :label="t('pages.settings.ossAccessKeySecret')">
<n-input v-model:value="form.ossAccessKeySecret" type="password" show-password-on="click" class="text-control" />
</n-form-item>
</div>
</template>
<div v-else class="identity-empty">{{ t('pages.settings.tianheIdentityMockHint') }}</div>
</section>
</div>
</n-form>
<div class="settings-backup-panel">
<backup-restore-panel />
</div>
</div>
</div>
</n-tab-pane>
<n-tab-pane name="storage" :tab="t('pages.settings.tabStorage')">
<div class="pane">
<div class="pane-toolbar">
<n-popover trigger="hover" placement="bottom-start" :style="{ maxWidth: '340px' }">
<template #trigger>
<n-icon class="hint-icon" :component="HelpCircleOutline" />
</template>
<span class="hint-popover">{{ t('pages.settings.storageHint') }}</span>
</n-popover>
<n-button size="small" :loading="testingStorage" @click="testStorage">{{ t('pages.settings.testStorage') }}</n-button>
<n-button size="small" :loading="migratingStorage" @click="migrateStorage">{{ t('pages.settings.migrateStorage') }}</n-button>
<n-button size="small" type="primary" :loading="confirmingStorage" @click="confirmStorage">{{ t('pages.settings.confirmStorage') }}</n-button>
</div>
<n-form class="settings-form" label-placement="left" label-align="left" :label-width="150" :show-feedback="false">
<n-form-item :label="t('pages.settings.storageDriver')">
<n-select v-model:value="form.storageDriver" :options="storageDriverOptions" />
</n-form-item>
<n-form-item :label="t('pages.settings.storageLocalDir')">
<n-input v-model:value="form.storageLocalDir" />
</n-form-item>
<n-form-item :label="t('pages.settings.cdnBaseUrl')">
<n-input v-model:value="form.cdnBaseUrl" />
</n-form-item>
<template v-if="form.storageDriver === 'oss'">
<n-form-item :label="t('pages.settings.ossEndpoint')">
<n-input v-model:value="form.ossEndpoint" />
</n-form-item>
<n-form-item :label="t('pages.settings.ossRegion')">
<n-input v-model:value="form.ossRegion" />
</n-form-item>
<n-form-item :label="t('pages.settings.ossBucket')">
<n-input v-model:value="form.ossBucket" />
</n-form-item>
<n-form-item :label="t('pages.settings.ossAccessKeyId')">
<n-input v-model:value="form.ossAccessKeyId" />
</n-form-item>
<n-form-item :label="t('pages.settings.ossAccessKeySecret')">
<n-input v-model:value="form.ossAccessKeySecret" type="password" show-password-on="click" />
</n-form-item>
</template>
</n-form>
</div>
</n-tab-pane>
</n-tabs>
<n-modal
v-model:show="manualEntryVisible"
preset="dialog"
:title="t('pages.settings.tianheManualEntry')"
:positive-text="t('pages.settings.tianheVerifySave')"
:negative-text="t('common.action.cancel')"
:loading="verifyingIdentity"
@positive-click="verifyIdentity"
>
<p class="identity-hint">{{ t('pages.settings.tianheManualHint') }}</p>
<n-form-item label="User ID">
<n-input v-model:value="manualEntry.userId" :placeholder="t('pages.settings.tianheManualUserIdPh')" />
</n-form-item>
<n-form-item label="User Key">
<n-input v-model:value="manualEntry.userKey" type="password" show-password-on="click" :placeholder="t('pages.settings.tianheManualUserKeyPh')" />
</n-form-item>
</n-modal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { settingsApi, storageApi } from '@/api';
import { dialog, message } from '@/utils/feedback';
import { HelpCircleOutline } from '@vicons/ionicons5';
import { CopyOutline, EyeOffOutline, EyeOutline, HelpCircleOutline } from '@vicons/ionicons5';
import BackupRestorePanel from '@/components/BackupRestorePanel.vue';
import MediaUpload from '@/components/MediaUpload.vue';
import { DEFAULT_APP_ICON_URL, resolveAppIcon, setFavicon } from '@/utils/appIcon';
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const TAB_NAMES = ['platform', 'logs', 'blockchain', 'storage', 'backup'];
const activeTab = ref(TAB_NAMES.includes(String(route.query.tab)) ? String(route.query.tab) : 'platform');
const saving = ref(false);
const testingStorage = ref(false);
const migratingStorage = ref(false);
@@ -260,9 +269,12 @@ const registeringIdentity = ref(false);
const verifyingIdentity = ref(false);
const rotatingIdentity = ref(false);
const revealKey = ref(false);
const appKeyRevealed = ref(false);
const manualEntryVisible = ref(false);
const identity = reactive({ userId: '', userKey: '', userKeyMasked: '', address: '' });
const manualEntry = reactive({ userId: '', userKey: '' });
// load() 时记录的 AppKey 掩码值,用于区分「服务端掩码」与「用户新填的值」
let loadedTianheAppKey = '';
const TIANHE_TEST_URL = 'https://test.api.tichain.tianhecloud.com';
const TIANHE_PRODUCTION_URL = 'https://api.tichain.tianhecloud.com';
const blockchainDriverOptions = computed(() => [
@@ -319,6 +331,20 @@ const form = reactive({
ossAccessKeySecret: '',
});
function onTabChange(name: string) {
activeTab.value = name;
void router.replace({ query: { ...route.query, tab: name } });
}
// 地址栏直接改 ?tab=(或浏览器前进后退)时同步切换
watch(
() => route.query.tab,
(tab) => {
const name = String(tab || 'platform');
if (TAB_NAMES.includes(name) && name !== activeTab.value) activeTab.value = name;
},
);
async function load() {
const s = await settingsApi.getAll();
form.appName = s.appName || '';
@@ -339,6 +365,8 @@ async function load() {
form.tianheBaseUrl = s.tianheBaseUrl || TIANHE_TEST_URL;
form.tianheAppId = s.tianheAppId || '';
form.tianheAppKey = s.tianheAppKey || '';
loadedTianheAppKey = form.tianheAppKey;
appKeyRevealed.value = false;
form.storageDriver = s.storageDriver || 'local';
form.storageLocalDir = s.storageLocalDir || './storage';
form.storagePublicPrefix = s.storagePublicPrefix || '/uploads';
@@ -368,6 +396,36 @@ async function loadIdentity() {
}
}
// 揭示 AppKey 明文:二次确认后经审计 POST 接口获取(写操作日志)。
// 收起时若用户未编辑过,恢复为服务端掩码,避免明文长期留在输入框。
let revealedPlainAppKey = '';
function toggleAppKeyReveal() {
if (appKeyRevealed.value) {
if (form.tianheAppKey === revealedPlainAppKey) {
form.tianheAppKey = loadedTianheAppKey;
}
appKeyRevealed.value = false;
return;
}
dialog.warning({
title: t('pages.settings.tianheAppKeyRevealTitle'),
content: t('pages.settings.tianheAppKeyRevealContent'),
positiveText: t('common.action.confirm'),
negativeText: t('common.action.cancel'),
onPositiveClick: async () => {
// 仅在输入框仍是服务端掩码(未被编辑)时回填明文,避免覆盖用户新填的值
if (form.tianheAppKey === loadedTianheAppKey) {
const res = await settingsApi.tianheRevealAppKey();
if (res.appKey) {
revealedPlainAppKey = res.appKey;
form.tianheAppKey = res.appKey;
}
}
appKeyRevealed.value = true;
},
});
}
// 揭示明文 userKey:二次确认后经 POST 接口获取(写操作日志、避免缓存)
async function revealUserKey() {
if (revealKey.value) {
@@ -387,15 +445,21 @@ async function revealUserKey() {
});
}
async function copyUserKey() {
let key = identity.userKey;
if (!key) {
const res = await settingsApi.tianheReveal();
key = res.userKey || '';
identity.userKey = key;
}
await navigator.clipboard.writeText(key);
message.success(t('pages.settings.tianheCopied'));
// 复制 userKey:二次确认后强制经审计 POST 接口取明文再写剪贴板,保证留痕
function copyUserKey() {
dialog.warning({
title: t('pages.settings.tianheCopyConfirmTitle'),
content: t('pages.settings.tianheCopyConfirmContent'),
positiveText: t('common.action.confirm'),
negativeText: t('common.action.cancel'),
onPositiveClick: async () => {
const res = await settingsApi.tianheReveal();
const key = res.userKey || '';
identity.userKey = key;
await navigator.clipboard.writeText(key);
message.success(t('pages.settings.tianheCopied'));
},
});
}
// 注册(或确认)平台托管钱包;注册前先保存表单里的 AppID/AppKey,避免「填了没存」
@@ -472,7 +536,7 @@ async function save() {
saving.value = true;
try {
const appIconUrl = form.appIconFiles[0]?.url || form.appIconFiles[0]?.key || '';
await settingsApi.update({
const s = await settingsApi.update({
appName: form.appName,
appIconUrl,
logRetentionDays: String(form.logRetentionDays),
@@ -491,6 +555,10 @@ async function save() {
tianheAppId: form.tianheAppId,
tianheAppKey: form.tianheAppKey,
});
// 保存后回填服务端掩码,避免输入框继续持有刚填的明文
form.tianheAppKey = (s as Record<string, string>)?.tianheAppKey || '';
loadedTianheAppKey = form.tianheAppKey;
appKeyRevealed.value = false;
setFavicon(appIconUrl);
window.dispatchEvent(new CustomEvent('artveris-settings-updated'));
message.success(t('pages.settings.saved'));
@@ -561,91 +629,75 @@ const identityKeyDisplay = computed(() => {
display: flex;
flex-direction: column;
overflow: hidden;
padding: 14px 16px 16px;
padding: 8px 24px 0;
}
.settings-shell {
width: 100%;
height: 100%;
min-width: 0;
.settings-tabs {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.settings-save {
position: absolute;
top: 0;
right: 0;
z-index: 8;
}
.settings-content {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
gap: 12px;
overflow: auto;
padding: 0 10px 24px 0;
}
.settings-form {
position: relative;
.settings-tabs :deep(.n-tabs-nav) {
flex: 0 0 auto;
width: 1300px;
max-width: 100%;
}
.settings-card-grid {
display: grid;
grid-template-columns: 448px 376px 376px;
align-items: start;
gap: 12px;
padding-right: 76px;
.settings-tabs :deep(.n-tabs-pane-wrapper) {
flex: 1 1 auto;
min-height: 0;
}
.settings-side-stack {
display: grid;
gap: 12px;
width: 376px;
.settings-tabs :deep(.n-tab-pane) {
height: 100%;
overflow: auto;
padding: 20px 4px 24px;
box-sizing: border-box;
}
.platform-card {
width: 448px;
}
.blockchain-card {
width: 376px;
}
.settings-card {
/* 备份页内部表格自填充,禁用外层滚动 */
.settings-tabs :deep(.n-tab-pane.pane-flex) {
overflow: hidden;
border: 1px solid var(--n-border-color);
border-radius: 8px;
background: var(--n-card-color);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
display: flex;
flex-direction: column;
}
.card-title {
.pane {
width: 100%;
}
.pane-column {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
/* 普通表单页:标题在左、控件在右,控件列自适应但整体不无限拉伸 */
.settings-form {
max-width: 720px;
}
.settings-form :deep(.n-form-item) {
margin-bottom: 18px;
}
.settings-form :deep(.n-form-item-label) {
font-weight: 600;
}
.number-control {
width: 200px;
}
.number-control :deep(.n-input__input-el) {
text-align: center;
}
.select-control {
width: 200px;
}
/* 存储页顶部操作条 */
.pane-toolbar {
display: flex;
align-items: center;
min-height: 36px;
padding: 0 12px;
border-bottom: 1px solid var(--n-border-color);
background: rgba(148, 163, 184, 0.08);
color: var(--n-text-color);
font-size: 14px;
font-weight: 700;
line-height: 20px;
justify-content: space-between;
gap: 8px;
}
.card-actions {
display: flex;
gap: 6px;
flex-wrap: wrap;
max-width: 720px;
margin-bottom: 16px;
justify-content: flex-end;
}
.card-title-text {
display: inline-flex;
align-items: center;
gap: 6px;
}
.hint-icon {
color: var(--n-text-color-3, #8a94a6);
font-size: 16px;
cursor: help;
margin-right: auto;
}
.hint-icon:hover {
color: var(--brand, #2f9e8f);
@@ -655,19 +707,86 @@ const identityKeyDisplay = computed(() => {
font-size: 12px;
line-height: 1.7;
}
.identity-head {
/* 备份策略:横排一行 */
.backup-policy-form {
flex-wrap: wrap;
row-gap: 8px;
}
.backup-policy-form :deep(.n-form-item-label) {
font-weight: 600;
}
.pane-divider {
margin: 12px 0;
}
.backup-fill {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.backup-fill :deep(.backup-panel) {
flex: 1 1 auto;
min-height: 0;
}
/* 区块链存证:两卡左右并排 */
.pane-full {
max-width: 1280px;
}
.chain-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(430px, 1fr));
gap: 16px;
align-items: start;
}
.chain-card {
border: 1px solid var(--n-border-color);
border-radius: 8px;
background: var(--n-card-color);
padding: 16px 20px;
}
.chain-card-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-height: 28px;
margin-bottom: 16px;
font-size: 14px;
font-weight: 700;
}
.identity-title {
font-size: 13px;
.card-actions {
display: flex;
gap: 6px;
flex-wrap: wrap;
justify-content: flex-end;
}
.chain-form :deep(.n-form-item) {
margin-bottom: 16px;
}
.chain-form :deep(.n-form-item:last-child) {
margin-bottom: 0;
}
.chain-form :deep(.n-form-item-label) {
font-weight: 600;
color: var(--n-text-color-2, #526070);
}
.secret-field {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
}
.secret-input {
flex: 1 1 auto;
min-width: 0;
}
.identity-empty {
color: var(--n-text-color-3, #8a94a6);
font-size: 13px;
line-height: 1.7;
}
.identity-value {
font-size: 12px;
font-size: 13px;
line-height: 22px;
word-break: break-all;
}
.identity-value.mono {
@@ -676,92 +795,25 @@ const identityKeyDisplay = computed(() => {
.identity-key {
display: flex;
align-items: center;
gap: 6px;
gap: 4px;
flex-wrap: wrap;
}
.identity-hint {
margin: 4px 12px 10px;
margin: 12px 0 0;
font-size: 12px;
line-height: 1.6;
color: #d03050;
}
.setting-row {
padding: 8px 12px;
border-bottom: 1px solid var(--n-border-color);
}
.setting-row:last-child {
border-bottom: 0;
}
.settings-form :deep(.n-form-item) {
display: grid;
grid-template-columns: 128px max-content;
grid-template-rows: auto;
grid-template-areas: "label blank";
align-items: center;
column-gap: 12px;
margin-bottom: 0;
}
.platform-card :deep(.n-form-item) {
grid-template-columns: 148px max-content;
}
.settings-form :deep(.n-form-item-label) {
min-height: auto;
padding: 0;
color: var(--n-text-color-2);
font-weight: 600;
line-height: 20px;
white-space: nowrap;
}
.settings-form :deep(.n-form-item-blank) {
min-height: 32px;
}
.setting-row :deep(.n-form-item-feedback-wrapper) {
display: none;
}
.control-wide {
width: 100%;
}
.text-control {
width: 180px;
}
.url-control {
width: 220px;
}
.number-control {
width: 128px;
}
.number-control :deep(.n-input__input-el) {
text-align: center;
}
.select-control {
width: 128px;
}
.setting-label {
color: var(--n-text-color-2);
font-weight: 600;
font-size: 14px;
line-height: 20px;
white-space: nowrap;
}
.icon-row {
display: grid;
grid-template-columns: 128px max-content;
align-items: center;
column-gap: 12px;
}
.platform-card .icon-row {
grid-template-columns: 148px max-content;
}
/* 系统图标设置 */
.icon-setting {
display: grid;
grid-template-columns: 60px minmax(0, 1fr);
display: flex;
align-items: center;
gap: 12px;
width: 100%;
}
.icon-preview-wrap {
width: 60px;
min-height: 60px;
height: 60px;
border-radius: 8px;
border: 1px solid var(--n-border-color);
background: var(--n-color);
@@ -790,42 +842,9 @@ const identityKeyDisplay = computed(() => {
.icon-upload :deep(.image-item.add span) {
display: none;
}
.settings-backup-panel {
flex: 1 1 320px;
display: flex;
flex-direction: column;
width: 100%;
min-height: 320px;
padding: 12px;
box-sizing: border-box;
border: 1px solid var(--n-border-color);
border-radius: 8px;
background: var(--n-card-color);
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}
.settings-backup-panel :deep(.backup-panel) {
flex: 1 1 auto;
min-height: 0;
}
@media (max-width: 900px) {
.settings-shell {
min-width: 0;
}
.settings-card-grid {
grid-template-columns: 448px 376px 376px;
}
.settings-save {
right: 0;
}
.icon-setting {
grid-template-columns: 60px minmax(0, 1fr);
}
}
@media (max-width: 640px) {
.settings-form :deep(.n-form-item),
.icon-row {
.chain-grid {
grid-template-columns: 1fr;
row-gap: 8px;
}
}
</style>
+135 -8
View File
@@ -23,6 +23,7 @@ interface MediaItem {
key: string;
name?: string;
type?: string;
url?: string;
}
interface TraceNodeSnapshot {
@@ -83,6 +84,80 @@ export class ArtworkService {
return `ARTVERIS-${String(id).padStart(6, '0')}`;
}
// 媒体目录层级:{模板ID}/{档案编号}/(追溯码出库图再下一级 {追溯码}/,见 outbound)
private mediaDir(templateId: number, archiveNo: string): string {
return `${templateId}/${archiveNo}`;
}
// 把作品的既有媒体(主图/节点图/证书原件+水印件)归位到 {模板ID}/{档案编号}/,
// 文件名人类可读:作品图_{时间戳}_{序号} / 节点-{标题}_... / 证书-{名称}_...;
// 同步更新 DB 引用,返回 oldKey->newKey 映射(供调用方改写快照/DTO 中的旧引用)。
private async relocateArtworkMedia(artworkId: number): Promise<Map<string, string>> {
const keyMap = new Map<string, string>();
const artwork = await this.prisma.artwork.findFirst({
where: { id: artworkId, deletedAt: null },
include: { traceNodes: true, certificates: true },
});
if (!artwork?.archiveNo) return keyMap;
const dir = this.mediaDir(artwork.templateId, artwork.archiveNo);
const images = await this.storage.relocateMedia((artwork.images ?? []) as unknown as MediaItem[], dir, '作品图');
images.keyMap.forEach((v, k) => keyMap.set(k, v));
if (images.changed) {
await this.prisma.artwork.update({
where: { id: artworkId },
data: { images: images.items as unknown as Prisma.InputJsonValue },
});
}
for (const node of artwork.traceNodes) {
const media = await this.storage.relocateMedia(
(node.mediaFiles ?? []) as unknown as MediaItem[],
dir,
`节点-${this.storage.sanitizeSegment(node.title)}`,
);
media.keyMap.forEach((v, k) => keyMap.set(k, v));
if (media.changed) {
await this.prisma.traceNode.update({
where: { id: node.id },
data: { mediaFiles: media.items as unknown as Prisma.InputJsonValue },
});
}
}
for (const cert of artwork.certificates) {
const origin = await this.storage.relocateMedia(
[{ key: cert.originFileUrl }],
dir,
`证书-${this.storage.sanitizeSegment(cert.name)}`,
);
const newOrigin = origin.items[0]?.key ?? cert.originFileUrl;
let newWatermark = cert.watermarkFileUrl;
if (origin.changed) {
keyMap.set(cert.originFileUrl, newOrigin);
// 水印件跟随原件命名(derivedKey 加 _wm 后缀、同目录)
if (cert.watermarkFileUrl) {
newWatermark = await this.storage.moveKey(cert.watermarkFileUrl, this.storage.derivedKey(newOrigin, 'wm'));
if (newWatermark !== cert.watermarkFileUrl) keyMap.set(cert.watermarkFileUrl, newWatermark);
}
await this.prisma.certificate.update({
where: { id: cert.id },
data: { originFileUrl: newOrigin, watermarkFileUrl: newWatermark },
});
}
}
return keyMap;
}
// 用 oldKey->newKey 映射改写媒体数组引用
private remapMedia(items: MediaItem[] | undefined, keyMap: Map<string, string>): MediaItem[] | undefined {
if (!items?.length || !keyMap.size) return items;
return items.map((item) => {
const next = item?.key ? keyMap.get(item.key) : undefined;
return next ? { ...item, key: next, ...(item.url ? { url: this.storage.getUrl(next) } : {}) } : item;
});
}
async create(dto: CreateArtworkDto, userId: number) {
const tpl = await this.prisma.template.findFirst({
where: { id: dto.templateId, deletedAt: null },
@@ -94,7 +169,7 @@ export class ArtworkService {
dto.traceNodes === undefined ? DEFAULT_TRACE_NODES : this.normalizeTraceNodeDto(dto.traceNodes);
const certificates = this.normalizeCertificateDto(dto.certificates ?? []);
const artwork = await this.prisma.$transaction(async (tx) => {
const { created: artwork, revisionId } = await this.prisma.$transaction(async (tx) => {
const created = await tx.artwork.create({
data: {
templateId: dto.templateId,
@@ -136,7 +211,7 @@ export class ArtworkService {
const archiveNo = this.buildArchiveNo(created.id);
await tx.artwork.update({ where: { id: created.id }, data: { archiveNo } });
const snapshot = this.snapshotFromRecord(created);
await tx.artworkRevision.create({
const revision = await tx.artworkRevision.create({
data: {
artworkId: created.id,
title: status === ArtworkStatus.DRAFT ? '创建草稿' : '提交初次审核',
@@ -147,9 +222,24 @@ export class ArtworkService {
submittedBy: userId,
},
});
return created;
return { created, revisionId: revision.id };
});
// 媒体归位到 {模板ID}/{档案编号}/(档案编号在事务内生成,只能事后归位),并同步初始快照引用
const keyMap = await this.relocateArtworkMedia(artwork.id);
if (keyMap.size) {
const refreshed = await this.prisma.artwork.findFirst({
where: { id: artwork.id },
include: { traceNodes: true, certificates: true },
});
if (refreshed) {
await this.prisma.artworkRevision.update({
where: { id: revisionId },
data: { afterSnapshot: this.snapshotFromRecord(refreshed) as unknown as Prisma.InputJsonObject },
});
}
}
await this.enqueuePendingCertificateWatermarks(artwork.id);
return this.get(artwork.id);
}
@@ -269,6 +359,45 @@ export class ArtworkService {
async update(id: number, dto: UpdateArtworkDto, user: AuthUser) {
const userId = user.id;
const artwork = await this.ensureExists(id);
// 先把既有媒体归位(含历史日期目录的旧文件),拿到 old->new 映射改写 DTO 引用;
// 再把 DTO 里新上传的媒体(仍在通用上传目录)归位,保证快照/落库全部使用最终 key
const keyMap = await this.relocateArtworkMedia(id);
const dir = artwork.archiveNo ? this.mediaDir(artwork.templateId, artwork.archiveNo) : null;
let dtoImages = this.remapMedia(dto.images as MediaItem[] | undefined, keyMap);
if (dtoImages && dir) {
dtoImages = (await this.storage.relocateMedia(dtoImages, dir, '作品图')).items;
}
let dtoNodes = dto.traceNodes ? this.normalizeTraceNodeDto(dto.traceNodes) : undefined;
if (dtoNodes && dir) {
dtoNodes = await Promise.all(
dtoNodes.map(async (node) => {
const media = this.remapMedia(node.mediaFiles, keyMap) ?? [];
const relocated = await this.storage.relocateMedia(media, dir, `节点-${this.storage.sanitizeSegment(node.title)}`);
return { ...node, mediaFiles: relocated.items };
}),
);
}
let dtoCerts = dto.certificates ? this.normalizeCertificateDto(dto.certificates) : undefined;
if (dtoCerts && dir) {
dtoCerts = await Promise.all(
dtoCerts.map(async (cert) => {
let originKey = keyMap.get(cert.originKey) ?? cert.originKey;
if (!originKey.startsWith(`${dir}/`)) {
const relocated = await this.storage.relocateMedia(
[{ key: originKey }],
dir,
`证书-${this.storage.sanitizeSegment(cert.name)}`,
);
originKey = relocated.items[0]?.key ?? originKey;
}
const watermarkKey = cert.watermarkKey ? keyMap.get(cert.watermarkKey) ?? cert.watermarkKey : cert.watermarkKey;
return { ...cert, originKey, watermarkKey };
}),
);
}
const current = await this.getSnapshot(id);
const nextStatus = dto.status === ArtworkStatus.DRAFT ? ArtworkStatus.ACTIVE : dto.status ?? current.artwork.status;
const afterSnapshot: ArtworkSnapshot = {
@@ -278,13 +407,11 @@ export class ArtworkService {
artist: dto.artist ?? current.artwork.artist,
status: nextStatus,
dynamicFields: dto.dynamicFields ?? current.artwork.dynamicFields,
images: (dto.images ?? current.artwork.images) as MediaItem[],
images: (dtoImages ?? current.artwork.images) as MediaItem[],
},
traceNodes: dto.traceNodes ? this.normalizeTraceNodeDto(dto.traceNodes) : current.traceNodes,
certificates: dto.certificates ? this.normalizeCertificateDto(dto.certificates) : current.certificates,
traceNodes: dtoNodes ?? current.traceNodes,
certificates: dtoCerts ?? current.certificates,
};
const artwork = await this.ensureExists(id);
const shouldApplyDirectly = artwork.status !== ArtworkStatus.ACTIVE || artwork.auditStatus !== AuditStatus.APPROVED;
const shouldAutoApprove = user.role === RoleType.SUPER_ADMIN;
if (!this.hasSnapshotChanged(current, afterSnapshot)) {
+22 -2
View File
@@ -4,6 +4,8 @@ import { Queue } from 'bullmq';
import { ErrorCode, ProofStatus, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { StorageService } from '../storage/storage.service';
import { isOutbound } from '../outbound/outbound.util';
import { BlockchainService } from './blockchain.service';
@Injectable()
@@ -11,9 +13,18 @@ export class AttestationService {
constructor(
private readonly prisma: PrismaService,
private readonly blockchain: BlockchainService,
private readonly storage: StorageService,
@InjectQueue(QUEUE_NAMES.ONCHAIN) private readonly queue: Queue,
) {}
// 取作品主图的公开 URL 作为发行 feature(天河文档:feature=作品对应媒体文件地址;媒体本体存我方 OSS)
private firstImageUrl(images: unknown): string | undefined {
const list = Array.isArray(images) ? images : [];
const first = list[0] as { key?: string } | string | undefined;
const key = typeof first === 'string' ? first : first?.key;
return key ? this.storage.getUrl(key) : undefined;
}
async trigger(traceCodeId: bigint) {
const code = await this.prisma.traceCode.findUnique({
where: { id: traceCodeId },
@@ -26,6 +37,10 @@ export class AttestationService {
if (!code.artworkId || !code.artwork) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '追溯码未绑定作品,无法上链');
}
// 上链代表已登记出库:未出库不允许上链(杜绝「已上链未登记」的不一致状态)
if (!isOutbound(code)) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '该追溯码尚未登记出库,请先登记出库再上链');
}
// 防重复上链:已存在「上链成功/上链中/待上链」的存证则拒绝;仅失败(FAILED)的可再次发起。
const active = await this.prisma.blockchainProof.findFirst({
@@ -66,8 +81,13 @@ export class AttestationService {
status: ProofStatus.PENDING,
rawResponse: {
requestMeta: summary,
// 发行 NFT 用的产品信息(天河链:productId=追溯码、name=作品名、author=艺术家)
product: { productId: code.shortCode, name: code.artwork.title, author: code.artwork.artist ?? undefined },
// 发行 NFT 用的产品信息(天河链:productId=追溯码、name=作品名、author=艺术家、feature=作品主图 OSS 地址)
product: {
productId: code.shortCode,
name: code.artwork.title,
author: code.artwork.artist ?? undefined,
feature: this.firstImageUrl(code.artwork.images),
},
},
},
});
+10 -11
View File
@@ -47,12 +47,13 @@ export class BlockchainService {
return provider.attest(payload);
}
// 天河链「存证 + 发行」双层:① upload 存证 JSON(拿存证哈希/digest/存证链接)
// ② publish 铸 1 个 NFT(productId=追溯码、feature=存证链接)→ mint 交易可经接口 9 确认拿区块信息。
// 天河链「仅发行」:直接 publish 铸 1 个 NFT(productId=追溯码、feature=作品主图 OSS 地址)→ mint 交易经接口 9 确认拿区块信息。
// 甲方确认:不做数字商品元数据上链存储(upload),作品详情/媒体存我方 OSS;链上凭据即 NFT(tokenId + mint 交易)。
// 合约地址与已发行最大 tokenId 存系统设置(上链队列串行,无并发争用)。
private async attestWithTianhe(provider: TianheProvider, payload: AttestPayload): Promise<AttestResult> {
const attest = await provider.attest(payload);
if (!payload.product) return attest; // 无产品信息时退化为纯存证(防御,正常流程总是携带)
if (!payload.product) {
throw new Error('天河链发行失败:缺少产品信息(productId/name)');
}
const settings = await this.settings.getAllRaw();
const contractAddress = (settings.tianheContractAddress || '').trim() || undefined;
@@ -61,7 +62,7 @@ export class BlockchainService {
productId: payload.product.productId,
name: payload.product.name,
author: payload.product.author,
feature: attest.explorerUrl ?? undefined,
feature: payload.product.feature ?? undefined,
contractAddress,
// 官方要求:指定 contractAddress 时 baseTokenId 须为「已发行 tokenId 的最大值」
baseTokenId: contractAddress ? maxTokenId : undefined,
@@ -75,23 +76,21 @@ export class BlockchainService {
return {
dataHash: payload.dataHash,
// 主凭据切换为 mint 交易(可确认、有区块信息、tokenId 资产语义);存证交易哈希保留在 raw.attestTxHash
// 凭据为 mint 交易(可确认、有区块信息、tokenId 资产语义)
txHash: pub.txHash,
blockHash: null,
blockHeight: null,
chainName: '天河链',
// 「查看存证」跳天河区块浏览器交易详情页(规范展示);UDFS 裸 JSON 存证链接保留在 raw.proofUrl / feature 字段
// 「查看存证」跳天河区块浏览器交易详情页(规范展示 mint 交易:追溯码 productId、作品主图 feature、tokenId)
explorerUrl: provider.explorerTxUrl(pub.txHash),
tokenId: pub.tokenId >= 0 ? pub.tokenId : null,
contractAddress: pub.contractAddress,
onchainAt: new Date(),
raw: {
...attest.raw,
attestTxHash: attest.txHash,
attestUrl: attest.explorerUrl,
product: payload.product,
publishResponse: pub.raw,
transactionStatus: 'submitted',
transactionStatusNote: '存证已生效(upload);NFT 铸造交易已提交,等待接口 9 确认区块信息。',
transactionStatusNote: 'NFT 铸造交易已提交,等待接口 9 确认区块信息。',
},
confirmationRequired: true,
};
+2 -2
View File
@@ -1,8 +1,8 @@
export interface AttestPayload {
dataHash: string;
meta?: Record<string, unknown>;
// 发行 NFT 用的产品信息(天河链 publish:productId=追溯码、name=专题名≤42、author≤120)
product?: { productId: string; name: string; author?: string };
// 发行 NFT 用的产品信息(天河链 publish:productId=追溯码、name=专题名≤42、author≤120、feature=作品主图地址≤500)
product?: { productId: string; name: string; author?: string; feature?: string };
}
export interface AttestResult {
+7 -3
View File
@@ -24,11 +24,15 @@ function requestMeta(raw: unknown): Record<string, unknown> | undefined {
return meta && typeof meta === 'object' ? (meta as Record<string, unknown>) : undefined;
}
function productInfo(raw: unknown): { productId: string; name: string; author?: string } | undefined {
function productInfo(
raw: unknown,
): { productId: string; name: string; author?: string; feature?: string } | undefined {
if (!raw || typeof raw !== 'object') return undefined;
const product = (raw as Record<string, unknown>).product as { productId?: string; name?: string; author?: string } | undefined;
const product = (raw as Record<string, unknown>).product as
| { productId?: string; name?: string; author?: string; feature?: string }
| undefined;
return product?.productId && product?.name
? { productId: product.productId, name: product.name, author: product.author }
? { productId: product.productId, name: product.name, author: product.author, feature: product.feature }
: undefined;
}
@@ -0,0 +1,34 @@
import { currentPreviewToken, isValidPreviewToken, PREVIEW_PERIOD_MS } from './preview-token.util';
describe('preview-token.util', () => {
const secret = 'test-secret';
const now = 1_800_000_000_000;
it('当前窗口令牌有效', () => {
const token = currentPreviewToken(secret, now);
expect(isValidPreviewToken(secret, token, now)).toBe(true);
});
it('上一窗口令牌在宽限期内有效', () => {
const prevToken = currentPreviewToken(secret, now - PREVIEW_PERIOD_MS);
expect(prevToken).not.toBe(currentPreviewToken(secret, now));
expect(isValidPreviewToken(secret, prevToken, now)).toBe(true);
});
it('更早窗口令牌失效', () => {
const oldToken = currentPreviewToken(secret, now - 2 * PREVIEW_PERIOD_MS);
expect(isValidPreviewToken(secret, oldToken, now)).toBe(false);
});
it('空/畸形/错误密钥令牌失效', () => {
expect(isValidPreviewToken(secret, undefined, now)).toBe(false);
expect(isValidPreviewToken(secret, '', now)).toBe(false);
expect(isValidPreviewToken(secret, 'short', now)).toBe(false);
expect(isValidPreviewToken(secret, currentPreviewToken('other-secret', now), now)).toBe(false);
});
it('同窗口内令牌稳定,跨窗口轮换', () => {
expect(currentPreviewToken(secret, now)).toBe(currentPreviewToken(secret, now + PREVIEW_PERIOD_MS - 1));
expect(currentPreviewToken(secret, now)).not.toBe(currentPreviewToken(secret, now + PREVIEW_PERIOD_MS));
});
});
@@ -0,0 +1,28 @@
import { createHmac, timingSafeEqual } from 'crypto';
// 追溯码预览令牌:类 TOTP 的时间窗口 HMAC 令牌。
// 周期 10 分钟;校验时接受「当前窗口 + 上一窗口」,即令牌实际有效 10~20 分钟。
// 无状态(不落库/不进 Redis),密钥复用 JWT_SECRET,后台随取随用、自动随时间轮换,
// 防止预览地址被打印/转发后长期有效。
export const PREVIEW_PERIOD_MS = 600_000;
const TOKEN_HEX_LEN = 16;
function tokenForWindow(secret: string, window: number): string {
return createHmac('sha256', secret).update(`preview:${window}`).digest('hex').slice(0, TOKEN_HEX_LEN);
}
export function currentPreviewToken(secret: string, now = Date.now()): string {
return tokenForWindow(secret, Math.floor(now / PREVIEW_PERIOD_MS));
}
export function isValidPreviewToken(secret: string, token: string | undefined, now = Date.now()): boolean {
if (!token || token.length !== TOKEN_HEX_LEN) return false;
const window = Math.floor(now / PREVIEW_PERIOD_MS);
const provided = Buffer.from(token, 'utf8');
// 当前窗口 + 上一窗口(宽限期),常量时间比较防时序侧信道
for (const w of [window, window - 1]) {
const expected = Buffer.from(tokenForWindow(secret, w), 'utf8');
if (provided.length === expected.length && timingSafeEqual(provided, expected)) return true;
}
return false;
}
+16 -5
View File
@@ -41,18 +41,29 @@ export class ImportProcessor extends WorkerHost {
let fail = 0;
for (const row of rows) {
try {
const code = await this.prisma.traceCode.findUnique({ where: { shortCode: row.shortCode || '' } });
const code = await this.prisma.traceCode.findUnique({
where: { shortCode: row.shortCode || '' },
include: { artwork: { select: { templateId: true, archiveNo: true } } },
});
if (!code) throw new Error('追溯码不存在');
// 预览到提交之间可能已被出库:再次校验,避免重复出库
if (isOutbound(code)) throw new Error('该追溯码已登记出库,不可重复出库');
const imageItems = jsonArray<{ key: string; url?: string; name?: string; type?: string }>(row.outImageKeys);
let imageItems = jsonArray<{ key: string; url?: string; name?: string; type?: string }>(row.outImageKeys).map(
(item) => ({ key: item.key, name: item.name, type: item.type || 'image' }),
);
// 出库实况图归位到 {模板ID}/{档案编号}/{追溯码}/出库实况_{时间戳}_{序号}
if (imageItems.length && code.artwork?.archiveNo) {
const dir = `${code.artwork.templateId}/${code.artwork.archiveNo}/${code.shortCode}`;
imageItems = (await this.storage.relocateMedia(imageItems, dir, '出库实况')).items.map((item) => ({
...item,
name: item.key.split('/').pop() || item.name,
}));
}
await this.prisma.traceCode.update({
where: { id: code.id },
data: {
outTime: row.outTime ?? undefined,
outImages: imageItems.length
? imageItems.map((item) => ({ key: item.key, name: item.name, type: item.type || 'image' }))
: undefined,
outImages: imageItems.length ? imageItems : undefined,
remark: row.remark || undefined,
},
});
+18 -4
View File
@@ -32,20 +32,34 @@ export class OutboundService {
) {}
async updateSingle(traceCodeId: bigint, dto: OutboundDto) {
const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId } });
const code = await this.prisma.traceCode.findUnique({
where: { id: traceCodeId },
include: { artwork: { select: { templateId: true, archiveNo: true } } },
});
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
// 一物一码只能出库一次:已登记出库时间或出库图任一即视为已出库
if (isOutbound(code)) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '该追溯码已登记出库,不可重复出库');
}
// 出库时间必填:出库登记必须有出库时间
if (!dto.outTime) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '出库时间不能为空');
}
const imageKeys = dto.outImageKeys ?? (dto.outImageKey ? [dto.outImageKey] : []);
const data: Prisma.TraceCodeUpdateInput = {};
if ('outTime' in dto) data.outTime = dto.outTime ? new Date(dto.outTime) : null;
if ('outImageKeys' in dto || 'outImageKey' in dto) {
let imageItems = imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' }));
// 出库实况图归位到 {模板ID}/{档案编号}/{追溯码}/出库实况_{时间戳}_{序号}
if (imageItems.length && code.artwork?.archiveNo) {
const dir = `${code.artwork.templateId}/${code.artwork.archiveNo}/${code.shortCode}`;
imageItems = (await this.storage.relocateMedia(imageItems, dir, '出库实况')).items.map((item) => ({
...item,
name: item.key.split('/').pop() || item.name,
}));
}
// 无图时写 DB NULL(而非 JSON null),保证出库状态筛选一致
data.outImages = imageKeys.length
? imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' }))
: Prisma.DbNull;
data.outImages = imageItems.length ? imageItems : Prisma.DbNull;
}
if ('remark' in dto) data.remark = dto.remark || null;
return this.prisma.traceCode.update({
@@ -1,9 +1,11 @@
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
import { Controller, Get, Param, Query, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Throttle } from '@nestjs/throttler';
import { ConfigService } from '@nestjs/config';
import { Public } from '../common/decorators/public.decorator';
import { extractIp } from '../common/utils/ua.util';
import { isValidPreviewToken } from '../common/utils/preview-token.util';
import { PublicTraceService } from './public-trace.service';
import { SettingsService } from '../settings/settings.service';
@@ -13,6 +15,7 @@ export class PublicTraceController {
constructor(
private readonly service: PublicTraceService,
private readonly settings: SettingsService,
private readonly config: ConfigService,
) {}
@Public()
@@ -26,6 +29,22 @@ export class PublicTraceController {
return this.service.trace(shortCode, { ip, userAgent });
}
// 后台预览:凭时间令牌访问,零副作用(不激活/不计数/不写日志)。令牌过期返回 PREVIEW_EXPIRED。
@Public()
@Get('public/trace/:shortCode/preview')
@Throttle({ default: { limit: 60, ttl: 60_000 } })
@ApiOperation({ summary: 'C 端溯源预览(令牌保护,不激活不计数)' })
preview(
@Param('shortCode') shortCode: string,
@Query('token') token?: string,
@Query('state') state?: string,
) {
if (!isValidPreviewToken(this.config.get<string>('jwt.secret') || '', token)) {
return { status: 'PREVIEW_EXPIRED' as const };
}
return this.service.preview(shortCode, state === 'active' ? 'active' : 'inactive');
}
// 短链跳转:扫码打开 /t/:shortCode -> 重定向到 C 端溯源页(不在 /api 前缀下)
@Public()
@Get('t/:shortCode')
@@ -8,6 +8,13 @@ import { REDIS_CLIENT } from '../redis/redis.module';
import { parseUserAgent } from '../common/utils/ua.util';
type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>;
type ArtworkWithRel = Prisma.ArtworkGetPayload<{
include: {
template: { include: { fields: true } };
traceNodes: true;
certificates: true;
};
}>;
export interface TraceContext {
ip: string;
@@ -186,6 +193,81 @@ export class PublicTraceService {
queryCount: updated.queryCount,
firstActivatedAt: updated.firstActivatedAt,
},
...this.buildArtworkPayload(artwork, code, proof),
};
}
// 后台预览:与 trace() 相同的数据组装,但零副作用——不激活、不计数、不写查询日志。
// state 决定防伪区块以「首次扫码」还是「重复访问」形态展示,antiCounterfeit 数值为演示占位/库中现值。
async preview(shortCode: string, state: 'inactive' | 'active') {
if (!TRACE_CODE_PATTERN.test(shortCode)) return { status: 'INVALID' as const };
const id = await this.resolveId(shortCode);
if (id === null) return { status: 'INVALID' as const };
const code = await this.prisma.traceCode.findUnique({
where: { id },
include: { batch: true, artwork: true },
});
if (!code) return { status: 'INVALID' as const };
if (code.status === TraceCodeStatus.DISABLED) return { status: 'DISABLED' as const };
if (code.status === TraceCodeStatus.ABNORMAL) return { status: 'ABNORMAL' as const };
const artwork = await this.prisma.artwork.findFirst({
where: { id: code.artworkId, deletedAt: null },
include: {
template: { include: { fields: { orderBy: { sortOrder: 'asc' } } } },
traceNodes: { orderBy: { sortOrder: 'asc' } },
certificates: { orderBy: { id: 'asc' } },
},
});
if (
!artwork ||
artwork.status === ArtworkStatus.DISABLED ||
artwork.auditStatus !== AuditStatus.APPROVED
) {
return { status: 'INVALID' as const };
}
const proof = await this.prisma.blockchainProof.findFirst({
where: { traceCodeId: id, status: ProofStatus.ONCHAIN },
orderBy: { id: 'desc' },
});
const now = new Date();
const firstQuery = state === 'inactive';
return {
status: 'OK' as const,
preview: true,
code: code.code,
queriedAt: now,
antiCounterfeit: firstQuery
? { firstQuery: true, queryCount: 1, firstActivatedAt: now }
: {
firstQuery: false,
queryCount: code.queryCount > 0 ? code.queryCount : 2,
firstActivatedAt: code.firstActivatedAt ?? now,
},
...this.buildArtworkPayload(artwork, code, proof),
};
}
// trace/preview 共用的作品展示数据(作品信息 / 时间线 / 证书 / 区块链存证)
private buildArtworkPayload(
artwork: ArtworkWithRel,
code: { outTime?: Date | null; outImages?: unknown },
proof: {
txHash: string | null;
dataHash: string;
blockHash: string | null;
blockHeight: bigint | null;
chainName: string | null;
onchainAt: Date | null;
explorerUrl: string | null;
tokenId: bigint | null;
contractAddress: string | null;
} | null,
) {
return {
artwork: {
title: artwork.title,
artist: artwork.artist,
@@ -62,6 +62,15 @@ export class SettingsController {
return { userId, address, userKeyMasked: this.settingsService.maskSecretPublic(userKey) };
}
@ApiBearerAuth()
@Roles(RoleType.SUPER_ADMIN)
@Post('tianhe/app-key/reveal')
@ApiOperation({ summary: '揭示天河链 App Key 明文;用 POST 以便写入操作日志(仅超管)' })
async revealTianheAppKey() {
const all = await this.settingsService.getAllRaw();
return { appKey: all.tianheAppKey || '' };
}
@ApiBearerAuth()
@Roles(RoleType.SUPER_ADMIN)
@Post('tianhe/identity/reveal')
+74
View File
@@ -23,6 +23,15 @@ const MIME_EXT: Record<string, string> = {
'application/pdf': '.pdf',
};
const EXT_MIME: Record<string, string> = Object.fromEntries(
Object.entries(MIME_EXT).map(([mime, ext]) => [ext, mime]),
);
export interface RelocatableMedia {
key: string;
url?: string;
}
@Injectable()
export class StorageService implements OnModuleInit {
private readonly logger = new Logger(StorageService.name);
@@ -120,6 +129,71 @@ export class StorageService implements OnModuleInit {
return `${base}_${suffix}${ext || '.jpg'}`;
}
// 清洗目录/文件名片段:去掉路径分隔与 Windows 非法字符,限长,空值兜底
sanitizeSegment(name: string, fallback = '未命名'): string {
const cleaned = (name || '')
// eslint-disable-next-line no-control-regex
.replace(/[\\/:*?"<>|\x00-\x1f]/g, '')
.replace(/\s+/g, ' ')
.trim()
.replace(/^\.+|\.+$/g, '');
return (cleaned || fallback).slice(0, 32);
}
// 移动(重命名)一个存储对象;失败时保留原 key 并告警,绝不让业务流程因归位失败而中断
async moveKey(oldKey: string, newKey: string): Promise<string> {
if (!oldKey || oldKey === newKey) return oldKey;
try {
const buffer = await this.driver.get(oldKey);
await this.driver.put(newKey, buffer, {
contentType: EXT_MIME[extname(newKey).toLowerCase()],
cacheControl: STATIC_ASSET_CACHE_CONTROL,
});
await this.driver.remove(oldKey).catch(() => undefined);
return newKey;
} catch (e) {
this.logger.warn(`媒体归位失败(${oldKey} -> ${newKey}):${(e as Error).message}`);
return oldKey;
}
}
// 把一组媒体归位到指定目录,命名 {基础名}_{时间戳}_{序号}{扩展名}(人类可读)。
// 已在目录内 / 外链(http/data:) 的条目跳过;同一 key 重复引用复用同一次移动结果。
// 返回改写后的条目、是否有变化、oldKey->newKey 映射(供调用方同步改写其它引用)。
async relocateMedia<T extends RelocatableMedia>(
items: T[] | undefined | null,
dir: string,
baseName: string,
): Promise<{ items: T[]; changed: boolean; keyMap: Map<string, string> }> {
const list = Array.isArray(items) ? items : [];
const keyMap = new Map<string, string>();
const result: T[] = [];
const stamp = dayjs().format('YYYYMMDDHHmmss');
let seq = 0;
let changed = false;
for (const item of list) {
const key = item?.key;
if (!key || /^(https?:|data:)/i.test(key) || key.startsWith(`${dir}/`)) {
result.push(item);
continue;
}
let nextKey = keyMap.get(key);
if (!nextKey) {
seq += 1;
const ext = extname(key) || '.jpg';
nextKey = await this.moveKey(key, `${dir}/${baseName}_${stamp}_${seq}${ext}`);
if (nextKey !== key) keyMap.set(key, nextKey);
}
if (nextKey !== key) {
changed = true;
result.push({ ...item, key: nextKey, ...(item.url ? { url: this.getUrl(nextKey) } : {}) });
} else {
result.push(item);
}
}
return { items: result, changed, keyMap };
}
getUrl(key: string): string {
return this.driver.getPublicUrl(key);
}
@@ -11,9 +11,12 @@ import {
Res,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ConfigService } from '@nestjs/config';
import { Response } from 'express';
import { RoleType } from '@artveris/shared';
import { TraceCodeService } from './trace-code.service';
import { SettingsService } from '../settings/settings.service';
import { currentPreviewToken, PREVIEW_PERIOD_MS } from '../common/utils/preview-token.util';
import {
BatchDeleteDto,
BatchGroupDto,
@@ -34,7 +37,23 @@ import { parseBigId } from '../common/utils/bigint.util';
@ApiBearerAuth()
@Controller()
export class TraceCodeController {
constructor(private readonly service: TraceCodeService) {}
constructor(
private readonly service: TraceCodeService,
private readonly settings: SettingsService,
private readonly config: ConfigService,
) {}
// 预览令牌:类 TOTP,随时间自动轮换(当前+上一窗口有效)。后台点开预览页时随取随用,
// 预览地址外泄后最长 2 个周期即失效,无法长期传播。
@Get('trace-codes/preview-token')
@ApiOperation({ summary: '获取 C 端预览令牌(自动轮换)' })
async previewToken() {
return {
token: currentPreviewToken(this.config.get<string>('jwt.secret') || ''),
clientBase: await this.settings.getClientBaseUrl(),
periodMs: PREVIEW_PERIOD_MS,
};
}
@Post('trace-codes/batch')
@Roles(RoleType.OPERATOR)
+7 -26
View File
@@ -1,6 +1,5 @@
import { Injectable } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { ConfigService } from '@nestjs/config';
import { Queue } from 'bullmq';
import { Prisma } from '@prisma/client';
import { Response } from 'express';
@@ -35,34 +34,16 @@ export class TraceCodeService {
constructor(
private readonly prisma: PrismaService,
private readonly jobs: JobsService,
private readonly config: ConfigService,
private readonly storage: StorageService,
private readonly settings: SettingsService,
@InjectQueue(QUEUE_NAMES.GEN_CODE) private readonly genQueue: Queue,
) {}
buildTraceUrl(shortCode: string): string {
const clientBase = (this.config.get<string>('clientOrigin') || this.config.get<string>('baseUrl') || 'http://localhost:3000/trace').replace(/\/$/, '');
return `${clientBase}/#/trace/${encodeURIComponent(shortCode)}`;
}
buildShortLink(shortCode: string): string {
const base = (this.config.get<string>('baseUrl') || 'http://localhost:3000').replace(/\/$/, '');
return `${base}/t/${encodeURIComponent(shortCode)}`;
}
// 短链 origin 以系统设置 clientBaseUrl 为准(换域名后所有链接自动跟随),失败回退 env baseUrl
private async shortLinkOrigin(): Promise<string> {
try {
const clientBaseUrl = await this.settings.getClientBaseUrl();
return new URL(clientBaseUrl).origin;
} catch {
return (this.config.get<string>('baseUrl') || 'http://localhost:3000').replace(/\/$/, '');
}
}
// 追溯码链接完全以系统设置「客户端地址」为准(含路径),列表/二维码/导出动态生成、换地址自动跟随。
// 不再经 /t 短链中转(/t 跳转接口保留,兼容历史已打印二维码)。
async buildDynamicShortLink(shortCode: string): Promise<string> {
return `${await this.shortLinkOrigin()}/t/${encodeURIComponent(shortCode)}`;
const clientBase = await this.settings.getClientBaseUrl();
return `${clientBase}/#/trace/${encodeURIComponent(shortCode)}`;
}
private mapOutImages(code: { outImages?: unknown }) {
@@ -464,8 +445,8 @@ export class TraceCodeService {
}),
this.prisma.traceCode.count({ where }),
]);
// 短链统一动态生成(DB 不固化 url,换域名后列表/导出/二维码自动跟随);origin 每页只计算一次
const origin = await this.shortLinkOrigin();
// 链接统一动态生成(DB 不固化 url,换客户端地址后列表/导出/二维码自动跟随);base 每页只取一次
const clientBase = await this.settings.getClientBaseUrl();
return buildPage(
list.map((code) => {
const { proofs, ...rest } = code;
@@ -473,7 +454,7 @@ export class TraceCodeService {
const outImages = this.mapOutImages(code);
return {
...rest,
url: `${origin}/t/${encodeURIComponent(code.shortCode)}`,
url: `${clientBase}/#/trace/${encodeURIComponent(code.shortCode)}`,
outImageUrl: outImages[0]?.url ?? null,
outImages,
latestProof: latestOnchainProof,
+5
View File
@@ -24,6 +24,11 @@ export function fetchTrace(shortCode: string): Promise<any> {
return instance.get(`/public/trace/${shortCode}`) as unknown as Promise<any>;
}
// 后台预览:凭时间令牌访问,零副作用(不激活/不计数/不写日志);state 控制未激活/已激活形态
export function fetchTracePreview(shortCode: string, token: string, state: 'inactive' | 'active'): Promise<any> {
return instance.get(`/public/trace/${shortCode}/preview`, { params: { token, state } }) as unknown as Promise<any>;
}
export function fetchAppInfo(): Promise<any> {
return instance.get('/settings/public') as unknown as Promise<any>;
}
+9 -1
View File
@@ -57,7 +57,15 @@
"disabledTitle": "Code Disabled",
"disabledDesc": "This code has been disabled. Please verify carefully.",
"abnormalTitle": "Abnormal Status",
"abnormalDesc": "This code status is abnormal. Please verify carefully."
"abnormalDesc": "This code status is abnormal. Please verify carefully.",
"previewExpiredTitle": "Preview Link Expired",
"previewExpiredDesc": "Preview links are time-limited. Please reopen the preview from the admin console."
},
"preview": {
"title": "Preview Mode",
"note": "Internal preview only. No activation, no query counting.",
"inactive": "Inactive",
"active": "Activated"
},
"viewer": {
"zoomIn": "Zoom in",
+9 -1
View File
@@ -57,7 +57,15 @@
"disabledTitle": "防伪码已停用",
"disabledDesc": "该防伪码已停用,请谨慎核验。",
"abnormalTitle": "防伪码状态异常",
"abnormalDesc": "该防伪码状态异常,请谨慎核验。"
"abnormalDesc": "该防伪码状态异常,请谨慎核验。",
"previewExpiredTitle": "预览链接已过期",
"previewExpiredDesc": "预览地址具有时效性,请回到管理后台重新打开预览页面。"
},
"preview": {
"title": "预览模式",
"note": "仅供内部预览,不激活、不计入查询次数",
"inactive": "未激活",
"active": "已激活"
},
"viewer": {
"zoomIn": "放大",
+2
View File
@@ -5,6 +5,8 @@ export default createRouter({
routes: [
{ path: '/', component: () => import('@/views/Home.vue') },
{ path: '/trace/:code', component: () => import('@/views/Trace.vue') },
// 后台预览模式:复用 Trace.vue,凭 ?token= 时间令牌访问,不激活/不计数
{ path: '/trace/preview/:code', component: () => import('@/views/Trace.vue') },
{ path: '/:pathMatch(.*)*', redirect: '/' },
],
});
+90 -2
View File
@@ -43,6 +43,30 @@
</div>
</header>
<!-- 预览模式条:后台预览专用,可切换未激活/已激活展示形态 -->
<div v-if="isPreview" class="preview-bar">
<span class="preview-badge">{{ t('preview.title') }}</span>
<span class="preview-note">{{ t('preview.note') }}</span>
<div class="preview-toggle">
<button
type="button"
class="preview-toggle-btn"
:class="{ active: previewState === 'inactive' }"
@click="setPreviewState('inactive')"
>
{{ t('preview.inactive') }}
</button>
<button
type="button"
class="preview-toggle-btn"
:class="{ active: previewState === 'active' }"
@click="setPreviewState('active')"
>
{{ t('preview.active') }}
</button>
</div>
</div>
<!-- 加载 -->
<div v-if="loading" class="state">
<div class="spinner" />
@@ -392,7 +416,7 @@ import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import { fetchTrace, fetchAppInfo } from '@/api';
import { fetchTrace, fetchTracePreview, fetchAppInfo } from '@/api';
import { setLocale, SUPPORTED_LOCALES } from '@/locales';
import { openMediaViewer } from '@/composables/openMediaViewer';
import { resolveAppIcon, setFavicon } from '@/utils/appIcon';
@@ -420,6 +444,17 @@ const antiModalOpen = ref(false);
const certIndex = ref(0);
const currentCert = computed(() => data.value?.certificates?.[certIndex.value] || null);
// 后台预览模式:/trace/preview/:code?token=xxx,零副作用(不激活/不计数),可切换未激活/已激活形态
const isPreview = computed(() => route.path.startsWith('/trace/preview/'));
const previewState = ref<'inactive' | 'active'>('inactive');
const previewExpired = computed(() => data.value?.status === 'PREVIEW_EXPIRED');
function setPreviewState(state: 'inactive' | 'active') {
if (previewState.value === state) return;
previewState.value = state;
const code = route.params.code;
if (code) load(String(code));
}
// 节点图片默认收缩,避免页面过长;点击展开
const expanded = ref<Set<number>>(new Set());
function toggleNode(i: number) {
@@ -432,6 +467,7 @@ const stateKey = computed(() => {
const s = data.value?.status;
if (s === 'DISABLED') return 'disabled';
if (s === 'ABNORMAL') return 'abnormal';
if (s === 'PREVIEW_EXPIRED') return 'previewExpired';
return 'invalid';
});
@@ -703,7 +739,9 @@ async function load(code: string) {
data.value = null;
expanded.value = new Set();
try {
data.value = await fetchTrace(code);
data.value = isPreview.value
? await fetchTracePreview(code, String(route.query.token || ''), previewState.value)
: await fetchTrace(code);
} catch {
data.value = { status: 'INVALID' };
} finally {
@@ -867,6 +905,56 @@ watch(
text-overflow: ellipsis;
white-space: nowrap;
}
.preview-bar {
position: sticky;
top: 48px;
z-index: 4;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
padding: 8px 14px;
background: #fff7e6;
color: #ad6800;
border-bottom: 1px solid #ffe7ba;
font-size: 13px;
}
:root[data-theme='dark'] .preview-bar,
.dark .preview-bar {
background: rgba(173, 104, 0, 0.18);
color: #ffd591;
border-bottom-color: rgba(255, 213, 145, 0.25);
}
.preview-badge {
font-weight: 700;
flex-shrink: 0;
}
.preview-note {
flex: 1;
min-width: 120px;
opacity: 0.85;
}
.preview-toggle {
display: inline-flex;
border: 1px solid currentColor;
border-radius: 8px;
overflow: hidden;
flex-shrink: 0;
}
.preview-toggle-btn {
padding: 4px 12px;
border: none;
background: transparent;
color: inherit;
font-size: 13px;
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
.preview-toggle-btn.active {
background: #ad6800;
color: #fff;
font-weight: 600;
}
.state {
padding: 80px 32px;
text-align: center;
+206
View File
@@ -0,0 +1,206 @@
# 天河链集成说明
> 本文档描述本平台与天河链(TiChain)的集成关系、业务流程与技术实现,以当前代码为准。
> 对接凭据与测试钱包信息见本地 `docs/系统测试信息.md`(已加入 .gitignore,不入库)。
## 一、集成概览
平台采用天河链官方「数字商品三步接入」中的**链上注册 + 数字商品发行(含首发)**:
- 平台持有**一个托管钱包**(公证者身份),由 UserID/UserKey 标识,全平台唯一;
- 每个**追溯码**(一物一码)在触发上链时铸造为一个链上 NFT(数字商品),productId 即追溯码,派发到平台钱包即完成「首发」;
- **不做** NFT 二级交易(转让 transfer / 合并销毁 burn),**不上传**元数据文件与媒体文件(图片/视频全部存放平台自有存储/OSS);
- 消费者可凭交易哈希在天河区块浏览器查验该商品的链上记录。
### 环境与地址
| 项 | 测试环境 | 生产环境 |
| --- | --- | --- |
| API 域名 | `https://test.api.tichain.tianhecloud.com` | `https://api.tichain.tianhecloud.com` |
| 区块浏览器 | `https://test.explorer.tianhecloud.com` | `https://explorer.tianhecloud.com` |
| 浏览器交易详情页 | `{浏览器域名}/#/tiChain/transDetail?hash={交易哈希}` | 同左 |
计费口径:**按每次调用上链接口计费**(非按存储容量)。当前每件商品上链 = 1 次发行调用(+ 少量交易确认查询)。
## 二、实体关系图
```mermaid
graph LR
subgraph platform [平台侧]
Template[溯源模板]
Artwork["艺术品档案 (档案编号)"]
Batch[批次]
TraceCode["追溯码 (一物一码)"]
Proof["存证记录 blockchain_proof"]
Settings["系统设置 (AppID/AppKey/UserID/UserKey/合约地址/maxTokenId)"]
end
subgraph tichain [天河链侧]
Merchant["商户身份 AppID + AppKey"]
Wallet["平台托管钱包 UserID + UserKey -> 钱包地址"]
Contract["合约 contractAddress (首铸自动部署)"]
NFT["NFT tokenId (productId = 追溯码)"]
end
Template --> Artwork
Artwork --> Batch
Batch --> TraceCode
TraceCode -->|"触发上链"| Proof
Proof -->|"txHash / tokenId / 合约地址"| NFT
Settings --> Merchant
Settings --> Wallet
Merchant --> Wallet
Wallet -->|"持有"| NFT
Contract --> NFT
```
要点:
- **钱包地址**标识"谁提交的"(平台公证者身份),不标识物品,不在 C 端展示;
- **每件实物的链上凭据互相独立**:交易哈希、tokenId 互不重复;
- 合约地址与已发行最大 tokenId 保存在系统设置(`tianheContractAddress` / `tianheMaxTokenId`),上链任务经队列串行执行,不存在并发争用。
## 三、业务全流程图
```mermaid
flowchart TD
A[创建溯源模板] --> B["建立艺术品档案 (生成档案编号)"]
B --> C[内容审核通过]
C --> D["批量生成追溯码 (一物一码 + 二维码)"]
D --> E["登记出库 (出库时间必填 + 实况图)"]
E --> F["触发上链 (单件或批量)"]
F --> G["天河链发行 NFT (productId = 追溯码)"]
G --> H["交易确认 (0s/10s/30s 自动查询)"]
H -->|确认进块| I["存证完成 ONCHAIN (tokenId/区块高度回填)"]
H -->|超过自动次数| J[等待手动重新确认]
J -->|手动确认| H
I --> K["C 端溯源页展示链上信息"]
I --> L["区块浏览器交易详情页可查验"]
D --> M["消费者扫码 -> 首次激活 / 重复查询"]
M --> K
```
业务约束(硬校验,后端强制):
1. **上链必须先登记出库**——未出库的追溯码触发上链会被拒绝;
2. **一物一码只能出库一次**——已有出库时间或出库图即拒绝重复出库;
3. **不允许重复上链**——存证状态为已上链/确认中/待处理时一律拒绝,仅失败(FAILED)可重试;交易一经提交即已广播上链,"确认中"也视为已上链。
## 四、上链时序图
```mermaid
sequenceDiagram
participant Admin as 管理后台
participant API as API(AttestationService)
participant Q as BullMQ 队列
participant BC as BlockchainService
participant TH as TianheProvider
participant Chain as 天河链
Admin->>API: POST /trace-codes/:id/onchain
API->>API: 校验:已绑定作品/已出库/无进行中存证
API->>API: 计算 dataHash(sha256 结构化摘要) 建 proof(PENDING)
API->>Q: 入队 onchain 任务
Q->>BC: attest(payload)
BC->>TH: ensureRegistered()(钱包不存在则注册)
BC->>TH: publish(productId=追溯码, name=作品名, author=艺术家, feature=作品主图URL, contractAddress?, baseTokenId?)
TH->>Chain: POST /api/v2/nfr/publish
Chain-->>TH: contractAddress + tokenId(或-1待确认) + mint 交易哈希
BC->>BC: 保存合约地址/维护 maxTokenId
BC-->>Q: proof 置 CONFIRMING(txHash=mint哈希)
loop 自动确认(0s / 10s / 30s 共3次)
Q->>TH: confirmTransaction(txHash)
TH->>Chain: GET(带JSON体) /api/v2/nfr/transaction/status
Chain-->>TH: status / blockHash / blockNum / tokenId
alt status="0x0" 且已进块
Q->>Q: proof 置 ONCHAIN(回填区块高度/tokenId)
end
end
Note over Q: 3 次未确认则停等,后台可手动「重新确认」
```
## 五、存证状态机
```mermaid
stateDiagram-v2
[*] --> PENDING: 触发上链(建 proof + 入队)
PENDING --> CONFIRMING: 发行成功(拿到 mint 交易哈希)
PENDING --> FAILED: 发行失败/入队失败
CONFIRMING --> ONCHAIN: 确认进块(status 0x0)
CONFIRMING --> CONFIRMING: 未进块,继续自动/手动确认
CONFIRMING --> FAILED: 明确失败
FAILED --> PENDING: 手动重试(retry)
ONCHAIN --> [*]
```
- `PENDING / CONFIRMING / ONCHAIN` 期间均**不允许**再次触发上链;
- 仅 `FAILED` 可通过重试接口原地重发;
- 后台列表中"确认中"状态即视为已上链(菜单显示「上链信息」,不提供再次上链入口)。
## 六、链上身份生命周期
```mermaid
flowchart LR
S0([无身份]) -->|"注册(接口:用户链上身份注册)"| S1["托管钱包 UserID/UserKey/地址"]
S0 -->|"手动录入(经身份查询接口校验)"| S1
S1 -->|"轮换密钥(链上修改,旧Key立即失效)"| S1
S1 -->|"揭示/复制(二次确认+操作日志)"| V[管理员离线保管]
```
身份管理规则:
- UserID/UserKey **明文**存于系统设置表——它是打开托管钱包的唯一凭据,天河链不留存、无法找回,明文存库才能随备份跨重装恢复;
- 后台 UI 默认掩码显示;揭示、复制、轮换均需二次确认,且全部写入操作日志;
- 重装或迁移系统后,在设置页「手动录入」填入原 UserID/UserKey 即可继续使用同一链上身份,**切勿重新注册**;
- AppKey 同样支持揭示(显示明文,需确认环境安全,记操作日志),保存时服务端加密存储。
## 七、使用的天河链接口
| 接口 | 路径 | 用途 |
| --- | --- | --- |
| 用户链上身份注册 | POST `/api/v2/user` | 首次注册平台托管钱包 |
| 用户链上身份查询 | POST `/api/v2/user/info` | 校验身份/手动录入验证 |
| 数字商品发行 | POST `/api/v2/nfr/publish` | 每件商品铸造 NFT(核心上链动作) |
| 用户秘钥修改 | POST `/api/v2/user/update` | 轮换 UserKey |
| 根据交易哈希查询 | GET `/api/v2/nfr/transaction/status` | 确认 mint 交易进块,取区块高度/tokenId |
**明确不使用**的接口及原因:
| 接口 | 原因 |
| --- | --- |
| 元数据上链存储(upload) | 已定稿不上传元数据/媒体文件;`TianheProvider.attest` 代码保留但不再调用,若未来需要恢复"存证+发行"双层,只需在 `BlockchainService.attestWithTianhe` 恢复两步调用 |
| 数字商品交易(transfer) | 不做 NFT 二级交易;消费者无链上钱包体系 |
| 销毁数字商品(burn) | 不做删除,链上记录一经写入不可删除 |
| 交易结果查询(detail) / NFR 所属查询与判断 | 现有确认链路已满足,无业务需要 |
## 八、发行参数与约束
| 参数 | 取值 | 约束 |
| --- | --- | --- |
| productId | 追溯码(12 位数字) | 每件唯一 |
| name | 作品名 | ≤ 42 字符(超长截断) |
| author | 艺术家 | ≤ 120 字符 |
| feature | 作品主图的平台存储 URL | ≤ 500 字符;浏览器藏品页/交易页展示用 |
| contractAddress | 首铸后保存于系统设置 | 后续铸造必须携带 |
| baseTokenId | 已发行最大 tokenId | 指定合约时必传;队列串行维护,无并发问题 |
| operateId | 随机幂等串 | ≤ 20 字符 |
已知接口行为(实测结论,官方文档未必写明):
- 发行可能返回 `tokenId = -1`(交易待处理),真实 tokenId 在交易确认时回填;
- 交易确认接口是 **GET 但参数放 JSON 请求体**(appKey 不能进 URL);`status` 字段 `"0x0"` 表示交易成功,否则为失败;
- 交易确认接口仅适用于 token 类交易(mint/transfer/burn)。
## 九、C 端与查验
- C 端溯源页区块链卡展示:链名、交易哈希、数据哈希(平台本地对结构化溯源信息计算的 sha256 指纹)、数字商品编号(tokenId)、合约地址、区块高度、上链时间;
- 「查看存证」跳转天河区块浏览器**交易详情页**(`transDetail?hash=...`),可看到交易状态、区块高度、发行动作、productId(追溯码)与 feature(作品主图);
- 数据哈希为平台自算指纹,用于内容比对,并非链上存证文件哈希(平台不上传存证文件)。
## 十、生产上线检查单
1. 更换生产环境 AppID/AppKey(设置页「区块链存证」);
2. 环境切换为「生产环境」(接口地址自动切换);
3. 在生产环境**重新注册**平台托管钱包(勿沿用测试钱包),并离线保存 UserID/UserKey;
4. 抽取一件真实商品走通「出库 → 上链 → 确认 → 浏览器查验」全链路;
5. 与天河链商务核对生产计费。
+177
View File
@@ -0,0 +1,177 @@
# 项目交接文档
> 面向新维护者(人与 AI 均可阅读)。本文档汇总项目从立项到首版定稿期间**所有已拍板的决策、业务边界、已知取舍与注意事项**,是继承开发记忆的入口。
>
> 阅读顺序建议:本文档(定稿决策) → `README.md`(运行方式) → `docs/天河链集成说明.md`(区块链细节) → `aidocs/project_context.md`(逐条开发流水记忆)。
>
> **冲突裁决规则:代码现状 > 本文档 > aidocs/project_context.md > docs/ 下 PRD/技术方案(含历史表述) > docs/天河链文档.md(过时快照)。**
## 一、项目定位
面向艺术品行业的"一物一码"全生命周期溯源与认证平台。三端一库:
- **管理后台**(`apps/admin`):模板、建档、审核、生码、出库、上链、日志、备份、设置;
- **消费者端**(`apps/client`):扫码打开的溯源详情页,首扫激活、重复查询计数;
- **API**(`apps/api`):NestJS 单服务,生产环境同端口托管三端(`/admin`、`/trace`、`/api`、`/t/:code`、`/uploads`)。
商业闭源(PolyForm Strict License 1.0.0,版权 Nixevol)。
## 二、核心业务流程(定稿)
```
溯源模板 → 艺术品档案(自动档案编号 ARTVERIS-000001) → 内容审核
→ 批量生码(批次 + 12位数字追溯码 + 二维码) → 登记出库(时间必填+实况图)
→ 触发上链(天河链铸造 NFT) → 交易确认 → C 端展示/区块浏览器查验
消费者扫码 → 首次访问激活(计数=1,记首扫时间) → 重复访问计数+1 → 查询日志留痕
```
### 数据模型三层结构(重要,曾反复澄清)
`Artwork(一款/一个档案) 1:N Batch(批次) 1:N TraceCode(每件实物)`
- "一款多码":一款作品可分批生产多件,每件实物独立编码、独立激活、独立上链,满足"一物一码";
- `archiveNo` 是**款级**唯一档案编号;`TraceCode.shortCode`(12 位纯数字)是**件级**唯一码;
- 历史上曾有"未绑定码池→绑定作品"、"SKU"等旧流程/字段,**均已移除**,文档中残留表述仅作背景。
### 追溯码生成规则
12 位纯数字 `RRYYRMMRDDRR`:6 位随机位由每日递增序号 + `TRACE_CODE_SALT` + 日期经 4 轮 Feistel 可逆置换生成,同日不重复,每日容量 100 万。`trace_code_daily_sequence` 表纳入备份,恢复后同日续生成不回退。
## 三、已拍板决策全清单
### 3.1 天河链(甲方微信定稿,2026-07-10 起多轮确认)
| 决策 | 结论 |
| --- | --- |
| 接入范围 | 官方"三步接入"的第①②步 + 第③步的"首发":链上注册 → 部署合约 → 铸造链上商品 → 首发。**首发 = 铸造到平台钱包,publish 接口即覆盖,无需额外接口** |
| NFT 二级交易 | **不做** transfer(转让)/burn(合并销毁)。甲方"不做 NFT"指的是不做二级交易,铸造/发行照做 |
| 元数据上链 | **不做**。upload(元数据上链存储)接口已从上链链路移除,每件上链 = 仅一次 publish 调用。`TianheProvider.attest` 代码保留未删,若要恢复"存证+发行"双层只需在 `attestWithTianhe` 恢复两步调用 |
| 媒体上链 | **不做**。图片/视频全部只存平台自有存储/OSS;发行的 `feature` 字段放作品主图 URL(天河浏览器藏品/交易页展示用)。已知副作用并被甲方接受:本地 dataHash 锁结构化溯源信息、不锁媒体本体,媒体被替换无法在链上发现 |
| 删除功能 | **不做**。链上记录不可删除(区块链本质);平台侧删除艺术品不触链,已有追溯码/查询记录的档案禁止删除(只能停用/归档) |
| 计费口径 | 按**每次调用上链接口**计费(非按容量)。"是否每件都上链/只上重点件"是纯运营成本决策,与代码无关 |
| 钱包粒度 | **单平台托管钱包**(公证者身份),UserID 固定 `artveris-platform`;每件实物的链上凭据(txHash/tokenId)互相独立,钱包地址不标识物品、不在 C 端展示 |
| 已售出标记 | **不需要**在链上做交易账单/已售出标记(甲方原话"不需要") |
| C 端查验入口 | 「查看存证」跳天河区块浏览器**交易详情页** `#/tiChain/transDetail?hash=<mintTxHash>`(不选藏品详情页,因不传媒体会显示"未获取到媒体内容") |
### 3.2 链上身份与密钥安全
- **UserID/UserKey 明文存库**(`system_setting`):它是全系统唯一无外部恢复途径的凭据(天河链不留存),明文存库使备份跨重装可恢复,不依赖 `.env` 的加密密钥。UI 默认掩码,揭示/复制/轮换需二次确认且全部写操作日志;
- **AppKey 加密存库**(AES-256-GCM,`enc:v1:` 前缀),揭示走审计 POST 接口**返回明文**(点眼睛 → 确认"将显示完整 AppKey 并记入操作日志" → 显示明文;收起时未编辑则恢复掩码);
- UserKey 支持**轮换**(链上修改,旧 key 立即失效,回显新 key 强提示离线保存);
- 重装/迁移后在设置页「手动录入」填原 UserID/UserKey 复用同一钱包,**切勿重新注册**;
- 生产上线必须在生产环境**重新注册**钱包(勿沿用测试钱包),测试凭据在本地 `docs/系统测试信息.md`(已 gitignore)。
### 3.3 出库/上链三条不变量(硬校验,前后端一致)
1. **一物一码只能出库一次**:`outTime` 或 `outImages` 任一存在即视为已出库,单件登记/导入预览/导入提交三处统一用 `outbound.util.isOutbound` 判重;
2. **出库时间必填**:弹窗默认当前时刻,前端拦截 + 后端强制非空;
3. **上链必须先出库,且不允许重复上链**:后端 `attestation.trigger` 校验未出库拒绝;存证状态为 ONCHAIN/CONFIRMING/PENDING 一律拒绝再次上链(**交易一经提交即已广播上链,"确认中"也视为已上链**——天河 publish 返回 mint 哈希即必然进块,除非明确失败),仅 FAILED 可通过独立 retry 接口重试。
前端菜单联动:未登记=「出库上链」(可编辑);已登记未上链=「上链」(只读回填,仅触发按钮);已登记已上链/确认中=「上链信息」(纯只读)。
### 3.4 上链确认节奏
提交后自动确认查询 **0s / 10s / 30s 共 3 次**,之后停等后台手动「重新确认」。确认接口 `status "0x0"` = 成功;仅适用于 token 类交易(mint 等)。
### 3.5 审核变更流
- 新建档案:默认创建 4 个溯源时间轴骨架节点(创作/选胚、制作过程、仓储/托管、出库/流转);普通保存进入待审核,可存草稿;
- 修改已通过的档案:写入 `artwork_revision` 快照,**审核通过才覆盖正式数据**,期间 C 端始终展示上一版已审核内容;
- **超级管理员修改自动通过**(留痕但立即生效);运营提交需审核员/超管审核;
- 空修改被前后端双重拦截("内容未变化,无需提交审核")。
### 3.6 消费者端(C 端)
- 公开匿名访问,仅展示**审核通过且未停用**的作品;停用/异常码显示警示页;
- 首扫激活用**条件更新**消除并发竞态(仅真正抢到 INACTIVE→ACTIVE 的请求算首扫);
- 单件出库记录自动追加到时间轴末尾(OUTBOUND 节点,由后端标记 `system:'OUTBOUND_RECORD'`、前端本地化文案);
- 查询日志完整记录 IP/UA/设备,不脱敏,仅后台可见;地理区域解析**已明确移除**;
- 追溯码链接 = `{系统设置 clientBaseUrl}/#/trace/{shortCode}`,**动态生成、DB 不固化**,换地址全部自动跟随;`/t/:code` 302 跳转端点保留兼容历史二维码。
### 3.7 预览功能(不激活查看 C 端)
- 后台点**追溯码**直接开预览页(hover 有提示);点**链接列**弹确认框(告知直接访问会激活/计数,提供[访问预览页面][访问实际页面]);
- 预览由**类 TOTP 时间令牌**保护:HMAC(jwt.secret, 窗口号),周期 10 分钟,接受当前+上一窗口(实际有效 10~20 分钟),无状态不落库,外泄链接最长 2 窗口失效;
- 预览接口零副作用(不激活/不计数/不写日志),预览页顶部橙色条可切「未激活/已激活」两种展示形态;
- 预览 URL 仅点击瞬间临时拼接,**不进入行数据、不进导出**。
### 3.8 媒体存储
- 目录层级(人类可读):`{模板ID}/{档案编号}/` 下放作品图/节点图/证书(命名 `作品图_{时间戳}_{序号}.ext`、`节点-{标题}_...`、`证书-{名称}_...`,水印件 `_wm` 后缀);出库实况图在 `{模板ID}/{档案编号}/{追溯码}/出库实况_...`;
- 实现方式 = "上传先进临时日期目录,实体保存时归位(move + 改写 DB 引用)",因为新建时档案编号尚未生成;归位失败不阻断业务;编辑旧档案会渐进迁移历史存量;
- 媒体统一以存储 key 入库,展示时经 `StorageService.getUrl` 转 URL(本地 `/uploads/` 相对路径或 CDN/OSS 绝对地址);
- 上传**禁止 SVG**(防存储型 XSS,系统图标除外的历史放行已收回)。
### 3.9 权限与安全
- 四角色 RBAC:超管(全通)/运营(写)/审核员(审核)/只读监管;JWT 每请求回库校验账号与角色,禁用立即 401;
- 操作日志拦截器记录所有写操作、密钥揭示/复制、导入导出、备份恢复,仅超管可见;
- 全局限流(登录 10/分钟,公开溯源 60/分钟/IP);安全响应头(nosniff 等);无效短码 Redis 负缓存防刷库;
- 设置项加密:OSS Secret、天河 AppKey 走 `SECRET_KEYS` 加密;`tianheUserKey` 例外明文(见 3.2)。
### 3.10 部署与配置
- **唯一配置文件 = 运行目录下的单一 `.env`**(带中文注释),没有 JSON 配置/config 目录;业务可调项(平台名/客户端地址/存储/链配置等)在系统设置表,优先于 `.env`;
- 首次启动无 `.env` 自动进**安装向导**(admin 内置 `/install` 页):填对外地址、MySQL/Redis、管理员,自动建库迁移初始化后写 `.env`;
- 三种部署形态共享该契约:本地 `scripts/dev.py`、宝塔/PM2 发布包(`build.py`)、离线 Docker 包(`build_docker.py` / `remote.py`);
- 持久层(升级永不覆盖):`.env`、`storage/`、`backups/`、数据库;
- 生产不再有默认管理员口令(种子弱口令仅限本地开发)。
### 3.11 其他产品决策
- 单平台模式,不做机构数据隔离;
- 证书文件:C 端展示水印图,后台保留原件(水印异步 sharp 生成,文案可配);
- 备份:ZIP 含 manifest/database.json/storage 全目录,恢复前预校验(app/版本/模型全集)+ 自动快照;备份包存非公开目录;
- 后台设置页为 5 个分页(平台/日志/区块链/存储/备份),URL 带 `?tab=` 刷新保留;
- 后台列表统一规范:`useTablePage` + 外置分页 + `pageSize=0` 不分页语义、表头下拉筛选、操作列右固定、长文本省略悬停;
- NFC、多机构隔离、主动预警、C 端骨架屏:**均明确不做**。
## 四、已知取舍与坑(新维护者必读)
1. **媒体不在防篡改闭环内**:链上仅有本地计算的结构化 dataHash 与 NFT,媒体文件替换无法在链上发现——甲方已知并接受,勿当 bug 修;
2. **历史 revision 快照持旧存储 key**:媒体归位迁移后,历史审核记录详情里的旧图预览可能 404(开发期无线上数据,已确认不处理);
3. **天河文档勘误**(踩过的坑,勿被官方文档误导):交易详情接口路径是 `/api/v2/nfr/transaction/detail`(语雀版少 `/nfr`);确认接口是 GET 但参数放 JSON 请求体;upload 的 multipart 必须手工构造(whatwg FormData 会强加 filename 导致 500);`operateId` 限 20 字符;确认接口对纯存证交易结构性 500;发行可能返回 tokenId=-1 待确认回填;
4. **`nest start --watch` 运行时勿删 `apps/api/dist`**,会导致缺模块错误;需要清理先停服务;
5. **Windows/PowerShell**:`&&` 不可用(用 `;`),中文输出注意 UTF-8;
6. **`.cell-link` 等表格内样式必须用 `:deep()`**:n-data-table 单元格由子组件渲染,不带本组件 scope 属性;
7. **短链/追溯码 URL 勿依赖 DB 的 url 列**(已废弃固化,一律动态生成);
8. **`TRACE_CODE_SALT` 写入 `.env` 后不可更改**,否则同日生成的码可能冲突;
9. seed 的追溯码短码必须符合 12 位数字 `TRACE_CODE_PATTERN`,否则 C 端判 INVALID;
10. pnpm 固定 `packageManager: pnpm@10.28.0`,原生依赖(prisma/sharp)在根 `pnpm.onlyBuiltDependencies` 放行。
## 五、关键代码地图
| 模块 | 位置 | 说明 |
| --- | --- | --- |
| 公开溯源 | `apps/api/src/public-trace/` | trace(激活/计数/日志) + preview(零副作用) + `/t` 跳转 |
| 生码 | `apps/api/src/trace-code/` | 批次/分组/导出 ZIP/二维码/预览令牌;`trace-code-generator.service.ts` 为 Feistel 码生成 |
| 建档与审核 | `apps/api/src/artwork/` | 修订快照流 `artwork_revision`、媒体归位 `relocateArtworkMedia` |
| 出库 | `apps/api/src/outbound/` | 单件登记 + ZIP 导入(预览/提交两段队列) + `outbound.util.isOutbound` |
| 区块链 | `apps/api/src/blockchain/` | `blockchain.service`(驱动选择/发行编排)、`tianhe.provider`(天河 API)、`attestation.service`(触发+校验)、`onchain.processor`(队列+确认循环) |
| 设置 | `apps/api/src/settings/` | 动态配置中心、密钥加密/掩码/揭示、天河身份生命周期 |
| 存储 | `apps/api/src/storage/` | Local/OSS 驱动、`relocateMedia` 归位、迁移接口 |
| 预览令牌 | `apps/api/src/common/utils/preview-token.util.ts` | 类 TOTP 实现 |
| 备份 | `apps/api/src/backup/` | 创建/下载/恢复(预校验+自动快照) |
| 后台复用组件 | `apps/admin/src/components/TraceCodePanel.vue` | 全局与档案内追溯码管理共用(列表/生码/出库上链/预览入口) |
| 后台设置页 | `apps/admin/src/views/Settings.vue` | 5 分页 + URL tab 同步 + 密钥交互 |
| C 端溯源页 | `apps/client/src/views/Trace.vue` | 轮播/时间轴/证书/区块链卡/预览条,`/trace/:code` 与 `/trace/preview/:code` 共用 |
| 开发/部署脚本 | `scripts/dev.py` `build.py` `build_docker.py` `remote.py` | 见 `scripts/README.md` |
## 六、运维要点
- **测试凭据**:本地 `docs/系统测试信息.md`(gitignore,不入库)——MySQL/Redis、天河测试 AppID/AppKey、UserID/UserKey、钱包地址、合约地址。重装环境后先看它;
- **生产上线检查单**:换生产 AppID/AppKey → 切生产环境 → 生产重新注册钱包并离线保存凭据 → 抽一件真实走通全链路 → 与天河商务核对计费;
- **备份策略**:后台设置定时备份 + 保留策略;恢复必须走"上传预校验 → 确认恢复"两步;
- **升级**:`build.py --upgrade` 生成升级包,仅替换代码,持久层不动;
- 后端单测:`pnpm --filter @artveris/api test`(32 项);全量构建:`pnpm build`。
## 七、AI 记忆继承指引
给接手的 AI 助手(或使用 AI 的维护者):
1. 首次进入项目,按顺序读:本文档 → `README.md` → `docs/天河链集成说明.md` → `aidocs/project_context.md`(全量流水记忆,含每个功能的实现细节、踩坑与验证记录);
2. `aidocs/project_context.md` 是**追加式流水**,同一主题后面的条目覆盖前面的;本文档是其中"已定稿部分"的提炼,冲突时以代码现状为最终裁决;
3. 修改代码后,请延续惯例:在 `aidocs/project_context.md` 追加一条记录(日期 + 改了什么 + 为什么 + 验证结果),重大决策变化同步更新本文档;
4. `aidocs/代码审查问题清单.md`、`aidocs/天河链对接分析与建议.md`、`aidocs/甲方待确认问题清单.md` 是历史专题记录,其结论已收敛进本文档,查证来龙去脉时再翻;
5. `docs/天河链文档.md` 是过时的官方文档快照,对接以 `docs/天河链集成说明.md` + APIFox 在线文档为准;
6. 提交信息格式 `<type>: <中文描述>`(feat/fix/refactor/style/docs/chore/revert);遵循 YAGNI/KISS,不做超出需求的抽象。