feat: 实现出库导入、区块链存证、查询日志、看板与系统设置

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-28 16:25:03 +08:00
co-authored by Cursor
parent 63c0488ff7
commit 23cbf37aa1
20 changed files with 720 additions and 6 deletions
+32
View File
@@ -0,0 +1,32 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsDateString, IsOptional, IsString, MaxLength } from 'class-validator';
export class OutboundDto {
@ApiPropertyOptional({ description: 'SKU' })
@IsOptional()
@IsString()
@MaxLength(80)
sku?: string;
@ApiPropertyOptional({ description: '档案编号' })
@IsOptional()
@IsString()
@MaxLength(80)
archiveNo?: string;
@ApiPropertyOptional({ description: '出库时间' })
@IsOptional()
@IsDateString()
outTime?: string;
@ApiPropertyOptional({ description: '出库实况图存储 key' })
@IsOptional()
@IsString()
outImageKey?: string;
@ApiPropertyOptional({ description: '备注' })
@IsOptional()
@IsString()
@MaxLength(255)
remark?: string;
}
+140
View File
@@ -0,0 +1,140 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import * as ExcelJS from 'exceljs';
import { JobStatus, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { JobsService } from '../jobs/jobs.service';
interface ImportJobData {
jobId: string;
fileKey: string;
}
interface RowResult {
values: Record<string, string>;
ok: boolean;
reason: string;
}
@Processor(QUEUE_NAMES.IMPORT_OUTBOUND)
export class ImportProcessor extends WorkerHost {
private readonly logger = new Logger(ImportProcessor.name);
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly jobs: JobsService,
) {
super();
}
async process(job: Job<ImportJobData>): Promise<void> {
const { jobId, fileKey } = job.data;
await this.jobs.start(jobId);
try {
const buffer = await this.storage.read(fileKey);
const wb = new ExcelJS.Workbook();
await wb.xlsx.load(buffer as unknown as ArrayBuffer);
const ws = wb.worksheets[0];
// 建立 表头文本 -> 字段键 映射
const headerToKey = new Map<string, string>();
OUTBOUND_IMPORT_COLUMNS.forEach((c) => headerToKey.set(c.header, c.key));
const colToKey = new Map<number, string>();
const headerRow = ws.getRow(1);
headerRow.eachCell((cell, col) => {
const key = headerToKey.get(String(cell.value ?? '').trim());
if (key) colToKey.set(col, key);
});
const rows: RowResult[] = [];
for (let r = 2; r <= ws.rowCount; r++) {
const row = ws.getRow(r);
const values: Record<string, string> = {};
let empty = true;
colToKey.forEach((key, col) => {
const v = row.getCell(col).value;
const text = v === null || v === undefined ? '' : String(v).trim();
if (text) empty = false;
values[key] = text;
});
if (empty) continue;
rows.push({ values, ok: false, reason: '' });
}
await this.jobs.progress(jobId, 0, 0);
let success = 0;
let fail = 0;
for (const row of rows) {
const shortCode = row.values.shortCode;
if (!shortCode) {
row.reason = '短码为空';
fail++;
continue;
}
const code = await this.prisma.traceCode.findUnique({ where: { shortCode } });
if (!code) {
row.reason = '短码不存在';
fail++;
continue;
}
try {
await this.prisma.traceCode.update({
where: { id: code.id },
data: {
sku: row.values.sku || undefined,
archiveNo: row.values.archiveNo || undefined,
outTime: row.values.outTime ? new Date(row.values.outTime) : undefined,
remark: row.values.remark || undefined,
},
});
row.ok = true;
success++;
} catch (e) {
row.reason = (e as Error).message;
fail++;
}
}
await this.jobs.progress(jobId, success, fail);
// 生成结果明细文件
const resultUrl = await this.buildResultFile(rows);
const status =
fail === 0 ? JobStatus.SUCCESS : success === 0 ? JobStatus.FAILED : JobStatus.PARTIAL;
await this.prisma.job.update({
where: { id: jobId },
data: {
total: rows.length,
successCount: success,
failCount: fail,
status,
resultFileUrl: resultUrl,
},
});
this.logger.log(`导入完成:成功 ${success},失败 ${fail}`);
} catch (e) {
await this.jobs.finish(jobId, { status: JobStatus.FAILED, error: (e as Error).message });
this.logger.error(`导入失败:${(e as Error).message}`);
}
}
private async buildResultFile(rows: RowResult[]): Promise<string> {
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet('导入结果');
ws.columns = [
...OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: 22 })),
{ header: '处理状态', key: 'status', width: 12 },
{ header: '失败原因', key: 'reason', width: 30 },
];
ws.getRow(1).font = { bold: true };
for (const row of rows) {
ws.addRow({ ...row.values, status: row.ok ? '成功' : '失败', reason: row.reason });
}
const buf = Buffer.from(await wb.xlsx.writeBuffer());
const saved = await this.storage.save(buf, 'import-result.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
return saved.url;
}
}
@@ -0,0 +1,48 @@
import {
Body,
Controller,
Get,
Param,
Post,
Put,
Res,
UploadedFile,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { MAX_FILE_SIZE, RoleType } from '@artveris/shared';
import { OutboundService } from './outbound.service';
import { OutboundDto } from './dto/outbound.dto';
import { Roles } from '../common/decorators/roles.decorator';
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
@ApiTags('出库与上链')
@ApiBearerAuth()
@Controller('outbound')
export class OutboundController {
constructor(private readonly outboundService: OutboundService) {}
@Put('trace-codes/:id')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '单条录入出库信息' })
updateSingle(@Param('id') id: string, @Body() dto: OutboundDto) {
return this.outboundService.updateSingle(BigInt(id), dto);
}
@Get('import/template')
@ApiOperation({ summary: '下载出库导入模板(xlsx)' })
template(@Res() res: Response) {
return this.outboundService.generateTemplate(res);
}
@Post('import')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '批量导入出库信息(异步)' })
@ApiConsumes('multipart/form-data')
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE } }))
import(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) {
return this.outboundService.startImport(file, user.id);
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { QUEUE_NAMES } from '@artveris/shared';
import { OutboundService } from './outbound.service';
import { OutboundController } from './outbound.controller';
import { ImportProcessor } from './import.processor';
@Module({
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.IMPORT_OUTBOUND })],
controllers: [OutboundController],
providers: [OutboundService, ImportProcessor],
exports: [OutboundService],
})
export class OutboundModule {}
+73
View File
@@ -0,0 +1,73 @@
import { Injectable } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { Response } from 'express';
import * as ExcelJS from 'exceljs';
import { ErrorCode, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { JobsService } from '../jobs/jobs.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { OutboundDto } from './dto/outbound.dto';
@Injectable()
export class OutboundService {
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly jobs: JobsService,
@InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND) private readonly queue: Queue,
) {}
async updateSingle(traceCodeId: bigint, dto: OutboundDto) {
const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId } });
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
return this.prisma.traceCode.update({
where: { id: traceCodeId },
data: {
sku: dto.sku,
archiveNo: dto.archiveNo,
outTime: dto.outTime ? new Date(dto.outTime) : undefined,
outImage: dto.outImageKey,
remark: dto.remark,
},
});
}
async generateTemplate(res: Response): Promise<void> {
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet('导入模板');
ws.columns = OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: 22 }));
ws.getRow(1).font = { bold: true };
const example: Record<string, string> = {};
OUTBOUND_IMPORT_COLUMNS.forEach((c) => (example[c.key] = c.example));
ws.addRow(example);
const note = wb.addWorksheet('字段说明');
note.columns = [
{ header: '列名', key: 'header', width: 18 },
{ header: '是否必填', key: 'required', width: 12 },
{ header: '说明', key: 'note', width: 50 },
];
note.getRow(1).font = { bold: true };
OUTBOUND_IMPORT_COLUMNS.forEach((c) =>
note.addRow({ header: c.header, required: c.required ? '是' : '否', note: c.note }),
);
res.setHeader(
'Content-Type',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
);
res.setHeader('Content-Disposition', 'attachment; filename="outbound-import-template.xlsx"');
await wb.xlsx.write(res);
res.end();
}
async startImport(file: Express.Multer.File, userId: number) {
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入文件');
const saved = await this.storage.save(file.buffer, file.originalname || 'import.xlsx', file.mimetype);
const job = await this.jobs.create(JobType.IMPORT_OUTBOUND, 0, userId, { fileKey: saved.key });
await this.queue.add('import', { jobId: job.id, fileKey: saved.key });
return { jobId: job.id };
}
}