feat: 追溯码支持批量导出 Excel/CSV(按筛选或所选)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-28 18:51:32 +08:00
co-authored by Cursor
parent 631982d980
commit 94d3ce18de
7 changed files with 120 additions and 22 deletions
+1
View File
@@ -64,4 +64,5 @@
- 阶段 12(审查与交付):全面审查功能(对照 PRD 全覆盖)、UI(商务/自适应/无内部文案)、代码(无残留调试日志);`pnpm -r build` 全量构建通过、后端 9 测试通过。交付物:完善 README(开发/账号/env/Mock 切换/部署)、`docker/Dockerfile.api`、`docker/nginx/nginx.conf`、`docker/docker-compose.full.yml`(全栈生产编排参考)。
- 已知优化点(非阻塞):admin 因 `app.use(naive)` 全量引入,index chunk 较大(~452KB gzip),内部后台可接受;如需可改按需引入或 manualChunks。
- 迭代(用户新需求):1) 语言包合并为单 json/语言(`locales/zh-CN.json`、`en-US.json`,含 common/menu/pages),默认中文;语言切换改为图标按钮(地球图标 + zh-CN 标记,下拉选择)。2) 主题改用 Naive 官方 light/darkTheme + 清凉青绿主色(theme.ts 仅最小覆盖),`useTheme` 组合式(light/dark/auto,auto 跟随系统),`ThemeSwitch` 图标下拉;App 用 n-global-style + :theme 切换;移除前端硬编码深蓝,统一 CSS 变量 `--brand`。3) 侧边栏改 `show-trigger="arrow-circle"`(官方垂直居中圆形收缩按钮),sider 取消 inverted 跟随主题。4) 追溯码新增分组(trace_code_group 表/groupId):分组管理弹窗、列表/生码按分组、短链列渲染为可点击 `<a target=_blank>`;5) 追溯码批量:DataTable 选择列 + 批量分组/启用/停用(后端 `/trace-codes/batch/group`、`/batch/status`,启用按激活/绑定状态恢复)。后端分组与批量已 API 验证通过。
- 追溯码批量导出(按 PRD 6.3):导出支持 Excel/CSV 两种格式,可按当前筛选(分组/批次/状态/关键词)或所选 ids 导出;列含批次编号、分组、追溯码、随机短码、短链、二维码数据(DataURL)、生成时间;CSV 加 UTF-8 BOM。后端 `GET /trace-codes/export?format=xlsx|csv&groupId&batchId&status&keyword&ids`;后台改为"导出"下拉(Excel/CSV × 当前筛选/所选)。已 API 验证 xlsx/csv/所选。
+1
View File
@@ -201,6 +201,7 @@
"queryCount": "Queries",
"firstActivatedAt": "First Activated",
"exportBatch": "Export Batch",
"exportCurrent": "Current filter",
"bindArtwork": "Bind Artwork",
"selectArtwork": "Select artwork",
"qrPreview": "QR Preview",
+1
View File
@@ -201,6 +201,7 @@
"queryCount": "查询次数",
"firstActivatedAt": "首次激活时间",
"exportBatch": "导出本批",
"exportCurrent": "当前筛选",
"bindArtwork": "绑定作品",
"selectArtwork": "选择作品",
"qrPreview": "二维码预览",
+32 -7
View File
@@ -41,10 +41,12 @@
<template #icon><n-icon :component="FolderOutline" /></template>
{{ t('pages.traceCode.manageGroups') }}
</n-button>
<n-button v-if="auth.canWrite && query.batchId" @click="exportBatch">
<template #icon><n-icon :component="DownloadOutline" /></template>
{{ t('pages.traceCode.exportBatch') }}
</n-button>
<n-dropdown v-if="auth.canWrite" trigger="click" :options="exportOptions" @select="onExport">
<n-button>
<template #icon><n-icon :component="DownloadOutline" /></template>
{{ t('common.action.export') }}
</n-button>
</n-dropdown>
<n-button v-if="auth.canWrite" type="primary" @click="genModal = true">
<template #icon><n-icon :component="AddOutline" /></template>
{{ t('pages.traceCode.generate') }}
@@ -278,9 +280,32 @@ function showQr(r: any) {
qrUrl.value = r.url;
qrModal.value = true;
}
async function exportBatch() {
if (!query.batchId) return;
await downloadFile('/trace-codes/export', `trace-codes-${query.batchId}.xlsx`, { batchId: query.batchId });
const exportOptions = computed(() => {
const cur = t('pages.traceCode.exportCurrent');
const opts: Array<{ label: string; key: string; type?: string }> = [
{ label: `Excel · ${cur}`, key: 'filter:xlsx' },
{ label: `CSV · ${cur}`, key: 'filter:csv' },
];
if (checkedKeys.value.length) {
const sel = t('pages.traceCode.selected', { n: checkedKeys.value.length });
opts.push({ label: `Excel · ${sel}`, key: 'selected:xlsx' });
opts.push({ label: `CSV · ${sel}`, key: 'selected:csv' });
}
return opts;
});
async function onExport(key: string) {
const [scope, format] = key.split(':');
const params: Record<string, unknown> = { format };
if (scope === 'selected') {
params.ids = checkedKeys.value.map(String).join(',');
} else {
if (query.groupId) params.groupId = query.groupId;
if (query.batchId) params.batchId = query.batchId;
if (query.status) params.status = query.status;
if (query.keyword) params.keyword = query.keyword;
}
await downloadFile('/trace-codes/export', `trace-codes.${format}`, params);
}
/* 批量操作 */
@@ -5,6 +5,7 @@ import {
IsArray,
IsBoolean,
IsEnum,
IsIn,
IsInt,
IsOptional,
IsString,
@@ -112,3 +113,37 @@ export class QueryBatchDto extends PaginationDto {
@IsString()
keyword?: string;
}
export class ExportTraceCodeDto {
@ApiPropertyOptional({ description: '导出格式', enum: ['xlsx', 'csv'] })
@IsOptional()
@IsIn(['xlsx', 'csv'])
format?: 'xlsx' | 'csv';
@ApiPropertyOptional({ description: '分组 ID' })
@IsOptional()
@Type(() => Number)
@IsInt()
groupId?: number;
@ApiPropertyOptional({ description: '批次 ID' })
@IsOptional()
@Type(() => Number)
@IsInt()
batchId?: number;
@ApiPropertyOptional({ description: '状态', enum: TraceCodeStatus })
@IsOptional()
@IsEnum(TraceCodeStatus)
status?: TraceCodeStatus;
@ApiPropertyOptional({ description: '关键词' })
@IsOptional()
@IsString()
keyword?: string;
@ApiPropertyOptional({ description: '指定追溯码 ID(逗号分隔,用于导出所选)' })
@IsOptional()
@IsString()
ids?: string;
}
@@ -18,6 +18,7 @@ import {
BatchGroupDto,
BatchStatusDto,
BindArtworkDto,
ExportTraceCodeDto,
GenerateBatchDto,
GroupDto,
QueryBatchDto,
@@ -95,9 +96,9 @@ export class TraceCodeController {
@Get('trace-codes/export')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '导出追溯码 Excel' })
export(@Query('batchId') batchId: string | undefined, @Res() res: Response) {
return this.service.exportExcel(batchId ? Number(batchId) : undefined, res);
@ApiOperation({ summary: '批量导出追溯码(Excel / CSV,可按筛选或所选)' })
export(@Query() query: ExportTraceCodeDto, @Res() res: Response) {
return this.service.exportCodes(query, res);
}
@Public()
+46 -12
View File
@@ -15,6 +15,7 @@ import { JobsService } from '../jobs/jobs.service';
import {
BatchGroupDto,
BatchStatusDto,
ExportTraceCodeDto,
GenerateBatchDto,
GroupDto,
QueryBatchDto,
@@ -207,12 +208,32 @@ export class TraceCodeService {
});
}
async exportExcel(batchId: number | undefined, res: Response): Promise<void> {
async exportCodes(dto: ExportTraceCodeDto, res: Response): Promise<void> {
const where: Prisma.TraceCodeWhereInput = {};
if (batchId) where.batchId = batchId;
if (dto.ids) {
const idList = dto.ids
.split(',')
.map((s) => s.trim())
.filter(Boolean)
.map((s) => BigInt(s));
where.id = { in: idList };
} else {
if (dto.batchId) where.batchId = dto.batchId;
if (dto.groupId) where.groupId = dto.groupId;
if (dto.status) where.status = dto.status;
if (dto.keyword) {
where.OR = [
{ shortCode: { contains: dto.keyword } },
{ code: { contains: dto.keyword } },
{ sku: { contains: dto.keyword } },
{ archiveNo: { contains: dto.keyword } },
];
}
}
const codes = await this.prisma.traceCode.findMany({
where,
include: { batch: { select: { batchNo: true } } },
include: { batch: { select: { batchNo: true } }, group: { select: { name: true } } },
orderBy: { id: 'asc' },
});
@@ -220,10 +241,11 @@ export class TraceCodeService {
const ws = wb.addWorksheet('追溯码');
ws.columns = [
{ header: '批次编号', key: 'batchNo', width: 22 },
{ header: '分组', key: 'group', width: 14 },
{ header: '追溯码', key: 'code', width: 24 },
{ header: '随机短码', key: 'shortCode', width: 16 },
{ header: '短链 URL', key: 'url', width: 40 },
{ header: '二维码数据(DataURL)', key: 'qr', width: 50 },
{ header: '短链', key: 'url', width: 40 },
{ header: '二维码数据', key: 'qr', width: 50 },
{ header: '生成时间', key: 'createdAt', width: 22 },
];
ws.getRow(1).font = { bold: true };
@@ -233,6 +255,7 @@ export class TraceCodeService {
const qr = await QRCode.toDataURL(url, { margin: 1, width: 200 });
ws.addRow({
batchNo: c.batch?.batchNo ?? '',
group: c.group?.name ?? '',
code: c.code,
shortCode: c.shortCode,
url,
@@ -241,12 +264,23 @@ export class TraceCodeService {
});
}
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader(
'Content-Disposition',
`attachment; filename="trace-codes-${batchId ?? 'all'}.xlsx"`,
);
await wb.xlsx.write(res);
res.end();
const format = dto.format === 'csv' ? 'csv' : 'xlsx';
const stamp = dayjs().format('YYYYMMDDHHmmss');
if (format === 'csv') {
const csvBuf = (await wb.csv.writeBuffer()) as unknown as Uint8Array;
// 加 UTF-8 BOM 以便 Excel 正确识别中文
const out = Buffer.concat([Buffer.from('\uFEFF', 'utf8'), Buffer.from(csvBuf)]);
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="trace-codes-${stamp}.csv"`);
res.end(out);
} else {
res.setHeader(
'Content-Type',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
);
res.setHeader('Content-Disposition', `attachment; filename="trace-codes-${stamp}.xlsx"`);
await wb.xlsx.write(res);
res.end();
}
}
}