feat(export): 订单导出区分范围与内容,并带出序列号数量/列表

- 导出范围:支持 ids(导出选中,最多 500 条)或按筛选条件全部
- 导出内容:export_mode=order(默认,一行一个订单,不含明细)/ item(一行一个商品明细,订单字段重复)
- 订单导出新增「序列号数量」「序列号列表」列;含明细时按行号取该行 SN(行号为空按商品编码兜底)
- 前端导出按钮:订单类型弹窗选择「导出选中 / 按条件全部」与「订单行 / 含明细」,其余类型行为不变
- 导出任务页隐藏 ids 这类由页面自动携带的筛选字段(filters[].hidden)
- 补充 exportDefs 订单导出单测(两种模式、选中、权限、参数顺序)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-14 00:48:56 +08:00
parent e080bcbb76
commit b7010921c9
7 changed files with 305 additions and 14 deletions

View File

@ -1290,5 +1290,9 @@ GET /api/order-status/list?status=delivery&sn_codes=SN1,SN2
- 后端先按 `(principal_id, sn_code)` 从 `order_sn_codes` 取命中的订单ID,再回状态表过滤;
- 订单导出的筛选条件同样支持「序列号」(`sn_codes`);
- 订单导出支持两个维度(提交参数):
- 范围:`ids`(导出选中,订单ID 逗号分隔,最多 500 个)/ 不传(按筛选条件全部);
- 内容:`export_mode=order`(默认,一行一个订单,**不含明细**)/ `export_mode=item`(一行一个商品明细,订单字段重复填充);
- 两种内容都带「序列号数量」「序列号列表」列:订单行取该订单全部回传 SN,含明细取该行 SN(按行号匹配,行号为空的回传记录按商品编码兜底);
- 订单详情(`GET /api/order-status/:id`)返回 `order.sn_codes`;页面详情抽屉在「商品明细」每行提供「SN码(N)」按钮,点击展开该行的序列号列表(含运单号 / 回传时间)。

View File

@ -178,6 +178,56 @@ function jsonText(value) {
return String(value);
}
/**
* 序列号列表 → 可读文本(MySQL JSON_ARRAYAGG 可能返回 JSON 字符串或数组)
* @param {*} value 原值
* @return {string} 用「、」连接后的文本
*/
function snListText(value) {
if (blank(value)) return '';
let list = value;
if (typeof list === 'string') {
const text = list.trim();
if (!text) return '';
if (text.startsWith('[')) {
try { list = JSON.parse(text); } catch { list = text.split(','); }
} else {
list = text.split(',');
}
}
if (Array.isArray(list)) return list.map(item => String(item == null ? '' : item).trim()).filter(Boolean).join('、');
return String(list);
}
/**
* 订单级序列号聚合表达式(order_sn_codes 一行一个 SN)
* @param {string} alias 订单表别名
* @return {{count: string, list: string}} 数量与列表表达式
*/
function orderSnExpr(alias) {
const where = `osc.order_id = ${alias}.id AND osc.principal_id = ${alias}.principal_id`;
return {
count: `(SELECT COUNT(*) FROM order_sn_codes osc WHERE ${where})`,
list: `(SELECT JSON_ARRAYAGG(x.sn_code) FROM (SELECT osc.sn_code FROM order_sn_codes osc WHERE ${where} ORDER BY osc.id) x)`,
};
}
/**
* 明细级序列号聚合表达式:按行号匹配,行号为空的回传记录按商品编码兜底
* @param {string} orderAlias 订单表别名(o)
* @param {string} itemAlias 明细表别名(oi)
* @return {{count: string, list: string}} 数量与列表表达式
*/
function itemSnExpr(orderAlias, itemAlias) {
const where = `osc.order_id = ${orderAlias}.id AND osc.principal_id = ${orderAlias}.principal_id`
+ ` AND (osc.order_line_no = ${itemAlias}.order_line_no`
+ ` OR (osc.order_line_no IS NULL AND osc.item_code = ${itemAlias}.item_code))`;
return {
count: `(SELECT COUNT(*) FROM order_sn_codes osc WHERE ${where})`,
list: `(SELECT JSON_ARRAYAGG(x.sn_code) FROM (SELECT osc.sn_code FROM order_sn_codes osc WHERE ${where} ORDER BY osc.id) x)`,
};
}
/* 日期边界:只写到天(YYYY-MM-DD)时补 00:00:00 / 23:59:59 */
function dateBound(value, isEnd) {
const text = String(value).trim();
@ -293,7 +343,11 @@ const ORDER_COLUMNS = [{ key: 'id', header: 'ID' },
{ key: 'shop_id', header: '店铺ID' },
{ key: 'shop_nick', header: '店铺名称' },
{ key: 'source_platform_name', header: '电商平台' },
{ key: 'subsidiary_name', header: '货主' },
{
key: 'subsidiary_name',
header: '货主',
expr: '(SELECT s.name FROM principal_subsidiaries s WHERE s.id = t.subsidiary_id)',
},
{ key: 'warehouse_id', header: '仓库ID' },
{ key: 'warehouse_code', header: '仓库编码' },
{ key: 'receiver', header: '收货人' },
@ -310,6 +364,9 @@ const ORDER_COLUMNS = [{ key: 'id', header: 'ID' },
{ key: 'logistics_name', header: '物流公司名称' },
{ key: 'express_code', header: '运单号' },
{ key: 'express_codes', header: '运单号集合', format: jsonText },
// 仓库回传的序列号(order_sn_codes):数量与列表,导出订单时一并带出
{ key: 'sn_count', header: '序列号数量', expr: orderSnExpr('t').count },
{ key: 'sn_codes', header: '序列号列表', expr: orderSnExpr('t').list, format: snListText },
{ key: 'wms_status', header: 'WMS状态' },
{ key: 'wms_order_no', header: 'WMS单号' },
// 回传外部打单平台(配送视图/配送异常视图关注;其它状态表同名字段恒为默认值)
@ -323,6 +380,37 @@ const ORDER_COLUMNS = [{ key: 'id', header: 'ID' },
{ key: 'remark', header: '备注' },
];
/** 订单级序列号列(导出含明细时改用明细级 SN,避免与明细列重名) */
const ORDER_SN_COLUMN_KEYS = [ 'sn_count', 'sn_codes' ];
/**
* 订单含明细(export_mode=item)的列:订单字段 + 明细字段 + 明细级序列号
* 订单字段从内层查询结果(别名 o)按列名取,明细字段取 order_status_items(别名 oi)
*/
const ORDER_ITEM_COLUMNS = [
...ORDER_COLUMNS
.filter(c => !ORDER_SN_COLUMN_KEYS.includes(c.key))
.map(c => ({ ...c, expr: `o.${c.key}` })),
{ key: 'order_line_no', header: '行号', expr: 'oi.order_line_no' },
{ key: 'item_code', header: '商品编码', expr: 'oi.item_code' },
{ key: 'item_name', header: '商品名称', expr: 'oi.item_name' },
{ key: 'sku_code', header: '商家编码', expr: 'oi.sku_code' },
{ key: 'spec', header: '规格', expr: 'oi.spec' },
{ key: 'plan_qty', header: '数量', expr: 'oi.plan_qty' },
{ key: 'actual_price', header: '单价', expr: 'oi.actual_price' },
{ key: 'line_amount', header: '金额', expr: 'ROUND(IFNULL(oi.plan_qty, 0) * IFNULL(oi.actual_price, 0), 2)' },
{ key: 'inventory_type', header: '库存类型', expr: 'oi.inventory_type', format: value => (value === 'CC' ? '残次' : '正品') },
{ key: 'outer_item_id', header: '平台商品ID', expr: 'oi.outer_item_id' },
{
key: 'parse_status',
header: '解析状态',
expr: 'oi.parse_status',
format: labels({ 0: '未解析', 1: '已解析', 2: '解析失败' }),
},
{ key: 'item_sn_count', header: '序列号数量', expr: itemSnExpr('o', 'oi').count },
{ key: 'item_sn_codes', header: '序列号列表', expr: itemSnExpr('o', 'oi').list, format: snListText },
];
/** 入库单列 */
const INBOUND_COLUMNS = [
{ key: 'id', header: 'ID' },
@ -782,14 +870,25 @@ const EXPORT_TYPES = {
{ key: 'archived_from', label: '归档时间起', type: 'date' },
{ key: 'archived_to', label: '归档时间止', type: 'date' },
{ key: 'exclude_unbound', label: '排除含未绑定商品的订单', type: 'select', options: [{ value: '1', label: '是' }] },
{
key: 'export_mode',
label: '导出内容',
type: 'select',
options: [
{ value: 'order', label: '订单行(不含明细)' },
{ value: 'item', label: '订单含明细(每商品一行)' },
],
placeholder: '默认订单行(不含明细)',
},
{ key: 'ids', label: '选中订单ID', type: 'text', hidden: true, placeholder: '页面「导出选中」时传入' },
],
build: (f, ctx) => {
// 导出内容:order=一行一个订单(不含明细);item=一行一个商品明细(订单字段重复填充)
const exportMode = String(f.export_mode || '').trim() === 'item' ? 'item' : 'order';
// 订单按状态分表存储:指定状态时只查对应表,未指定时 UNION ALL 各状态表
const stages = ORDER_TABLE_BY_STATUS[f.order_stage] ? [ f.order_stage ] : ORDER_STATUS_ORDER;
const select = ORDER_COLUMNS
.map(c => (c.key === 'subsidiary_name'
? '(SELECT s.name FROM principal_subsidiaries s WHERE s.id = t.subsidiary_id) AS subsidiary_name'
: c.key))
.map(c => (c.expr ? `${c.expr} AS ${c.key}` : c.key))
.join(', ');
// 所在公司权限:只能导出自己所属公司(货主)的订单,条件写进各状态表子查询
const ownIds = ctx.access && !ctx.access.isGroup ? (ctx.access.ownCompanyIds || []).map(Number) : null;
@ -799,7 +898,9 @@ const EXPORT_TYPES = {
const inner = stages.map(stage => {
const table = ORDER_TABLE_BY_STATUS[stage];
const archived = stage === ORDER_STATUS.HISTORY ? 't.archived_at' : 'NULL AS archived_at';
return `SELECT ${select}, ${archived} FROM ${table} t WHERE t.principal_id = ?${scopeSql}`;
// 含明细模式外层要按 principal_id 关联明细表,内层额外带上该列(不输出到导出表)
const extra = exportMode === 'item' ? ', t.principal_id AS principal_id' : '';
return `SELECT ${select}${extra}, ${archived} FROM ${table} t WHERE t.principal_id = ?${scopeSql}`;
}).join(' UNION ALL ');
const wh = makeWhere();
wh.like('order_no', f.order_no)
@ -838,13 +939,35 @@ const EXPORT_TYPES = {
`AND oi.principal_id = ${Number(ctx.principalId)} AND oi.parse_status = 2)`
);
}
// 导出选中:页面勾选的行按订单ID(order_index.id)精确过滤,与筛选条件同时生效
const selectedIds = csvValues(f.ids, 500)
.map(value => Number(value))
.filter(id => Number.isInteger(id) && id > 0);
if (selectedIds.length) whereIn(wh, 't.id', selectedIds);
const stageRepl = stages.flatMap(() => (ownIds && ownIds.length
? [ ctx.principalId, ...ownIds ]
: [ ctx.principalId ]));
if (exportMode === 'item') {
// 含明细:先按条件收敛订单,再 JOIN 明细表;订单级筛选条件留在子查询里,避免列名歧义
const orderPart = `(SELECT * FROM (${inner}) AS t${wh.sql()}) AS o`;
return buildResult({
columns: ORDER_ITEM_COLUMNS,
from: `${orderPart} JOIN order_status_items oi ON oi.order_id = o.id AND oi.principal_id = o.principal_id`,
// 条件已在子查询内生效,外层不再追加,但 WHERE 参数需跟在订单参数之后
wh: makeWhere(),
orderBy: 'o.id DESC, oi.order_line_no ASC, oi.id ASC',
leadRepl: [ ...stageRepl, ...wh.replacements ],
});
}
return buildResult({
columns: ORDER_COLUMNS,
// 外层只按列名取值:计算列(货主名称 / SN 聚合)已在内层子查询算好
columns: ORDER_COLUMNS.map(c => (c.expr ? { ...c, expr: undefined } : c)),
from: `(${inner}) AS t`,
wh,
leadRepl: stages.flatMap(() => (ownIds && ownIds.length
? [ ctx.principalId, ...ownIds ]
: [ ctx.principalId ])),
leadRepl: stageRepl,
});
},
},

View File

@ -0,0 +1,89 @@
'use strict';
const { assert } = require('egg-mock/bootstrap');
const { buildExportSql, cleanFilters } = require('../../../app/utils/exportDefs');
/** 集团账号(不受货主范围限制) */
const GROUP_ACCESS = { isGroup: true, ownCompanyIds: [] };
describe('test/app/lib/exportDefsOrder.test.js', () => {
it('默认导出一行一个订单:不含明细列,带序列号数量/列表', () => {
const { sql, columns } = buildExportSql('order', { order_stage: 'pending' }, 5, 1, GROUP_ACCESS);
const headers = columns.map(c => c.header);
assert(headers.includes('序列号数量'));
assert(headers.includes('序列号列表'));
assert(!headers.includes('行号'));
assert(!headers.includes('商家编码'));
assert(sql.includes('JSON_ARRAYAGG'), 'SN 列表用 JSON_ARRAYAGG 聚合');
assert(!sql.includes('JOIN order_status_items'));
assert(!sql.includes('t.principal_id AS principal_id'));
});
it('订单含明细:JOIN 明细表,一行一个商品并带明细级序列号', () => {
const { sql, columns, replacements } = buildExportSql(
'order',
{ order_stage: 'pending', export_mode: 'item' },
5,
1,
GROUP_ACCESS
);
const headers = columns.map(c => c.header);
assert(headers.includes('行号'));
assert(headers.includes('商品编码'));
assert(headers.includes('序列号数量'));
assert(sql.includes('JOIN order_status_items oi ON oi.order_id = o.id'));
assert(sql.includes('oi.order_line_no'));
assert(sql.includes('t.principal_id AS principal_id'), '内层需带 principal_id 供关联明细');
assert(sql.includes('ORDER BY o.id DESC'));
assert.deepEqual(replacements, [ 5 ]);
});
it('导出选中:ids 转成订单ID过滤,与筛选条件同时生效', () => {
const { sql, replacements } = buildExportSql(
'order',
{ order_stage: 'delivery', ids: '11, 22,abc' },
5,
1,
GROUP_ACCESS
);
assert(sql.includes('t.id IN (?,?)'), '非法ID被丢弃,只保留两个有效ID');
assert.deepEqual(replacements, [ 5, 11, 22 ]);
});
it('含明细 + 条件:订单条件留在子查询内,参数顺序为订单→条件', () => {
const { sql, replacements } = buildExportSql(
'order',
{ order_stage: 'delivery', export_mode: 'item', order_no: 'A1', ids: '9' },
7,
1,
GROUP_ACCESS
);
// 条件子查询在内层 `AS t WHERE ...`,外层只做 JOIN;参数按 WHERE 中占位顺序:订单→条件→选中ID
assert(sql.includes(') AS t WHERE'));
assert(sql.includes(') AS o JOIN order_status_items oi'));
assert.deepEqual(replacements, [ 7, '%A1%', 9 ]);
});
it('所在公司权限:内层子查询追加 subsidiary_id 过滤,参数顺序保持一致', () => {
const { sql, replacements } = buildExportSql(
'order',
{ order_stage: 'pending', ids: '3' },
5,
1,
{ isGroup: false, ownCompanyIds: [ 4, 7 ] }
);
assert(sql.includes('t.subsidiary_id IN (?,?)'));
assert.deepEqual(replacements, [ 5, 4, 7, 3 ]);
});
it('cleanFilters 保留 export_mode / ids,丢弃未声明字段', () => {
const filters = cleanFilters('order', { export_mode: 'item', ids: '1,2', unknown: 'x', order_no: '' });
assert.deepEqual(filters, { export_mode: 'item', ids: '1,2' });
});
it('ids 标记为 hidden,不进入通用导出表单', () => {
const def = require('../../../app/utils/exportDefs').EXPORT_TYPES.order;
const idsField = def.filters.find(f => f.key === 'ids');
assert(idsField && idsField.hidden === true);
});
});

View File

@ -33,6 +33,8 @@ export interface ExportFilterDef {
placeholder?: string
/** 是否多选:多选值提交时按英文逗号拼接(如店铺/平台类型) */
multiple?: boolean
/** 不在通用「新建导出」表单里展示(如 ids:由列表页「导出选中」自动携带) */
hidden?: boolean
}
/** 导出任务状态:0待处理 1处理中 2已完成 3失败 */

View File

@ -1,5 +1,6 @@
<script setup lang="ts">
import { computed } from 'vue'
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useExportTasks } from '@/composables/useExportTasks'
import type { ExportFilters, ExportType } from '@/api/exportTask'
@ -8,6 +9,10 @@ import type { ExportFilters, ExportType } from '@/api/exportTask'
*
* 用法:<ExportButton type="product" :filters="exportFilters" />
* 点击后按当前页面筛选条件提交导出任务,完成时自动下载(逻辑见 composables/useExportTasks)。
*
* 订单导出(type="order")额外提供两个维度,提交前弹窗选择:
* - 范围:导出选中的 N 条(按订单ID) / 按当前筛选条件导出全部
* - 内容:订单行(一行一个订单,不含明细) / 订单含明细(一行一个商品,订单字段重复填充,带每行序列号)
*/
const props = withDefaults(
@ -22,20 +27,55 @@ const props = withDefaults(
size?: 'large' | 'default' | 'small'
/** 是否朴素按钮(列表页次级操作) */
plain?: boolean
/** 列表当前勾选的记录ID(订单导出「导出选中」用) */
selectedIds?: number[]
}>(),
{
filters: () => ({}),
label: '导出',
size: 'default',
plain: false,
selectedIds: () => [],
},
)
/** 单次导出选中最多条数(与后端 ids 白名单上限一致) */
const MAX_SELECTED = 500
const { submitting, submit } = useExportTasks()
const text = computed(() => props.label)
/** 订单导出走弹窗(区分范围与内容),其它类型点一下直接按条件导出 */
const isOrderExport = computed(() => props.type === 'order')
const dialogVisible = ref(false)
const scope = ref<'selected' | 'filtered'>('filtered')
const mode = ref<'order' | 'item'>('order')
const selectedCount = computed(() => (props.selectedIds || []).length)
function handleClick() {
submit(props.type, props.filters || {})
if (!isOrderExport.value) {
submit(props.type, props.filters || {})
return
}
// 有勾选时默认导出选中,否则默认按条件全部
scope.value = selectedCount.value ? 'selected' : 'filtered'
mode.value = 'order'
dialogVisible.value = true
}
async function confirmOrderExport() {
const filters: ExportFilters = { ...(props.filters || {}), export_mode: mode.value }
if (scope.value === 'selected') {
const ids = (props.selectedIds || []).slice(0, MAX_SELECTED)
if (!ids.length) {
ElMessage.warning('请先在列表中勾选要导出的订单')
return
}
filters.ids = ids.join(',')
}
await submit(props.type, filters)
dialogVisible.value = false
}
</script>
@ -44,4 +84,37 @@ function handleClick() {
<el-icon><Download /></el-icon>
<span>{{ text }}</span>
</el-button>
<el-dialog v-model="dialogVisible" title="导出订单" width="440px" append-to-body>
<el-form label-width="76px" size="small">
<el-form-item label="导出范围">
<el-radio-group v-model="scope">
<el-radio value="selected" :disabled="!selectedCount">
导出选中({{ selectedCount }} 条)
</el-radio>
<el-radio value="filtered">按条件全部</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="导出内容">
<el-radio-group v-model="mode">
<el-radio value="order">订单行(不含明细)</el-radio>
<el-radio value="item">订单含明细(每商品一行)</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item v-if="selectedCount > MAX_SELECTED && scope === 'selected'" label=" ">
<span class="hint">单次最多导出 {{ MAX_SELECTED }} 条选中订单,超出部分请分批导出</span>
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" :loading="submitting" @click="confirmOrderExport">提交导出</el-button>
</template>
</el-dialog>
</template>
<style scoped>
.hint {
color: var(--el-text-color-secondary);
font-size: 12px;
}
</style>

View File

@ -70,9 +70,9 @@ async function fetchTypes() {
const dialogVisible = ref(false)
const { submitting, submit } = useExportTasks()
/** 当前导出类型可传的筛选字段 */
/** 当前导出类型可传的筛选字段(hidden 的字段只由列表页自动携带,不在表单里展示) */
const currentFilters = computed(
() => typeOptions.value.find(o => o.value === form.type)?.filters || [],
() => (typeOptions.value.find(o => o.value === form.type)?.filters || []).filter(fd => !fd.hidden),
)
const form = reactive({

View File

@ -925,7 +925,7 @@ onBeforeUnmount(() => {
class="unbound-switch"
@change="onUnboundSwitchChange"
/>
<ExportButton type="order" :filters="exportFilters" size="small" plain />
<ExportButton type="order" :filters="exportFilters" :selected-ids="selectedIds" size="small" plain />
<el-button v-if="props.status === 'pending'" size="small" @click="syncDialogVisible = true">
一键拉取订单
</el-button>