feat: 完善安装部署与数字溯源码
This commit is contained in:
@@ -27,6 +27,8 @@ REDIS_PASSWORD=
|
|||||||
# ===== JWT =====
|
# ===== JWT =====
|
||||||
JWT_SECRET=please_change_this_to_a_long_random_secret_in_production
|
JWT_SECRET=please_change_this_to_a_long_random_secret_in_production
|
||||||
JWT_EXPIRES_IN=7d
|
JWT_EXPIRES_IN=7d
|
||||||
|
# 系统设置中 OSS/天河链等 Secret 的加密密钥;已安装系统请保持不变
|
||||||
|
SETTING_ENCRYPTION_KEY=please_change_this_to_a_long_random_settings_key
|
||||||
|
|
||||||
# ===== 种子超级管理员 =====
|
# ===== 种子超级管理员 =====
|
||||||
SEED_ADMIN_USERNAME=admin
|
SEED_ADMIN_USERNAME=admin
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ Desktop.ini
|
|||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
.deploy/
|
.deploy/
|
||||||
|
.release/
|
||||||
|
|
||||||
# 本地启动偏好/记忆的连接信息(含密码,勿提交)
|
# 本地启动偏好/记忆的连接信息(含密码,勿提交)
|
||||||
scripts/.dev.local.json
|
scripts/.dev.local.json
|
||||||
@@ -30,6 +31,8 @@ unpackage/
|
|||||||
# 本地文件存储(运行时上传目录)
|
# 本地文件存储(运行时上传目录)
|
||||||
/storage/
|
/storage/
|
||||||
apps/api/storage/
|
apps/api/storage/
|
||||||
|
apps/api/public/
|
||||||
|
apps/api/runtime/
|
||||||
backups/
|
backups/
|
||||||
apps/api/backups/
|
apps/api/backups/
|
||||||
|
|
||||||
|
|||||||
@@ -203,3 +203,9 @@
|
|||||||
- 天河链用户身份临时策略(2026-07-06):天河链文档中的 `userId/userKey` 属于托管链上用户身份,不是平台截图里提供的商户 API 凭证。当前设置页先只展示 `App ID/App Key`,后端仍兼容 `.env` 或历史设置中的 `TIANHE_USER_ID/TIANHE_USER_KEY`;若未配置,则使用平台级默认 `userId=artveris-platform`,`userKey=sha256(artveris:tianhe:{appId}:{appKey})` 派生。后续需再讨论是继续平台级托管用户,还是按运营账号/机构/作品批次生成链上用户。
|
- 天河链用户身份临时策略(2026-07-06):天河链文档中的 `userId/userKey` 属于托管链上用户身份,不是平台截图里提供的商户 API 凭证。当前设置页先只展示 `App ID/App Key`,后端仍兼容 `.env` 或历史设置中的 `TIANHE_USER_ID/TIANHE_USER_KEY`;若未配置,则使用平台级默认 `userId=artveris-platform`,`userKey=sha256(artveris:tianhe:{appId}:{appKey})` 派生。后续需再讨论是继续平台级托管用户,还是按运营账号/机构/作品批次生成链上用户。
|
||||||
- 天河链文档归档与字段校准(2026-07-06):新增 `docs/天河链文档.md` 作为本地对接资料。文档确认 `POST /api/v2/nfr/upload` 返回 `data.digest`(数字商品唯一哈希/文件哈希)、`data.url`(链上 URI/存证链接)、`data.transactionHash`(链上存证交易哈希);`TianheProvider` 现在优先使用 `transactionHash` 写入平台 `txHash`,使用 `url` 写入 `explorerUrl`,并把 `digest` 与 `transactionStatus=submitted` 保存在 `rawResponse`。天河链 FAQ 明确接口成功只代表交易已提交,不代表链上最终确认;后续如要严格展示“已确认”,应基于交易结果查询接口补延时确认任务。
|
- 天河链文档归档与字段校准(2026-07-06):新增 `docs/天河链文档.md` 作为本地对接资料。文档确认 `POST /api/v2/nfr/upload` 返回 `data.digest`(数字商品唯一哈希/文件哈希)、`data.url`(链上 URI/存证链接)、`data.transactionHash`(链上存证交易哈希);`TianheProvider` 现在优先使用 `transactionHash` 写入平台 `txHash`,使用 `url` 写入 `explorerUrl`,并把 `digest` 与 `transactionStatus=submitted` 保存在 `rawResponse`。天河链 FAQ 明确接口成功只代表交易已提交,不代表链上最终确认;后续如要严格展示“已确认”,应基于交易结果查询接口补延时确认任务。
|
||||||
- 天河链延时确认(2026-07-06):区块链凭证状态新增 `CONFIRMING`。Mock 存证仍一次完成并直接进入 `ONCHAIN`;天河链 `nfr/upload` 成功后仅标记为 `CONFIRMING`,保存交易哈希、存证链接和提交响应,然后由同一个 `ONCHAIN` 队列延时 30 秒调用 `GET /api/v2/nfr/transaction/status` 查询交易状态。首次自动查询未确认时,系统只在 1 分钟后再自动查询一次;第二次仍未拿到 `blockHash/blockNum` 时不再自动请求、不判失败,继续保留 `CONFIRMING` 并标记 `rawResponse.confirmationManualRequired=true`,后台展示为“未确认”。运营可点“重新确认”手动查询已有交易哈希,不重新提交上链;查到区块信息后才更新为 `ONCHAIN` 并写入 `onchainAt/blockHash/blockHeight`。客户端公开页仍只展示最终 `ONCHAIN` 的凭证。
|
- 天河链延时确认(2026-07-06):区块链凭证状态新增 `CONFIRMING`。Mock 存证仍一次完成并直接进入 `ONCHAIN`;天河链 `nfr/upload` 成功后仅标记为 `CONFIRMING`,保存交易哈希、存证链接和提交响应,然后由同一个 `ONCHAIN` 队列延时 30 秒调用 `GET /api/v2/nfr/transaction/status` 查询交易状态。首次自动查询未确认时,系统只在 1 分钟后再自动查询一次;第二次仍未拿到 `blockHash/blockNum` 时不再自动请求、不判失败,继续保留 `CONFIRMING` 并标记 `rawResponse.confirmationManualRequired=true`,后台展示为“未确认”。运营可点“重新确认”手动查询已有交易哈希,不重新提交上链;查到区块信息后才更新为 `ONCHAIN` 并写入 `onchainAt/blockHash/blockHeight`。客户端公开页仍只展示最终 `ONCHAIN` 的凭证。
|
||||||
|
- 可交付部署与安装骨架(2026-07-06):新增安装模式与运行时配置。`apps/api/src/config/runtime-config.ts` 会预读 `.env`、`runtime/.env` 和 `runtime/artveris.config.json`;没有 `DATABASE_URL` 且没有运行时配置时进入安装模式,也可用 `ARTVERIS_INSTALL_MODE=1` 强制。安装模式只加载 `InstallAppModule`,开放 `/api/install/status` 与 `/api/install`,安装页静态资源位于 `/install`;安装成功写入 `runtime/artveris.config.json`、`runtime/.env`,执行 Prisma migrate、创建超管和基础设置后退出,由 PM2/systemd/宝塔/1Panel/Docker restart policy 重启进入完整系统。安装页只展示只读 `traceCodeSalt`,不允许用户填写或修改。
|
||||||
|
- 单端口路径部署(2026-07-06):API 生产服务可直接托管三个前端静态产物,统一一个端口暴露 `/admin` 后台、`/trace` 客户端、`/api` API、`/t/:code` 短链、`/uploads` 本地资源。后台/客户端/安装页 Vite base 分别为 `/admin/`、`/trace/`、`/install/`。`docker/docker-compose.full.yml` 已改为 MySQL + Redis + API 单服务,不再需要 Nginx 容器;Redis 默认关闭 AOF 持久化。`scripts/build_release.py` 会构建 shared/api/admin/client/install,输出 zip/tar 非 Docker 包和 PM2 `ecosystem.config.cjs`,包内不写死数据库、Redis、域名、OSS/CDN、链配置。
|
||||||
|
- 12 位纯数字溯源码(2026-07-06):`shortCode` 长度改为 12,格式 `RRYYRMMRDDRR`,日期取 Asia/Shanghai。6 位 `R` 由每日递增序号、`traceCodeSalt`、日期经 4 轮 Feistel 可逆置换生成,看起来不连续但同日序号不重复时码不重复;每日容量 1,000,000。新增 `trace_code_daily_sequence` 表并纳入备份恢复,备份同时保留 `traceCodeSalt` 和已有追溯码数据,恢复后同日继续生成不会回到 0。二维码与导出使用 `/t/:code` 短链,短链跳转动态读取系统设置 `clientBaseUrl`。
|
||||||
|
- 存储/CDN 设置与迁移接口(2026-07-06):系统设置新增 `clientBaseUrl`、存储方式、本地目录、CDN、OSS/S3 配置;OSS Secret 返回时脱敏。新增 `/api/storage/test`、`/api/storage/migrate`、`/api/storage/confirm`:可测试目标存储、把当前存储文件复制到目标存储、确认切换设置。第一版迁移按存储 key 复制业务文件,配置变更仍需重启后完整服务使用新驱动。
|
||||||
|
- i18n 响应结构(2026-07-06):共享 `ApiResponse` 扩展 `messageKey`/`params`,后端 `BusinessException` 和全局异常过滤器返回稳定 `error.*` key,前端请求统一带 `Accept-Language`,后台错误提示优先按 `messageKey` 翻译、再按错误码兜底。后台 locales 已补 `error.*` 中英文别名,避免英文模式直接显示中文后端消息。
|
||||||
|
- 发布包与存储迁移收口(2026-07-06):非 Docker 发布包新增 `install-deps.sh` / `install-deps.ps1`,标准安装流程为 `pnpm install --prod --frozen-lockfile` 后在 `apps/api` 目录执行 `prisma generate --schema ./prisma/schema.prisma`,避免生产包启动时报缺 `.prisma/client/default`。发布包只复制 shared 的 `dist` 与 `package.json`,不再带源码和局部 node_modules。存储迁移状态只保存脱敏目标配置和 `storageMigrationFingerprint`,确认切换前必须匹配同目标迁移记录;OSS/Tianhe Secret 继续 AES-GCM 加密保存,接口返回脱敏,备份使用 raw 设置值。最终验证过发布包安装脚本、安装模式 `/api/install/status` 200、未安装 `/admin` 404、单端口监听正常。
|
||||||
|
|||||||
@@ -116,6 +116,12 @@ export const settingsApi = {
|
|||||||
update: (data: object) => put('/settings', data),
|
update: (data: object) => put('/settings', data),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const storageApi = {
|
||||||
|
test: (data: object) => post('/storage/test', data),
|
||||||
|
migrate: (data: object) => post('/storage/migrate', data),
|
||||||
|
confirm: (data: object) => post('/storage/confirm', data),
|
||||||
|
};
|
||||||
|
|
||||||
export const operationLogApi = {
|
export const operationLogApi = {
|
||||||
list: (params: object) => get<PageResult<any>>('/operation-logs', params),
|
list: (params: object) => get<PageResult<any>>('/operation-logs', params),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -20,6 +20,10 @@ const instance: AxiosInstance = axios.create({
|
|||||||
});
|
});
|
||||||
|
|
||||||
function resolveErrorMessage(body: any, fallbackKey = 'common.msg.networkError'): string {
|
function resolveErrorMessage(body: any, fallbackKey = 'common.msg.networkError'): string {
|
||||||
|
if (body?.messageKey) {
|
||||||
|
const translated = i18n.global.t(body.messageKey, body.params || {});
|
||||||
|
if (translated !== body.messageKey) return translated;
|
||||||
|
}
|
||||||
if (body?.code !== undefined && body?.code !== null) {
|
if (body?.code !== undefined && body?.code !== null) {
|
||||||
const key = `common.errorCode.${body.code}`;
|
const key = `common.errorCode.${body.code}`;
|
||||||
const translated = i18n.global.t(key);
|
const translated = i18n.global.t(key);
|
||||||
@@ -38,6 +42,8 @@ instance.interceptors.request.use((config) => {
|
|||||||
config.headers = config.headers ?? {};
|
config.headers = config.headers ?? {};
|
||||||
config.headers.Authorization = `Bearer ${token}`;
|
config.headers.Authorization = `Bearer ${token}`;
|
||||||
}
|
}
|
||||||
|
config.headers = config.headers ?? {};
|
||||||
|
config.headers['Accept-Language'] = String(i18n.global.locale.value || 'zh-CN');
|
||||||
return config;
|
return config;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -442,6 +442,24 @@
|
|||||||
"filingInfo": "Filing Info",
|
"filingInfo": "Filing Info",
|
||||||
"carouselInterval": "Carousel Interval",
|
"carouselInterval": "Carousel Interval",
|
||||||
"carouselIntervalHint": "Seconds each media stays; decimals allowed. 0 disables auto-advance (manual loop still works).",
|
"carouselIntervalHint": "Seconds each media stays; decimals allowed. 0 disables auto-advance (manual loop still works).",
|
||||||
|
"clientBaseUrl": "Client URL",
|
||||||
|
"storageSettings": "Storage & CDN",
|
||||||
|
"storageDriver": "Storage",
|
||||||
|
"storageDriverLocal": "Local",
|
||||||
|
"storageDriverOss": "OSS/S3",
|
||||||
|
"storageLocalDir": "Local Dir",
|
||||||
|
"cdnBaseUrl": "CDN URL",
|
||||||
|
"ossEndpoint": "OSS Endpoint",
|
||||||
|
"ossRegion": "OSS Region",
|
||||||
|
"ossBucket": "OSS Bucket",
|
||||||
|
"ossAccessKeyId": "AccessKey ID",
|
||||||
|
"ossAccessKeySecret": "AccessKey Secret",
|
||||||
|
"testStorage": "Test",
|
||||||
|
"migrateStorage": "Migrate",
|
||||||
|
"confirmStorage": "Switch",
|
||||||
|
"storageTested": "Storage connection verified",
|
||||||
|
"storageMigrated": "{n} files migrated",
|
||||||
|
"storageConfirmed": "Storage settings switched",
|
||||||
"backupEnabled": "Enable Scheduled Backup",
|
"backupEnabled": "Enable Scheduled Backup",
|
||||||
"backupSchedule": "Scheduled Backup",
|
"backupSchedule": "Scheduled Backup",
|
||||||
"backupRetentionDays": "Backup Days",
|
"backupRetentionDays": "Backup Days",
|
||||||
@@ -542,5 +560,37 @@
|
|||||||
"AUTO_BEFORE_RESTORE": "Auto Snapshot Before Restore"
|
"AUTO_BEFORE_RESTORE": "Auto Snapshot Before Restore"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"SUCCESS": "Success",
|
||||||
|
"BAD_REQUEST": "Invalid request",
|
||||||
|
"UNAUTHORIZED": "Not logged in or session expired",
|
||||||
|
"FORBIDDEN": "You do not have permission",
|
||||||
|
"NOT_FOUND": "Resource not found",
|
||||||
|
"VALIDATION_FAILED": "Validation failed",
|
||||||
|
"INTERNAL_ERROR": "Internal server error",
|
||||||
|
"TOO_MANY_REQUESTS": "Too many requests. Please try again later.",
|
||||||
|
"INVALID_CREDENTIALS": "Incorrect username or password",
|
||||||
|
"TOKEN_EXPIRED": "Session expired. Please log in again.",
|
||||||
|
"USER_DISABLED": "This account has been disabled",
|
||||||
|
"OLD_PASSWORD_WRONG": "Current password is incorrect",
|
||||||
|
"USERNAME_EXISTS": "Username already exists",
|
||||||
|
"TEMPLATE_NOT_FOUND": "Template not found",
|
||||||
|
"TEMPLATE_IN_USE": "Template is in use and cannot be deleted",
|
||||||
|
"ARTWORK_NOT_FOUND": "Artwork not found",
|
||||||
|
"TRACE_CODE_NOT_FOUND": "Trace code not found",
|
||||||
|
"TRACE_CODE_INVALID": "Trace code is invalid",
|
||||||
|
"TRACE_CODE_DISABLED": "Trace code has been disabled",
|
||||||
|
"TRACE_CODE_ABNORMAL": "Trace code status is abnormal",
|
||||||
|
"TRACE_CODE_ALREADY_BOUND": "Trace code is already bound to an artwork",
|
||||||
|
"IMPORT_PARSE_FAILED": "Import file parsing failed",
|
||||||
|
"FILE_TYPE_NOT_ALLOWED": "File type is not supported",
|
||||||
|
"FILE_TOO_LARGE": "File exceeds the size limit",
|
||||||
|
"CERTIFICATE_NOT_FOUND": "Certificate not found",
|
||||||
|
"JOB_NOT_FOUND": "Task not found",
|
||||||
|
"BATCH_NOT_FOUND": "Batch not found",
|
||||||
|
"ARTWORK_IN_USE": "Artwork file has business data and cannot be deleted",
|
||||||
|
"OSS_CONFIG_INCOMPLETE": "OSS configuration is incomplete",
|
||||||
|
"STORAGE_MIGRATION_REQUIRED": "Please migrate files to the target storage before switching"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -442,6 +442,24 @@
|
|||||||
"filingInfo": "备案信息",
|
"filingInfo": "备案信息",
|
||||||
"carouselInterval": "客户端轮播间隔",
|
"carouselInterval": "客户端轮播间隔",
|
||||||
"carouselIntervalHint": "每张媒体停留秒数,支持小数;填 0 则不自动切换(仍可手动循环切换)",
|
"carouselIntervalHint": "每张媒体停留秒数,支持小数;填 0 则不自动切换(仍可手动循环切换)",
|
||||||
|
"clientBaseUrl": "客户端地址",
|
||||||
|
"storageSettings": "存储与 CDN",
|
||||||
|
"storageDriver": "存储方式",
|
||||||
|
"storageDriverLocal": "本地",
|
||||||
|
"storageDriverOss": "OSS/S3",
|
||||||
|
"storageLocalDir": "本地目录",
|
||||||
|
"cdnBaseUrl": "CDN 地址",
|
||||||
|
"ossEndpoint": "OSS Endpoint",
|
||||||
|
"ossRegion": "OSS Region",
|
||||||
|
"ossBucket": "OSS Bucket",
|
||||||
|
"ossAccessKeyId": "AccessKey ID",
|
||||||
|
"ossAccessKeySecret": "AccessKey Secret",
|
||||||
|
"testStorage": "测试",
|
||||||
|
"migrateStorage": "迁移",
|
||||||
|
"confirmStorage": "切换",
|
||||||
|
"storageTested": "存储连接测试通过",
|
||||||
|
"storageMigrated": "已迁移 {n} 个文件",
|
||||||
|
"storageConfirmed": "存储配置已切换",
|
||||||
"backupEnabled": "启用定时备份",
|
"backupEnabled": "启用定时备份",
|
||||||
"backupSchedule": "定时备份",
|
"backupSchedule": "定时备份",
|
||||||
"backupRetentionDays": "备份保留天数",
|
"backupRetentionDays": "备份保留天数",
|
||||||
@@ -542,5 +560,37 @@
|
|||||||
"AUTO_BEFORE_RESTORE": "恢复前自动快照"
|
"AUTO_BEFORE_RESTORE": "恢复前自动快照"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"SUCCESS": "成功",
|
||||||
|
"BAD_REQUEST": "请求参数有误",
|
||||||
|
"UNAUTHORIZED": "未登录或登录已过期",
|
||||||
|
"FORBIDDEN": "没有操作权限",
|
||||||
|
"NOT_FOUND": "资源不存在",
|
||||||
|
"VALIDATION_FAILED": "数据校验失败",
|
||||||
|
"INTERNAL_ERROR": "服务器内部错误",
|
||||||
|
"TOO_MANY_REQUESTS": "请求过于频繁,请稍后再试",
|
||||||
|
"INVALID_CREDENTIALS": "用户名或密码错误",
|
||||||
|
"TOKEN_EXPIRED": "登录已过期,请重新登录",
|
||||||
|
"USER_DISABLED": "账号已被停用",
|
||||||
|
"OLD_PASSWORD_WRONG": "原密码不正确",
|
||||||
|
"USERNAME_EXISTS": "用户名已存在",
|
||||||
|
"TEMPLATE_NOT_FOUND": "模板不存在",
|
||||||
|
"TEMPLATE_IN_USE": "模板已被使用,无法删除",
|
||||||
|
"ARTWORK_NOT_FOUND": "艺术品不存在",
|
||||||
|
"TRACE_CODE_NOT_FOUND": "追溯码不存在",
|
||||||
|
"TRACE_CODE_INVALID": "追溯码无效",
|
||||||
|
"TRACE_CODE_DISABLED": "追溯码已停用",
|
||||||
|
"TRACE_CODE_ABNORMAL": "追溯码状态异常",
|
||||||
|
"TRACE_CODE_ALREADY_BOUND": "追溯码已绑定作品",
|
||||||
|
"IMPORT_PARSE_FAILED": "导入文件解析失败",
|
||||||
|
"FILE_TYPE_NOT_ALLOWED": "不支持的文件类型",
|
||||||
|
"FILE_TOO_LARGE": "文件超出大小限制",
|
||||||
|
"CERTIFICATE_NOT_FOUND": "认证文件不存在",
|
||||||
|
"JOB_NOT_FOUND": "任务不存在",
|
||||||
|
"BATCH_NOT_FOUND": "批次不存在",
|
||||||
|
"ARTWORK_IN_USE": "艺术品档案已有业务数据,无法删除",
|
||||||
|
"OSS_CONFIG_INCOMPLETE": "OSS 配置不完整",
|
||||||
|
"STORAGE_MIGRATION_REQUIRED": "请先完成目标存储迁移,再确认切换"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,6 +47,11 @@
|
|||||||
/>
|
/>
|
||||||
</n-form-item>
|
</n-form-item>
|
||||||
</div>
|
</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>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<div class="settings-side-stack">
|
<div class="settings-side-stack">
|
||||||
@@ -112,6 +117,59 @@
|
|||||||
</n-form-item>
|
</n-form-item>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="settings-card storage-card">
|
||||||
|
<div class="card-title">
|
||||||
|
<span>{{ t('pages.settings.storageSettings') }}</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>
|
||||||
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</n-form>
|
</n-form>
|
||||||
|
|
||||||
@@ -126,7 +184,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, reactive, ref } from 'vue';
|
import { computed, onMounted, reactive, ref } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { settingsApi } from '@/api';
|
import { settingsApi, storageApi } from '@/api';
|
||||||
import { message } from '@/utils/feedback';
|
import { message } from '@/utils/feedback';
|
||||||
import BackupRestorePanel from '@/components/BackupRestorePanel.vue';
|
import BackupRestorePanel from '@/components/BackupRestorePanel.vue';
|
||||||
import MediaUpload from '@/components/MediaUpload.vue';
|
import MediaUpload from '@/components/MediaUpload.vue';
|
||||||
@@ -134,6 +192,9 @@ import { DEFAULT_APP_ICON_URL, resolveAppIcon, setFavicon } from '@/utils/appIco
|
|||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const saving = ref(false);
|
const saving = ref(false);
|
||||||
|
const testingStorage = ref(false);
|
||||||
|
const migratingStorage = ref(false);
|
||||||
|
const confirmingStorage = ref(false);
|
||||||
const TIANHE_TEST_URL = 'https://test.api.tichain.tianhecloud.com';
|
const TIANHE_TEST_URL = 'https://test.api.tichain.tianhecloud.com';
|
||||||
const TIANHE_PRODUCTION_URL = 'https://api.tichain.tianhecloud.com';
|
const TIANHE_PRODUCTION_URL = 'https://api.tichain.tianhecloud.com';
|
||||||
const blockchainDriverOptions = computed(() => [
|
const blockchainDriverOptions = computed(() => [
|
||||||
@@ -150,6 +211,10 @@ const backupScheduleOptions = computed(() => [
|
|||||||
{ label: t('pages.settings.scheduleDaily'), value: 'daily' },
|
{ label: t('pages.settings.scheduleDaily'), value: 'daily' },
|
||||||
{ label: t('pages.settings.scheduleWeekly'), value: 'weekly' },
|
{ label: t('pages.settings.scheduleWeekly'), value: 'weekly' },
|
||||||
]);
|
]);
|
||||||
|
const storageDriverOptions = computed(() => [
|
||||||
|
{ label: t('pages.settings.storageDriverLocal'), value: 'local' },
|
||||||
|
{ label: t('pages.settings.storageDriverOss'), value: 'oss' },
|
||||||
|
]);
|
||||||
const backupScheduleValue = computed({
|
const backupScheduleValue = computed({
|
||||||
get: () => (form.backupEnabled ? form.backupSchedule : 'off'),
|
get: () => (form.backupEnabled ? form.backupSchedule : 'off'),
|
||||||
set: (value: string) => {
|
set: (value: string) => {
|
||||||
@@ -165,6 +230,7 @@ const form = reactive({
|
|||||||
watermarkText: '',
|
watermarkText: '',
|
||||||
filingInfo: '',
|
filingInfo: '',
|
||||||
carouselInterval: 3,
|
carouselInterval: 3,
|
||||||
|
clientBaseUrl: '',
|
||||||
backupEnabled: false,
|
backupEnabled: false,
|
||||||
backupSchedule: 'daily',
|
backupSchedule: 'daily',
|
||||||
backupRetentionDays: 30,
|
backupRetentionDays: 30,
|
||||||
@@ -174,6 +240,15 @@ const form = reactive({
|
|||||||
tianheBaseUrl: TIANHE_TEST_URL,
|
tianheBaseUrl: TIANHE_TEST_URL,
|
||||||
tianheAppId: '',
|
tianheAppId: '',
|
||||||
tianheAppKey: '',
|
tianheAppKey: '',
|
||||||
|
storageDriver: 'local',
|
||||||
|
storageLocalDir: './storage',
|
||||||
|
storagePublicPrefix: '/uploads',
|
||||||
|
cdnBaseUrl: '',
|
||||||
|
ossEndpoint: '',
|
||||||
|
ossRegion: '',
|
||||||
|
ossBucket: '',
|
||||||
|
ossAccessKeyId: '',
|
||||||
|
ossAccessKeySecret: '',
|
||||||
});
|
});
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
@@ -186,6 +261,7 @@ async function load() {
|
|||||||
form.watermarkText = s.watermarkText || '';
|
form.watermarkText = s.watermarkText || '';
|
||||||
form.filingInfo = s.filingInfo || '';
|
form.filingInfo = s.filingInfo || '';
|
||||||
form.carouselInterval = Number(s.carouselInterval ?? 3);
|
form.carouselInterval = Number(s.carouselInterval ?? 3);
|
||||||
|
form.clientBaseUrl = s.clientBaseUrl || `${location.origin}/trace`;
|
||||||
form.backupEnabled = s.backupEnabled === 'true';
|
form.backupEnabled = s.backupEnabled === 'true';
|
||||||
form.backupSchedule = s.backupSchedule || 'daily';
|
form.backupSchedule = s.backupSchedule || 'daily';
|
||||||
form.backupRetentionDays = Number(s.backupRetentionDays || 30);
|
form.backupRetentionDays = Number(s.backupRetentionDays || 30);
|
||||||
@@ -195,6 +271,15 @@ async function load() {
|
|||||||
form.tianheBaseUrl = s.tianheBaseUrl || TIANHE_TEST_URL;
|
form.tianheBaseUrl = s.tianheBaseUrl || TIANHE_TEST_URL;
|
||||||
form.tianheAppId = s.tianheAppId || '';
|
form.tianheAppId = s.tianheAppId || '';
|
||||||
form.tianheAppKey = s.tianheAppKey || '';
|
form.tianheAppKey = s.tianheAppKey || '';
|
||||||
|
form.storageDriver = s.storageDriver || 'local';
|
||||||
|
form.storageLocalDir = s.storageLocalDir || './storage';
|
||||||
|
form.storagePublicPrefix = s.storagePublicPrefix || '/uploads';
|
||||||
|
form.cdnBaseUrl = s.cdnBaseUrl || '';
|
||||||
|
form.ossEndpoint = s.ossEndpoint || '';
|
||||||
|
form.ossRegion = s.ossRegion || '';
|
||||||
|
form.ossBucket = s.ossBucket || '';
|
||||||
|
form.ossAccessKeyId = s.ossAccessKeyId || '';
|
||||||
|
form.ossAccessKeySecret = s.ossAccessKeySecret || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function onTianheEnvChange(value: string) {
|
function onTianheEnvChange(value: string) {
|
||||||
@@ -214,6 +299,7 @@ async function save() {
|
|||||||
watermarkText: form.watermarkText,
|
watermarkText: form.watermarkText,
|
||||||
filingInfo: form.filingInfo,
|
filingInfo: form.filingInfo,
|
||||||
carouselInterval: String(form.carouselInterval),
|
carouselInterval: String(form.carouselInterval),
|
||||||
|
clientBaseUrl: form.clientBaseUrl,
|
||||||
backupEnabled: String(form.backupEnabled),
|
backupEnabled: String(form.backupEnabled),
|
||||||
backupSchedule: form.backupSchedule,
|
backupSchedule: form.backupSchedule,
|
||||||
backupRetentionDays: String(form.backupRetentionDays),
|
backupRetentionDays: String(form.backupRetentionDays),
|
||||||
@@ -232,6 +318,49 @@ async function save() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function storagePayload() {
|
||||||
|
return {
|
||||||
|
driver: form.storageDriver,
|
||||||
|
localDir: form.storageLocalDir,
|
||||||
|
cdnBaseUrl: form.cdnBaseUrl,
|
||||||
|
ossEndpoint: form.ossEndpoint,
|
||||||
|
ossRegion: form.ossRegion,
|
||||||
|
ossBucket: form.ossBucket,
|
||||||
|
ossAccessKeyId: form.ossAccessKeyId,
|
||||||
|
ossAccessKeySecret: form.ossAccessKeySecret,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testStorage() {
|
||||||
|
testingStorage.value = true;
|
||||||
|
try {
|
||||||
|
await storageApi.test(storagePayload());
|
||||||
|
message.success(t('pages.settings.storageTested'));
|
||||||
|
} finally {
|
||||||
|
testingStorage.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function migrateStorage() {
|
||||||
|
migratingStorage.value = true;
|
||||||
|
try {
|
||||||
|
const res: any = await storageApi.migrate(storagePayload());
|
||||||
|
message.success(t('pages.settings.storageMigrated', { n: res.copied ?? 0 }));
|
||||||
|
} finally {
|
||||||
|
migratingStorage.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmStorage() {
|
||||||
|
confirmingStorage.value = true;
|
||||||
|
try {
|
||||||
|
await storageApi.confirm(storagePayload());
|
||||||
|
message.success(t('pages.settings.storageConfirmed'));
|
||||||
|
} finally {
|
||||||
|
confirmingStorage.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(load);
|
onMounted(load);
|
||||||
|
|
||||||
const currentIconUrl = computed(() => resolveAppIcon(form.appIconFiles[0]?.url || form.appIconFiles[0]?.key));
|
const currentIconUrl = computed(() => resolveAppIcon(form.appIconFiles[0]?.url || form.appIconFiles[0]?.key));
|
||||||
@@ -311,6 +440,14 @@ const currentIconUrl = computed(() => resolveAppIcon(form.appIconFiles[0]?.url |
|
|||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
line-height: 20px;
|
line-height: 20px;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.card-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: flex-end;
|
||||||
}
|
}
|
||||||
.setting-row {
|
.setting-row {
|
||||||
padding: 8px 12px;
|
padding: 8px 12px;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import vue from '@vitejs/plugin-vue';
|
|||||||
import { fileURLToPath, URL } from 'node:url';
|
import { fileURLToPath, URL } from 'node:url';
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
|
base: process.env.VITE_BASE || '/admin/',
|
||||||
plugins: [vue()],
|
plugins: [vue()],
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
|
|||||||
@@ -42,6 +42,7 @@
|
|||||||
"exceljs": "^4.4.0",
|
"exceljs": "^4.4.0",
|
||||||
"ioredis": "^5.4.2",
|
"ioredis": "^5.4.2",
|
||||||
"nanoid": "^3.3.8",
|
"nanoid": "^3.3.8",
|
||||||
|
"prisma": "^5.22.0",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
@@ -60,7 +61,6 @@
|
|||||||
"@types/qrcode": "^1.5.5",
|
"@types/qrcode": "^1.5.5",
|
||||||
"dotenv-cli": "^7.4.4",
|
"dotenv-cli": "^7.4.4",
|
||||||
"jest": "^29.7.0",
|
"jest": "^29.7.0",
|
||||||
"prisma": "^5.22.0",
|
|
||||||
"ts-jest": "^29.2.5",
|
"ts-jest": "^29.2.5",
|
||||||
"ts-node": "^10.9.2",
|
"ts-node": "^10.9.2",
|
||||||
"tsconfig-paths": "^4.2.0",
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- 12 位纯数字追溯码的每日序号状态。
|
||||||
|
CREATE TABLE `trace_code_daily_sequence` (
|
||||||
|
`date_key` VARCHAR(6) NOT NULL,
|
||||||
|
`next_seq` INTEGER NOT NULL DEFAULT 0,
|
||||||
|
`updated_at` DATETIME(3) NOT NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (`date_key`)
|
||||||
|
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
@@ -336,6 +336,14 @@ model TraceCode {
|
|||||||
@@map("trace_code")
|
@@map("trace_code")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model TraceCodeDailySequence {
|
||||||
|
dateKey String @id @map("date_key") @db.VarChar(6)
|
||||||
|
nextSeq Int @default(0) @map("next_seq")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("trace_code_daily_sequence")
|
||||||
|
}
|
||||||
|
|
||||||
model BlockchainProof {
|
model BlockchainProof {
|
||||||
id Int @id @default(autoincrement())
|
id Int @id @default(autoincrement())
|
||||||
traceCodeId BigInt @map("trace_code_id")
|
traceCodeId BigInt @map("trace_code_id")
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { buildOrderBy } from '../common/utils/sort.util';
|
|||||||
import { AuthUser } from '../common/decorators/current-user.decorator';
|
import { AuthUser } from '../common/decorators/current-user.decorator';
|
||||||
import { QueryBackupDto } from './dto/backup.dto';
|
import { QueryBackupDto } from './dto/backup.dto';
|
||||||
import { SettingsService } from '../settings/settings.service';
|
import { SettingsService } from '../settings/settings.service';
|
||||||
|
import { StorageService } from '../storage/storage.service';
|
||||||
|
|
||||||
const MODELS = [
|
const MODELS = [
|
||||||
'sysUser',
|
'sysUser',
|
||||||
@@ -26,6 +27,7 @@ const MODELS = [
|
|||||||
'traceCodeGroup',
|
'traceCodeGroup',
|
||||||
'batch',
|
'batch',
|
||||||
'traceCode',
|
'traceCode',
|
||||||
|
'traceCodeDailySequence',
|
||||||
'blockchainProof',
|
'blockchainProof',
|
||||||
'queryLog',
|
'queryLog',
|
||||||
'job',
|
'job',
|
||||||
@@ -48,6 +50,7 @@ const PRISMA_MODEL_BY_DELEGATE: Record<(typeof MODELS)[number], string> = {
|
|||||||
traceCodeGroup: 'TraceCodeGroup',
|
traceCodeGroup: 'TraceCodeGroup',
|
||||||
batch: 'Batch',
|
batch: 'Batch',
|
||||||
traceCode: 'TraceCode',
|
traceCode: 'TraceCode',
|
||||||
|
traceCodeDailySequence: 'TraceCodeDailySequence',
|
||||||
blockchainProof: 'BlockchainProof',
|
blockchainProof: 'BlockchainProof',
|
||||||
queryLog: 'QueryLog',
|
queryLog: 'QueryLog',
|
||||||
job: 'Job',
|
job: 'Job',
|
||||||
@@ -112,6 +115,7 @@ export class BackupService {
|
|||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly config: ConfigService,
|
private readonly config: ConfigService,
|
||||||
private readonly settings: SettingsService,
|
private readonly settings: SettingsService,
|
||||||
|
private readonly storage: StorageService,
|
||||||
) {
|
) {
|
||||||
this.storageRoot = resolve(this.config.get<string>('storage.localDir') || './storage');
|
this.storageRoot = resolve(this.config.get<string>('storage.localDir') || './storage');
|
||||||
this.backupRoot = resolve(process.env.BACKUP_DIR || join(dirname(this.storageRoot), 'backups'));
|
this.backupRoot = resolve(process.env.BACKUP_DIR || join(dirname(this.storageRoot), 'backups'));
|
||||||
@@ -141,7 +145,7 @@ export class BackupService {
|
|||||||
try {
|
try {
|
||||||
const db = await this.dumpDatabase();
|
const db = await this.dumpDatabase();
|
||||||
const zip = new AdmZip();
|
const zip = new AdmZip();
|
||||||
const fileList = this.addStorageFiles(zip);
|
const fileList = await this.addStorageFiles(zip);
|
||||||
const manifest = {
|
const manifest = {
|
||||||
app: 'artveris',
|
app: 'artveris',
|
||||||
version: '0.1.0',
|
version: '0.1.0',
|
||||||
@@ -221,7 +225,7 @@ export class BackupService {
|
|||||||
try {
|
try {
|
||||||
const zip = new AdmZip(readFileSync(record.filePath));
|
const zip = new AdmZip(readFileSync(record.filePath));
|
||||||
await this.restoreDatabase(zip);
|
await this.restoreDatabase(zip);
|
||||||
this.restoreStorage(zip);
|
await this.restoreStorage(zip);
|
||||||
return this.prisma.backupRecord.update({
|
return this.prisma.backupRecord.update({
|
||||||
where: { id: restoreId },
|
where: { id: restoreId },
|
||||||
data: { status: BackupStatus.SUCCESS, error: null },
|
data: { status: BackupStatus.SUCCESS, error: null },
|
||||||
@@ -256,7 +260,7 @@ export class BackupService {
|
|||||||
private async dumpEffectiveSettings() {
|
private async dumpEffectiveSettings() {
|
||||||
const rows = await this.prisma.systemSetting.findMany();
|
const rows = await this.prisma.systemSetting.findMany();
|
||||||
const byKey = new Map(rows.map((row) => [row.key, row]));
|
const byKey = new Map(rows.map((row) => [row.key, row]));
|
||||||
const all = await this.settings.getAll();
|
const all = await this.settings.getAllRaw();
|
||||||
let nextId = rows.reduce((max, row) => Math.max(max, row.id), 0) + 1;
|
let nextId = rows.reduce((max, row) => Math.max(max, row.id), 0) + 1;
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
for (const [key, value] of Object.entries(all)) {
|
for (const [key, value] of Object.entries(all)) {
|
||||||
@@ -267,8 +271,17 @@ export class BackupService {
|
|||||||
return [...byKey.values()];
|
return [...byKey.values()];
|
||||||
}
|
}
|
||||||
|
|
||||||
private addStorageFiles(zip: AdmZip) {
|
private async addStorageFiles(zip: AdmZip) {
|
||||||
const files: string[] = [];
|
const files: string[] = [];
|
||||||
|
const storageKeys = await this.storage.listKeys();
|
||||||
|
if (storageKeys.length) {
|
||||||
|
for (const key of storageKeys) {
|
||||||
|
if (!isSafeZipPath(key)) continue;
|
||||||
|
files.push(key);
|
||||||
|
zip.addFile(`storage/${key}`, await this.storage.read(key));
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
}
|
||||||
if (!existsSync(this.storageRoot)) return files;
|
if (!existsSync(this.storageRoot)) return files;
|
||||||
const walk = (dir: string) => {
|
const walk = (dir: string) => {
|
||||||
for (const name of readdirSync(dir)) {
|
for (const name of readdirSync(dir)) {
|
||||||
@@ -304,20 +317,25 @@ export class BackupService {
|
|||||||
}, { timeout: 120000 });
|
}, { timeout: 120000 });
|
||||||
}
|
}
|
||||||
|
|
||||||
private restoreStorage(zip: AdmZip) {
|
private async restoreStorage(zip: AdmZip) {
|
||||||
mkdirSync(this.storageRoot, { recursive: true });
|
const currentKeys = await this.storage.listKeys();
|
||||||
for (const name of readdirSync(this.storageRoot)) {
|
if (currentKeys.length) {
|
||||||
const full = join(this.storageRoot, name);
|
for (const key of currentKeys) {
|
||||||
if (isSameOrChildPath(this.backupRoot, full)) continue;
|
if (!key.startsWith('.health/')) await this.storage.remove(key);
|
||||||
rmSync(full, { recursive: true, force: true });
|
}
|
||||||
|
} else {
|
||||||
|
mkdirSync(this.storageRoot, { recursive: true });
|
||||||
|
for (const name of readdirSync(this.storageRoot)) {
|
||||||
|
const full = join(this.storageRoot, name);
|
||||||
|
if (isSameOrChildPath(this.backupRoot, full)) continue;
|
||||||
|
rmSync(full, { recursive: true, force: true });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for (const entry of zip.getEntries()) {
|
for (const entry of zip.getEntries()) {
|
||||||
if (entry.isDirectory || !entry.entryName.startsWith('storage/')) continue;
|
if (entry.isDirectory || !entry.entryName.startsWith('storage/')) continue;
|
||||||
const rel = entry.entryName.slice('storage/'.length);
|
const rel = entry.entryName.slice('storage/'.length);
|
||||||
if (!isSafeZipPath(rel)) throw new Error(`备份包包含不安全文件路径:${entry.entryName}`);
|
if (!isSafeZipPath(rel)) throw new Error(`备份包包含不安全文件路径:${entry.entryName}`);
|
||||||
const full = join(this.storageRoot, rel);
|
await this.storage.putKey(rel, entry.getData());
|
||||||
mkdirSync(dirname(full), { recursive: true });
|
|
||||||
writeFileSync(full, entry.getData());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ function makeService(): BlockchainService {
|
|||||||
} as unknown as ConfigService;
|
} as unknown as ConfigService;
|
||||||
const settings = {
|
const settings = {
|
||||||
getAll: async () => ({ blockchainDriver: 'mock' }),
|
getAll: async () => ({ blockchainDriver: 'mock' }),
|
||||||
|
getAllRaw: async () => ({ blockchainDriver: 'mock' }),
|
||||||
} as unknown as SettingsService;
|
} as unknown as SettingsService;
|
||||||
return new BlockchainService(config, settings);
|
return new BlockchainService(config, settings);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ export class BlockchainService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async buildProvider(): Promise<AttestationProvider> {
|
private async buildProvider(): Promise<AttestationProvider> {
|
||||||
const settings = await this.settings.getAll();
|
const settings = await this.settings.getAllRaw();
|
||||||
const driver = (settings.blockchainDriver || this.config.get<string>('blockchain.driver') || 'mock') as 'mock' | 'tianhe';
|
const driver = (settings.blockchainDriver || this.config.get<string>('blockchain.driver') || 'mock') as 'mock' | 'tianhe';
|
||||||
if (driver !== 'tianhe') return new MockProvider();
|
if (driver !== 'tianhe') return new MockProvider();
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ErrorMessage } from '@artveris/shared';
|
import { ErrorMessage, ErrorMessageKey } from '@artveris/shared';
|
||||||
|
|
||||||
// 业务异常:携带统一业务码,由全局过滤器转换为标准响应体。
|
// 业务异常:携带统一业务码,由全局过滤器转换为标准响应体。
|
||||||
export class BusinessException extends Error {
|
export class BusinessException extends Error {
|
||||||
@@ -6,6 +6,8 @@ export class BusinessException extends Error {
|
|||||||
public readonly code: number,
|
public readonly code: number,
|
||||||
message?: string,
|
message?: string,
|
||||||
public readonly httpStatus = 400,
|
public readonly httpStatus = 400,
|
||||||
|
public readonly messageKey = ErrorMessageKey[code],
|
||||||
|
public readonly params?: Record<string, unknown>,
|
||||||
) {
|
) {
|
||||||
super(message || ErrorMessage[code] || '业务处理失败');
|
super(message || ErrorMessage[code] || '业务处理失败');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import {
|
|||||||
Logger,
|
Logger,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import { Response } from 'express';
|
import { Response } from 'express';
|
||||||
import { ErrorCode } from '@artveris/shared';
|
import { ErrorCode, ErrorMessageKey } from '@artveris/shared';
|
||||||
import { BusinessException } from '../exceptions/business.exception';
|
import { BusinessException } from '../exceptions/business.exception';
|
||||||
|
|
||||||
@Catch()
|
@Catch()
|
||||||
@@ -21,11 +21,15 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
|||||||
let httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
|
let httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
let code: number = ErrorCode.INTERNAL_ERROR;
|
let code: number = ErrorCode.INTERNAL_ERROR;
|
||||||
let message = '服务器内部错误';
|
let message = '服务器内部错误';
|
||||||
|
let messageKey = ErrorMessageKey[ErrorCode.INTERNAL_ERROR];
|
||||||
|
let params: Record<string, unknown> | undefined;
|
||||||
|
|
||||||
if (exception instanceof BusinessException) {
|
if (exception instanceof BusinessException) {
|
||||||
httpStatus = exception.httpStatus;
|
httpStatus = exception.httpStatus;
|
||||||
code = exception.code;
|
code = exception.code;
|
||||||
message = exception.message;
|
message = exception.message;
|
||||||
|
messageKey = exception.messageKey || ErrorMessageKey[code];
|
||||||
|
params = exception.params;
|
||||||
} else if (exception instanceof HttpException) {
|
} else if (exception instanceof HttpException) {
|
||||||
httpStatus = exception.getStatus();
|
httpStatus = exception.getStatus();
|
||||||
const r = exception.getResponse();
|
const r = exception.getResponse();
|
||||||
@@ -36,6 +40,7 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
|||||||
message = Array.isArray(m) ? String(m[0]) : String(m ?? exception.message);
|
message = Array.isArray(m) ? String(m[0]) : String(m ?? exception.message);
|
||||||
}
|
}
|
||||||
code = this.mapStatusToCode(httpStatus);
|
code = this.mapStatusToCode(httpStatus);
|
||||||
|
messageKey = ErrorMessageKey[code];
|
||||||
} else {
|
} else {
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
(exception as Error)?.message ?? String(exception),
|
(exception as Error)?.message ?? String(exception),
|
||||||
@@ -43,7 +48,7 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(httpStatus).json({ code, message, data: null });
|
res.status(httpStatus).json({ code, message, messageKey, params, data: null });
|
||||||
}
|
}
|
||||||
|
|
||||||
private mapStatusToCode(status: number): number {
|
private mapStatusToCode(status: number): number {
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ export class TransformInterceptor<T> implements NestInterceptor<T, ApiResponse<T
|
|||||||
) {
|
) {
|
||||||
return data as unknown as ApiResponse<T>;
|
return data as unknown as ApiResponse<T>;
|
||||||
}
|
}
|
||||||
return { code: 0, message: 'success', data: (data ?? null) as T | null };
|
return { code: 0, message: 'success', messageKey: 'common.success', data: (data ?? null) as T | null };
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { loadRuntimeConfig } from './runtime-config';
|
||||||
|
|
||||||
export interface AppConfig {
|
export interface AppConfig {
|
||||||
appName: string;
|
appName: string;
|
||||||
env: string;
|
env: string;
|
||||||
@@ -8,6 +10,7 @@ export interface AppConfig {
|
|||||||
clientOrigin: string;
|
clientOrigin: string;
|
||||||
traceUrlTemplate: string;
|
traceUrlTemplate: string;
|
||||||
jwt: { secret: string; expiresIn: string };
|
jwt: { secret: string; expiresIn: string };
|
||||||
|
settingsEncryptionKey: string;
|
||||||
redis: { host: string; port: number; password?: string };
|
redis: { host: string; port: number; password?: string };
|
||||||
storage: {
|
storage: {
|
||||||
driver: 'local' | 'oss';
|
driver: 'local' | 'oss';
|
||||||
@@ -32,47 +35,60 @@ export interface AppConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default (): AppConfig => {
|
export default (): AppConfig => {
|
||||||
const clientOrigin = process.env.CLIENT_ORIGIN || 'http://localhost:5174';
|
const runtime = loadRuntimeConfig();
|
||||||
|
if (!process.env.DATABASE_URL && runtime.databaseUrl) process.env.DATABASE_URL = runtime.databaseUrl;
|
||||||
|
if (!process.env.BACKUP_DIR && runtime.backupDir) process.env.BACKUP_DIR = runtime.backupDir;
|
||||||
|
const storage = runtime.storage || {};
|
||||||
|
const oss = storage.oss || {};
|
||||||
|
const blockchain = runtime.blockchain || {};
|
||||||
|
const tianhe = blockchain.tianhe || {};
|
||||||
|
const clientOrigin = process.env.CLIENT_ORIGIN || runtime.clientOrigin || 'http://localhost:5174';
|
||||||
return {
|
return {
|
||||||
appName: process.env.APP_NAME || '艺术品溯源平台',
|
appName: process.env.APP_NAME || runtime.appName || '艺术品溯源平台',
|
||||||
env: process.env.NODE_ENV || 'development',
|
env: process.env.NODE_ENV || 'development',
|
||||||
port: parseInt(process.env.API_PORT || '3000', 10),
|
port: parseInt(process.env.API_PORT || String(runtime.port || 3000), 10),
|
||||||
baseUrl: process.env.BASE_URL || 'http://localhost:3000',
|
baseUrl: process.env.BASE_URL || runtime.baseUrl || 'http://localhost:3000',
|
||||||
publicTracePath: process.env.PUBLIC_TRACE_PATH || '/t',
|
publicTracePath: process.env.PUBLIC_TRACE_PATH || '/t',
|
||||||
adminOrigin: process.env.ADMIN_ORIGIN || 'http://localhost:5173',
|
adminOrigin: process.env.ADMIN_ORIGIN || runtime.adminOrigin || 'http://localhost:5173',
|
||||||
clientOrigin,
|
clientOrigin,
|
||||||
// 短链跳转到 C 端溯源页的地址模板,{code} 会被替换为短码
|
// 短链跳转到 C 端溯源页的地址模板,{code} 会被替换为短码
|
||||||
traceUrlTemplate: process.env.TRACE_URL_TEMPLATE || `${clientOrigin}/#/trace/{code}`,
|
traceUrlTemplate: process.env.TRACE_URL_TEMPLATE || `${clientOrigin}/#/trace/{code}`,
|
||||||
jwt: {
|
jwt: {
|
||||||
secret: process.env.JWT_SECRET || 'artveris_dev_secret',
|
secret: process.env.JWT_SECRET || runtime.jwt?.secret || 'artveris_dev_secret',
|
||||||
expiresIn: process.env.JWT_EXPIRES_IN || '7d',
|
expiresIn: process.env.JWT_EXPIRES_IN || runtime.jwt?.expiresIn || '7d',
|
||||||
},
|
},
|
||||||
|
settingsEncryptionKey:
|
||||||
|
process.env.SETTING_ENCRYPTION_KEY ||
|
||||||
|
runtime.settingsEncryptionKey ||
|
||||||
|
process.env.JWT_SECRET ||
|
||||||
|
runtime.jwt?.secret ||
|
||||||
|
'artveris_dev_secret',
|
||||||
redis: {
|
redis: {
|
||||||
host: process.env.REDIS_HOST || 'localhost',
|
host: process.env.REDIS_HOST || runtime.redis?.host || 'localhost',
|
||||||
port: parseInt(process.env.REDIS_PORT || '6379', 10),
|
port: parseInt(process.env.REDIS_PORT || String(runtime.redis?.port || 6379), 10),
|
||||||
password: process.env.REDIS_PASSWORD || undefined,
|
password: process.env.REDIS_PASSWORD || runtime.redis?.password || undefined,
|
||||||
},
|
},
|
||||||
storage: {
|
storage: {
|
||||||
driver: (process.env.STORAGE_DRIVER as 'local' | 'oss') || 'local',
|
driver: (process.env.STORAGE_DRIVER as 'local' | 'oss') || storage.driver || 'local',
|
||||||
localDir: process.env.STORAGE_LOCAL_DIR || './storage',
|
localDir: process.env.STORAGE_LOCAL_DIR || storage.localDir || './storage',
|
||||||
publicPrefix: process.env.STORAGE_PUBLIC_PREFIX || '/uploads',
|
publicPrefix: process.env.STORAGE_PUBLIC_PREFIX || storage.publicPrefix || '/uploads',
|
||||||
cdnBaseUrl: process.env.CDN_BASE_URL || '',
|
cdnBaseUrl: process.env.CDN_BASE_URL || storage.cdnBaseUrl || '',
|
||||||
oss: {
|
oss: {
|
||||||
endpoint: process.env.OSS_ENDPOINT || '',
|
endpoint: process.env.OSS_ENDPOINT || oss.endpoint || '',
|
||||||
region: process.env.OSS_REGION || '',
|
region: process.env.OSS_REGION || oss.region || '',
|
||||||
bucket: process.env.OSS_BUCKET || '',
|
bucket: process.env.OSS_BUCKET || oss.bucket || '',
|
||||||
accessKeyId: process.env.OSS_ACCESS_KEY_ID || '',
|
accessKeyId: process.env.OSS_ACCESS_KEY_ID || oss.accessKeyId || '',
|
||||||
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET || '',
|
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET || oss.accessKeySecret || '',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
blockchain: {
|
blockchain: {
|
||||||
driver: (process.env.BLOCKCHAIN_DRIVER as 'mock' | 'tianhe') || 'mock',
|
driver: (process.env.BLOCKCHAIN_DRIVER as 'mock' | 'tianhe') || blockchain.driver || 'mock',
|
||||||
tianhe: {
|
tianhe: {
|
||||||
baseUrl: process.env.TIANHE_BASE_URL || 'https://test.api.tichain.tianhecloud.com',
|
baseUrl: process.env.TIANHE_BASE_URL || tianhe.baseUrl || 'https://test.api.tichain.tianhecloud.com',
|
||||||
appId: process.env.TIANHE_APP_ID || '',
|
appId: process.env.TIANHE_APP_ID || tianhe.appId || '',
|
||||||
appKey: process.env.TIANHE_APP_KEY || '',
|
appKey: process.env.TIANHE_APP_KEY || tianhe.appKey || '',
|
||||||
userId: process.env.TIANHE_USER_ID || '',
|
userId: process.env.TIANHE_USER_ID || tianhe.userId || '',
|
||||||
userKey: process.env.TIANHE_USER_KEY || '',
|
userKey: process.env.TIANHE_USER_KEY || tianhe.userKey || '',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
seedAdmin: {
|
seedAdmin: {
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import { existsSync, readFileSync } from 'fs';
|
||||||
|
import { dirname, resolve } from 'path';
|
||||||
|
|
||||||
|
export interface RuntimeConfigFile {
|
||||||
|
appName?: string;
|
||||||
|
port?: number;
|
||||||
|
baseUrl?: string;
|
||||||
|
adminOrigin?: string;
|
||||||
|
clientOrigin?: string;
|
||||||
|
databaseUrl?: string;
|
||||||
|
redis?: { host?: string; port?: number; password?: string };
|
||||||
|
jwt?: { secret?: string; expiresIn?: string };
|
||||||
|
settingsEncryptionKey?: string;
|
||||||
|
storage?: {
|
||||||
|
driver?: 'local' | 'oss';
|
||||||
|
localDir?: string;
|
||||||
|
publicPrefix?: string;
|
||||||
|
cdnBaseUrl?: string;
|
||||||
|
oss?: {
|
||||||
|
endpoint?: string;
|
||||||
|
region?: string;
|
||||||
|
bucket?: string;
|
||||||
|
accessKeyId?: string;
|
||||||
|
accessKeySecret?: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
backupDir?: string;
|
||||||
|
blockchain?: {
|
||||||
|
driver?: 'mock' | 'tianhe';
|
||||||
|
tianhe?: { baseUrl?: string; appId?: string; appKey?: string; userId?: string; userKey?: string };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runtimeRoot(): string {
|
||||||
|
return resolve(process.env.ARTVERIS_RUNTIME_DIR || process.env.RUNTIME_DIR || resolve(process.cwd(), 'runtime'));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runtimeConfigPath(): string {
|
||||||
|
return resolve(process.env.ARTVERIS_CONFIG_PATH || resolve(runtimeRoot(), 'artveris.config.json'));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runtimeEnvPath(): string {
|
||||||
|
return resolve(dirname(runtimeConfigPath()), '.env');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadRuntimeConfig(): RuntimeConfigFile {
|
||||||
|
const path = runtimeConfigPath();
|
||||||
|
if (!existsSync(path)) return {};
|
||||||
|
try {
|
||||||
|
return JSON.parse(readFileSync(path, 'utf8')) as RuntimeConfigFile;
|
||||||
|
} catch {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadEnvFile(path: string): void {
|
||||||
|
if (!existsSync(path)) return;
|
||||||
|
const text = readFileSync(path, 'utf8');
|
||||||
|
for (const rawLine of text.split(/\r?\n/)) {
|
||||||
|
const line = rawLine.trim();
|
||||||
|
if (!line || line.startsWith('#')) continue;
|
||||||
|
const eq = line.indexOf('=');
|
||||||
|
if (eq <= 0) continue;
|
||||||
|
const key = line.slice(0, eq).trim();
|
||||||
|
if (process.env[key] !== undefined) continue;
|
||||||
|
let value = line.slice(eq + 1).trim();
|
||||||
|
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
||||||
|
value = value.slice(1, -1);
|
||||||
|
}
|
||||||
|
process.env[key] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function preloadRuntimeEnv(): void {
|
||||||
|
loadEnvFile(resolve(process.cwd(), '.env'));
|
||||||
|
loadEnvFile(resolve(process.cwd(), '../../.env'));
|
||||||
|
loadEnvFile(runtimeEnvPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasRuntimeConfig(): boolean {
|
||||||
|
return existsSync(runtimeConfigPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isInstallMode(): boolean {
|
||||||
|
preloadRuntimeEnv();
|
||||||
|
if (process.env.ARTVERIS_INSTALL_MODE === '1') return true;
|
||||||
|
if (process.env.ARTVERIS_INSTALL_MODE === '0') return false;
|
||||||
|
if (process.env.DATABASE_URL) return false;
|
||||||
|
return !hasRuntimeConfig();
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import configuration from './config/configuration';
|
||||||
|
import { InstallModule } from './install/install.module';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
load: [configuration],
|
||||||
|
envFilePath: ['../../.env', '.env'],
|
||||||
|
}),
|
||||||
|
InstallModule,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class InstallAppModule {}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { Type } from 'class-transformer';
|
||||||
|
import { IsBoolean, IsIn, IsInt, IsNotEmpty, IsOptional, IsString, IsUrl, MaxLength, Min, MinLength, ValidateNested } from 'class-validator';
|
||||||
|
|
||||||
|
export class InstallMysqlDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
host!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ default: 3306 })
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
port!: number;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
database!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
username!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
password!: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class InstallRedisDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
host!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ default: 6379 })
|
||||||
|
@Type(() => Number)
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
port!: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
password?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class InstallAdminDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
@MaxLength(50)
|
||||||
|
username!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(6)
|
||||||
|
@MaxLength(64)
|
||||||
|
password!: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
@MaxLength(50)
|
||||||
|
realName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class InstallStorageDto {
|
||||||
|
@ApiProperty({ enum: ['local', 'oss'] })
|
||||||
|
@IsIn(['local', 'oss'])
|
||||||
|
driver!: 'local' | 'oss';
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
localDir?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
cdnBaseUrl?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ossEndpoint?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ossRegion?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ossBucket?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ossAccessKeyId?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ossAccessKeySecret?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class InstallRequestDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
appName!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsUrl({ require_tld: false })
|
||||||
|
baseUrl!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsUrl({ require_tld: false })
|
||||||
|
clientBaseUrl!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => InstallMysqlDto)
|
||||||
|
mysql!: InstallMysqlDto;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => InstallRedisDto)
|
||||||
|
redis!: InstallRedisDto;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => InstallAdminDto)
|
||||||
|
admin!: InstallAdminDto;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => InstallStorageDto)
|
||||||
|
storage!: InstallStorageDto;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
jwtSecret?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ default: '7d' })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
jwtExpiresIn?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ default: false })
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
backupEnabled?: boolean;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { Body, Controller, Get, Post } from '@nestjs/common';
|
||||||
|
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { Public } from '../common/decorators/public.decorator';
|
||||||
|
import { InstallRequestDto } from './dto/install.dto';
|
||||||
|
import { InstallService } from './install.service';
|
||||||
|
|
||||||
|
@ApiTags('Install')
|
||||||
|
@Controller('install')
|
||||||
|
export class InstallController {
|
||||||
|
constructor(private readonly installService: InstallService) {}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Get('status')
|
||||||
|
@ApiOperation({ summary: 'Installation status' })
|
||||||
|
status() {
|
||||||
|
return this.installService.status();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Public()
|
||||||
|
@Post()
|
||||||
|
@ApiOperation({ summary: 'Initialize installation' })
|
||||||
|
install(@Body() dto: InstallRequestDto) {
|
||||||
|
return this.installService.install(dto);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { InstallController } from './install.controller';
|
||||||
|
import { InstallService } from './install.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [InstallController],
|
||||||
|
providers: [InstallService],
|
||||||
|
})
|
||||||
|
export class InstallModule {}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { createCipheriv, createHash, randomBytes } from 'crypto';
|
||||||
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
||||||
|
import { dirname, resolve } from 'path';
|
||||||
|
import { execFileSync } from 'child_process';
|
||||||
|
import * as bcrypt from 'bcryptjs';
|
||||||
|
import { PrismaClient, RoleType, UserStatus } from '@prisma/client';
|
||||||
|
import Redis from 'ioredis';
|
||||||
|
import { runtimeConfigPath, runtimeEnvPath, runtimeRoot } from '../config/runtime-config';
|
||||||
|
import { InstallRequestDto } from './dto/install.dto';
|
||||||
|
|
||||||
|
const INSTALL_STATE_FILE = 'install-state.json';
|
||||||
|
const ENCRYPTED_PREFIX = 'enc:v1:';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class InstallService {
|
||||||
|
status() {
|
||||||
|
const configPath = runtimeConfigPath();
|
||||||
|
const installed = existsSync(configPath) || (process.env.ARTVERIS_INSTALL_MODE !== '1' && Boolean(process.env.DATABASE_URL));
|
||||||
|
return {
|
||||||
|
installed,
|
||||||
|
configPath,
|
||||||
|
traceCodeSalt: installed ? null : this.pendingTraceCodeSalt(),
|
||||||
|
defaults: {
|
||||||
|
mysqlHost: process.env.INSTALL_MYSQL_HOST || 'mysql',
|
||||||
|
mysqlPort: Number(process.env.INSTALL_MYSQL_PORT || 3306),
|
||||||
|
mysqlDatabase: process.env.MYSQL_DATABASE || 'artveris',
|
||||||
|
mysqlUser: process.env.MYSQL_USER || 'artveris',
|
||||||
|
redisHost: process.env.INSTALL_REDIS_HOST || 'redis',
|
||||||
|
redisPort: Number(process.env.INSTALL_REDIS_PORT || 6379),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async install(dto: InstallRequestDto) {
|
||||||
|
if (existsSync(runtimeConfigPath()) || (process.env.ARTVERIS_INSTALL_MODE !== '1' && process.env.DATABASE_URL)) {
|
||||||
|
return { installed: true, restartRequired: false };
|
||||||
|
}
|
||||||
|
const traceCodeSalt = this.pendingTraceCodeSalt();
|
||||||
|
const databaseUrl = this.buildMysqlUrl(dto);
|
||||||
|
await this.assertMysql(databaseUrl);
|
||||||
|
await this.assertRedis(dto);
|
||||||
|
const config = this.buildRuntimeConfig(dto, databaseUrl);
|
||||||
|
this.runPrismaMigrate(databaseUrl);
|
||||||
|
await this.seedInstallData(databaseUrl, dto, traceCodeSalt, String(config.settingsEncryptionKey || ''));
|
||||||
|
this.writeRuntimeConfig(config, traceCodeSalt);
|
||||||
|
setTimeout(() => process.exit(0), 600);
|
||||||
|
return { installed: true, restartRequired: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
private pendingTraceCodeSalt(): string {
|
||||||
|
const path = resolve(runtimeRoot(), INSTALL_STATE_FILE);
|
||||||
|
try {
|
||||||
|
if (existsSync(path)) {
|
||||||
|
const state = JSON.parse(readFileSync(path, 'utf8')) as { traceCodeSalt?: string };
|
||||||
|
if (state.traceCodeSalt) return state.traceCodeSalt;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Regenerate below when the pending state file is malformed.
|
||||||
|
}
|
||||||
|
const traceCodeSalt = randomBytes(32).toString('hex');
|
||||||
|
mkdirSync(dirname(path), { recursive: true });
|
||||||
|
writeFileSync(path, JSON.stringify({ traceCodeSalt }, null, 2), 'utf8');
|
||||||
|
return traceCodeSalt;
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildMysqlUrl(dto: InstallRequestDto): string {
|
||||||
|
const user = encodeURIComponent(dto.mysql.username);
|
||||||
|
const password = encodeURIComponent(dto.mysql.password);
|
||||||
|
const db = encodeURIComponent(dto.mysql.database);
|
||||||
|
return `mysql://${user}:${password}@${dto.mysql.host}:${dto.mysql.port}/${db}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertMysql(databaseUrl: string): Promise<void> {
|
||||||
|
const prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } } });
|
||||||
|
try {
|
||||||
|
await prisma.$connect();
|
||||||
|
await prisma.$queryRaw`SELECT 1`;
|
||||||
|
} finally {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertRedis(dto: InstallRequestDto): Promise<void> {
|
||||||
|
const redis = new Redis({
|
||||||
|
host: dto.redis.host,
|
||||||
|
port: dto.redis.port,
|
||||||
|
password: dto.redis.password || undefined,
|
||||||
|
maxRetriesPerRequest: 1,
|
||||||
|
lazyConnect: true,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await redis.connect();
|
||||||
|
await redis.ping();
|
||||||
|
} finally {
|
||||||
|
redis.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildRuntimeConfig(dto: InstallRequestDto, databaseUrl: string) {
|
||||||
|
const localDir = dto.storage.localDir || resolve(process.cwd(), 'storage');
|
||||||
|
return {
|
||||||
|
appName: dto.appName,
|
||||||
|
port: Number(process.env.API_PORT || 3000),
|
||||||
|
baseUrl: dto.baseUrl.replace(/\/$/, ''),
|
||||||
|
adminOrigin: `${dto.baseUrl.replace(/\/$/, '')}/admin`,
|
||||||
|
clientOrigin: dto.clientBaseUrl.replace(/\/$/, ''),
|
||||||
|
databaseUrl,
|
||||||
|
redis: {
|
||||||
|
host: dto.redis.host,
|
||||||
|
port: dto.redis.port,
|
||||||
|
password: dto.redis.password || '',
|
||||||
|
},
|
||||||
|
jwt: {
|
||||||
|
secret: dto.jwtSecret || randomBytes(32).toString('hex'),
|
||||||
|
expiresIn: dto.jwtExpiresIn || '7d',
|
||||||
|
},
|
||||||
|
settingsEncryptionKey: randomBytes(32).toString('hex'),
|
||||||
|
storage: {
|
||||||
|
driver: dto.storage.driver,
|
||||||
|
localDir,
|
||||||
|
publicPrefix: '/uploads',
|
||||||
|
cdnBaseUrl: dto.storage.cdnBaseUrl || '',
|
||||||
|
oss: {
|
||||||
|
endpoint: dto.storage.ossEndpoint || '',
|
||||||
|
region: dto.storage.ossRegion || '',
|
||||||
|
bucket: dto.storage.ossBucket || '',
|
||||||
|
accessKeyId: dto.storage.ossAccessKeyId || '',
|
||||||
|
accessKeySecret: '',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
backupDir: resolve(process.cwd(), 'backups'),
|
||||||
|
blockchain: { driver: 'mock', tianhe: {} },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private writeRuntimeConfig(config: Record<string, unknown>, traceCodeSalt: string): void {
|
||||||
|
const path = runtimeConfigPath();
|
||||||
|
mkdirSync(dirname(path), { recursive: true });
|
||||||
|
writeFileSync(path, JSON.stringify(config, null, 2), 'utf8');
|
||||||
|
const envLines = [
|
||||||
|
`DATABASE_URL="${config.databaseUrl}"`,
|
||||||
|
`TRACE_CODE_SALT=${traceCodeSalt}`,
|
||||||
|
`ARTVERIS_CONFIG_PATH=${path.replace(/\\/g, '/')}`,
|
||||||
|
];
|
||||||
|
writeFileSync(runtimeEnvPath(), `${envLines.join('\n')}\n`, 'utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
private runPrismaMigrate(databaseUrl: string): void {
|
||||||
|
const prismaBin = require.resolve('prisma/build/index.js');
|
||||||
|
execFileSync(process.execPath, [prismaBin, 'migrate', 'deploy', '--schema', this.prismaSchemaPath()], {
|
||||||
|
stdio: 'inherit',
|
||||||
|
env: { ...process.env, DATABASE_URL: databaseUrl },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private prismaSchemaPath(): string {
|
||||||
|
const candidates = [
|
||||||
|
resolve(process.cwd(), 'prisma/schema.prisma'),
|
||||||
|
resolve(process.cwd(), 'apps/api/prisma/schema.prisma'),
|
||||||
|
resolve(__dirname, '../../prisma/schema.prisma'),
|
||||||
|
];
|
||||||
|
const found = candidates.find((path) => existsSync(path));
|
||||||
|
if (!found) throw new Error(`Prisma schema not found: ${candidates.join(', ')}`);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async seedInstallData(databaseUrl: string, dto: InstallRequestDto, traceCodeSalt: string, settingsEncryptionKey: string): Promise<void> {
|
||||||
|
const prisma = new PrismaClient({ datasources: { db: { url: databaseUrl } } });
|
||||||
|
try {
|
||||||
|
await prisma.$connect();
|
||||||
|
const passwordHash = await bcrypt.hash(dto.admin.password, 10);
|
||||||
|
const realName = dto.admin.realName || dto.admin.username;
|
||||||
|
await prisma.sysUser.upsert({
|
||||||
|
where: { username: dto.admin.username },
|
||||||
|
update: { passwordHash, realName, role: RoleType.SUPER_ADMIN, status: UserStatus.ACTIVE },
|
||||||
|
create: { username: dto.admin.username, passwordHash, realName, role: RoleType.SUPER_ADMIN, status: UserStatus.ACTIVE },
|
||||||
|
});
|
||||||
|
const settings: Record<string, string> = {
|
||||||
|
appName: dto.appName,
|
||||||
|
clientBaseUrl: dto.clientBaseUrl.replace(/\/$/, ''),
|
||||||
|
traceCodeSalt,
|
||||||
|
settingsEncryptionKey,
|
||||||
|
backupEnabled: String(Boolean(dto.backupEnabled)),
|
||||||
|
storageDriver: dto.storage.driver,
|
||||||
|
storageLocalDir: dto.storage.localDir || resolve(process.cwd(), 'storage'),
|
||||||
|
storagePublicPrefix: '/uploads',
|
||||||
|
cdnBaseUrl: dto.storage.cdnBaseUrl || '',
|
||||||
|
ossEndpoint: dto.storage.ossEndpoint || '',
|
||||||
|
ossRegion: dto.storage.ossRegion || '',
|
||||||
|
ossBucket: dto.storage.ossBucket || '',
|
||||||
|
ossAccessKeyId: dto.storage.ossAccessKeyId || '',
|
||||||
|
ossAccessKeySecret: this.encryptSecret(dto.storage.ossAccessKeySecret || '', settingsEncryptionKey),
|
||||||
|
};
|
||||||
|
for (const [key, value] of Object.entries(settings)) {
|
||||||
|
await prisma.systemSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private encryptSecret(value: string, key: string): string {
|
||||||
|
if (!value) return '';
|
||||||
|
const iv = randomBytes(12);
|
||||||
|
const cipher = createCipheriv('aes-256-gcm', createHash('sha256').update(key).digest(), iv);
|
||||||
|
const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
|
||||||
|
const tag = cipher.getAuthTag();
|
||||||
|
return `${ENCRYPTED_PREFIX}${Buffer.concat([iv, tag, encrypted]).toString('base64url')}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
+48
-25
@@ -1,24 +1,35 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { ValidationPipe, RequestMethod, Logger } from '@nestjs/common';
|
import { Logger, RequestMethod, ValidationPipe } from '@nestjs/common';
|
||||||
import { NestExpressApplication } from '@nestjs/platform-express';
|
import { NestExpressApplication } from '@nestjs/platform-express';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||||
import { existsSync, mkdirSync } from 'fs';
|
import { existsSync, mkdirSync } from 'fs';
|
||||||
import { resolve } from 'path';
|
import { join, resolve } from 'path';
|
||||||
import { AppModule } from './app.module';
|
import { InstallAppModule } from './install-app.module';
|
||||||
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
|
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
|
||||||
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
|
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
|
||||||
import { OperationLogInterceptor } from './operation-log/operation-log.interceptor';
|
import { OperationLogInterceptor } from './operation-log/operation-log.interceptor';
|
||||||
import { STATIC_ASSET_CACHE_CONTROL } from './storage/storage.service';
|
import { STATIC_ASSET_CACHE_CONTROL } from './storage/storage.service';
|
||||||
|
import { isInstallMode } from './config/runtime-config';
|
||||||
|
|
||||||
// 让 BigInt 可被 JSON 序列化为字符串,避免精度问题。
|
|
||||||
(BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () {
|
(BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () {
|
||||||
return this.toString();
|
return this.toString();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function mountSpa(app: NestExpressApplication, prefix: string, root: string): void {
|
||||||
|
if (!existsSync(root)) return;
|
||||||
|
app.useStaticAssets(root, { prefix });
|
||||||
|
const http = app.getHttpAdapter().getInstance();
|
||||||
|
const index = resolve(root, 'index.html');
|
||||||
|
http.get(prefix, (_req, res) => res.sendFile(index));
|
||||||
|
http.get(`${prefix}/*`, (_req, res) => res.sendFile(index));
|
||||||
|
}
|
||||||
|
|
||||||
async function bootstrap(): Promise<void> {
|
async function bootstrap(): Promise<void> {
|
||||||
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
|
const installing = isInstallMode();
|
||||||
|
const rootModule = installing ? InstallAppModule : (await import('./app.module')).AppModule;
|
||||||
|
const app = await NestFactory.create<NestExpressApplication>(rootModule, {
|
||||||
bodyParser: true,
|
bodyParser: true,
|
||||||
});
|
});
|
||||||
const config = app.get(ConfigService);
|
const config = app.get(ConfigService);
|
||||||
@@ -46,28 +57,40 @@ async function bootstrap(): Promise<void> {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
app.useGlobalFilters(new AllExceptionsFilter());
|
app.useGlobalFilters(new AllExceptionsFilter());
|
||||||
app.useGlobalInterceptors(app.get(OperationLogInterceptor), new TransformInterceptor());
|
if (installing) {
|
||||||
|
app.useGlobalInterceptors(new TransformInterceptor());
|
||||||
|
} else {
|
||||||
|
app.useGlobalInterceptors(app.get(OperationLogInterceptor), new TransformInterceptor());
|
||||||
|
}
|
||||||
|
|
||||||
// 本地文件存储静态访问
|
const publicRoot = resolve(process.env.ARTVERIS_PUBLIC_DIR || join(process.cwd(), 'public'));
|
||||||
const localDir = resolve(config.get<string>('storage.localDir') || './storage');
|
const http = app.getHttpAdapter().getInstance();
|
||||||
if (!existsSync(localDir)) {
|
if (installing) {
|
||||||
mkdirSync(localDir, { recursive: true });
|
mountSpa(app, '/install', resolve(publicRoot, 'install'));
|
||||||
|
http.get('/', (_req, res) => res.redirect('/install'));
|
||||||
|
} else {
|
||||||
|
const localDir = resolve(config.get<string>('storage.localDir') || './storage');
|
||||||
|
if (!existsSync(localDir)) mkdirSync(localDir, { recursive: true });
|
||||||
|
app.useStaticAssets(localDir, {
|
||||||
|
prefix: config.get<string>('storage.publicPrefix') || '/uploads',
|
||||||
|
etag: true,
|
||||||
|
lastModified: true,
|
||||||
|
maxAge: '1y',
|
||||||
|
immutable: true,
|
||||||
|
setHeaders: (res) => {
|
||||||
|
res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
mountSpa(app, '/admin', resolve(publicRoot, 'admin'));
|
||||||
|
mountSpa(app, '/trace', resolve(publicRoot, 'trace'));
|
||||||
|
if (existsSync(resolve(publicRoot, 'admin', 'index.html'))) {
|
||||||
|
http.get('/', (_req, res) => res.redirect('/admin'));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
app.useStaticAssets(localDir, {
|
|
||||||
prefix: config.get<string>('storage.publicPrefix') || '/uploads',
|
|
||||||
etag: true,
|
|
||||||
lastModified: true,
|
|
||||||
maxAge: '1y',
|
|
||||||
immutable: true,
|
|
||||||
setHeaders: (res) => {
|
|
||||||
res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
// Swagger(开发文档)
|
|
||||||
const swaggerConfig = new DocumentBuilder()
|
const swaggerConfig = new DocumentBuilder()
|
||||||
.setTitle('artveris API')
|
.setTitle('Artveris API')
|
||||||
.setDescription('艺术品可信溯源与认证系统接口文档')
|
.setDescription('Artveris traceability and certification API')
|
||||||
.setVersion('0.1.0')
|
.setVersion('0.1.0')
|
||||||
.addBearerAuth()
|
.addBearerAuth()
|
||||||
.build();
|
.build();
|
||||||
@@ -76,8 +99,8 @@ async function bootstrap(): Promise<void> {
|
|||||||
|
|
||||||
const port = config.get<number>('port') || 3000;
|
const port = config.get<number>('port') || 3000;
|
||||||
await app.listen(port);
|
await app.listen(port);
|
||||||
logger.log(`API 已启动: http://localhost:${port}/api`);
|
logger.log(`${installing ? 'Install server' : 'API'} started: http://localhost:${port}/api`);
|
||||||
logger.log(`接口文档: http://localhost:${port}/api/docs`);
|
logger.log(`Swagger: http://localhost:${port}/api/docs`);
|
||||||
}
|
}
|
||||||
|
|
||||||
void bootstrap();
|
void bootstrap();
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
|
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
|
||||||
import { Request, Response } from 'express';
|
import { Request, Response } from 'express';
|
||||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
import { Public } from '../common/decorators/public.decorator';
|
import { Public } from '../common/decorators/public.decorator';
|
||||||
import { extractIp } from '../common/utils/ua.util';
|
import { extractIp } from '../common/utils/ua.util';
|
||||||
import { PublicTraceService } from './public-trace.service';
|
import { PublicTraceService } from './public-trace.service';
|
||||||
|
import { SettingsService } from '../settings/settings.service';
|
||||||
|
|
||||||
@ApiTags('公开溯源')
|
@ApiTags('公开溯源')
|
||||||
@Controller()
|
@Controller()
|
||||||
export class PublicTraceController {
|
export class PublicTraceController {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly service: PublicTraceService,
|
private readonly service: PublicTraceService,
|
||||||
private readonly config: ConfigService,
|
private readonly settings: SettingsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Public()
|
@Public()
|
||||||
@@ -26,10 +26,8 @@ export class PublicTraceController {
|
|||||||
// 短链跳转:扫码打开 /t/:shortCode -> 重定向到 C 端溯源页(不在 /api 前缀下)
|
// 短链跳转:扫码打开 /t/:shortCode -> 重定向到 C 端溯源页(不在 /api 前缀下)
|
||||||
@Public()
|
@Public()
|
||||||
@Get('t/:shortCode')
|
@Get('t/:shortCode')
|
||||||
redirect(@Param('shortCode') shortCode: string, @Res() res: Response) {
|
async redirect(@Param('shortCode') shortCode: string, @Res() res: Response) {
|
||||||
const template =
|
const clientBaseUrl = await this.settings.getClientBaseUrl();
|
||||||
this.config.get<string>('traceUrlTemplate') ||
|
res.redirect(302, `${clientBaseUrl}/#/trace/${encodeURIComponent(shortCode)}`);
|
||||||
'http://localhost:5174/#/pages/trace/index?code={code}';
|
|
||||||
res.redirect(302, template.replace('{code}', encodeURIComponent(shortCode)));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
import { Inject, Injectable, Logger } from '@nestjs/common';
|
||||||
import type Redis from 'ioredis';
|
import type Redis from 'ioredis';
|
||||||
import { Prisma } from '@prisma/client';
|
import { Prisma } from '@prisma/client';
|
||||||
import { ArtworkStatus, AuditStatus, QueryResult, ProofStatus, TraceCodeStatus } from '@artveris/shared';
|
import { ArtworkStatus, AuditStatus, QueryResult, ProofStatus, TRACE_CODE_PATTERN, TraceCodeStatus } from '@artveris/shared';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { StorageService } from '../storage/storage.service';
|
import { StorageService } from '../storage/storage.service';
|
||||||
import { REDIS_CLIENT } from '../redis/redis.module';
|
import { REDIS_CLIENT } from '../redis/redis.module';
|
||||||
@@ -92,6 +92,10 @@ export class PublicTraceService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async trace(shortCode: string, ctx: TraceContext) {
|
async trace(shortCode: string, ctx: TraceContext) {
|
||||||
|
if (!TRACE_CODE_PATTERN.test(shortCode)) {
|
||||||
|
await this.writeLog(null, null, shortCode, QueryResult.INVALID, ctx);
|
||||||
|
return { status: 'INVALID' as const };
|
||||||
|
}
|
||||||
const id = await this.resolveId(shortCode);
|
const id = await this.resolveId(shortCode);
|
||||||
if (id === null) {
|
if (id === null) {
|
||||||
await this.writeLog(null, null, shortCode, QueryResult.INVALID, ctx);
|
await this.writeLog(null, null, shortCode, QueryResult.INVALID, ctx);
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
const EDITABLE_KEYS = [
|
const EDITABLE_KEYS = [
|
||||||
@@ -14,6 +15,20 @@ const EDITABLE_KEYS = [
|
|||||||
'backupSchedule',
|
'backupSchedule',
|
||||||
'backupRetentionDays',
|
'backupRetentionDays',
|
||||||
'backupRetentionCount',
|
'backupRetentionCount',
|
||||||
|
'clientBaseUrl',
|
||||||
|
'storageDriver',
|
||||||
|
'storageLocalDir',
|
||||||
|
'storagePublicPrefix',
|
||||||
|
'cdnBaseUrl',
|
||||||
|
'ossEndpoint',
|
||||||
|
'ossRegion',
|
||||||
|
'ossBucket',
|
||||||
|
'ossAccessKeyId',
|
||||||
|
'ossAccessKeySecret',
|
||||||
|
'settingsEncryptionKey',
|
||||||
|
'storageMigrationTarget',
|
||||||
|
'storageMigrationFingerprint',
|
||||||
|
'storageMigrationCopied',
|
||||||
'blockchainDriver',
|
'blockchainDriver',
|
||||||
'tianheEnv',
|
'tianheEnv',
|
||||||
'tianheBaseUrl',
|
'tianheBaseUrl',
|
||||||
@@ -23,6 +38,9 @@ const EDITABLE_KEYS = [
|
|||||||
'tianheUserKey',
|
'tianheUserKey',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const SECRET_KEYS = new Set(['ossAccessKeySecret', 'tianheAppKey', 'tianheUserKey']);
|
||||||
|
const ENCRYPTED_PREFIX = 'enc:v1:';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SettingsService {
|
export class SettingsService {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -31,6 +49,14 @@ export class SettingsService {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
async getAll(): Promise<Record<string, string>> {
|
async getAll(): Promise<Record<string, string>> {
|
||||||
|
return this.getAllInternal(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAllRaw(): Promise<Record<string, string>> {
|
||||||
|
return this.getAllInternal(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getAllInternal(maskSecrets: boolean): Promise<Record<string, string>> {
|
||||||
const rows = await this.prisma.systemSetting.findMany();
|
const rows = await this.prisma.systemSetting.findMany();
|
||||||
const map: Record<string, string> = {
|
const map: Record<string, string> = {
|
||||||
appName: this.config.get<string>('appName') || '',
|
appName: this.config.get<string>('appName') || '',
|
||||||
@@ -44,6 +70,17 @@ export class SettingsService {
|
|||||||
backupSchedule: 'daily',
|
backupSchedule: 'daily',
|
||||||
backupRetentionDays: '30',
|
backupRetentionDays: '30',
|
||||||
backupRetentionCount: '10',
|
backupRetentionCount: '10',
|
||||||
|
clientBaseUrl: this.config.get<string>('clientOrigin') || 'http://localhost:5174',
|
||||||
|
storageDriver: this.config.get<string>('storage.driver') || 'local',
|
||||||
|
storageLocalDir: this.config.get<string>('storage.localDir') || './storage',
|
||||||
|
storagePublicPrefix: this.config.get<string>('storage.publicPrefix') || '/uploads',
|
||||||
|
cdnBaseUrl: this.config.get<string>('storage.cdnBaseUrl') || '',
|
||||||
|
ossEndpoint: this.config.get<string>('storage.oss.endpoint') || '',
|
||||||
|
ossRegion: this.config.get<string>('storage.oss.region') || '',
|
||||||
|
ossBucket: this.config.get<string>('storage.oss.bucket') || '',
|
||||||
|
ossAccessKeyId: this.config.get<string>('storage.oss.accessKeyId') || '',
|
||||||
|
ossAccessKeySecret: this.config.get<string>('storage.oss.accessKeySecret') || '',
|
||||||
|
settingsEncryptionKey: this.config.get<string>('settingsEncryptionKey') || '',
|
||||||
blockchainDriver: this.config.get<string>('blockchain.driver') || 'mock',
|
blockchainDriver: this.config.get<string>('blockchain.driver') || 'mock',
|
||||||
tianheEnv: 'test',
|
tianheEnv: 'test',
|
||||||
tianheBaseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com',
|
tianheBaseUrl: this.config.get<string>('blockchain.tianhe.baseUrl') || 'https://test.api.tichain.tianhecloud.com',
|
||||||
@@ -53,26 +90,85 @@ export class SettingsService {
|
|||||||
tianheUserKey: this.config.get<string>('blockchain.tianhe.userKey') || '',
|
tianheUserKey: this.config.get<string>('blockchain.tianhe.userKey') || '',
|
||||||
};
|
};
|
||||||
for (const r of rows) {
|
for (const r of rows) {
|
||||||
map[r.key] = r.key === 'appName' && r.value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : r.value;
|
const value = SECRET_KEYS.has(r.key) ? await this.decryptSecret(r.value) : r.value;
|
||||||
|
map[r.key] = r.key === 'appName' && value === '艺术品可信溯源与认证平台' ? '艺术品溯源平台' : value;
|
||||||
}
|
}
|
||||||
if (!map.appIconUrl) map.appIconUrl = '/app-icon.svg';
|
if (!map.appIconUrl) map.appIconUrl = '/app-icon.svg';
|
||||||
|
if (maskSecrets) {
|
||||||
|
if (map.ossAccessKeySecret) map.ossAccessKeySecret = this.maskSecret(map.ossAccessKeySecret);
|
||||||
|
if (map.tianheAppKey) map.tianheAppKey = this.maskSecret(map.tianheAppKey);
|
||||||
|
if (map.tianheUserKey) map.tianheUserKey = this.maskSecret(map.tianheUserKey);
|
||||||
|
delete map.settingsEncryptionKey;
|
||||||
|
}
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
async get(key: string): Promise<string | null> {
|
async get(key: string): Promise<string | null> {
|
||||||
const row = await this.prisma.systemSetting.findUnique({ where: { key } });
|
const row = await this.prisma.systemSetting.findUnique({ where: { key } });
|
||||||
return row?.value ?? null;
|
if (!row) return null;
|
||||||
|
return SECRET_KEYS.has(key) ? this.decryptSecret(row.value) : row.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getClientBaseUrl(): Promise<string> {
|
||||||
|
const fromDb = await this.get('clientBaseUrl');
|
||||||
|
return (fromDb || this.config.get<string>('clientOrigin') || 'http://localhost:5174').replace(/\/$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
private maskSecret(value: string): string {
|
||||||
|
if (!value || value.length <= 8) return value ? '******' : '';
|
||||||
|
return `${value.slice(0, 3)}******${value.slice(-3)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
isMaskedSecret(value?: string | null): boolean {
|
||||||
|
return typeof value === 'string' && /^\*+$|^.{1,8}\*{3,}.{1,8}$/.test(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(values: Record<string, string>): Promise<Record<string, string>> {
|
async update(values: Record<string, string>): Promise<Record<string, string>> {
|
||||||
for (const [key, value] of Object.entries(values)) {
|
for (const [key, value] of Object.entries(values)) {
|
||||||
if (!EDITABLE_KEYS.includes(key)) continue;
|
if (!EDITABLE_KEYS.includes(key)) continue;
|
||||||
|
if (SECRET_KEYS.has(key) && this.isMaskedSecret(value)) continue;
|
||||||
|
const nextValue = SECRET_KEYS.has(key) ? await this.encryptSecret(String(value)) : String(value);
|
||||||
await this.prisma.systemSetting.upsert({
|
await this.prisma.systemSetting.upsert({
|
||||||
where: { key },
|
where: { key },
|
||||||
update: { value: String(value) },
|
update: { value: nextValue },
|
||||||
create: { key, value: String(value) },
|
create: { key, value: nextValue },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return this.getAll();
|
return this.getAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async encryptionKey(): Promise<Buffer> {
|
||||||
|
const row = await this.prisma.systemSetting.findUnique({ where: { key: 'settingsEncryptionKey' } }).catch(() => null);
|
||||||
|
const secret =
|
||||||
|
row?.value ||
|
||||||
|
this.config.get<string>('settingsEncryptionKey') ||
|
||||||
|
process.env.SETTING_ENCRYPTION_KEY ||
|
||||||
|
this.config.get<string>('jwt.secret') ||
|
||||||
|
'artveris_dev_secret';
|
||||||
|
return createHash('sha256').update(secret).digest();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async encryptSecret(value: string): Promise<string> {
|
||||||
|
if (!value || value.startsWith(ENCRYPTED_PREFIX)) return value;
|
||||||
|
const iv = randomBytes(12);
|
||||||
|
const cipher = createCipheriv('aes-256-gcm', await this.encryptionKey(), iv);
|
||||||
|
const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
|
||||||
|
const tag = cipher.getAuthTag();
|
||||||
|
return `${ENCRYPTED_PREFIX}${Buffer.concat([iv, tag, encrypted]).toString('base64url')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async decryptSecret(value: string): Promise<string> {
|
||||||
|
if (!value?.startsWith(ENCRYPTED_PREFIX)) return value;
|
||||||
|
try {
|
||||||
|
const raw = Buffer.from(value.slice(ENCRYPTED_PREFIX.length), 'base64url');
|
||||||
|
const iv = raw.subarray(0, 12);
|
||||||
|
const tag = raw.subarray(12, 28);
|
||||||
|
const encrypted = raw.subarray(28);
|
||||||
|
const decipher = createDecipheriv('aes-256-gcm', await this.encryptionKey(), iv);
|
||||||
|
decipher.setAuthTag(tag);
|
||||||
|
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8');
|
||||||
|
} catch {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { IsIn, IsOptional, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class StorageConfigDto {
|
||||||
|
@ApiPropertyOptional({ enum: ['local', 'oss'] })
|
||||||
|
@IsOptional()
|
||||||
|
@IsIn(['local', 'oss'])
|
||||||
|
driver?: 'local' | 'oss';
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
localDir?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
cdnBaseUrl?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ossEndpoint?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ossRegion?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ossBucket?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ossAccessKeyId?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
ossAccessKeySecret?: string;
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { existsSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'fs';
|
import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync, rmSync, readFileSync } from 'fs';
|
||||||
import { dirname, relative, resolve } from 'path';
|
import { dirname, join, relative, resolve } from 'path';
|
||||||
import { PutOptions, StorageDriver } from './storage.types';
|
import { PutOptions, StorageDriver } from './storage.types';
|
||||||
|
|
||||||
export interface LocalDriverOptions {
|
export interface LocalDriverOptions {
|
||||||
@@ -43,6 +43,24 @@ export class LocalDriver implements StorageDriver {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async list(): Promise<string[]> {
|
||||||
|
if (!existsSync(this.root)) return [];
|
||||||
|
const keys: string[] = [];
|
||||||
|
const walk = (dir: string) => {
|
||||||
|
for (const name of readdirSync(dir)) {
|
||||||
|
const full = join(dir, name);
|
||||||
|
const st = statSync(full);
|
||||||
|
if (st.isDirectory()) {
|
||||||
|
walk(full);
|
||||||
|
} else {
|
||||||
|
keys.push(relative(this.root, full).replace(/\\/g, '/'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(this.root);
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
getPublicUrl(key: string): string {
|
getPublicUrl(key: string): string {
|
||||||
if (this.opts.cdnBaseUrl) {
|
if (this.opts.cdnBaseUrl) {
|
||||||
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
|
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
DeleteObjectCommand,
|
DeleteObjectCommand,
|
||||||
GetObjectCommand,
|
GetObjectCommand,
|
||||||
|
ListObjectsV2Command,
|
||||||
PutObjectCommand,
|
PutObjectCommand,
|
||||||
S3Client,
|
S3Client,
|
||||||
} from '@aws-sdk/client-s3';
|
} from '@aws-sdk/client-s3';
|
||||||
@@ -56,6 +57,19 @@ export class OssDriver implements StorageDriver {
|
|||||||
await this.client.send(new DeleteObjectCommand({ Bucket: this.opts.bucket, Key: key }));
|
await this.client.send(new DeleteObjectCommand({ Bucket: this.opts.bucket, Key: key }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async list(): Promise<string[]> {
|
||||||
|
const keys: string[] = [];
|
||||||
|
let token: string | undefined;
|
||||||
|
do {
|
||||||
|
const res = await this.client.send(new ListObjectsV2Command({ Bucket: this.opts.bucket, ContinuationToken: token }));
|
||||||
|
for (const item of res.Contents || []) {
|
||||||
|
if (item.Key) keys.push(item.Key);
|
||||||
|
}
|
||||||
|
token = res.NextContinuationToken;
|
||||||
|
} while (token);
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
getPublicUrl(key: string): string {
|
getPublicUrl(key: string): string {
|
||||||
if (this.opts.cdnBaseUrl) {
|
if (this.opts.cdnBaseUrl) {
|
||||||
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
|
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { Body, Controller, Post } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { RoleType } from '@artveris/shared';
|
||||||
|
import { Roles } from '../common/decorators/roles.decorator';
|
||||||
|
import { StorageAdminService } from './storage-admin.service';
|
||||||
|
import { StorageConfigDto } from './dto/storage-migration.dto';
|
||||||
|
|
||||||
|
@ApiTags('Storage')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@Roles(RoleType.SUPER_ADMIN)
|
||||||
|
@Controller('storage')
|
||||||
|
export class StorageAdminController {
|
||||||
|
constructor(private readonly service: StorageAdminService) {}
|
||||||
|
|
||||||
|
@Post('test')
|
||||||
|
@ApiOperation({ summary: 'Test storage connection' })
|
||||||
|
test(@Body() dto: StorageConfigDto) {
|
||||||
|
return this.service.test(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('migrate')
|
||||||
|
@ApiOperation({ summary: 'Migrate business files to target storage' })
|
||||||
|
migrate(@Body() dto: StorageConfigDto) {
|
||||||
|
return this.service.migrate(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('confirm')
|
||||||
|
@ApiOperation({ summary: 'Confirm target storage switch' })
|
||||||
|
confirm(@Body() dto: StorageConfigDto) {
|
||||||
|
return this.service.confirm(dto);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { createHash } from 'crypto';
|
||||||
|
import { ErrorCode } from '@artveris/shared';
|
||||||
|
import { SettingsService } from '../settings/settings.service';
|
||||||
|
import { BusinessException } from '../common/exceptions/business.exception';
|
||||||
|
import { StorageService } from './storage.service';
|
||||||
|
import { LocalDriver } from './local.driver';
|
||||||
|
import { OssDriver } from './oss.driver';
|
||||||
|
import { StorageConfigDto } from './dto/storage-migration.dto';
|
||||||
|
import { StorageDriver } from './storage.types';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class StorageAdminService {
|
||||||
|
constructor(
|
||||||
|
private readonly config: ConfigService,
|
||||||
|
private readonly settings: SettingsService,
|
||||||
|
private readonly storage: StorageService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async test(dto: StorageConfigDto) {
|
||||||
|
await this.storage.test(await this.driverFromDto(dto));
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async migrate(dto: StorageConfigDto) {
|
||||||
|
const source = await this.currentDriver();
|
||||||
|
const target = await this.driverFromDto(dto);
|
||||||
|
const keys = source.list ? await source.list() : await this.storage.listKeys();
|
||||||
|
let copied = 0;
|
||||||
|
for (const key of keys) {
|
||||||
|
if (key.startsWith('.health/')) continue;
|
||||||
|
const buffer = await source.get(key);
|
||||||
|
await target.put(key, buffer);
|
||||||
|
copied += 1;
|
||||||
|
}
|
||||||
|
await this.settings.update({
|
||||||
|
storageMigrationTarget: JSON.stringify(this.sanitizedTarget(dto)),
|
||||||
|
storageMigrationFingerprint: this.targetFingerprint(dto),
|
||||||
|
storageMigrationCopied: String(copied),
|
||||||
|
});
|
||||||
|
return { success: true, copied };
|
||||||
|
}
|
||||||
|
|
||||||
|
async confirm(dto: StorageConfigDto) {
|
||||||
|
const fingerprint = await this.settings.get('storageMigrationFingerprint');
|
||||||
|
if (fingerprint !== this.targetFingerprint(dto)) {
|
||||||
|
throw new BusinessException(ErrorCode.BAD_REQUEST, undefined, 400, 'error.STORAGE_MIGRATION_REQUIRED');
|
||||||
|
}
|
||||||
|
await this.settings.update(this.settingsPayload(dto));
|
||||||
|
await this.storage.reloadFromSettings();
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
private async currentDriver(): Promise<StorageDriver> {
|
||||||
|
const s = await this.settings.getAllRaw();
|
||||||
|
return this.storage.createDriver({
|
||||||
|
driver: s.storageDriver || this.config.get<string>('storage.driver') || 'local',
|
||||||
|
localDir: s.storageLocalDir || this.config.get<string>('storage.localDir') || './storage',
|
||||||
|
publicPrefix: s.storagePublicPrefix || this.config.get<string>('storage.publicPrefix') || '/uploads',
|
||||||
|
cdnBaseUrl: s.cdnBaseUrl || this.config.get<string>('storage.cdnBaseUrl') || '',
|
||||||
|
oss: {
|
||||||
|
endpoint: s.ossEndpoint || this.config.get<string>('storage.oss.endpoint') || '',
|
||||||
|
region: s.ossRegion || this.config.get<string>('storage.oss.region') || '',
|
||||||
|
bucket: s.ossBucket || this.config.get<string>('storage.oss.bucket') || '',
|
||||||
|
accessKeyId: s.ossAccessKeyId || this.config.get<string>('storage.oss.accessKeyId') || '',
|
||||||
|
accessKeySecret: s.ossAccessKeySecret || this.config.get<string>('storage.oss.accessKeySecret') || '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async driverFromDto(dto: StorageConfigDto): Promise<StorageDriver> {
|
||||||
|
const driver = dto.driver || 'local';
|
||||||
|
if (driver === 'oss') {
|
||||||
|
const secret = await this.resolveOssSecret(dto.ossAccessKeySecret);
|
||||||
|
if (!dto.ossBucket || !dto.ossAccessKeyId || !secret) {
|
||||||
|
throw new BusinessException(ErrorCode.BAD_REQUEST, undefined, 400, 'error.OSS_CONFIG_INCOMPLETE');
|
||||||
|
}
|
||||||
|
return new OssDriver({
|
||||||
|
endpoint: dto.ossEndpoint || '',
|
||||||
|
region: dto.ossRegion || '',
|
||||||
|
bucket: dto.ossBucket,
|
||||||
|
accessKeyId: dto.ossAccessKeyId,
|
||||||
|
accessKeySecret: secret,
|
||||||
|
cdnBaseUrl: dto.cdnBaseUrl || '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return new LocalDriver({
|
||||||
|
localDir: dto.localDir || this.config.get<string>('storage.localDir') || './storage',
|
||||||
|
publicPrefix: '/uploads',
|
||||||
|
cdnBaseUrl: dto.cdnBaseUrl || '',
|
||||||
|
baseUrl: this.config.get<string>('baseUrl') || 'http://localhost:3000',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private settingsPayload(dto: StorageConfigDto): Record<string, string> {
|
||||||
|
const payload: Record<string, string> = {
|
||||||
|
storageDriver: dto.driver || 'local',
|
||||||
|
storageLocalDir: dto.localDir || '',
|
||||||
|
storagePublicPrefix: '/uploads',
|
||||||
|
cdnBaseUrl: dto.cdnBaseUrl || '',
|
||||||
|
ossEndpoint: dto.ossEndpoint || '',
|
||||||
|
ossRegion: dto.ossRegion || '',
|
||||||
|
ossBucket: dto.ossBucket || '',
|
||||||
|
ossAccessKeyId: dto.ossAccessKeyId || '',
|
||||||
|
};
|
||||||
|
if (!this.settings.isMaskedSecret(dto.ossAccessKeySecret)) {
|
||||||
|
payload.ossAccessKeySecret = dto.ossAccessKeySecret || '';
|
||||||
|
}
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sanitizedTarget(dto: StorageConfigDto): Record<string, string> {
|
||||||
|
return {
|
||||||
|
storageDriver: dto.driver || 'local',
|
||||||
|
storageLocalDir: dto.localDir || '',
|
||||||
|
storagePublicPrefix: '/uploads',
|
||||||
|
cdnBaseUrl: dto.cdnBaseUrl || '',
|
||||||
|
ossEndpoint: dto.ossEndpoint || '',
|
||||||
|
ossRegion: dto.ossRegion || '',
|
||||||
|
ossBucket: dto.ossBucket || '',
|
||||||
|
ossAccessKeyId: dto.ossAccessKeyId || '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private targetFingerprint(dto: StorageConfigDto): string {
|
||||||
|
return createHash('sha256').update(JSON.stringify(this.sanitizedTarget(dto))).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resolveOssSecret(value?: string): Promise<string> {
|
||||||
|
if (value && !this.settings.isMaskedSecret(value)) return value;
|
||||||
|
return (await this.settings.get('ossAccessKeySecret')) || this.config.get<string>('storage.oss.accessKeySecret') || '';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
import { Global, Module } from '@nestjs/common';
|
import { Global, Module } from '@nestjs/common';
|
||||||
import { StorageService } from './storage.service';
|
import { StorageService } from './storage.service';
|
||||||
|
import { StorageAdminService } from './storage-admin.service';
|
||||||
|
import { StorageAdminController } from './storage-admin.controller';
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
providers: [StorageService],
|
controllers: [StorageAdminController],
|
||||||
exports: [StorageService],
|
providers: [StorageService, StorageAdminService],
|
||||||
|
exports: [StorageService, StorageAdminService],
|
||||||
})
|
})
|
||||||
export class StorageModule {}
|
export class StorageModule {}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { Injectable, Logger } from '@nestjs/common';
|
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { createHash } from 'crypto';
|
import { createHash } from 'crypto';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { nanoid } from 'nanoid';
|
import { nanoid } from 'nanoid';
|
||||||
import { extname } from 'path';
|
import { extname } from 'path';
|
||||||
|
import { SettingsService } from '../settings/settings.service';
|
||||||
import { LocalDriver } from './local.driver';
|
import { LocalDriver } from './local.driver';
|
||||||
import { OssDriver } from './oss.driver';
|
import { OssDriver } from './oss.driver';
|
||||||
import { SavedFile, StorageDriver } from './storage.types';
|
import { SavedFile, StorageDriver } from './storage.types';
|
||||||
@@ -23,14 +24,42 @@ const MIME_EXT: Record<string, string> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class StorageService {
|
export class StorageService implements OnModuleInit {
|
||||||
private readonly logger = new Logger(StorageService.name);
|
private readonly logger = new Logger(StorageService.name);
|
||||||
private readonly driver: StorageDriver;
|
private driver: StorageDriver;
|
||||||
|
|
||||||
constructor(private readonly config: ConfigService) {
|
constructor(
|
||||||
|
private readonly config: ConfigService,
|
||||||
|
private readonly settings: SettingsService,
|
||||||
|
) {
|
||||||
const s = this.config.get<Record<string, any>>('storage')!;
|
const s = this.config.get<Record<string, any>>('storage')!;
|
||||||
|
this.driver = this.createDriver(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
async onModuleInit(): Promise<void> {
|
||||||
|
await this.reloadFromSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
async reloadFromSettings(): Promise<void> {
|
||||||
|
const s = await this.settings.getAllRaw();
|
||||||
|
this.driver = this.createDriver({
|
||||||
|
driver: s.storageDriver || this.config.get<string>('storage.driver') || 'local',
|
||||||
|
localDir: s.storageLocalDir || this.config.get<string>('storage.localDir') || './storage',
|
||||||
|
publicPrefix: s.storagePublicPrefix || this.config.get<string>('storage.publicPrefix') || '/uploads',
|
||||||
|
cdnBaseUrl: s.cdnBaseUrl || this.config.get<string>('storage.cdnBaseUrl') || '',
|
||||||
|
oss: {
|
||||||
|
endpoint: s.ossEndpoint || this.config.get<string>('storage.oss.endpoint') || '',
|
||||||
|
region: s.ossRegion || this.config.get<string>('storage.oss.region') || '',
|
||||||
|
bucket: s.ossBucket || this.config.get<string>('storage.oss.bucket') || '',
|
||||||
|
accessKeyId: s.ossAccessKeyId || this.config.get<string>('storage.oss.accessKeyId') || '',
|
||||||
|
accessKeySecret: s.ossAccessKeySecret || this.config.get<string>('storage.oss.accessKeySecret') || '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
createDriver(s: Record<string, any>): StorageDriver {
|
||||||
if (s.driver === 'oss') {
|
if (s.driver === 'oss') {
|
||||||
this.driver = new OssDriver({
|
const driver = new OssDriver({
|
||||||
endpoint: s.oss.endpoint,
|
endpoint: s.oss.endpoint,
|
||||||
region: s.oss.region,
|
region: s.oss.region,
|
||||||
bucket: s.oss.bucket,
|
bucket: s.oss.bucket,
|
||||||
@@ -39,14 +68,16 @@ export class StorageService {
|
|||||||
cdnBaseUrl: s.cdnBaseUrl,
|
cdnBaseUrl: s.cdnBaseUrl,
|
||||||
});
|
});
|
||||||
this.logger.log('存储驱动:OSS/S3 兼容');
|
this.logger.log('存储驱动:OSS/S3 兼容');
|
||||||
|
return driver;
|
||||||
} else {
|
} else {
|
||||||
this.driver = new LocalDriver({
|
const driver = new LocalDriver({
|
||||||
localDir: s.localDir,
|
localDir: s.localDir,
|
||||||
publicPrefix: s.publicPrefix,
|
publicPrefix: s.publicPrefix,
|
||||||
cdnBaseUrl: s.cdnBaseUrl,
|
cdnBaseUrl: s.cdnBaseUrl,
|
||||||
baseUrl: this.config.get<string>('baseUrl') || 'http://localhost:3000',
|
baseUrl: this.config.get<string>('baseUrl') || 'http://localhost:3000',
|
||||||
});
|
});
|
||||||
this.logger.log('存储驱动:本地磁盘');
|
this.logger.log('存储驱动:本地磁盘');
|
||||||
|
return driver;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,4 +132,16 @@ export class StorageService {
|
|||||||
async remove(key: string): Promise<void> {
|
async remove(key: string): Promise<void> {
|
||||||
await this.driver.remove(key);
|
await this.driver.remove(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async listKeys(): Promise<string[]> {
|
||||||
|
return this.driver.list ? this.driver.list() : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async test(driver: StorageDriver): Promise<boolean> {
|
||||||
|
const key = `.health/${Date.now()}-${nanoid()}.txt`;
|
||||||
|
await driver.put(key, Buffer.from('ok'), { contentType: 'text/plain' });
|
||||||
|
await driver.get(key);
|
||||||
|
await driver.remove(key);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ export interface StorageDriver {
|
|||||||
get(key: string): Promise<Buffer>;
|
get(key: string): Promise<Buffer>;
|
||||||
remove(key: string): Promise<void>;
|
remove(key: string): Promise<void>;
|
||||||
getPublicUrl(key: string): string;
|
getPublicUrl(key: string): string;
|
||||||
|
list?(): Promise<string[]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SavedFile {
|
export interface SavedFile {
|
||||||
|
|||||||
@@ -2,13 +2,13 @@ import { Processor, WorkerHost } from '@nestjs/bullmq';
|
|||||||
import { Logger } from '@nestjs/common';
|
import { Logger } from '@nestjs/common';
|
||||||
import { Job } from 'bullmq';
|
import { Job } from 'bullmq';
|
||||||
import { customAlphabet } from 'nanoid';
|
import { customAlphabet } from 'nanoid';
|
||||||
import { BatchStatus, JobStatus, QUEUE_NAMES, SHORT_CODE_LENGTH } from '@artveris/shared';
|
import { BatchStatus, JobStatus, QUEUE_NAMES } from '@artveris/shared';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { JobsService } from '../jobs/jobs.service';
|
import { JobsService } from '../jobs/jobs.service';
|
||||||
import { TraceCodeService } from './trace-code.service';
|
import { TraceCodeService } from './trace-code.service';
|
||||||
|
import { TraceCodeGeneratorService } from './trace-code-generator.service';
|
||||||
|
|
||||||
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
||||||
const shortId = customAlphabet(ALPHABET, SHORT_CODE_LENGTH);
|
|
||||||
const codeId = customAlphabet(ALPHABET, 18);
|
const codeId = customAlphabet(ALPHABET, 18);
|
||||||
|
|
||||||
interface GenJobData {
|
interface GenJobData {
|
||||||
@@ -27,6 +27,7 @@ export class GenCodeProcessor extends WorkerHost {
|
|||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly jobs: JobsService,
|
private readonly jobs: JobsService,
|
||||||
private readonly traceCode: TraceCodeService,
|
private readonly traceCode: TraceCodeService,
|
||||||
|
private readonly generator: TraceCodeGeneratorService,
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
@@ -41,19 +42,19 @@ export class GenCodeProcessor extends WorkerHost {
|
|||||||
try {
|
try {
|
||||||
while (generated < quantity) {
|
while (generated < quantity) {
|
||||||
const n = Math.min(chunkSize, quantity - generated);
|
const n = Math.min(chunkSize, quantity - generated);
|
||||||
const rows = Array.from({ length: n }, () => {
|
const shortCodes = await this.generator.generate(n);
|
||||||
const shortCode = shortId();
|
const rows = shortCodes.map((shortCode) => {
|
||||||
return {
|
return {
|
||||||
code: codeId(),
|
code: codeId(),
|
||||||
shortCode,
|
shortCode,
|
||||||
artworkId,
|
artworkId,
|
||||||
batchId,
|
batchId,
|
||||||
groupId: groupId ?? null,
|
groupId: groupId ?? null,
|
||||||
url: this.traceCode.buildTraceUrl(shortCode),
|
url: null,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
await this.prisma.traceCode.createMany({ data: rows, skipDuplicates: true });
|
const result = await this.prisma.traceCode.createMany({ data: rows, skipDuplicates: true });
|
||||||
generated += n;
|
generated += result.count;
|
||||||
await this.jobs.progress(jobId, generated, 0);
|
await this.jobs.progress(jobId, generated, 0);
|
||||||
await this.prisma.batch.update({
|
await this.prisma.batch.update({
|
||||||
where: { id: batchId },
|
where: { id: batchId },
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { TraceCodeGeneratorService } from './trace-code-generator.service';
|
||||||
|
|
||||||
|
describe('TraceCodeGeneratorService', () => {
|
||||||
|
const prisma: any = {
|
||||||
|
systemSetting: {
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
create: jest.fn(),
|
||||||
|
},
|
||||||
|
traceCodeDailySequence: {
|
||||||
|
upsert: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
},
|
||||||
|
$transaction: jest.fn(async (fn) => fn(prisma)),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.useFakeTimers().setSystemTime(new Date('2026-07-06T08:00:00.000Z'));
|
||||||
|
prisma.systemSetting.findUnique.mockResolvedValue({ value: 'salt-for-test' });
|
||||||
|
prisma.traceCodeDailySequence.upsert.mockResolvedValue({});
|
||||||
|
prisma.traceCodeDailySequence.update.mockResolvedValue({ nextSeq: 1000 });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('generates unique 12-digit codes with the Shanghai date embedded', async () => {
|
||||||
|
const service = new TraceCodeGeneratorService(prisma);
|
||||||
|
const codes = await service.generate(1000);
|
||||||
|
|
||||||
|
expect(codes).toHaveLength(1000);
|
||||||
|
expect(new Set(codes).size).toBe(1000);
|
||||||
|
for (const code of codes) {
|
||||||
|
expect(code).toMatch(/^\d{12}$/);
|
||||||
|
expect(`${code.slice(2, 4)}${code.slice(5, 7)}${code.slice(8, 10)}`).toBe('260706');
|
||||||
|
}
|
||||||
|
expect(codes.slice(0, 5)).not.toEqual(['002600700600', '002600700601', '002600700602', '002600700603', '002600700604']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { createHmac, randomBytes } from 'crypto';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import { SHORT_CODE_LENGTH } from '@artveris/shared';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
|
const TRACE_CODE_SALT_KEY = 'traceCodeSalt';
|
||||||
|
const MAX_DAILY_SEQUENCE = 1_000_000;
|
||||||
|
const FEISTEL_ROUNDS = 4;
|
||||||
|
|
||||||
|
interface SequenceRange {
|
||||||
|
dateKey: string;
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TraceCodeGeneratorService {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async ensureSalt(): Promise<string> {
|
||||||
|
const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
|
||||||
|
if (existing?.value) return existing.value;
|
||||||
|
const salt = randomBytes(32).toString('hex');
|
||||||
|
try {
|
||||||
|
await this.prisma.systemSetting.create({ data: { key: TRACE_CODE_SALT_KEY, value: salt } });
|
||||||
|
return salt;
|
||||||
|
} catch (e) {
|
||||||
|
if (this.isUniqueError(e)) {
|
||||||
|
const row = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
|
||||||
|
if (row?.value) return row.value;
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async generate(count: number): Promise<string[]> {
|
||||||
|
const salt = await this.ensureSalt();
|
||||||
|
const range = await this.allocateRange(count);
|
||||||
|
return Array.from({ length: range.end - range.start + 1 }, (_, index) =>
|
||||||
|
this.formatCode(this.permute6(range.start + index, salt, range.dateKey), range.dateKey),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async allocateRange(count: number): Promise<SequenceRange> {
|
||||||
|
const dateKey = this.shanghaiDateKey();
|
||||||
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||||
|
try {
|
||||||
|
return await this.prisma.$transaction(async (tx) => {
|
||||||
|
await tx.traceCodeDailySequence.upsert({
|
||||||
|
where: { dateKey },
|
||||||
|
update: {},
|
||||||
|
create: { dateKey, nextSeq: 0 },
|
||||||
|
});
|
||||||
|
const row = await tx.traceCodeDailySequence.update({
|
||||||
|
where: { dateKey },
|
||||||
|
data: { nextSeq: { increment: count } },
|
||||||
|
});
|
||||||
|
const start = row.nextSeq - count;
|
||||||
|
const end = row.nextSeq - 1;
|
||||||
|
if (end >= MAX_DAILY_SEQUENCE) {
|
||||||
|
throw new Error('trace.code.dailyLimitExceeded');
|
||||||
|
}
|
||||||
|
return { dateKey, start, end };
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (!this.isUniqueError(e) || attempt === 2) throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error('trace.code.sequenceAllocationFailed');
|
||||||
|
}
|
||||||
|
|
||||||
|
private shanghaiDateKey(date = new Date()): string {
|
||||||
|
const parts = new Intl.DateTimeFormat('en-US', {
|
||||||
|
timeZone: 'Asia/Shanghai',
|
||||||
|
year: '2-digit',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
}).formatToParts(date);
|
||||||
|
const get = (type: string) => parts.find((part) => part.type === type)?.value.padStart(2, '0') ?? '00';
|
||||||
|
return `${get('year')}${get('month')}${get('day')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private permute6(seq: number, salt: string, dateKey: string): string {
|
||||||
|
let left = Math.floor(seq / 1000);
|
||||||
|
let right = seq % 1000;
|
||||||
|
const keys = this.roundKeys(salt, dateKey);
|
||||||
|
for (let round = 0; round < FEISTEL_ROUNDS; round += 1) {
|
||||||
|
const nextLeft = right;
|
||||||
|
const f = (right * keys[round].mul + keys[round].add) % 1000;
|
||||||
|
right = (left + f) % 1000;
|
||||||
|
left = nextLeft;
|
||||||
|
}
|
||||||
|
return `${left.toString().padStart(3, '0')}${right.toString().padStart(3, '0')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private roundKeys(salt: string, dateKey: string): Array<{ mul: number; add: number }> {
|
||||||
|
const digest = createHmac('sha256', salt).update(`trace-code:${dateKey}`).digest();
|
||||||
|
return Array.from({ length: FEISTEL_ROUNDS }, (_, index) => {
|
||||||
|
const rawMul = digest.readUInt16BE(index * 4) % 1000;
|
||||||
|
return {
|
||||||
|
mul: rawMul % 2 === 0 ? rawMul + 1 : rawMul,
|
||||||
|
add: digest.readUInt16BE(index * 4 + 2) % 1000,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatCode(scrambled: string, dateKey: string): string {
|
||||||
|
const code = `${scrambled.slice(0, 2)}${dateKey.slice(0, 2)}${scrambled[2]}${dateKey.slice(2, 4)}${scrambled[3]}${dateKey.slice(4, 6)}${scrambled.slice(4)}`;
|
||||||
|
if (code.length !== SHORT_CODE_LENGTH || !/^\d{12}$/.test(code)) {
|
||||||
|
throw new Error('trace.code.invalidGeneratedCode');
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isUniqueError(error: unknown): boolean {
|
||||||
|
return error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,11 +4,12 @@ import { QUEUE_NAMES } from '@artveris/shared';
|
|||||||
import { TraceCodeService } from './trace-code.service';
|
import { TraceCodeService } from './trace-code.service';
|
||||||
import { TraceCodeController } from './trace-code.controller';
|
import { TraceCodeController } from './trace-code.controller';
|
||||||
import { GenCodeProcessor } from './gen-code.processor';
|
import { GenCodeProcessor } from './gen-code.processor';
|
||||||
|
import { TraceCodeGeneratorService } from './trace-code-generator.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.GEN_CODE })],
|
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.GEN_CODE })],
|
||||||
controllers: [TraceCodeController],
|
controllers: [TraceCodeController],
|
||||||
providers: [TraceCodeService, GenCodeProcessor],
|
providers: [TraceCodeService, TraceCodeGeneratorService, GenCodeProcessor],
|
||||||
exports: [TraceCodeService],
|
exports: [TraceCodeService, TraceCodeGeneratorService],
|
||||||
})
|
})
|
||||||
export class TraceCodeModule {}
|
export class TraceCodeModule {}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { BusinessException } from '../common/exceptions/business.exception';
|
|||||||
import { buildPage } from '../common/utils/pagination.util';
|
import { buildPage } from '../common/utils/pagination.util';
|
||||||
import { buildOrderBy } from '../common/utils/sort.util';
|
import { buildOrderBy } from '../common/utils/sort.util';
|
||||||
import { JobsService } from '../jobs/jobs.service';
|
import { JobsService } from '../jobs/jobs.service';
|
||||||
|
import { SettingsService } from '../settings/settings.service';
|
||||||
import {
|
import {
|
||||||
BatchDeleteDto,
|
BatchDeleteDto,
|
||||||
BatchGroupDto,
|
BatchGroupDto,
|
||||||
@@ -35,13 +36,28 @@ export class TraceCodeService {
|
|||||||
private readonly jobs: JobsService,
|
private readonly jobs: JobsService,
|
||||||
private readonly config: ConfigService,
|
private readonly config: ConfigService,
|
||||||
private readonly storage: StorageService,
|
private readonly storage: StorageService,
|
||||||
|
private readonly settings: SettingsService,
|
||||||
@InjectQueue(QUEUE_NAMES.GEN_CODE) private readonly genQueue: Queue,
|
@InjectQueue(QUEUE_NAMES.GEN_CODE) private readonly genQueue: Queue,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
buildTraceUrl(shortCode: string): string {
|
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(/\/$/, '');
|
const base = (this.config.get<string>('baseUrl') || 'http://localhost:3000').replace(/\/$/, '');
|
||||||
const path = this.config.get<string>('publicTracePath') || '/t';
|
return `${base}/t/${encodeURIComponent(shortCode)}`;
|
||||||
return `${base}${path}/${shortCode}`;
|
}
|
||||||
|
|
||||||
|
async buildDynamicShortLink(shortCode: string): Promise<string> {
|
||||||
|
try {
|
||||||
|
const clientBaseUrl = await this.settings.getClientBaseUrl();
|
||||||
|
const origin = new URL(clientBaseUrl).origin;
|
||||||
|
return `${origin}/t/${encodeURIComponent(shortCode)}`;
|
||||||
|
} catch {
|
||||||
|
return this.buildShortLink(shortCode);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private mapOutImages(code: { outImage?: string | null; outImages?: unknown }) {
|
private mapOutImages(code: { outImage?: string | null; outImages?: unknown }) {
|
||||||
@@ -453,7 +469,7 @@ export class TraceCodeService {
|
|||||||
async getQrPng(id: bigint): Promise<Buffer> {
|
async getQrPng(id: bigint): Promise<Buffer> {
|
||||||
const code = await this.prisma.traceCode.findUnique({ where: { id } });
|
const code = await this.prisma.traceCode.findUnique({ where: { id } });
|
||||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
||||||
return QRCode.toBuffer(code.url || this.buildTraceUrl(code.shortCode), {
|
return QRCode.toBuffer(await this.buildDynamicShortLink(code.shortCode), {
|
||||||
type: 'png',
|
type: 'png',
|
||||||
width: 320,
|
width: 320,
|
||||||
margin: 1,
|
margin: 1,
|
||||||
@@ -502,7 +518,7 @@ export class TraceCodeService {
|
|||||||
|
|
||||||
const qrImages: Array<{ name: string; buffer: Buffer }> = [];
|
const qrImages: Array<{ name: string; buffer: Buffer }> = [];
|
||||||
for (const c of codes) {
|
for (const c of codes) {
|
||||||
const url = c.url || this.buildTraceUrl(c.shortCode);
|
const url = await this.buildDynamicShortLink(c.shortCode);
|
||||||
const row = ws.addRow({
|
const row = ws.addRow({
|
||||||
archiveNo: c.artwork?.archiveNo ?? '',
|
archiveNo: c.artwork?.archiveNo ?? '',
|
||||||
title: c.artwork?.title ?? '',
|
title: c.artwork?.title ?? '',
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
import { i18n } from './locales';
|
||||||
|
|
||||||
const instance = axios.create({ baseURL: '/api', timeout: 20000 });
|
const instance = axios.create({ baseURL: '/api', timeout: 20000 });
|
||||||
|
|
||||||
|
instance.interceptors.request.use((config) => {
|
||||||
|
config.headers = config.headers ?? {};
|
||||||
|
config.headers['Accept-Language'] = String(i18n.global.locale.value || 'zh-CN');
|
||||||
|
return config;
|
||||||
|
});
|
||||||
|
|
||||||
instance.interceptors.response.use(
|
instance.interceptors.response.use(
|
||||||
(res) => {
|
(res) => {
|
||||||
const body = res.data;
|
const body = res.data;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import vue from '@vitejs/plugin-vue';
|
|||||||
import { fileURLToPath, URL } from 'node:url';
|
import { fileURLToPath, URL } from 'node:url';
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
|
base: process.env.VITE_BASE || '/trace/',
|
||||||
plugins: [vue()],
|
plugins: [vue()],
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Artveris Install</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"name": "@artveris/install",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"build": "vite build",
|
||||||
|
"dev": "vite --host 0.0.0.0 --port 5175",
|
||||||
|
"lint": "echo \"(install) lint skipped\""
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^1.7.9",
|
||||||
|
"vue": "^3.5.13"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-vue": "^5.2.1",
|
||||||
|
"typescript": "^5.6.3",
|
||||||
|
"vite": "^5.4.11"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
<template>
|
||||||
|
<main class="install-page">
|
||||||
|
<section class="panel">
|
||||||
|
<header>
|
||||||
|
<h1>Artveris</h1>
|
||||||
|
<button v-if="!installed" :disabled="submitting" @click="submit">
|
||||||
|
{{ submitting ? t('installing') : t('start') }}
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<p v-if="loading" class="muted">{{ t('loading') }}</p>
|
||||||
|
<p v-else-if="installed" class="success">{{ t('installed') }}</p>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<div class="salt-row">
|
||||||
|
<span>traceCodeSalt</span>
|
||||||
|
<code>{{ traceCodeSalt }}</code>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid">
|
||||||
|
<section>
|
||||||
|
<h2>{{ t('base') }}</h2>
|
||||||
|
<label>{{ t('appName') }}<input v-model="form.appName" /></label>
|
||||||
|
<label>{{ t('baseUrl') }}<input v-model="form.baseUrl" /></label>
|
||||||
|
<label>{{ t('clientBaseUrl') }}<input v-model="form.clientBaseUrl" /></label>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>MySQL</h2>
|
||||||
|
<label>{{ t('host') }}<input v-model="form.mysql.host" /></label>
|
||||||
|
<label>{{ t('port') }}<input v-model.number="form.mysql.port" type="number" /></label>
|
||||||
|
<label>{{ t('database') }}<input v-model="form.mysql.database" /></label>
|
||||||
|
<label>{{ t('username') }}<input v-model="form.mysql.username" /></label>
|
||||||
|
<label>{{ t('password') }}<input v-model="form.mysql.password" type="password" /></label>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>Redis</h2>
|
||||||
|
<label>{{ t('host') }}<input v-model="form.redis.host" /></label>
|
||||||
|
<label>{{ t('port') }}<input v-model.number="form.redis.port" type="number" /></label>
|
||||||
|
<label>{{ t('password') }}<input v-model="form.redis.password" type="password" /></label>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>{{ t('admin') }}</h2>
|
||||||
|
<label>{{ t('username') }}<input v-model="form.admin.username" /></label>
|
||||||
|
<label>{{ t('password') }}<input v-model="form.admin.password" type="password" /></label>
|
||||||
|
<label>{{ t('realName') }}<input v-model="form.admin.realName" /></label>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2>{{ t('storage') }}</h2>
|
||||||
|
<label>
|
||||||
|
{{ t('driver') }}
|
||||||
|
<select v-model="form.storage.driver">
|
||||||
|
<option value="local">{{ t('local') }}</option>
|
||||||
|
<option value="oss">OSS/S3</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>{{ t('localDir') }}<input v-model="form.storage.localDir" /></label>
|
||||||
|
<label>{{ t('cdnBaseUrl') }}<input v-model="form.storage.cdnBaseUrl" /></label>
|
||||||
|
<template v-if="form.storage.driver === 'oss'">
|
||||||
|
<label>Endpoint<input v-model="form.storage.ossEndpoint" /></label>
|
||||||
|
<label>Region<input v-model="form.storage.ossRegion" /></label>
|
||||||
|
<label>Bucket<input v-model="form.storage.ossBucket" /></label>
|
||||||
|
<label>AccessKey ID<input v-model="form.storage.ossAccessKeyId" /></label>
|
||||||
|
<label>AccessKey Secret<input v-model="form.storage.ossAccessKeySecret" type="password" /></label>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-if="error" class="error">{{ error }}</p>
|
||||||
|
<p v-if="success" class="success">{{ success }}</p>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, reactive, ref } from 'vue';
|
||||||
|
|
||||||
|
type StorageDriver = 'local' | 'oss';
|
||||||
|
|
||||||
|
interface InstallForm {
|
||||||
|
appName: string;
|
||||||
|
baseUrl: string;
|
||||||
|
clientBaseUrl: string;
|
||||||
|
mysql: { host: string; port: number; database: string; username: string; password: string };
|
||||||
|
redis: { host: string; port: number; password: string };
|
||||||
|
admin: { username: string; password: string; realName: string };
|
||||||
|
storage: {
|
||||||
|
driver: StorageDriver;
|
||||||
|
localDir: string;
|
||||||
|
cdnBaseUrl: string;
|
||||||
|
ossEndpoint: string;
|
||||||
|
ossRegion: string;
|
||||||
|
ossBucket: string;
|
||||||
|
ossAccessKeyId: string;
|
||||||
|
ossAccessKeySecret: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const messages = {
|
||||||
|
'zh-CN': {
|
||||||
|
start: '开始安装',
|
||||||
|
installing: '安装中',
|
||||||
|
loading: '正在读取安装状态...',
|
||||||
|
installed: '系统已完成初始化。',
|
||||||
|
base: '基础',
|
||||||
|
appName: '平台名称',
|
||||||
|
baseUrl: '服务地址',
|
||||||
|
clientBaseUrl: '客户端地址',
|
||||||
|
host: '主机',
|
||||||
|
port: '端口',
|
||||||
|
database: '数据库',
|
||||||
|
username: '账号',
|
||||||
|
password: '密码',
|
||||||
|
admin: '管理员',
|
||||||
|
realName: '姓名',
|
||||||
|
storage: '存储',
|
||||||
|
driver: '方式',
|
||||||
|
local: '本地',
|
||||||
|
localDir: '本地目录',
|
||||||
|
cdnBaseUrl: 'CDN 地址',
|
||||||
|
installFailed: '安装失败',
|
||||||
|
installDone: '初始化完成,服务正在重启。稍后访问管理后台。',
|
||||||
|
defaultAppName: '艺术品溯源平台',
|
||||||
|
defaultAdminName: '管理员',
|
||||||
|
},
|
||||||
|
'en-US': {
|
||||||
|
start: 'Start Install',
|
||||||
|
installing: 'Installing',
|
||||||
|
loading: 'Reading installation status...',
|
||||||
|
installed: 'The system has already been initialized.',
|
||||||
|
base: 'Base',
|
||||||
|
appName: 'Platform Name',
|
||||||
|
baseUrl: 'Service URL',
|
||||||
|
clientBaseUrl: 'Client URL',
|
||||||
|
host: 'Host',
|
||||||
|
port: 'Port',
|
||||||
|
database: 'Database',
|
||||||
|
username: 'Username',
|
||||||
|
password: 'Password',
|
||||||
|
admin: 'Admin',
|
||||||
|
realName: 'Name',
|
||||||
|
storage: 'Storage',
|
||||||
|
driver: 'Driver',
|
||||||
|
local: 'Local',
|
||||||
|
localDir: 'Local Directory',
|
||||||
|
cdnBaseUrl: 'CDN URL',
|
||||||
|
installFailed: 'Installation failed',
|
||||||
|
installDone: 'Initialization completed. The service is restarting; open the admin console shortly.',
|
||||||
|
defaultAppName: 'Artwork Traceability Platform',
|
||||||
|
defaultAdminName: 'Administrator',
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
type MessageKey = keyof (typeof messages)['zh-CN'];
|
||||||
|
const locale = navigator.language.toLowerCase().startsWith('zh') ? 'zh-CN' : 'en-US';
|
||||||
|
|
||||||
|
function t(key: MessageKey): string {
|
||||||
|
return messages[locale][key] || messages['zh-CN'][key];
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultText(key: MessageKey): string {
|
||||||
|
const lang = navigator.language.toLowerCase().startsWith('zh') ? 'zh-CN' : 'en-US';
|
||||||
|
return messages[lang][key] || messages['zh-CN'][key];
|
||||||
|
}
|
||||||
|
|
||||||
|
const form = reactive<InstallForm>({
|
||||||
|
appName: defaultText('defaultAppName'),
|
||||||
|
baseUrl: location.origin,
|
||||||
|
clientBaseUrl: `${location.origin}/trace`,
|
||||||
|
mysql: { host: '127.0.0.1', port: 3306, database: 'artveris', username: 'artveris', password: '' },
|
||||||
|
redis: { host: '127.0.0.1', port: 6379, password: '' },
|
||||||
|
admin: { username: 'admin', password: '', realName: defaultText('defaultAdminName') },
|
||||||
|
storage: {
|
||||||
|
driver: 'local',
|
||||||
|
localDir: './storage',
|
||||||
|
cdnBaseUrl: '',
|
||||||
|
ossEndpoint: '',
|
||||||
|
ossRegion: '',
|
||||||
|
ossBucket: '',
|
||||||
|
ossAccessKeyId: '',
|
||||||
|
ossAccessKeySecret: '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const loading = ref(true);
|
||||||
|
const submitting = ref(false);
|
||||||
|
const installed = ref(false);
|
||||||
|
const traceCodeSalt = ref('');
|
||||||
|
const error = ref('');
|
||||||
|
const success = ref('');
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/install/status');
|
||||||
|
const body = await res.json();
|
||||||
|
installed.value = Boolean(body.data?.installed);
|
||||||
|
traceCodeSalt.value = body.data?.traceCodeSalt || '';
|
||||||
|
const defaults = body.data?.defaults || {};
|
||||||
|
form.mysql.host = defaults.mysqlHost || form.mysql.host;
|
||||||
|
form.mysql.port = defaults.mysqlPort || form.mysql.port;
|
||||||
|
form.mysql.database = defaults.mysqlDatabase || form.mysql.database;
|
||||||
|
form.mysql.username = defaults.mysqlUser || form.mysql.username;
|
||||||
|
form.redis.host = defaults.redisHost || form.redis.host;
|
||||||
|
form.redis.port = defaults.redisPort || form.redis.port;
|
||||||
|
} catch (e) {
|
||||||
|
error.value = (e as Error).message;
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
error.value = '';
|
||||||
|
success.value = '';
|
||||||
|
submitting.value = true;
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/install', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(form),
|
||||||
|
});
|
||||||
|
const body = await res.json();
|
||||||
|
if (!res.ok || body.code !== 0) throw new Error(body.message || t('installFailed'));
|
||||||
|
success.value = t('installDone');
|
||||||
|
setTimeout(() => {
|
||||||
|
location.href = '/admin';
|
||||||
|
}, 5000);
|
||||||
|
} catch (e) {
|
||||||
|
error.value = (e as Error).message;
|
||||||
|
} finally {
|
||||||
|
submitting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { createApp } from 'vue';
|
||||||
|
import App from './App.vue';
|
||||||
|
import './styles.css';
|
||||||
|
|
||||||
|
createApp(App).mount('#app');
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: "Microsoft YaHei", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||||
|
color: #172033;
|
||||||
|
background: #eef2f7;
|
||||||
|
}
|
||||||
|
.install-page {
|
||||||
|
min-height: 100vh;
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
.panel {
|
||||||
|
max-width: 1180px;
|
||||||
|
margin: 0 auto;
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #d9e0ea;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 16px;
|
||||||
|
border-bottom: 1px solid #e4e9f1;
|
||||||
|
padding-bottom: 14px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
h1,
|
||||||
|
h2 {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
font-size: 22px;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
font-size: 15px;
|
||||||
|
padding-bottom: 10px;
|
||||||
|
border-bottom: 1px solid #e9edf4;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
height: 36px;
|
||||||
|
padding: 0 18px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: #1769e0;
|
||||||
|
color: #fff;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
button:disabled {
|
||||||
|
opacity: 0.65;
|
||||||
|
cursor: wait;
|
||||||
|
}
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
section {
|
||||||
|
border: 1px solid #e1e7f0;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 14px;
|
||||||
|
}
|
||||||
|
label {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 96px 1fr;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
min-height: 42px;
|
||||||
|
color: #526070;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
input,
|
||||||
|
select {
|
||||||
|
width: 100%;
|
||||||
|
height: 32px;
|
||||||
|
border: 1px solid #cad3df;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0 10px;
|
||||||
|
color: #172033;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
.salt-row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 120px 1fr;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
background: #f7f9fc;
|
||||||
|
border: 1px solid #e1e7f0;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
code {
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
color: #25324a;
|
||||||
|
}
|
||||||
|
.muted {
|
||||||
|
color: #6a7687;
|
||||||
|
}
|
||||||
|
.error,
|
||||||
|
.success {
|
||||||
|
margin: 14px 0 0;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: 6px;
|
||||||
|
}
|
||||||
|
.error {
|
||||||
|
color: #a61b1b;
|
||||||
|
background: #fff1f0;
|
||||||
|
}
|
||||||
|
.success {
|
||||||
|
color: #17643b;
|
||||||
|
background: #edf9f1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"module": "ESNext",
|
||||||
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"moduleResolution": "Bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "preserve",
|
||||||
|
"strict": true
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "src/**/*.vue"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { defineConfig } from 'vite';
|
||||||
|
import vue from '@vitejs/plugin-vue';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
base: process.env.VITE_BASE || '/install/',
|
||||||
|
plugins: [vue()],
|
||||||
|
server: {
|
||||||
|
port: 5175,
|
||||||
|
host: true,
|
||||||
|
proxy: {
|
||||||
|
'/api': { target: 'http://localhost:3000', changeOrigin: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
+14
-4
@@ -14,12 +14,23 @@ COPY packages/shared/package.json ./packages/shared/
|
|||||||
COPY apps/api/package.json ./apps/api/
|
COPY apps/api/package.json ./apps/api/
|
||||||
COPY apps/admin/package.json ./apps/admin/
|
COPY apps/admin/package.json ./apps/admin/
|
||||||
COPY apps/client/package.json ./apps/client/
|
COPY apps/client/package.json ./apps/client/
|
||||||
|
COPY apps/install/package.json ./apps/install/
|
||||||
RUN pnpm install --frozen-lockfile
|
RUN pnpm install --frozen-lockfile
|
||||||
COPY packages/shared ./packages/shared
|
COPY packages/shared ./packages/shared
|
||||||
COPY apps/api ./apps/api
|
COPY apps/api ./apps/api
|
||||||
|
COPY apps/admin ./apps/admin
|
||||||
|
COPY apps/client ./apps/client
|
||||||
|
COPY apps/install ./apps/install
|
||||||
RUN pnpm --filter @artveris/shared build \
|
RUN pnpm --filter @artveris/shared build \
|
||||||
&& pnpm --filter @artveris/api exec prisma generate \
|
&& pnpm --filter @artveris/api exec prisma generate \
|
||||||
&& pnpm --filter @artveris/api build
|
&& pnpm --filter @artveris/api build \
|
||||||
|
&& pnpm --filter @artveris/admin build \
|
||||||
|
&& pnpm --filter @artveris/client build \
|
||||||
|
&& pnpm --filter @artveris/install build \
|
||||||
|
&& mkdir -p apps/api/public/admin apps/api/public/trace apps/api/public/install \
|
||||||
|
&& cp -r apps/admin/dist/. apps/api/public/admin/ \
|
||||||
|
&& cp -r apps/client/dist/. apps/api/public/trace/ \
|
||||||
|
&& cp -r apps/install/dist/. apps/api/public/install/
|
||||||
|
|
||||||
FROM ${NODE_IMAGE} AS runner
|
FROM ${NODE_IMAGE} AS runner
|
||||||
RUN apt-get update && apt-get install -y openssl ca-certificates && rm -rf /var/lib/apt/lists/*
|
RUN apt-get update && apt-get install -y openssl ca-certificates && rm -rf /var/lib/apt/lists/*
|
||||||
@@ -30,6 +41,5 @@ COPY --from=builder /app/apps/api ./apps/api
|
|||||||
WORKDIR /app/apps/api
|
WORKDIR /app/apps/api
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
# 启动前应用数据库迁移,再运行服务。
|
ENV ARTVERIS_PUBLIC_DIR=/app/apps/api/public
|
||||||
# pnpm 隔离布局下 prisma CLI 位于 apps/api/node_modules/prisma(非根 node_modules),故用相对本目录的路径。
|
CMD ["node", "dist/main.js"]
|
||||||
CMD ["sh", "-c", "node node_modules/prisma/build/index.js migrate deploy --schema prisma/schema.prisma && node prisma/seed-production.js && node dist/main.js"]
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# ============================================================
|
# ============================================================
|
||||||
# 全栈编排(生产/演示参考):MySQL + Redis + 后端 API + Nginx 静态站
|
# 全栈编排(生产/演示参考):MySQL + Redis + Artveris 单端口服务
|
||||||
# ------------------------------------------------------------
|
# ------------------------------------------------------------
|
||||||
# 使用前置条件:先在仓库根执行 pnpm -r build 生成 apps/admin/dist 与 apps/client/dist
|
# 使用前置条件:先在仓库根执行 pnpm -r build 生成 apps/admin/dist 与 apps/client/dist
|
||||||
# 启动: docker compose -f docker/docker-compose.full.yml up -d --build
|
# 启动: docker compose -f docker/docker-compose.full.yml up -d --build
|
||||||
@@ -43,17 +43,15 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
command: >-
|
command: >-
|
||||||
sh -c 'if [ -n "$${REDIS_PASSWORD}" ]; then
|
sh -c 'if [ -n "$${REDIS_PASSWORD}" ]; then
|
||||||
redis-server --appendonly yes --requirepass "$${REDIS_PASSWORD}";
|
redis-server --appendonly no --requirepass "$${REDIS_PASSWORD}";
|
||||||
else
|
else
|
||||||
redis-server --appendonly yes;
|
redis-server --appendonly no;
|
||||||
fi'
|
fi'
|
||||||
environment:
|
environment:
|
||||||
REDIS_PASSWORD: ${REDIS_PASSWORD:-}
|
REDIS_PASSWORD: ${REDIS_PASSWORD:-}
|
||||||
volumes:
|
# 说明:Redis 仅作为缓存/队列,不默认持久化,不对外映射端口。
|
||||||
- artveris_redis:/data # Redis 持久化
|
|
||||||
# 说明:生产未对外映射 Redis 端口,仅供容器内网访问,更安全
|
|
||||||
|
|
||||||
# -------------------- 后端 API(NestJS) --------------------
|
# -------------------- Artveris 单端口服务 --------------------
|
||||||
api:
|
api:
|
||||||
build:
|
build:
|
||||||
context: .. # 构建上下文 = 仓库根目录
|
context: .. # 构建上下文 = 仓库根目录
|
||||||
@@ -65,59 +63,25 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
NODE_ENV: production # 运行模式(保持 production)
|
NODE_ENV: production # 运行模式(保持 production)
|
||||||
API_PORT: 3000 # 容器内监听端口(被 nginx 反代,一般不改)
|
API_PORT: 3000 # 容器内监听端口(被 nginx 反代,一般不改)
|
||||||
# 数据库连接串:用户名/密码/库名取自上面的 MYSQL_*,主机名固定为服务名 mysql
|
# 首次启动默认进入安装页;如要跳过安装页,可显式提供 DATABASE_URL。
|
||||||
DATABASE_URL: "mysql://${MYSQL_USER:-artveris}:${MYSQL_PASSWORD:-artveris123}@mysql:3306/${MYSQL_DATABASE:-artveris}"
|
DATABASE_URL: ${DATABASE_URL:-}
|
||||||
REDIS_HOST: redis # 缓存主机名 = 服务名 redis(勿改为 localhost)
|
|
||||||
REDIS_PORT: 6379
|
|
||||||
REDIS_PASSWORD: ${REDIS_PASSWORD:-}
|
|
||||||
JWT_SECRET: ${JWT_SECRET:-please_change_in_prod} # 登录令牌签名密钥(生产必改)
|
|
||||||
JWT_EXPIRES_IN: ${JWT_EXPIRES_IN:-7d}
|
|
||||||
BASE_URL: ${BASE_URL:-http://localhost} # 对外访问基址,短链/二维码用,须填真实域名
|
|
||||||
PUBLIC_TRACE_PATH: ${PUBLIC_TRACE_PATH:-/t}
|
|
||||||
ADMIN_ORIGIN: ${ADMIN_ORIGIN:-http://localhost}
|
|
||||||
CLIENT_ORIGIN: ${CLIENT_ORIGIN:-http://localhost:8080} # 客户端站点地址(CORS/跳转用)
|
|
||||||
TRACE_URL_TEMPLATE: ${TRACE_URL_TEMPLATE:-http://localhost:8080/#/trace/{code}}
|
|
||||||
STORAGE_DRIVER: ${STORAGE_DRIVER:-local} # 文件存储:local 本地 | oss 对象存储
|
|
||||||
STORAGE_LOCAL_DIR: ${STORAGE_LOCAL_DIR:-./storage}
|
|
||||||
STORAGE_PUBLIC_PREFIX: ${STORAGE_PUBLIC_PREFIX:-/uploads}
|
|
||||||
CDN_BASE_URL: ${CDN_BASE_URL:-}
|
|
||||||
BACKUP_DIR: ${BACKUP_DIR:-/app/apps/api/backups}
|
|
||||||
BLOCKCHAIN_DRIVER: ${BLOCKCHAIN_DRIVER:-mock} # 存证驱动:mock 模拟 | tianhe 天河链
|
|
||||||
TIANHE_BASE_URL: ${TIANHE_BASE_URL:-}
|
|
||||||
TIANHE_APP_ID: ${TIANHE_APP_ID:-}
|
|
||||||
TIANHE_APP_KEY: ${TIANHE_APP_KEY:-}
|
|
||||||
TIANHE_USER_ID: ${TIANHE_USER_ID:-}
|
|
||||||
TIANHE_USER_KEY: ${TIANHE_USER_KEY:-}
|
|
||||||
OSS_ENDPOINT: ${OSS_ENDPOINT:-}
|
|
||||||
OSS_REGION: ${OSS_REGION:-}
|
|
||||||
OSS_BUCKET: ${OSS_BUCKET:-}
|
|
||||||
OSS_ACCESS_KEY_ID: ${OSS_ACCESS_KEY_ID:-}
|
|
||||||
OSS_ACCESS_KEY_SECRET: ${OSS_ACCESS_KEY_SECRET:-}
|
|
||||||
GEO_DRIVER: mock # IP 归属地驱动
|
GEO_DRIVER: mock # IP 归属地驱动
|
||||||
|
ARTVERIS_PUBLIC_DIR: /app/apps/api/public
|
||||||
|
ARTVERIS_RUNTIME_DIR: /app/apps/api/runtime
|
||||||
|
INSTALL_MYSQL_HOST: mysql
|
||||||
|
INSTALL_REDIS_HOST: redis
|
||||||
|
MYSQL_DATABASE: ${MYSQL_DATABASE:-artveris}
|
||||||
|
MYSQL_USER: ${MYSQL_USER:-artveris}
|
||||||
volumes:
|
volumes:
|
||||||
- artveris_storage:/app/apps/api/storage # 本地存储模式下的上传文件持久化
|
- artveris_storage:/app/apps/api/storage # 本地存储模式下的上传文件持久化
|
||||||
- artveris_backups:/app/apps/api/backups # 备份包持久化,非公开目录
|
- artveris_backups:/app/apps/api/backups # 备份包持久化,非公开目录
|
||||||
|
- artveris_runtime:/app/apps/api/runtime # 安装页生成的运行时配置
|
||||||
# -------------------- Nginx 静态站 + 反向代理 --------------------
|
|
||||||
web:
|
|
||||||
image: nginx:alpine
|
|
||||||
restart: unless-stopped
|
|
||||||
depends_on:
|
|
||||||
- api
|
|
||||||
ports:
|
ports:
|
||||||
# 对外端口(宿主机:容器)。要换对外端口改左侧,例如管理后台用 8000 则 "8000:80"
|
- "${ARTVERIS_PORT:-3000}:3000"
|
||||||
- "80:80" # 管理后台(admin)
|
|
||||||
- "8080:8080" # 客户端溯源页
|
|
||||||
volumes:
|
|
||||||
# 前端构建产物挂载(只读):改这两个 dist 路径需先 pnpm -r build
|
|
||||||
- ../apps/admin/dist:/usr/share/nginx/html/admin:ro
|
|
||||||
- ../apps/client/dist:/usr/share/nginx/html/client:ro
|
|
||||||
# Nginx 站点配置(端口/反代规则在此文件内调整)
|
|
||||||
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
|
||||||
|
|
||||||
# 具名数据卷:容器删除后数据仍保留;彻底清空用 `down -v`(谨慎,会丢数据)
|
# 具名数据卷:容器删除后数据仍保留;彻底清空用 `down -v`(谨慎,会丢数据)
|
||||||
volumes:
|
volumes:
|
||||||
artveris_mysql:
|
artveris_mysql:
|
||||||
artveris_redis:
|
|
||||||
artveris_storage:
|
artveris_storage:
|
||||||
artveris_backups:
|
artveris_backups:
|
||||||
|
artveris_runtime:
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
"dev:admin": "pnpm --filter @artveris/admin dev",
|
"dev:admin": "pnpm --filter @artveris/admin dev",
|
||||||
"dev:client": "pnpm --filter @artveris/client dev:client",
|
"dev:client": "pnpm --filter @artveris/client dev:client",
|
||||||
"build": "pnpm -r build",
|
"build": "pnpm -r build",
|
||||||
|
"build:release": "python scripts/build_release.py",
|
||||||
"lint": "pnpm -r lint",
|
"lint": "pnpm -r lint",
|
||||||
"db:up": "docker compose --env-file .env -f docker/docker-compose.dev.yml up -d",
|
"db:up": "docker compose --env-file .env -f docker/docker-compose.dev.yml up -d",
|
||||||
"db:down": "docker compose --env-file .env -f docker/docker-compose.dev.yml down",
|
"db:down": "docker compose --env-file .env -f docker/docker-compose.dev.yml down",
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ export const QUEUE_NAMES = {
|
|||||||
RESTORE: 'restore',
|
RESTORE: 'restore',
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export const SHORT_CODE_LENGTH = 10;
|
export const SHORT_CODE_LENGTH = 12;
|
||||||
|
export const TRACE_CODE_PATTERN = /^\d{12}$/;
|
||||||
|
|
||||||
export const MAX_IMAGE_SIZE = 10 * 1024 * 1024;
|
export const MAX_IMAGE_SIZE = 10 * 1024 * 1024;
|
||||||
export const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
|
export const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
|
||||||
@@ -31,7 +32,7 @@ export const OUTBOUND_IMPORT_COLUMNS: ImportColumn[] = [
|
|||||||
header: '追溯码',
|
header: '追溯码',
|
||||||
required: true,
|
required: true,
|
||||||
note: '必填,生码导出文件中的追溯码,定位到具体一件作品。',
|
note: '必填,生码导出文件中的追溯码,定位到具体一件作品。',
|
||||||
example: 'a8K3pQ9x2M',
|
example: '482630790612',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
key: 'batchNo',
|
key: 'batchNo',
|
||||||
|
|||||||
@@ -39,6 +39,10 @@ export const ErrorCode = {
|
|||||||
|
|
||||||
export type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode];
|
export type ErrorCodeValue = (typeof ErrorCode)[keyof typeof ErrorCode];
|
||||||
|
|
||||||
|
export const ErrorMessageKey: Record<number, string> = Object.fromEntries(
|
||||||
|
Object.entries(ErrorCode).map(([key, value]) => [value, `error.${key}`]),
|
||||||
|
) as Record<number, string>;
|
||||||
|
|
||||||
// 后端默认中文兜底文案(前端优先用 i18n,缺失时回退此文案)。
|
// 后端默认中文兜底文案(前端优先用 i18n,缺失时回退此文案)。
|
||||||
export const ErrorMessage: Record<number, string> = {
|
export const ErrorMessage: Record<number, string> = {
|
||||||
[ErrorCode.SUCCESS]: '成功',
|
[ErrorCode.SUCCESS]: '成功',
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
export interface ApiResponse<T = unknown> {
|
export interface ApiResponse<T = unknown> {
|
||||||
code: number;
|
code: number;
|
||||||
message: string;
|
message: string;
|
||||||
|
messageKey?: string;
|
||||||
|
params?: Record<string, unknown>;
|
||||||
data: T | null;
|
data: T | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Generated
+22
-3
@@ -125,6 +125,9 @@ importers:
|
|||||||
nanoid:
|
nanoid:
|
||||||
specifier: ^3.3.8
|
specifier: ^3.3.8
|
||||||
version: 3.3.15
|
version: 3.3.15
|
||||||
|
prisma:
|
||||||
|
specifier: ^5.22.0
|
||||||
|
version: 5.22.0
|
||||||
qrcode:
|
qrcode:
|
||||||
specifier: ^1.5.4
|
specifier: ^1.5.4
|
||||||
version: 1.5.4
|
version: 1.5.4
|
||||||
@@ -174,9 +177,6 @@ importers:
|
|||||||
jest:
|
jest:
|
||||||
specifier: ^29.7.0
|
specifier: ^29.7.0
|
||||||
version: 29.7.0(@types/node@22.20.0)(ts-node@10.9.2(@types/node@22.20.0)(typescript@5.9.3))
|
version: 29.7.0(@types/node@22.20.0)(ts-node@10.9.2(@types/node@22.20.0)(typescript@5.9.3))
|
||||||
prisma:
|
|
||||||
specifier: ^5.22.0
|
|
||||||
version: 5.22.0
|
|
||||||
ts-jest:
|
ts-jest:
|
||||||
specifier: ^29.2.5
|
specifier: ^29.2.5
|
||||||
version: 29.4.11(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.20.0)(ts-node@10.9.2(@types/node@22.20.0)(typescript@5.9.3)))(typescript@5.9.3)
|
version: 29.4.11(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.20.0)(ts-node@10.9.2(@types/node@22.20.0)(typescript@5.9.3)))(typescript@5.9.3)
|
||||||
@@ -221,6 +221,25 @@ importers:
|
|||||||
specifier: ^5.4.11
|
specifier: ^5.4.11
|
||||||
version: 5.4.21(@types/node@22.20.0)(terser@5.48.0)
|
version: 5.4.21(@types/node@22.20.0)(terser@5.48.0)
|
||||||
|
|
||||||
|
apps/install:
|
||||||
|
dependencies:
|
||||||
|
axios:
|
||||||
|
specifier: ^1.7.9
|
||||||
|
version: 1.18.1
|
||||||
|
vue:
|
||||||
|
specifier: ^3.5.13
|
||||||
|
version: 3.5.39(typescript@5.9.3)
|
||||||
|
devDependencies:
|
||||||
|
'@vitejs/plugin-vue':
|
||||||
|
specifier: ^5.2.1
|
||||||
|
version: 5.2.4(vite@5.4.21(@types/node@22.20.0)(terser@5.48.0))(vue@3.5.39(typescript@5.9.3))
|
||||||
|
typescript:
|
||||||
|
specifier: ^5.6.3
|
||||||
|
version: 5.9.3
|
||||||
|
vite:
|
||||||
|
specifier: ^5.4.11
|
||||||
|
version: 5.4.21(@types/node@22.20.0)(terser@5.48.0)
|
||||||
|
|
||||||
packages/shared:
|
packages/shared:
|
||||||
devDependencies:
|
devDependencies:
|
||||||
typescript:
|
typescript:
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
# /// script
|
||||||
|
# requires-python = ">=3.9"
|
||||||
|
# dependencies = ["pyyaml"]
|
||||||
|
# ///
|
||||||
|
"""Build a portable Artveris release archive.
|
||||||
|
|
||||||
|
The archive contains the compiled API, admin/client/install static assets,
|
||||||
|
runtime templates, and PM2 startup config. It does not bake database, Redis,
|
||||||
|
domain, OSS, CDN, or blockchain secrets into the build.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
import zipfile
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
DIST = ROOT / ".release"
|
||||||
|
|
||||||
|
|
||||||
|
def run(cmd: str) -> None:
|
||||||
|
print(f"[artveris-release] $ {cmd}")
|
||||||
|
proc = subprocess.run(cmd, cwd=str(ROOT), shell=True)
|
||||||
|
if proc.returncode != 0:
|
||||||
|
sys.exit(proc.returncode)
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_pnpm() -> None:
|
||||||
|
if shutil.which("pnpm"):
|
||||||
|
return
|
||||||
|
if not shutil.which("corepack"):
|
||||||
|
raise SystemExit("pnpm/corepack not found. Please install Node.js 20+.")
|
||||||
|
run("corepack enable")
|
||||||
|
run("corepack prepare pnpm@10.28.0 --activate")
|
||||||
|
|
||||||
|
|
||||||
|
def copytree(src: Path, dst: Path) -> None:
|
||||||
|
if dst.exists():
|
||||||
|
shutil.rmtree(dst)
|
||||||
|
shutil.copytree(src, dst)
|
||||||
|
|
||||||
|
|
||||||
|
def write_json(path: Path, data: dict) -> None:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def write_text(path: Path, text: str) -> None:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_text(text, encoding="utf-8", newline="\n")
|
||||||
|
|
||||||
|
|
||||||
|
def build() -> Path:
|
||||||
|
stamp = datetime.now().strftime("%Y%m%d%H%M%S")
|
||||||
|
package_dir = DIST / f"artveris-{stamp}"
|
||||||
|
if DIST.exists():
|
||||||
|
shutil.rmtree(DIST)
|
||||||
|
package_dir.mkdir(parents=True)
|
||||||
|
|
||||||
|
ensure_pnpm()
|
||||||
|
run("pnpm install --frozen-lockfile")
|
||||||
|
run("pnpm build:shared")
|
||||||
|
run("pnpm --filter @artveris/api exec prisma generate")
|
||||||
|
run("pnpm --filter @artveris/api build")
|
||||||
|
run("pnpm --filter @artveris/admin build")
|
||||||
|
run("pnpm --filter @artveris/client build")
|
||||||
|
run("pnpm --filter @artveris/install build")
|
||||||
|
|
||||||
|
copytree(ROOT / "apps/api/dist", package_dir / "apps/api/dist")
|
||||||
|
copytree(ROOT / "apps/api/prisma", package_dir / "apps/api/prisma")
|
||||||
|
shutil.copy2(ROOT / "apps/api/package.json", package_dir / "apps/api/package.json")
|
||||||
|
shared_dir = package_dir / "packages/shared"
|
||||||
|
shared_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(ROOT / "packages/shared/package.json", shared_dir / "package.json")
|
||||||
|
copytree(ROOT / "packages/shared/dist", shared_dir / "dist")
|
||||||
|
for app in ("admin", "client", "install"):
|
||||||
|
app_dir = package_dir / "apps" / app
|
||||||
|
app_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(ROOT / "apps" / app / "package.json", app_dir / "package.json")
|
||||||
|
copytree(ROOT / "apps/admin/dist", package_dir / "apps/api/public/admin")
|
||||||
|
copytree(ROOT / "apps/client/dist", package_dir / "apps/api/public/trace")
|
||||||
|
copytree(ROOT / "apps/install/dist", package_dir / "apps/api/public/install")
|
||||||
|
shutil.copy2(ROOT / "package.json", package_dir / "package.json")
|
||||||
|
shutil.copy2(ROOT / "pnpm-lock.yaml", package_dir / "pnpm-lock.yaml")
|
||||||
|
shutil.copy2(ROOT / "pnpm-workspace.yaml", package_dir / "pnpm-workspace.yaml")
|
||||||
|
shutil.copy2(ROOT / ".env.example", package_dir / ".env.example")
|
||||||
|
|
||||||
|
write_json(
|
||||||
|
package_dir / "ecosystem.config.cjs",
|
||||||
|
{
|
||||||
|
"apps": [
|
||||||
|
{
|
||||||
|
"name": "artveris",
|
||||||
|
"cwd": "./apps/api",
|
||||||
|
"script": "dist/main.js",
|
||||||
|
"instances": 1,
|
||||||
|
"exec_mode": "fork",
|
||||||
|
"env": {
|
||||||
|
"NODE_ENV": "production",
|
||||||
|
"ARTVERIS_RUNTIME_DIR": "../../runtime",
|
||||||
|
"ARTVERIS_PUBLIC_DIR": "./public",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
)
|
||||||
|
write_text(
|
||||||
|
package_dir / "install-deps.sh",
|
||||||
|
"""#!/usr/bin/env sh
|
||||||
|
set -eu
|
||||||
|
pnpm install --prod --frozen-lockfile
|
||||||
|
pnpm --dir apps/api exec prisma generate --schema ./prisma/schema.prisma
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
write_text(
|
||||||
|
package_dir / "install-deps.ps1",
|
||||||
|
"""$ErrorActionPreference = 'Stop'
|
||||||
|
pnpm install --prod --frozen-lockfile
|
||||||
|
pnpm --dir apps/api exec prisma generate --schema ./prisma/schema.prisma
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
write_text(
|
||||||
|
package_dir / "README-deploy.md",
|
||||||
|
"""# Artveris Release
|
||||||
|
|
||||||
|
1. Install Node.js 20+ and pnpm.
|
||||||
|
2. Run `sh install-deps.sh` in this directory.
|
||||||
|
3. Start with `pm2 start ecosystem.config.cjs`.
|
||||||
|
4. Open `http://server:3000/install` for first-time initialization.
|
||||||
|
|
||||||
|
After installation the process exits once. PM2, systemd, 1Panel, BaoTa, or Docker
|
||||||
|
should restart it automatically, then `/admin`, `/trace`, `/api`, `/t/:code`,
|
||||||
|
and `/uploads` are served by the same port.
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
|
zip_path = DIST / f"{package_dir.name}.zip"
|
||||||
|
tar_path = DIST / f"{package_dir.name}.tar.gz"
|
||||||
|
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
for file in package_dir.rglob("*"):
|
||||||
|
zf.write(file, file.relative_to(package_dir.parent))
|
||||||
|
with tarfile.open(tar_path, "w:gz") as tf:
|
||||||
|
tf.add(package_dir, arcname=package_dir.name)
|
||||||
|
return package_dir
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
package_dir = build()
|
||||||
|
print("[artveris] Release package created:")
|
||||||
|
print(f" {package_dir}")
|
||||||
|
print(f" {package_dir.with_suffix('.zip')}")
|
||||||
|
print(f" {package_dir.with_suffix('.tar.gz')}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user