fix: 修复后端竞态/安全/数据处理问题并移除冗余 outImage 列
首次激活改条件更新消除并发竞态;备份恢复补模型全集与版本校验防清库; 审核列表分页总数、操作日志未捕获 Promise、出库导入重复码、加密密钥可编辑、 溯源码盐以 env 为准、证书按 originKey reconcile、env 加载去重等修复; 新增 parseBigId 防非法入参 500、全局安全响应头、去除 SVG 上传、接入 throttler 限流、 入队失败补偿、hashData 稳定序列化、无效码负缓存、看板已激活口径调整; 移除冗余 TraceCode.outImage 列统一 outImages(迁移 drop_trace_code_out_image)。
This commit is contained in:
@@ -32,6 +32,7 @@
|
|||||||
"@nestjs/schedule": "^6.1.3",
|
"@nestjs/schedule": "^6.1.3",
|
||||||
"@nestjs/serve-static": "^4.0.2",
|
"@nestjs/serve-static": "^4.0.2",
|
||||||
"@nestjs/swagger": "^8.1.0",
|
"@nestjs/swagger": "^8.1.0",
|
||||||
|
"@nestjs/throttler": "^6.5.0",
|
||||||
"@prisma/client": "^5.22.0",
|
"@prisma/client": "^5.22.0",
|
||||||
"adm-zip": "^0.5.18",
|
"adm-zip": "^0.5.18",
|
||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- 统一出库实况图为多图 JSON 字段 out_images,移除冗余的单图列 out_image。
|
||||||
|
-- 先把仍只有 out_image 的历史数据并入 out_images,再删除该列。
|
||||||
|
UPDATE `trace_code`
|
||||||
|
SET `out_images` = JSON_ARRAY(JSON_OBJECT('key', `out_image`, 'type', 'image'))
|
||||||
|
WHERE `out_image` IS NOT NULL AND `out_image` <> '' AND `out_images` IS NULL;
|
||||||
|
|
||||||
|
ALTER TABLE `trace_code` DROP COLUMN `out_image`;
|
||||||
@@ -313,7 +313,6 @@ model TraceCode {
|
|||||||
batchId Int @map("batch_id")
|
batchId Int @map("batch_id")
|
||||||
groupId Int? @map("group_id")
|
groupId Int? @map("group_id")
|
||||||
outTime DateTime? @map("out_time")
|
outTime DateTime? @map("out_time")
|
||||||
outImage String? @map("out_image")
|
|
||||||
outImages Json? @map("out_images")
|
outImages Json? @map("out_images")
|
||||||
remark String?
|
remark String?
|
||||||
status TraceCodeStatus @default(INACTIVE)
|
status TraceCodeStatus @default(INACTIVE)
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
const { PrismaClient, RoleType, UserStatus } = require('@prisma/client');
|
|
||||||
const bcrypt = require('bcryptjs');
|
|
||||||
|
|
||||||
const prisma = new PrismaClient();
|
|
||||||
|
|
||||||
async function ensureAdmin() {
|
|
||||||
const username = process.env.SEED_ADMIN_USERNAME || 'admin';
|
|
||||||
const password = process.env.SEED_ADMIN_PASSWORD || 'Admin@12345';
|
|
||||||
const realName = process.env.SEED_ADMIN_NAME || '超级管理员';
|
|
||||||
|
|
||||||
const existing = await prisma.sysUser.findUnique({ where: { username } });
|
|
||||||
if (existing) return;
|
|
||||||
|
|
||||||
await prisma.sysUser.create({
|
|
||||||
data: {
|
|
||||||
username,
|
|
||||||
passwordHash: await bcrypt.hash(password, 10),
|
|
||||||
realName,
|
|
||||||
role: RoleType.SUPER_ADMIN,
|
|
||||||
status: UserStatus.ACTIVE,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
console.log(`[seed-production] 已创建超级管理员:${username}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function ensureSettings() {
|
|
||||||
const defaults = {
|
|
||||||
appName: process.env.APP_NAME || '艺术品溯源平台',
|
|
||||||
appIconUrl: '',
|
|
||||||
logRetentionDays: process.env.LOG_RETENTION_DAYS || '365',
|
|
||||||
operationLogRetentionDays: process.env.OPERATION_LOG_RETENTION_DAYS || '365',
|
|
||||||
watermarkText: process.env.WATERMARK_TEXT || '仅供溯源核验使用',
|
|
||||||
filingInfo: '备案信息待补充',
|
|
||||||
backupEnabled: 'false',
|
|
||||||
backupSchedule: 'off',
|
|
||||||
backupRetentionDays: '30',
|
|
||||||
backupRetentionCount: '10',
|
|
||||||
clientCarouselInterval: '5',
|
|
||||||
};
|
|
||||||
|
|
||||||
for (const [key, value] of Object.entries(defaults)) {
|
|
||||||
await prisma.systemSetting.upsert({
|
|
||||||
where: { key },
|
|
||||||
update: {},
|
|
||||||
create: { key, value },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
await ensureAdmin();
|
|
||||||
await ensureSettings();
|
|
||||||
}
|
|
||||||
|
|
||||||
main()
|
|
||||||
.catch((error) => {
|
|
||||||
console.error('[seed-production] 初始化失败', error);
|
|
||||||
process.exit(1);
|
|
||||||
})
|
|
||||||
.finally(async () => {
|
|
||||||
await prisma.$disconnect();
|
|
||||||
});
|
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
import { ConfigModule } from '@nestjs/config';
|
||||||
import { ScheduleModule } from '@nestjs/schedule';
|
import { ScheduleModule } from '@nestjs/schedule';
|
||||||
|
import { APP_GUARD } from '@nestjs/core';
|
||||||
|
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
|
||||||
import configuration from './config/configuration';
|
import configuration from './config/configuration';
|
||||||
import { PrismaModule } from './prisma/prisma.module';
|
import { PrismaModule } from './prisma/prisma.module';
|
||||||
import { AppController } from './app.controller';
|
import { AppController } from './app.controller';
|
||||||
@@ -31,9 +33,11 @@ import { InstallModule } from './install/install.module';
|
|||||||
ConfigModule.forRoot({
|
ConfigModule.forRoot({
|
||||||
isGlobal: true,
|
isGlobal: true,
|
||||||
load: [configuration],
|
load: [configuration],
|
||||||
envFilePath: ['../../.env', '.env'],
|
ignoreEnvFile: true,
|
||||||
}),
|
}),
|
||||||
ScheduleModule.forRoot(),
|
ScheduleModule.forRoot(),
|
||||||
|
// 全局限流:默认每 IP 60 秒 600 次(宽松兜底);登录/公开溯源在各自处理器加严格限流
|
||||||
|
ThrottlerModule.forRoot([{ ttl: 60_000, limit: 600 }]),
|
||||||
PrismaModule,
|
PrismaModule,
|
||||||
RedisModule,
|
RedisModule,
|
||||||
StorageModule,
|
StorageModule,
|
||||||
@@ -58,5 +62,6 @@ import { InstallModule } from './install/install.module';
|
|||||||
InstallModule,
|
InstallModule,
|
||||||
],
|
],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
|
providers: [{ provide: APP_GUARD, useClass: ThrottlerGuard }],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
@@ -326,7 +326,11 @@ export class ArtworkService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async auditList(query: QueryArtworkRevisionDto) {
|
async auditList(query: QueryArtworkRevisionDto) {
|
||||||
const where: Prisma.ArtworkRevisionWhereInput = {};
|
// 把作品维度的过滤(未删除、非草稿)下推到 where.artwork,
|
||||||
|
// 使 count 与 findMany 用同一条件,避免分页总数虚高、末页出现空行
|
||||||
|
const where: Prisma.ArtworkRevisionWhereInput = {
|
||||||
|
artwork: { deletedAt: null, status: { not: ArtworkStatus.DRAFT } },
|
||||||
|
};
|
||||||
if (query.status) where.status = query.status;
|
if (query.status) where.status = query.status;
|
||||||
else where.status = ArtworkRevisionStatus.PENDING;
|
else where.status = ArtworkRevisionStatus.PENDING;
|
||||||
if (query.keyword) {
|
if (query.keyword) {
|
||||||
@@ -359,7 +363,6 @@ export class ArtworkService {
|
|||||||
this.prisma.artworkRevision.count({ where }),
|
this.prisma.artworkRevision.count({ where }),
|
||||||
]);
|
]);
|
||||||
const list = rows
|
const list = rows
|
||||||
.filter((r) => !r.artwork.deletedAt && r.artwork.status !== ArtworkStatus.DRAFT)
|
|
||||||
.map((r) => {
|
.map((r) => {
|
||||||
const after = this.snapshotWithUrls(r.afterSnapshot) as ArtworkSnapshot & {
|
const after = this.snapshotWithUrls(r.afterSnapshot) as ArtworkSnapshot & {
|
||||||
artwork?: { images?: Array<MediaItem & { url: string }> };
|
artwork?: { images?: Array<MediaItem & { url: string }> };
|
||||||
@@ -680,19 +683,33 @@ export class ArtworkService {
|
|||||||
})),
|
})),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
await tx.certificate.deleteMany({ where: { artworkId: id } });
|
// 证书按 originFileUrl(originKey) reconcile,而非全删重建:
|
||||||
if (snapshot.certificates.length) {
|
// 未变的原件保留原证书 id 与已生成的 watermarkFileUrl,避免 ID 漂移和重复水印任务;
|
||||||
await tx.certificate.createMany({
|
// 只删除快照中不再存在的证书、更新元数据、新增缺失证书。
|
||||||
data: snapshot.certificates.map((cert) => ({
|
const existingCerts = await tx.certificate.findMany({ where: { artworkId: id } });
|
||||||
artworkId: id,
|
const snapshotOriginKeys = new Set(snapshot.certificates.map((c) => c.originKey));
|
||||||
|
const staleIds = existingCerts.filter((c) => !snapshotOriginKeys.has(c.originFileUrl)).map((c) => c.id);
|
||||||
|
if (staleIds.length) await tx.certificate.deleteMany({ where: { id: { in: staleIds } } });
|
||||||
|
const byOrigin = new Map(existingCerts.map((c) => [c.originFileUrl, c]));
|
||||||
|
for (const cert of snapshot.certificates) {
|
||||||
|
const prev = byOrigin.get(cert.originKey);
|
||||||
|
const data = {
|
||||||
name: cert.name,
|
name: cert.name,
|
||||||
issuer: cert.issuer,
|
issuer: cert.issuer,
|
||||||
issuedAt: cert.issuedAt ? new Date(cert.issuedAt) : null,
|
issuedAt: cert.issuedAt ? new Date(cert.issuedAt) : null,
|
||||||
type: cert.type as any,
|
type: cert.type as any,
|
||||||
originFileUrl: cert.originKey,
|
};
|
||||||
watermarkFileUrl: cert.watermarkKey ?? null,
|
if (prev) {
|
||||||
})),
|
// 原件不变:保留 id 与 watermarkFileUrl(快照带则以快照为准,否则沿用已生成的)
|
||||||
|
await tx.certificate.update({
|
||||||
|
where: { id: prev.id },
|
||||||
|
data: { ...data, watermarkFileUrl: cert.watermarkKey ?? prev.watermarkFileUrl },
|
||||||
});
|
});
|
||||||
|
} else {
|
||||||
|
await tx.certificate.create({
|
||||||
|
data: { ...data, artworkId: id, originFileUrl: cert.originKey, watermarkFileUrl: cert.watermarkKey ?? null },
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Body, Controller, Get, Post } from '@nestjs/common';
|
import { Body, Controller, Get, Post } from '@nestjs/common';
|
||||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { Throttle } from '@nestjs/throttler';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { LoginDto } from './dto/login.dto';
|
import { LoginDto } from './dto/login.dto';
|
||||||
import { ChangePasswordDto } from './dto/change-password.dto';
|
import { ChangePasswordDto } from './dto/change-password.dto';
|
||||||
@@ -13,6 +14,8 @@ export class AuthController {
|
|||||||
|
|
||||||
@Public()
|
@Public()
|
||||||
@Post('login')
|
@Post('login')
|
||||||
|
// 登录严格限流:每 IP 每分钟最多 10 次,防止离线字典爆破
|
||||||
|
@Throttle({ default: { limit: 10, ttl: 60_000 } })
|
||||||
@ApiOperation({ summary: '登录' })
|
@ApiOperation({ summary: '登录' })
|
||||||
login(@Body() dto: LoginDto) {
|
login(@Body() dto: LoginDto) {
|
||||||
return this.authService.login(dto);
|
return this.authService.login(dto);
|
||||||
|
|||||||
@@ -97,10 +97,38 @@ function reviveRow(row: Record<string, any>): Record<string, any> {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const BACKUP_FORMAT_VERSION = '0.1.0';
|
||||||
|
|
||||||
function isSafeZipPath(path: string): boolean {
|
function isSafeZipPath(path: string): boolean {
|
||||||
return !path.includes('\\') && !path.includes('..') && !path.startsWith('/') && !/^[a-z]:/i.test(path);
|
return !path.includes('\\') && !path.includes('..') && !path.startsWith('/') && !/^[a-z]:/i.test(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 恢复前的强校验:确认是 Artveris 备份、版本主号兼容、且 database.json 覆盖全部业务表,
|
||||||
|
// 防止残缺/异构备份包在「先清空全表再按存在的键写回」时把整库清空。
|
||||||
|
function validateBackupPayload(manifest: any, db: unknown): void {
|
||||||
|
if (!manifest || manifest.app !== 'artveris') {
|
||||||
|
throw new BusinessException(ErrorCode.BAD_REQUEST, '不是 Artveris 备份包');
|
||||||
|
}
|
||||||
|
const version = String(manifest.version || '');
|
||||||
|
if (version.split('.')[0] !== BACKUP_FORMAT_VERSION.split('.')[0]) {
|
||||||
|
throw new BusinessException(
|
||||||
|
ErrorCode.BAD_REQUEST,
|
||||||
|
`备份包版本不兼容(备份 ${version || '未知'},当前 ${BACKUP_FORMAT_VERSION})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!db || typeof db !== 'object' || Array.isArray(db)) {
|
||||||
|
throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包 database.json 结构无效');
|
||||||
|
}
|
||||||
|
const data = db as Record<string, unknown>;
|
||||||
|
const missing = MODELS.filter((model) => !Array.isArray(data[model]));
|
||||||
|
if (missing.length) {
|
||||||
|
throw new BusinessException(
|
||||||
|
ErrorCode.BAD_REQUEST,
|
||||||
|
`备份包缺少数据表:${missing.join(', ')};已中止恢复以避免清空现有数据`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function isSameOrChildPath(parent: string, child: string): boolean {
|
function isSameOrChildPath(parent: string, child: string): boolean {
|
||||||
const rel = relative(resolve(parent), resolve(child));
|
const rel = relative(resolve(parent), resolve(child));
|
||||||
return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
|
return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
|
||||||
@@ -196,7 +224,8 @@ export class BackupService {
|
|||||||
const dbEntry = zip.getEntry('database.json');
|
const dbEntry = zip.getEntry('database.json');
|
||||||
if (!manifestEntry || !dbEntry) throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包缺少 manifest.json 或 database.json');
|
if (!manifestEntry || !dbEntry) throw new BusinessException(ErrorCode.BAD_REQUEST, '备份包缺少 manifest.json 或 database.json');
|
||||||
const manifest = JSON.parse(manifestEntry.getData().toString('utf8'));
|
const manifest = JSON.parse(manifestEntry.getData().toString('utf8'));
|
||||||
if (manifest.app !== 'artveris') throw new BusinessException(ErrorCode.BAD_REQUEST, '不是 Artveris 备份包');
|
const db = JSON.parse(dbEntry.getData().toString('utf8'));
|
||||||
|
validateBackupPayload(manifest, db);
|
||||||
|
|
||||||
const fileName = `restore-${dayjs().format('YYYYMMDDHHmmss')}.zip`;
|
const fileName = `restore-${dayjs().format('YYYYMMDDHHmmss')}.zip`;
|
||||||
const filePath = join(this.backupRoot, fileName);
|
const filePath = join(this.backupRoot, fileName);
|
||||||
@@ -304,8 +333,11 @@ export class BackupService {
|
|||||||
|
|
||||||
private async restoreDatabase(zip: AdmZip) {
|
private async restoreDatabase(zip: AdmZip) {
|
||||||
const entry = zip.getEntry('database.json');
|
const entry = zip.getEntry('database.json');
|
||||||
if (!entry) throw new Error('备份包缺少 database.json');
|
const manifestEntry = zip.getEntry('manifest.json');
|
||||||
|
if (!entry || !manifestEntry) throw new Error('备份包缺少 database.json 或 manifest.json');
|
||||||
const db = JSON.parse(entry.getData().toString('utf8'));
|
const db = JSON.parse(entry.getData().toString('utf8'));
|
||||||
|
// 清库前再次校验,纵深防御,避免绕过 preview 直接 commit 的坏包清空数据
|
||||||
|
validateBackupPayload(JSON.parse(manifestEntry.getData().toString('utf8')), db);
|
||||||
await this.prisma.$transaction(async (tx) => {
|
await this.prisma.$transaction(async (tx) => {
|
||||||
for (const model of DELETE_ORDER) {
|
for (const model of DELETE_ORDER) {
|
||||||
await (tx as any)[model].deleteMany();
|
await (tx as any)[model].deleteMany();
|
||||||
|
|||||||
@@ -36,7 +36,6 @@ export class AttestationService {
|
|||||||
batchNo: code.batch.batchNo,
|
batchNo: code.batch.batchNo,
|
||||||
outbound: {
|
outbound: {
|
||||||
outTime: code.outTime,
|
outTime: code.outTime,
|
||||||
outImage: code.outImage,
|
|
||||||
outImages: code.outImages,
|
outImages: code.outImages,
|
||||||
},
|
},
|
||||||
dynamicFields: code.artwork.dynamicFields,
|
dynamicFields: code.artwork.dynamicFields,
|
||||||
@@ -52,10 +51,30 @@ export class AttestationService {
|
|||||||
rawResponse: { requestMeta: summary },
|
rawResponse: { requestMeta: summary },
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
// 入队失败(如 Redis 抖动)时把 proof 标记 FAILED,避免留下永远处理不了的 PENDING 悬挂记录
|
||||||
|
try {
|
||||||
await this.queue.add('onchain', { proofId: proof.id });
|
await this.queue.add('onchain', { proofId: proof.id });
|
||||||
|
} catch (e) {
|
||||||
|
await this.markQueueFailed(proof.id, proof.rawResponse, e);
|
||||||
|
throw new BusinessException(ErrorCode.INTERNAL_ERROR, '上链任务入队失败,请稍后重试');
|
||||||
|
}
|
||||||
return proof;
|
return proof;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async markQueueFailed(proofId: number, raw: unknown, e: unknown) {
|
||||||
|
await this.prisma.blockchainProof.update({
|
||||||
|
where: { id: proofId },
|
||||||
|
data: {
|
||||||
|
status: ProofStatus.FAILED,
|
||||||
|
rawResponse: {
|
||||||
|
...(raw && typeof raw === 'object' ? (raw as object) : {}),
|
||||||
|
enqueueError: (e as Error).message,
|
||||||
|
failedAt: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async retry(proofId: number) {
|
async retry(proofId: number) {
|
||||||
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
|
const proof = await this.prisma.blockchainProof.findUnique({ where: { id: proofId } });
|
||||||
if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '存证记录不存在', 404);
|
if (!proof) throw new BusinessException(ErrorCode.NOT_FOUND, '存证记录不存在', 404);
|
||||||
@@ -75,7 +94,12 @@ export class AttestationService {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
try {
|
||||||
await this.queue.add('onchain', { proofId });
|
await this.queue.add('onchain', { proofId });
|
||||||
|
} catch (e) {
|
||||||
|
await this.markQueueFailed(proofId, proof.rawResponse, e);
|
||||||
|
throw new BusinessException(ErrorCode.INTERNAL_ERROR, '上链任务入队失败,请稍后重试');
|
||||||
|
}
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
|||||||
import { RoleType } from '@artveris/shared';
|
import { RoleType } from '@artveris/shared';
|
||||||
import { AttestationService } from './attestation.service';
|
import { AttestationService } from './attestation.service';
|
||||||
import { Roles } from '../common/decorators/roles.decorator';
|
import { Roles } from '../common/decorators/roles.decorator';
|
||||||
|
import { parseBigId } from '../common/utils/bigint.util';
|
||||||
|
|
||||||
@ApiTags('区块链存证')
|
@ApiTags('区块链存证')
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@@ -14,7 +15,7 @@ export class BlockchainController {
|
|||||||
@Roles(RoleType.OPERATOR)
|
@Roles(RoleType.OPERATOR)
|
||||||
@ApiOperation({ summary: '为追溯码触发数据存证上链' })
|
@ApiOperation({ summary: '为追溯码触发数据存证上链' })
|
||||||
onchain(@Param('id') id: string) {
|
onchain(@Param('id') id: string) {
|
||||||
return this.attestation.trigger(BigInt(id));
|
return this.attestation.trigger(parseBigId(id, '追溯码 ID'));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post('blockchain-proofs/:id/retry')
|
@Post('blockchain-proofs/:id/retry')
|
||||||
|
|||||||
@@ -10,6 +10,15 @@ 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 DEFAULT_TIANHE_USER_ID = 'artveris-platform';
|
const DEFAULT_TIANHE_USER_ID = 'artveris-platform';
|
||||||
|
|
||||||
|
// 递归按 key 排序的稳定序列化,用于内容哈希(与 JSON.stringify 不同,属性顺序不影响结果)
|
||||||
|
function stableStringify(value: unknown): string {
|
||||||
|
if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
|
||||||
|
if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
|
||||||
|
const keys = Object.keys(value as Record<string, unknown>).sort();
|
||||||
|
const entries = keys.map((k) => `${JSON.stringify(k)}:${stableStringify((value as Record<string, unknown>)[k])}`);
|
||||||
|
return `{${entries.join(',')}}`;
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BlockchainService {
|
export class BlockchainService {
|
||||||
private readonly logger = new Logger(BlockchainService.name);
|
private readonly logger = new Logger(BlockchainService.name);
|
||||||
@@ -20,7 +29,8 @@ export class BlockchainService {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
hashData(data: unknown): string {
|
hashData(data: unknown): string {
|
||||||
return '0x' + createHash('sha256').update(JSON.stringify(data)).digest('hex');
|
// 稳定序列化:递归按 key 排序,确保「同数据同哈希」,不受对象属性顺序影响
|
||||||
|
return '0x' + createHash('sha256').update(stableStringify(data)).digest('hex');
|
||||||
}
|
}
|
||||||
|
|
||||||
async attest(payload: AttestPayload): Promise<AttestResult> {
|
async attest(payload: AttestPayload): Promise<AttestResult> {
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { ErrorCode } from '@artveris/shared';
|
||||||
|
import { BusinessException } from '../exceptions/business.exception';
|
||||||
|
|
||||||
|
// 把路径参数/字符串安全转 BigInt。非法输入抛统一 BusinessException(400),
|
||||||
|
// 避免裸 BigInt() 抛原生 SyntaxError 被全局过滤器归为 500。
|
||||||
|
export function parseBigId(value: string | number | bigint, label = 'ID'): bigint {
|
||||||
|
if (typeof value === 'bigint') return value;
|
||||||
|
const text = String(value).trim();
|
||||||
|
if (!/^\d+$/.test(text)) {
|
||||||
|
throw new BusinessException(ErrorCode.BAD_REQUEST, `无效的${label}:${value}`, 400);
|
||||||
|
}
|
||||||
|
return BigInt(text);
|
||||||
|
}
|
||||||
@@ -26,16 +26,14 @@ function loadEnvFile(path: string): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 启动早期把 .env 载入 process.env:优先 ARTVERIS_ENV_FILE / 运行目录 .env,
|
// 启动早期把 .env 载入 process.env:优先 ARTVERIS_ENV_FILE / 运行目录 .env,
|
||||||
// 再兼容仓库根 ../../.env(本地开发时 API 的 cwd 为 apps/api)。
|
// 再兼容仓库根 ../../.env(本地开发时 API 的 cwd 为 apps/api)。去重避免重复加载同一文件。
|
||||||
export function preloadRuntimeEnv(): void {
|
export function preloadRuntimeEnv(): void {
|
||||||
loadEnvFile(envFilePath());
|
const seen = new Set<string>();
|
||||||
loadEnvFile(resolve(process.cwd(), '.env'));
|
for (const path of [envFilePath(), resolve(process.cwd(), '.env'), resolve(process.cwd(), '../../.env')]) {
|
||||||
loadEnvFile(resolve(process.cwd(), '../../.env'));
|
if (seen.has(path)) continue;
|
||||||
}
|
seen.add(path);
|
||||||
|
loadEnvFile(path);
|
||||||
export function isInstalled(): boolean {
|
}
|
||||||
preloadRuntimeEnv();
|
|
||||||
return Boolean(process.env.DATABASE_URL) || existsSync(envFilePath());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isInstallMode(): boolean {
|
export function isInstallMode(): boolean {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { QueryResult, TraceCodeStatus } from '@artveris/shared';
|
import { QueryResult } from '@artveris/shared';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
|
||||||
export interface DashboardOverviewQuery {
|
export interface DashboardOverviewQuery {
|
||||||
@@ -37,7 +37,8 @@ export class DashboardService {
|
|||||||
] = await this.prisma.$transaction([
|
] = await this.prisma.$transaction([
|
||||||
this.prisma.artwork.count({ where: { deletedAt: null } }),
|
this.prisma.artwork.count({ where: { deletedAt: null } }),
|
||||||
this.prisma.traceCode.count(),
|
this.prisma.traceCode.count(),
|
||||||
this.prisma.traceCode.count({ where: { status: TraceCodeStatus.ACTIVE } }),
|
// 已激活口径:累计激活过(firstActivatedAt 非空),激活后又被停用/异常的仍计入
|
||||||
|
this.prisma.traceCode.count({ where: { firstActivatedAt: { not: null } } }),
|
||||||
this.prisma.queryLog.count(),
|
this.prisma.queryLog.count(),
|
||||||
this.prisma.queryLog.count({ where: { queriedAt: { gte: todayStart } } }),
|
this.prisma.queryLog.count({ where: { queriedAt: { gte: todayStart } } }),
|
||||||
this.prisma.queryLog.count({
|
this.prisma.queryLog.count({
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { InstallModule } from './install/install.module';
|
|||||||
ConfigModule.forRoot({
|
ConfigModule.forRoot({
|
||||||
isGlobal: true,
|
isGlobal: true,
|
||||||
load: [configuration],
|
load: [configuration],
|
||||||
envFilePath: ['../../.env', '.env'],
|
ignoreEnvFile: true,
|
||||||
}),
|
}),
|
||||||
InstallModule,
|
InstallModule,
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -49,6 +49,18 @@ async function bootstrap(): Promise<void> {
|
|||||||
credentials: true,
|
credentials: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 最小安全响应头:禁止 MIME 嗅探、禁止被 iframe 嵌套、限制 Referer 外泄
|
||||||
|
const httpAdapter = app.getHttpAdapter().getInstance();
|
||||||
|
httpAdapter.disable('x-powered-by');
|
||||||
|
// 信任前置反代(Nginx/宝塔/1Panel)的 X-Forwarded-For,使限流与日志拿到真实客户端 IP
|
||||||
|
httpAdapter.set('trust proxy', 1);
|
||||||
|
app.use((_req: unknown, res: { setHeader: (k: string, v: string) => void }, next: () => void) => {
|
||||||
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||||
|
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
|
||||||
|
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
app.useGlobalPipes(
|
app.useGlobalPipes(
|
||||||
new ValidationPipe({
|
new ValidationPipe({
|
||||||
whitelist: true,
|
whitelist: true,
|
||||||
@@ -80,6 +92,9 @@ async function bootstrap(): Promise<void> {
|
|||||||
immutable: true,
|
immutable: true,
|
||||||
setHeaders: (res) => {
|
setHeaders: (res) => {
|
||||||
res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL);
|
res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL);
|
||||||
|
// 纵深防御:即便历史遗留 svg 等,直接打开也不作为可执行文档渲染
|
||||||
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||||
|
res.setHeader('Content-Disposition', 'inline');
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
mountSpa(app, '/admin', resolve(publicRoot, 'admin'));
|
mountSpa(app, '/admin', resolve(publicRoot, 'admin'));
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common';
|
||||||
import { Request } from 'express';
|
import { Request } from 'express';
|
||||||
import { Observable, throwError } from 'rxjs';
|
import { Observable, throwError } from 'rxjs';
|
||||||
import { catchError, tap } from 'rxjs/operators';
|
import { catchError, tap } from 'rxjs/operators';
|
||||||
@@ -79,8 +79,15 @@ function shouldLog(method: string, path: string): boolean {
|
|||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class OperationLogInterceptor implements NestInterceptor {
|
export class OperationLogInterceptor implements NestInterceptor {
|
||||||
|
private readonly logger = new Logger(OperationLogInterceptor.name);
|
||||||
|
|
||||||
constructor(private readonly logs: OperationLogService) {}
|
constructor(private readonly logs: OperationLogService) {}
|
||||||
|
|
||||||
|
private write(data: Parameters<OperationLogService['create']>[0]): void {
|
||||||
|
// 操作日志写入失败不应影响主流程,也不能抛未捕获 Promise
|
||||||
|
this.logs.create(data).catch((e) => this.logger.warn(`操作日志写入失败:${(e as Error).message}`));
|
||||||
|
}
|
||||||
|
|
||||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||||
const req = context.switchToHttp().getRequest<Request & { user?: AuthUser }>();
|
const req = context.switchToHttp().getRequest<Request & { user?: AuthUser }>();
|
||||||
const method = req.method.toUpperCase();
|
const method = req.method.toUpperCase();
|
||||||
@@ -105,14 +112,14 @@ export class OperationLogInterceptor implements NestInterceptor {
|
|||||||
|
|
||||||
return next.handle().pipe(
|
return next.handle().pipe(
|
||||||
tap(() => {
|
tap(() => {
|
||||||
void this.logs.create({
|
this.write({
|
||||||
...base,
|
...base,
|
||||||
status: 'SUCCESS',
|
status: 'SUCCESS',
|
||||||
durationMs: Date.now() - started,
|
durationMs: Date.now() - started,
|
||||||
});
|
});
|
||||||
}),
|
}),
|
||||||
catchError((err) => {
|
catchError((err) => {
|
||||||
void this.logs.create({
|
this.write({
|
||||||
...base,
|
...base,
|
||||||
status: 'FAILED',
|
status: 'FAILED',
|
||||||
message: (err as Error)?.message || String(err),
|
message: (err as Error)?.message || String(err),
|
||||||
|
|||||||
@@ -34,6 +34,13 @@ function parseDate(v?: string): Date | undefined | null {
|
|||||||
return Number.isNaN(d.getTime()) ? null : d;
|
return Number.isNaN(d.getTime()) ? null : d;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function mimeOf(path: string): string {
|
||||||
|
const ext = path.slice(path.lastIndexOf('.')).toLowerCase();
|
||||||
|
if (ext === '.png') return 'image/png';
|
||||||
|
if (ext === '.webp') return 'image/webp';
|
||||||
|
return 'image/jpeg';
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeImagePath(raw: string): string {
|
function normalizeImagePath(raw: string): string {
|
||||||
const p = raw.trim().replace(/^image\//i, 'images/');
|
const p = raw.trim().replace(/^image\//i, 'images/');
|
||||||
if (!p) return '';
|
if (!p) return '';
|
||||||
@@ -94,6 +101,7 @@ export class ImportPreviewProcessor extends WorkerHost {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const storedImages = new Map<string, { key: string; url: string; name: string; type: string }>();
|
const storedImages = new Map<string, { key: string; url: string; name: string; type: string }>();
|
||||||
|
const seenShortCodes = new Map<string, number>(); // shortCode -> 首次出现行号,用于包内去重
|
||||||
const rows: any[] = [];
|
const rows: any[] = [];
|
||||||
let valid = 0;
|
let valid = 0;
|
||||||
let invalid = 0;
|
let invalid = 0;
|
||||||
@@ -122,6 +130,11 @@ export class ImportPreviewProcessor extends WorkerHost {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (!values.shortCode) throw new Error('追溯码为空');
|
if (!values.shortCode) throw new Error('追溯码为空');
|
||||||
|
const firstRow = seenShortCodes.get(values.shortCode);
|
||||||
|
if (firstRow) {
|
||||||
|
throw new Error(`追溯码在本次导入中重复(首次出现于第 ${firstRow} 行)`);
|
||||||
|
}
|
||||||
|
seenShortCodes.set(values.shortCode, r);
|
||||||
const code = await this.prisma.traceCode.findUnique({
|
const code = await this.prisma.traceCode.findUnique({
|
||||||
where: { shortCode: values.shortCode },
|
where: { shortCode: values.shortCode },
|
||||||
include: { batch: true },
|
include: { batch: true },
|
||||||
@@ -144,7 +157,7 @@ export class ImportPreviewProcessor extends WorkerHost {
|
|||||||
if (!img) throw new Error(`图片不存在:${p}`);
|
if (!img) throw new Error(`图片不存在:${p}`);
|
||||||
if (!storedImages.has(p)) {
|
if (!storedImages.has(p)) {
|
||||||
await sharp(img).metadata();
|
await sharp(img).metadata();
|
||||||
const saved = await this.storage.save(img, p.split('/').pop() || 'outbound.jpg', `image/${p.endsWith('.png') ? 'png' : 'jpeg'}`);
|
const saved = await this.storage.save(img, p.split('/').pop() || 'outbound.jpg', mimeOf(p));
|
||||||
storedImages.set(p, { key: saved.key, url: saved.url, name: saved.name, type: 'image' });
|
storedImages.set(p, { key: saved.key, url: saved.url, name: saved.name, type: 'image' });
|
||||||
}
|
}
|
||||||
imageItems.push(storedImages.get(p)!);
|
imageItems.push(storedImages.get(p)!);
|
||||||
|
|||||||
@@ -47,7 +47,6 @@ export class ImportProcessor extends WorkerHost {
|
|||||||
where: { id: code.id },
|
where: { id: code.id },
|
||||||
data: {
|
data: {
|
||||||
outTime: row.outTime ?? undefined,
|
outTime: row.outTime ?? undefined,
|
||||||
outImage: imageItems[0]?.key || undefined,
|
|
||||||
outImages: imageItems.length
|
outImages: imageItems.length
|
||||||
? imageItems.map((item) => ({ key: item.key, name: item.name, type: item.type || 'image' }))
|
? imageItems.map((item) => ({ key: item.key, name: item.name, type: item.type || 'image' }))
|
||||||
: undefined,
|
: undefined,
|
||||||
@@ -68,16 +67,22 @@ export class ImportProcessor extends WorkerHost {
|
|||||||
|
|
||||||
const resultUrl = await this.buildResultFile(sessionId);
|
const resultUrl = await this.buildResultFile(sessionId);
|
||||||
const status = fail === 0 ? JobStatus.SUCCESS : success === 0 ? JobStatus.FAILED : JobStatus.PARTIAL;
|
const status = fail === 0 ? JobStatus.SUCCESS : success === 0 ? JobStatus.FAILED : JobStatus.PARTIAL;
|
||||||
|
const imported = fail === 0;
|
||||||
|
const session = await this.prisma.outboundImportSession.findUnique({ where: { id: sessionId }, select: { fileKey: true } });
|
||||||
await this.prisma.$transaction([
|
await this.prisma.$transaction([
|
||||||
this.prisma.outboundImportSession.update({
|
this.prisma.outboundImportSession.update({
|
||||||
where: { id: sessionId },
|
where: { id: sessionId },
|
||||||
data: { status: fail === 0 ? 'IMPORTED' : 'FAILED' },
|
data: { status: imported ? 'IMPORTED' : 'FAILED', fileKey: imported ? null : undefined },
|
||||||
}),
|
}),
|
||||||
this.prisma.job.update({
|
this.prisma.job.update({
|
||||||
where: { id: jobId },
|
where: { id: jobId },
|
||||||
data: { total: rows.length, successCount: success, failCount: fail, status, resultFileUrl: resultUrl },
|
data: { total: rows.length, successCount: success, failCount: fail, status, resultFileUrl: resultUrl },
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
// 导入成功后删除原始上传 ZIP,避免长期占用存储(预览图片已成为业务数据,保留)
|
||||||
|
if (imported && session?.fileKey) {
|
||||||
|
await this.storage.remove(session.fileKey).catch((e) => this.logger.warn(`删除导入 ZIP 失败:${(e as Error).message}`));
|
||||||
|
}
|
||||||
this.logger.log(`出库导入完成:成功 ${success},失败 ${fail}`);
|
this.logger.log(`出库导入完成:成功 ${success},失败 ${fail}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import { OutboundDto } from './dto/outbound.dto';
|
|||||||
import { QueryImportRowsDto } from './dto/import-session.dto';
|
import { QueryImportRowsDto } from './dto/import-session.dto';
|
||||||
import { Roles } from '../common/decorators/roles.decorator';
|
import { Roles } from '../common/decorators/roles.decorator';
|
||||||
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
||||||
|
import { parseBigId } from '../common/utils/bigint.util';
|
||||||
|
|
||||||
@ApiTags('出库与上链')
|
@ApiTags('出库与上链')
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@@ -30,7 +31,7 @@ export class OutboundController {
|
|||||||
@Roles(RoleType.OPERATOR)
|
@Roles(RoleType.OPERATOR)
|
||||||
@ApiOperation({ summary: '单条登记出库 / 上链信息' })
|
@ApiOperation({ summary: '单条登记出库 / 上链信息' })
|
||||||
updateSingle(@Param('id') id: string, @Body() dto: OutboundDto) {
|
updateSingle(@Param('id') id: string, @Body() dto: OutboundDto) {
|
||||||
return this.outboundService.updateSingle(BigInt(id), dto);
|
return this.outboundService.updateSingle(parseBigId(id, '追溯码 ID'), dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('import/template')
|
@Get('import/template')
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import * as ExcelJS from 'exceljs';
|
|||||||
import AdmZip from 'adm-zip';
|
import AdmZip from 'adm-zip';
|
||||||
import sharp from 'sharp';
|
import sharp from 'sharp';
|
||||||
import { Prisma, RoleType } from '@prisma/client';
|
import { Prisma, RoleType } from '@prisma/client';
|
||||||
import { ErrorCode, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
|
import { ErrorCode, JobStatus, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
import { StorageService } from '../storage/storage.service';
|
import { StorageService } from '../storage/storage.service';
|
||||||
import { JobsService } from '../jobs/jobs.service';
|
import { JobsService } from '../jobs/jobs.service';
|
||||||
@@ -37,10 +37,10 @@ export class OutboundService {
|
|||||||
const data: Prisma.TraceCodeUpdateInput = {};
|
const data: Prisma.TraceCodeUpdateInput = {};
|
||||||
if ('outTime' in dto) data.outTime = dto.outTime ? new Date(dto.outTime) : null;
|
if ('outTime' in dto) data.outTime = dto.outTime ? new Date(dto.outTime) : null;
|
||||||
if ('outImageKeys' in dto || 'outImageKey' in dto) {
|
if ('outImageKeys' in dto || 'outImageKey' in dto) {
|
||||||
data.outImage = imageKeys[0] || null;
|
// 无图时写 DB NULL(而非 JSON null),保证出库状态筛选一致
|
||||||
data.outImages = imageKeys.length
|
data.outImages = imageKeys.length
|
||||||
? imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' }))
|
? imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' }))
|
||||||
: Prisma.JsonNull;
|
: Prisma.DbNull;
|
||||||
}
|
}
|
||||||
if ('remark' in dto) data.remark = dto.remark || null;
|
if ('remark' in dto) data.remark = dto.remark || null;
|
||||||
return this.prisma.traceCode.update({
|
return this.prisma.traceCode.update({
|
||||||
@@ -184,7 +184,14 @@ export class OutboundService {
|
|||||||
where: { id },
|
where: { id },
|
||||||
data: { status: 'IMPORTING', committedAt: new Date() },
|
data: { status: 'IMPORTING', committedAt: new Date() },
|
||||||
});
|
});
|
||||||
|
// 入队失败时回退会话状态为 READY,避免卡在 IMPORTING 且无对应队列任务
|
||||||
|
try {
|
||||||
await this.importQueue.add('import', { jobId: job.id, sessionId: id });
|
await this.importQueue.add('import', { jobId: job.id, sessionId: id });
|
||||||
|
} catch (e) {
|
||||||
|
await this.prisma.outboundImportSession.update({ where: { id }, data: { status: 'READY', committedAt: null } });
|
||||||
|
await this.jobs.finish(job.id, { status: JobStatus.FAILED, error: (e as Error).message });
|
||||||
|
throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入任务入队失败,请稍后重试');
|
||||||
|
}
|
||||||
return { jobId: job.id, sessionId: id };
|
return { jobId: job.id, sessionId: id };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
|
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
|
||||||
import { Request, Response } from 'express';
|
import { Request, Response } from 'express';
|
||||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { Throttle } from '@nestjs/throttler';
|
||||||
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';
|
||||||
@@ -16,6 +17,8 @@ export class PublicTraceController {
|
|||||||
|
|
||||||
@Public()
|
@Public()
|
||||||
@Get('public/trace/:shortCode')
|
@Get('public/trace/:shortCode')
|
||||||
|
// 公开溯源软限流:每 IP 每分钟 60 次,抑制脚本刷量污染防伪统计与日志
|
||||||
|
@Throttle({ default: { limit: 60, ttl: 60_000 } })
|
||||||
@ApiOperation({ summary: 'C 端溯源查询(匿名)' })
|
@ApiOperation({ summary: 'C 端溯源查询(匿名)' })
|
||||||
trace(@Param('shortCode') shortCode: string, @Req() req: Request) {
|
trace(@Param('shortCode') shortCode: string, @Req() req: Request) {
|
||||||
const ip = extractIp(req.headers as Record<string, unknown>, req.ip);
|
const ip = extractIp(req.headers as Record<string, unknown>, req.ip);
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ export interface TraceContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const MAP_TTL = 3600; // 短码→id 映射缓存 1 小时
|
const MAP_TTL = 3600; // 短码→id 映射缓存 1 小时
|
||||||
const OUTBOUND_TRACE_TITLE = '本件出库记录';
|
const MISS_TTL = 60; // 无效码负缓存 60 秒,降低无效码刷库压力
|
||||||
const OUTBOUND_TRACE_DESC = '该追溯码对应实物的出库实况记录。';
|
const MISS_SENTINEL = '0'; // 负缓存哨兵值(真实 id 从 1 起,不会为 0)
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PublicTraceService {
|
export class PublicTraceService {
|
||||||
@@ -44,12 +44,13 @@ export class PublicTraceService {
|
|||||||
description: string | null;
|
description: string | null;
|
||||||
mediaFiles: unknown;
|
mediaFiles: unknown;
|
||||||
}>,
|
}>,
|
||||||
code: { outTime?: Date | null; outImage?: string | null; outImages?: unknown },
|
code: { outTime?: Date | null; outImages?: unknown },
|
||||||
) {
|
) {
|
||||||
const timeline = nodes.map((n) => ({
|
const timeline = nodes.map((n) => ({
|
||||||
nodeType: n.nodeType,
|
nodeType: n.nodeType,
|
||||||
title: n.title,
|
system: null as string | null,
|
||||||
occurredAt: n.occurredAt,
|
title: n.title as string | null,
|
||||||
|
occurredAt: n.occurredAt as Date | null,
|
||||||
location: n.location,
|
location: n.location,
|
||||||
description: n.description,
|
description: n.description,
|
||||||
media: this.mapMedia(n.mediaFiles),
|
media: this.mapMedia(n.mediaFiles),
|
||||||
@@ -60,17 +61,17 @@ export class PublicTraceService {
|
|||||||
.map((item) => (typeof item === 'string' ? { key: item } : item))
|
.map((item) => (typeof item === 'string' ? { key: item } : item))
|
||||||
.filter((item) => item?.key)
|
.filter((item) => item?.key)
|
||||||
.map((item) => ({ name: item.name || '出库实况图', type: item.type || 'image', url: this.storage.getUrl(item.key as string) }))
|
.map((item) => ({ name: item.name || '出库实况图', type: item.type || 'image', url: this.storage.getUrl(item.key as string) }))
|
||||||
: code.outImage
|
|
||||||
? [{ name: '出库实况图', type: 'image', url: this.storage.getUrl(code.outImage) }]
|
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
if (code.outTime || outMedia.length) {
|
if (code.outTime || outMedia.length) {
|
||||||
|
// 单件出库记录:不下发中文标题/说明,标记 system=OUTBOUND_RECORD 由 C 端按语言本地化
|
||||||
timeline.push({
|
timeline.push({
|
||||||
nodeType: 'OUTBOUND',
|
nodeType: 'OUTBOUND',
|
||||||
title: OUTBOUND_TRACE_TITLE,
|
system: 'OUTBOUND_RECORD',
|
||||||
|
title: null,
|
||||||
occurredAt: code.outTime ?? null,
|
occurredAt: code.outTime ?? null,
|
||||||
location: null,
|
location: null,
|
||||||
description: OUTBOUND_TRACE_DESC,
|
description: null,
|
||||||
media: outMedia,
|
media: outMedia,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -81,12 +82,17 @@ export class PublicTraceService {
|
|||||||
private async resolveId(shortCode: string): Promise<bigint | null> {
|
private async resolveId(shortCode: string): Promise<bigint | null> {
|
||||||
const cacheKey = `trace:map:${shortCode}`;
|
const cacheKey = `trace:map:${shortCode}`;
|
||||||
const cached = await this.redis.get(cacheKey);
|
const cached = await this.redis.get(cacheKey);
|
||||||
|
if (cached === MISS_SENTINEL) return null;
|
||||||
if (cached) return BigInt(cached);
|
if (cached) return BigInt(cached);
|
||||||
const code = await this.prisma.traceCode.findUnique({
|
const code = await this.prisma.traceCode.findUnique({
|
||||||
where: { shortCode },
|
where: { shortCode },
|
||||||
select: { id: true },
|
select: { id: true },
|
||||||
});
|
});
|
||||||
if (!code) return null;
|
if (!code) {
|
||||||
|
// 负缓存无效码,避免被脚本高频扫描时每次都落库
|
||||||
|
await this.redis.set(cacheKey, MISS_SENTINEL, 'EX', MISS_TTL);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
await this.redis.set(cacheKey, code.id.toString(), 'EX', MAP_TTL);
|
await this.redis.set(cacheKey, code.id.toString(), 'EX', MAP_TTL);
|
||||||
return code.id;
|
return code.id;
|
||||||
}
|
}
|
||||||
@@ -137,13 +143,14 @@ export class PublicTraceService {
|
|||||||
return { status: 'INVALID' as const };
|
return { status: 'INVALID' as const };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 激活 / 计数
|
// 激活 / 计数:用条件更新消除并发首次扫码的竞态。
|
||||||
|
// 只有真正把 INACTIVE 抢成 ACTIVE 的那一次请求 firstActivate=true(updateMany 返回 count=1),
|
||||||
|
// 其余并发请求 count=0,退化为原子自增,避免 queryCount 被双双写成 1、firstActivatedAt 被覆盖。
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
let firstActivate = false;
|
let firstActivate = false;
|
||||||
let updated;
|
|
||||||
if (code.status === TraceCodeStatus.INACTIVE) {
|
if (code.status === TraceCodeStatus.INACTIVE) {
|
||||||
updated = await this.prisma.traceCode.update({
|
const claimed = await this.prisma.traceCode.updateMany({
|
||||||
where: { id },
|
where: { id, status: TraceCodeStatus.INACTIVE },
|
||||||
data: {
|
data: {
|
||||||
status: TraceCodeStatus.ACTIVE,
|
status: TraceCodeStatus.ACTIVE,
|
||||||
firstActivatedAt: now,
|
firstActivatedAt: now,
|
||||||
@@ -151,13 +158,16 @@ export class PublicTraceService {
|
|||||||
lastQueriedAt: now,
|
lastQueriedAt: now,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
firstActivate = true;
|
firstActivate = claimed.count > 0;
|
||||||
} else {
|
}
|
||||||
updated = await this.prisma.traceCode.update({
|
if (!firstActivate) {
|
||||||
|
await this.prisma.traceCode.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: { queryCount: { increment: 1 }, lastQueriedAt: now },
|
data: { queryCount: { increment: 1 }, lastQueriedAt: now },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// 回查最新值组装响应(首次激活时读到自身写入,重复查询读到自增后的值)
|
||||||
|
const updated = await this.prisma.traceCode.findUniqueOrThrow({ where: { id } });
|
||||||
|
|
||||||
const proof = await this.prisma.blockchainProof.findFirst({
|
const proof = await this.prisma.blockchainProof.findFirst({
|
||||||
where: { traceCodeId: id, status: ProofStatus.ONCHAIN },
|
where: { traceCodeId: id, status: ProofStatus.ONCHAIN },
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
|
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto';
|
||||||
import { PrismaService } from '../prisma/prisma.service';
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
@@ -25,7 +25,6 @@ const EDITABLE_KEYS = [
|
|||||||
'ossBucket',
|
'ossBucket',
|
||||||
'ossAccessKeyId',
|
'ossAccessKeyId',
|
||||||
'ossAccessKeySecret',
|
'ossAccessKeySecret',
|
||||||
'settingsEncryptionKey',
|
|
||||||
'storageMigrationTarget',
|
'storageMigrationTarget',
|
||||||
'storageMigrationFingerprint',
|
'storageMigrationFingerprint',
|
||||||
'storageMigrationCopied',
|
'storageMigrationCopied',
|
||||||
@@ -43,6 +42,8 @@ const ENCRYPTED_PREFIX = 'enc:v1:';
|
|||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SettingsService {
|
export class SettingsService {
|
||||||
|
private readonly logger = new Logger(SettingsService.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly prisma: PrismaService,
|
private readonly prisma: PrismaService,
|
||||||
private readonly config: ConfigService,
|
private readonly config: ConfigService,
|
||||||
@@ -167,7 +168,10 @@ export class SettingsService {
|
|||||||
const decipher = createDecipheriv('aes-256-gcm', await this.encryptionKey(), iv);
|
const decipher = createDecipheriv('aes-256-gcm', await this.encryptionKey(), iv);
|
||||||
decipher.setAuthTag(tag);
|
decipher.setAuthTag(tag);
|
||||||
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8');
|
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8');
|
||||||
} catch {
|
} catch (e) {
|
||||||
|
// 解密失败通常意味着 SETTING_ENCRYPTION_KEY 与加密时不一致(配置损坏),
|
||||||
|
// 显式告警而非静默返回空串,避免把「配置损坏」误当成「未配置」
|
||||||
|
this.logger.warn(`密钥解密失败,可能是 SETTING_ENCRYPTION_KEY 已变更:${(e as Error).message}`);
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,20 @@ export class TraceCodeGeneratorService {
|
|||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
async ensureSalt(): Promise<string> {
|
async ensureSalt(): Promise<string> {
|
||||||
|
// 溯源码盐优先以 .env 的 TRACE_CODE_SALT 为权威来源(安装向导写入、升级不覆盖);
|
||||||
|
// DB 中的 systemSetting.traceCodeSalt 仅作兜底缓存,二者以 env 为准,使「勿更改」注释名副其实。
|
||||||
|
const envSalt = process.env.TRACE_CODE_SALT?.trim();
|
||||||
|
if (envSalt) {
|
||||||
|
const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
|
||||||
|
if (!existing?.value) {
|
||||||
|
await this.prisma.systemSetting.upsert({
|
||||||
|
where: { key: TRACE_CODE_SALT_KEY },
|
||||||
|
update: { value: envSalt },
|
||||||
|
create: { key: TRACE_CODE_SALT_KEY, value: envSalt },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return envSalt;
|
||||||
|
}
|
||||||
const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
|
const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
|
||||||
if (existing?.value) return existing.value;
|
if (existing?.value) return existing.value;
|
||||||
const salt = randomBytes(32).toString('hex');
|
const salt = randomBytes(32).toString('hex');
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import {
|
|||||||
} from './dto/trace-code.dto';
|
} from './dto/trace-code.dto';
|
||||||
import { Roles } from '../common/decorators/roles.decorator';
|
import { Roles } from '../common/decorators/roles.decorator';
|
||||||
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
||||||
|
import { parseBigId } from '../common/utils/bigint.util';
|
||||||
|
|
||||||
@ApiTags('批量生码')
|
@ApiTags('批量生码')
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@@ -134,7 +135,7 @@ export class TraceCodeController {
|
|||||||
@Get('trace-codes/:id/qrcode')
|
@Get('trace-codes/:id/qrcode')
|
||||||
@ApiOperation({ summary: '获取追溯码二维码 PNG' })
|
@ApiOperation({ summary: '获取追溯码二维码 PNG' })
|
||||||
async qrcode(@Param('id') id: string, @Res() res: Response) {
|
async qrcode(@Param('id') id: string, @Res() res: Response) {
|
||||||
const buf = await this.service.getQrPng(BigInt(id));
|
const buf = await this.service.getQrPng(parseBigId(id, '追溯码 ID'));
|
||||||
res.setHeader('Content-Type', 'image/png');
|
res.setHeader('Content-Type', 'image/png');
|
||||||
res.end(buf);
|
res.end(buf);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,12 +8,13 @@ import * as ExcelJS from 'exceljs';
|
|||||||
import * as QRCode from 'qrcode';
|
import * as QRCode from 'qrcode';
|
||||||
import AdmZip from 'adm-zip';
|
import AdmZip from 'adm-zip';
|
||||||
import dayjs from 'dayjs';
|
import dayjs from 'dayjs';
|
||||||
import { BatchStatus, ErrorCode, JobType, QUEUE_NAMES, TraceCodeStatus } from '@artveris/shared';
|
import { BatchStatus, ErrorCode, JobStatus, JobType, QUEUE_NAMES, 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 { BusinessException } from '../common/exceptions/business.exception';
|
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 { parseBigId } from '../common/utils/bigint.util';
|
||||||
import { JobsService } from '../jobs/jobs.service';
|
import { JobsService } from '../jobs/jobs.service';
|
||||||
import { SettingsService } from '../settings/settings.service';
|
import { SettingsService } from '../settings/settings.service';
|
||||||
import {
|
import {
|
||||||
@@ -60,13 +61,12 @@ export class TraceCodeService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private mapOutImages(code: { outImage?: string | null; outImages?: unknown }) {
|
private mapOutImages(code: { outImages?: unknown }) {
|
||||||
const keys = Array.isArray(code.outImages)
|
const keys = Array.isArray(code.outImages)
|
||||||
? (code.outImages as Array<{ key?: string; name?: string; type?: string }>)
|
? (code.outImages as Array<{ key?: string; name?: string; type?: string }>)
|
||||||
.map((item) => (typeof item === 'string' ? { key: item } : item))
|
.map((item) => (typeof item === 'string' ? { key: item } : item))
|
||||||
.filter((item) => item?.key)
|
.filter((item) => item?.key)
|
||||||
: [];
|
: [];
|
||||||
if (!keys.length && code.outImage) keys.push({ key: code.outImage });
|
|
||||||
return keys.map((item) => ({
|
return keys.map((item) => ({
|
||||||
...item,
|
...item,
|
||||||
url: this.storage.getUrl(item.key as string),
|
url: this.storage.getUrl(item.key as string),
|
||||||
@@ -96,6 +96,8 @@ export class TraceCodeService {
|
|||||||
artworkId: dto.artworkId,
|
artworkId: dto.artworkId,
|
||||||
groupId: dto.groupId ?? null,
|
groupId: dto.groupId ?? null,
|
||||||
});
|
});
|
||||||
|
// 入队失败时回滚 batch 并把 job 标记失败,避免留下永远 PENDING 的悬挂批次
|
||||||
|
try {
|
||||||
await this.genQueue.add('generate', {
|
await this.genQueue.add('generate', {
|
||||||
batchId: batch.id,
|
batchId: batch.id,
|
||||||
artworkId: dto.artworkId,
|
artworkId: dto.artworkId,
|
||||||
@@ -103,6 +105,11 @@ export class TraceCodeService {
|
|||||||
quantity: dto.quantity,
|
quantity: dto.quantity,
|
||||||
groupId: dto.groupId ?? null,
|
groupId: dto.groupId ?? null,
|
||||||
});
|
});
|
||||||
|
} catch (e) {
|
||||||
|
await this.jobs.finish(job.id, { status: JobStatus.FAILED, error: (e as Error).message });
|
||||||
|
await this.prisma.batch.update({ where: { id: batch.id }, data: { status: BatchStatus.FAILED } });
|
||||||
|
throw new BusinessException(ErrorCode.INTERNAL_ERROR, '生码任务入队失败,请稍后重试');
|
||||||
|
}
|
||||||
return { batchId: batch.id, batchNo, jobId: job.id, quantity: dto.quantity };
|
return { batchId: batch.id, batchNo, jobId: job.id, quantity: dto.quantity };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,30 +146,34 @@ export class TraceCodeService {
|
|||||||
|
|
||||||
// ===== 批量操作 =====
|
// ===== 批量操作 =====
|
||||||
async batchSetGroup(dto: BatchGroupDto) {
|
async batchSetGroup(dto: BatchGroupDto) {
|
||||||
const ids = dto.ids.map((i) => BigInt(i));
|
const ids = dto.ids.map((i) => parseBigId(i, '追溯码 ID'));
|
||||||
await this.prisma.traceCode.updateMany({
|
if (dto.groupId !== undefined && dto.groupId !== null) await this.ensureGroup(dto.groupId);
|
||||||
|
const res = await this.prisma.traceCode.updateMany({
|
||||||
where: { id: { in: ids } },
|
where: { id: { in: ids } },
|
||||||
data: { groupId: dto.groupId ?? null },
|
data: { groupId: dto.groupId ?? null },
|
||||||
});
|
});
|
||||||
return { success: true, count: ids.length };
|
return { success: true, count: res.count };
|
||||||
}
|
}
|
||||||
|
|
||||||
async batchSetStatus(dto: BatchStatusDto) {
|
async batchSetStatus(dto: BatchStatusDto) {
|
||||||
const ids = dto.ids.map((i) => BigInt(i));
|
const ids = dto.ids.map((i) => parseBigId(i, '追溯码 ID'));
|
||||||
if (dto.abnormal) {
|
if (dto.abnormal) {
|
||||||
// 标记异常:用于运营人员标注疑似被复制/盗用的码
|
// 标记异常:用于运营人员标注疑似被复制/盗用的码
|
||||||
await this.prisma.traceCode.updateMany({
|
const res = await this.prisma.traceCode.updateMany({
|
||||||
where: { id: { in: ids } },
|
where: { id: { in: ids } },
|
||||||
data: { status: TraceCodeStatus.ABNORMAL },
|
data: { status: TraceCodeStatus.ABNORMAL },
|
||||||
});
|
});
|
||||||
} else if (dto.disabled) {
|
return { success: true, count: res.count };
|
||||||
await this.prisma.traceCode.updateMany({
|
}
|
||||||
|
if (dto.disabled) {
|
||||||
|
const res = await this.prisma.traceCode.updateMany({
|
||||||
where: { id: { in: ids } },
|
where: { id: { in: ids } },
|
||||||
data: { status: TraceCodeStatus.DISABLED },
|
data: { status: TraceCodeStatus.DISABLED },
|
||||||
});
|
});
|
||||||
} else {
|
return { success: true, count: res.count };
|
||||||
|
}
|
||||||
// 启用:已激活过的恢复为 ACTIVE,否则恢复为 INACTIVE
|
// 启用:已激活过的恢复为 ACTIVE,否则恢复为 INACTIVE
|
||||||
await this.prisma.$transaction([
|
const [active, inactive] = await this.prisma.$transaction([
|
||||||
this.prisma.traceCode.updateMany({
|
this.prisma.traceCode.updateMany({
|
||||||
where: { id: { in: ids }, firstActivatedAt: { not: null } },
|
where: { id: { in: ids }, firstActivatedAt: { not: null } },
|
||||||
data: { status: TraceCodeStatus.ACTIVE },
|
data: { status: TraceCodeStatus.ACTIVE },
|
||||||
@@ -172,8 +183,7 @@ export class TraceCodeService {
|
|||||||
data: { status: TraceCodeStatus.INACTIVE },
|
data: { status: TraceCodeStatus.INACTIVE },
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
}
|
return { success: true, count: active.count + inactive.count };
|
||||||
return { success: true, count: ids.length };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async resolveTargetBatch(options: {
|
private async resolveTargetBatch(options: {
|
||||||
@@ -223,7 +233,7 @@ export class TraceCodeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async batchMove(dto: BatchMoveDto, userId: number) {
|
async batchMove(dto: BatchMoveDto, userId: number) {
|
||||||
const ids = dto.ids.map((i) => BigInt(i));
|
const ids = dto.ids.map((i) => parseBigId(i, '追溯码 ID'));
|
||||||
const codes = await this.prisma.traceCode.findMany({
|
const codes = await this.prisma.traceCode.findMany({
|
||||||
where: { id: { in: ids } },
|
where: { id: { in: ids } },
|
||||||
select: { id: true, artworkId: true, batchId: true },
|
select: { id: true, artworkId: true, batchId: true },
|
||||||
@@ -277,7 +287,7 @@ export class TraceCodeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async updateOne(id: string, dto: UpdateTraceCodeDto, userId?: number) {
|
async updateOne(id: string, dto: UpdateTraceCodeDto, userId?: number) {
|
||||||
const traceCodeId = BigInt(id);
|
const traceCodeId = parseBigId(id, '追溯码 ID');
|
||||||
const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId } });
|
const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId } });
|
||||||
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
|
||||||
|
|
||||||
@@ -349,7 +359,7 @@ export class TraceCodeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async batchDelete(dto: BatchDeleteDto) {
|
async batchDelete(dto: BatchDeleteDto) {
|
||||||
const ids = dto.ids.map((item) => BigInt(item));
|
const ids = dto.ids.map((item) => parseBigId(item, '追溯码 ID'));
|
||||||
const codes = await this.prisma.traceCode.findMany({
|
const codes = await this.prisma.traceCode.findMany({
|
||||||
where: { id: { in: ids } },
|
where: { id: { in: ids } },
|
||||||
select: { id: true, batchId: true },
|
select: { id: true, batchId: true },
|
||||||
@@ -404,9 +414,9 @@ export class TraceCodeService {
|
|||||||
if (query.groupId) where.groupId = query.groupId;
|
if (query.groupId) where.groupId = query.groupId;
|
||||||
if (query.status) where.status = query.status;
|
if (query.status) where.status = query.status;
|
||||||
if (query.outboundStatus === 'OUTBOUND') {
|
if (query.outboundStatus === 'OUTBOUND') {
|
||||||
and.push({ OR: [{ outTime: { not: null } }, { outImage: { not: null } }] });
|
and.push({ OR: [{ outTime: { not: null } }, { outImages: { not: Prisma.DbNull } }] });
|
||||||
} else if (query.outboundStatus === 'NOT_OUTBOUND') {
|
} else if (query.outboundStatus === 'NOT_OUTBOUND') {
|
||||||
and.push({ outTime: null, outImage: null });
|
and.push({ outTime: null, outImages: { equals: Prisma.DbNull } });
|
||||||
}
|
}
|
||||||
if (query.keyword) {
|
if (query.keyword) {
|
||||||
and.push({
|
and.push({
|
||||||
@@ -452,10 +462,11 @@ export class TraceCodeService {
|
|||||||
list.map((code) => {
|
list.map((code) => {
|
||||||
const { proofs, ...rest } = code;
|
const { proofs, ...rest } = code;
|
||||||
const latestOnchainProof = proofs.find((p) => p.status === 'ONCHAIN') ?? null;
|
const latestOnchainProof = proofs.find((p) => p.status === 'ONCHAIN') ?? null;
|
||||||
|
const outImages = this.mapOutImages(code);
|
||||||
return {
|
return {
|
||||||
...rest,
|
...rest,
|
||||||
outImageUrl: code.outImage ? this.storage.getUrl(code.outImage) : null,
|
outImageUrl: outImages[0]?.url ?? null,
|
||||||
outImages: this.mapOutImages(code),
|
outImages,
|
||||||
latestProof: latestOnchainProof,
|
latestProof: latestOnchainProof,
|
||||||
latestAnyProof: proofs[0] ?? null,
|
latestAnyProof: proofs[0] ?? null,
|
||||||
};
|
};
|
||||||
@@ -483,7 +494,7 @@ export class TraceCodeService {
|
|||||||
.split(',')
|
.split(',')
|
||||||
.map((s) => s.trim())
|
.map((s) => s.trim())
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.map((s) => BigInt(s));
|
.map((s) => parseBigId(s, '追溯码 ID'));
|
||||||
where.id = { in: idList };
|
where.id = { in: idList };
|
||||||
} else {
|
} else {
|
||||||
Object.assign(where, this.buildTraceCodeWhere(dto));
|
Object.assign(where, this.buildTraceCodeWhere(dto));
|
||||||
|
|||||||
@@ -14,7 +14,9 @@ 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;
|
||||||
export const MAX_FILE_SIZE = 20 * 1024 * 1024;
|
export const MAX_FILE_SIZE = 20 * 1024 * 1024;
|
||||||
export const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/svg+xml'];
|
// 不允许上传 SVG:SVG 可内嵌脚本,从同源 /uploads 直接打开会造成存储型 XSS。
|
||||||
|
// 内置默认图标是打包进前端的静态 svg(/admin、/trace 下),不经上传,不受影响。
|
||||||
|
export const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
|
||||||
export const ALLOWED_VIDEO_TYPES = ['video/mp4', 'video/webm', 'video/quicktime'];
|
export const ALLOWED_VIDEO_TYPES = ['video/mp4', 'video/webm', 'video/quicktime'];
|
||||||
export const ALLOWED_DOC_TYPES = ['application/pdf', 'image/jpeg', 'image/png'];
|
export const ALLOWED_DOC_TYPES = ['application/pdf', 'image/jpeg', 'image/png'];
|
||||||
|
|
||||||
|
|||||||
Generated
+16
@@ -95,6 +95,9 @@ importers:
|
|||||||
'@nestjs/swagger':
|
'@nestjs/swagger':
|
||||||
specifier: ^8.1.0
|
specifier: ^8.1.0
|
||||||
version: 8.1.1(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)
|
version: 8.1.1(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)
|
||||||
|
'@nestjs/throttler':
|
||||||
|
specifier: ^6.5.0
|
||||||
|
version: 6.5.0(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(reflect-metadata@0.2.2)
|
||||||
'@prisma/client':
|
'@prisma/client':
|
||||||
specifier: ^5.22.0
|
specifier: ^5.22.0
|
||||||
version: 5.22.0(prisma@5.22.0)
|
version: 5.22.0(prisma@5.22.0)
|
||||||
@@ -1100,6 +1103,13 @@ packages:
|
|||||||
'@nestjs/platform-express':
|
'@nestjs/platform-express':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
'@nestjs/throttler@6.5.0':
|
||||||
|
resolution: {integrity: sha512-9j0ZRfH0QE1qyrj9JjIRDz5gQLPqq9yVC2nHsrosDVAfI5HHw08/aUAWx9DZLSdQf4HDkmhTTEGLrRFHENvchQ==}
|
||||||
|
peerDependencies:
|
||||||
|
'@nestjs/common': ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0
|
||||||
|
'@nestjs/core': ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0
|
||||||
|
reflect-metadata: ^0.1.13 || ^0.2.0
|
||||||
|
|
||||||
'@nuxtjs/opencollective@0.3.2':
|
'@nuxtjs/opencollective@0.3.2':
|
||||||
resolution: {integrity: sha512-um0xL3fO7Mf4fDxcqx9KryrB7zgRM5JSlvGN5AGkP6JLM5XEKyjeAiPbNxdXVXQ16isuAhYpvP88NgL2BGd6aA==}
|
resolution: {integrity: sha512-um0xL3fO7Mf4fDxcqx9KryrB7zgRM5JSlvGN5AGkP6JLM5XEKyjeAiPbNxdXVXQ16isuAhYpvP88NgL2BGd6aA==}
|
||||||
engines: {node: '>=8.0.0', npm: '>=5.0.0'}
|
engines: {node: '>=8.0.0', npm: '>=5.0.0'}
|
||||||
@@ -5049,6 +5059,12 @@ snapshots:
|
|||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@nestjs/platform-express': 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)
|
'@nestjs/platform-express': 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)
|
||||||
|
|
||||||
|
'@nestjs/throttler@6.5.0(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/core@10.4.22)(reflect-metadata@0.2.2)':
|
||||||
|
dependencies:
|
||||||
|
'@nestjs/common': 10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
|
'@nestjs/core': 10.4.22(@nestjs/common@10.4.22(class-transformer@0.5.1)(class-validator@0.14.4)(reflect-metadata@0.2.2)(rxjs@7.8.2))(@nestjs/platform-express@10.4.22)(reflect-metadata@0.2.2)(rxjs@7.8.2)
|
||||||
|
reflect-metadata: 0.2.2
|
||||||
|
|
||||||
'@nuxtjs/opencollective@0.3.2':
|
'@nuxtjs/opencollective@0.3.2':
|
||||||
dependencies:
|
dependencies:
|
||||||
chalk: 4.1.2
|
chalk: 4.1.2
|
||||||
|
|||||||
Reference in New Issue
Block a user