feat(order-import): 重构规格编码补录为左侧表格直接编辑

This commit is contained in:
小蟑螂
2026-05-12 00:59:44 +08:00
parent 42a433328a
commit 4279af3fb4
3 changed files with 266 additions and 176 deletions
@@ -1,72 +0,0 @@
<script setup lang="ts">
import { Input as AntInput } from 'ant-design-vue';
interface MissingSpecCodeRow {
orderNo: string;
productName: string;
rowIndex: number;
specCode: string;
}
const props = defineProps<{
rows: MissingSpecCodeRow[];
}>();
const isEmptyValue = (value: unknown) => String(value ?? '').trim() === '';
const autoFillSpecCodeByProductName = (productName: string, specCode: string) => {
const code = specCode.trim();
if (!code) return;
props.rows.forEach((row) => {
if (row.productName === productName && isEmptyValue(row.specCode)) {
row.specCode = code;
}
});
};
</script>
<template>
<div class="space-y-3">
<div class="text-sm text-gray-500 dark:text-gray-400">
共 {{ rows.length }} 行缺少规格编码,请补全后在右侧确认应用
</div>
<div
class="max-h-[420px] overflow-y-auto rounded border border-gray-200 dark:border-gray-700"
>
<table class="w-full text-sm">
<thead class="bg-gray-50 dark:bg-gray-800">
<tr>
<th class="px-3 py-2 text-left font-medium">行号</th>
<th class="px-3 py-2 text-left font-medium">订单号</th>
<th class="px-3 py-2 text-left font-medium">商品</th>
<th class="px-3 py-2 text-left font-medium">规格编码</th>
</tr>
</thead>
<tbody>
<tr
v-for="row in rows"
:key="row.rowIndex"
class="border-t border-gray-100 dark:border-gray-700"
>
<td class="px-3 py-2">{{ row.rowIndex + 2 }}</td>
<td class="px-3 py-2">{{ row.orderNo || '-' }}</td>
<td class="px-3 py-2">{{ row.productName || '-' }}</td>
<td class="px-3 py-2">
<AntInput
v-model:value="row.specCode"
placeholder="请输入规格编码"
:maxlength="100"
@blur="
autoFillSpecCodeByProductName(row.productName, row.specCode)
"
/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
@@ -8,7 +8,7 @@ import type { ImportTaskDTO } from '#/api/ecommerce/import-task';
import type { OrderStatusVO } from '#/api/ecommerce/order-status';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { computed, ref } from 'vue';
import { computed, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
@@ -35,7 +35,6 @@ import { getAllOrderStatusListApi } from '#/api/ecommerce/order-status';
import { getShopPageApi } from '#/api/ecommerce/shop';
import { useImportTaskStore } from '#/store';
import { uploadFileToOss } from '#/utils/oss-upload';
import FixSpecCodeEditor from './FixSpecCodeEditor.vue';
import { createPatchedFile } from '../utils/specCodePatch';
// 定义映射项数据结构
@@ -62,6 +61,10 @@ defineOptions({ name: 'ImportTaskWizard' });
const emit = defineEmits<{
success: [];
/** 规格编码列绑定到的 CSV 表头变化时,供左侧表格开启该列编辑 */
specCodeColumnChange: [header: string | undefined];
/** 规格编码空行预检结果变化(含左侧编辑后) */
specMissingAfterPrecheck: [payload: { count: number; indices: number[] }];
}>();
// 响应式数据
@@ -71,7 +74,10 @@ const fieldDefsLoading = ref(false);
/** 创建导入任务提交中(与 message.loading 配合,仅按钮 loading) */
const createTaskSubmitting = ref(false);
const csvHeaders = ref<string[]>([]);
const csvData = ref<any[]>([]);
/** 与左侧「数据预览」表格共用同一数组引用,便于就地编辑规格编码 */
const previewData = defineModel<any[]>('previewData', { default: () => [] });
/** 用户上传的原始文件,生成补录文件时始终以此为基准,避免多次 _patched 链式后缀 */
const originalImportFile = ref<File | null>(null);
const selectedFile = ref<File | null>(null);
// 规格编码补录(仅本次导入)
@@ -83,7 +89,6 @@ interface MissingSpecCodeRow {
}
const missingSpecCodeCount = ref(0);
const missingSpecCodeRows = ref<MissingSpecCodeRow[]>([]);
const editableMissingSpecCodeRows = ref<MissingSpecCodeRow[]>([]);
const specCodePrechecked = ref(false);
const hasPatchedFile = ref(false);
@@ -223,22 +228,6 @@ const [SaveStatusTemplateModal, saveStatusTemplateModalApi] = useVbenModal({
},
});
// 创建补录规格编码模态框
const [FixSpecCodeModal, fixSpecCodeModalApi] = useVbenModal({
draggable: true,
class: 'w-[900px]',
title: '补充规格编码',
showCancelButton: true,
showConfirmButton: true,
confirmText: '应用并替换导入文件',
cancelText: '取消',
onConfirm: handleConfirmFixSpecCode,
onCancel() {
editableMissingSpecCodeRows.value = [];
fixSpecCodeModalApi.close();
},
});
// 导入任务store
const importTaskStore = useImportTaskStore();
@@ -955,7 +944,7 @@ const parseOrderStatuses = () => {
const statusColumn = statusMapping.mappedHeader;
const statusSet = new Set<string>();
csvData.value.forEach((row) => {
previewData.value.forEach((row) => {
const statusValue = row[statusColumn];
if (
statusValue !== null &&
@@ -1030,6 +1019,7 @@ const runMissingSpecCodePrecheck = () => {
missingSpecCodeRows.value = [];
missingSpecCodeCount.value = 0;
specCodePrechecked.value = true;
emit('specMissingAfterPrecheck', { count: 0, indices: [] });
return;
}
@@ -1037,7 +1027,7 @@ const runMissingSpecCodePrecheck = () => {
const productNameHeader = getProductNameHeader();
const rows: MissingSpecCodeRow[] = [];
csvData.value.forEach((row, index) => {
previewData.value.forEach((row, index) => {
if (isEmptyValue(row[specCodeHeader])) {
rows.push({
rowIndex: index,
@@ -1051,67 +1041,32 @@ const runMissingSpecCodePrecheck = () => {
missingSpecCodeRows.value = rows;
missingSpecCodeCount.value = rows.length;
specCodePrechecked.value = true;
emit('specMissingAfterPrecheck', {
count: missingSpecCodeCount.value,
indices: missingSpecCodeRows.value.map((r) => r.rowIndex),
});
};
// createPatchedFile 抽到 utils
const handleOpenFixSpecCodeModal = () => {
if (missingSpecCodeCount.value === 0) {
message.info('当前不存在需要补充规格编码的行');
return;
}
editableMissingSpecCodeRows.value = missingSpecCodeRows.value.map((row) => ({
...row,
}));
fixSpecCodeModalApi.open();
};
async function handleConfirmFixSpecCode() {
const hasEmpty = editableMissingSpecCodeRows.value.some((row) =>
isEmptyValue(row.specCode),
/** 用当前预览行从「原始上传文件」重新生成待上传文件(规格编码列编辑后调用) */
function syncPreviewToUploadFile() {
if (!originalImportFile.value || previewData.value.length === 0) return;
selectedFile.value = createPatchedFile(
originalImportFile.value,
csvHeaders.value,
previewData.value,
);
if (hasEmpty) {
message.warning('请先补全所有待处理行的规格编码');
return;
}
if (!selectedFile.value) {
message.error('源文件不存在,请重新上传');
return;
}
hasPatchedFile.value = true;
}
try {
fixSpecCodeModalApi.lock();
const specCodeHeader = getMappedHeaderByFieldCandidates(
['spec_code', 'specCode'],
'规格编码',
);
if (!specCodeHeader) {
message.error('未找到规格编码映射列,请返回上一步检查字段映射');
return;
}
const updatedRows = csvData.value.map((row) => ({ ...row }));
editableMissingSpecCodeRows.value.forEach((item) => {
updatedRows[item.rowIndex][specCodeHeader] = item.specCode.trim();
});
const patchedFile = createPatchedFile(
selectedFile.value,
csvHeaders.value,
updatedRows,
);
csvData.value = updatedRows;
selectedFile.value = patchedFile;
hasPatchedFile.value = true;
runMissingSpecCodePrecheck();
message.success('已生成补录后的新文件,将用于本次导入');
fixSpecCodeModalApi.close();
} catch (error: any) {
console.error('补录规格编码失败:', error);
message.error(error?.message || '补录规格编码失败');
} finally {
fixSpecCodeModalApi.unlock();
}
/** 左侧表格规格编码单元格编辑结束并落盘后,由父级防抖调用 */
function onPreviewSpecCodeCellSaved() {
const specHeader = getMappedHeaderByFieldCandidates(
['spec_code', 'specCode'],
'规格编码',
);
if (!specHeader || !originalImportFile.value) return;
syncPreviewToUploadFile();
runMissingSpecCodePrecheck();
}
// 下一步(顺序:字段映射 → 订单状态映射 → 确认信息含选店铺)
@@ -1133,7 +1088,7 @@ const handleNext = async () => {
runMissingSpecCodePrecheck();
if (missingSpecCodeCount.value > 0) {
message.warning(
`检测到 ${missingSpecCodeCount.value} 行规格编码为空,可在确认步骤补充后再创建任务`,
`检测到 ${missingSpecCodeCount.value} 行规格编码为空,请在左侧「数据预览」表格中,找到已映射为「规格编码」的列,直接点击单元格补全`,
);
}
@@ -1197,6 +1152,22 @@ const handleCreateTask = async () => {
return;
}
runMissingSpecCodePrecheck();
if (missingSpecCodeCount.value > 0) {
message.warning(
`仍有 ${missingSpecCodeCount.value} 行规格编码为空,请在左侧表格对应列补全后再创建任务`,
);
return;
}
if (hasPatchedFile.value && originalImportFile.value) {
selectedFile.value = createPatchedFile(
originalImportFile.value,
csvHeaders.value,
previewData.value,
);
}
try {
createTaskSubmitting.value = true;
@@ -1260,12 +1231,12 @@ const handleCreateTask = async () => {
uniqueStatusValues.value = [];
missingSpecCodeCount.value = 0;
missingSpecCodeRows.value = [];
editableMissingSpecCodeRows.value = [];
specCodePrechecked.value = false;
hasPatchedFile.value = false;
csvHeaders.value = [];
csvData.value = [];
previewData.value = [];
selectedFile.value = null;
originalImportFile.value = null;
selectedTemplateId.value = undefined;
selectedStatusTemplateId.value = undefined;
clearObsoleteSystemTargetRemind();
@@ -1279,17 +1250,16 @@ const handleCreateTask = async () => {
}
};
// 暴露给父组件的方法(第一步为字段映射,需预拉字段定义与映射模板)
async function open(headers: string[], file?: File, data?: any[]) {
// 暴露给父组件的方法(第一步为字段映射,需预拉字段定义与映射模板;预览行数据与父级 v-model:preview-data 共用)
async function open(headers: string[], file?: File) {
const headersChanged =
JSON.stringify(csvHeaders.value) !== JSON.stringify(headers);
csvHeaders.value = headers;
csvData.value = data || [];
selectedFile.value = file || null;
originalImportFile.value = file ?? null;
selectedFile.value = file ?? null;
missingSpecCodeCount.value = 0;
missingSpecCodeRows.value = [];
editableMissingSpecCodeRows.value = [];
specCodePrechecked.value = false;
hasPatchedFile.value = false;
@@ -1300,7 +1270,6 @@ async function open(headers: string[], file?: File, data?: any[]) {
clearObsoleteSystemTargetRemind();
missingSpecCodeCount.value = 0;
missingSpecCodeRows.value = [];
editableMissingSpecCodeRows.value = [];
specCodePrechecked.value = false;
hasPatchedFile.value = false;
currentStep.value = 0;
@@ -1343,21 +1312,33 @@ function reset() {
uniqueStatusValues.value = [];
missingSpecCodeCount.value = 0;
missingSpecCodeRows.value = [];
editableMissingSpecCodeRows.value = [];
specCodePrechecked.value = false;
hasPatchedFile.value = false;
csvHeaders.value = [];
csvData.value = [];
previewData.value = [];
selectedFile.value = null;
originalImportFile.value = null;
selectedTemplateId.value = undefined;
selectedStatusTemplateId.value = undefined;
clearObsoleteSystemTargetRemind();
}
watch(
() =>
fieldDefs.value.length > 0
? getMappedHeaderByFieldCandidates(['spec_code', 'specCode'], '规格编码')
: undefined,
(h) => {
emit('specCodeColumnChange', h);
},
{ flush: 'post', immediate: true },
);
// 暴露方法给父组件
defineExpose({
open,
reset,
onPreviewSpecCodeCellSaved,
});
// 店铺选项
@@ -1381,7 +1362,7 @@ const shopOptions = computed(() => {
v-if="selectedFile"
class="mb-0 mt-1 truncate text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
{{ selectedFile.name }} · {{ csvData.length }} 条
{{ selectedFile.name }} · {{ previewData.length }} 条
</p>
</div>
<!-- 不用整页 Spin 包裹可滚动区域:ant-spin-container 默认会限制内部滚动交互,见官方嵌套/高度讨论 -->
@@ -1803,15 +1784,10 @@ const shopOptions = computed(() => {
v-if="specCodePrechecked && missingSpecCodeCount > 0"
type="warning"
show-icon
:message="`检测到 ${missingSpecCodeCount} 行规格编码为空`"
:message="`仍有 ${missingSpecCodeCount} 行规格编码为空`"
>
<template #description>
<div class="flex flex-wrap items-center gap-3">
<span>可先补充规格编码,再创建导入任务。</span>
<Button size="small" type="primary" @click="handleOpenFixSpecCodeModal">
去补充规格编码
</Button>
</div>
请在左侧「数据预览」中点击已映射为「规格编码」的列单元格,直接填写后创建任务。
</template>
</Alert>
<Alert
@@ -1921,9 +1897,6 @@ const shopOptions = computed(() => {
</Form>
</SaveStatusTemplateModal>
<FixSpecCodeModal>
<FixSpecCodeEditor :rows="editableMissingSpecCodeRows" />
</FixSpecCodeModal>
</template>
<style scoped>
@@ -3,6 +3,8 @@ import type { VxeGridProps } from '#/adapter/vxe-table';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { Page } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
@@ -24,6 +26,16 @@ const tableHeight = ref<number>(600);
const importTaskWizardRef = ref<InstanceType<typeof ImportTaskWizard>>();
/** 与向导中「规格编码」字段映射绑定的 CSV 表头,用于左侧表格该列可编辑 */
const specCodeCsvHeader = ref<string | undefined>();
const specMissingCount = ref(0);
/** 规格编码为空的行在 csvData 中的全局下标(0-based) */
const specMissingRowIndices = ref<Set<number>>(new Set());
/** 与表格分页条 pageSize 同步,用于计算空缺所在页 */
const tablePageSize = ref(50);
/** 「下一处空缺」循环游标,-1 表示尚未开始循环 */
const missingCycleCursor = ref(-1);
// 动态生成Grid列配置
const gridColumns = computed(() => {
if (csvHeaders.value.length === 0) {
@@ -40,11 +52,14 @@ const gridColumns = computed(() => {
];
csvHeaders.value.forEach((header) => {
const isSpecCol =
!!specCodeCsvHeader.value && header === specCodeCsvHeader.value;
columns.push({
field: header,
title: header,
minWidth: 150,
minWidth: isSpecCol ? 180 : 150,
showOverflow: 'tooltip' as const,
...(isSpecCol ? { editRender: { name: 'input' as const } } : {}),
});
});
@@ -60,6 +75,10 @@ const gridOptions: VxeGridProps<any> = {
showOverflow: true,
size: 'small',
data: [],
editConfig: {
mode: 'cell',
trigger: 'click',
},
pagerConfig: {
enabled: true,
pageSize: 50,
@@ -100,6 +119,10 @@ const gridOptions: VxeGridProps<any> = {
const endIndex = startIndex + pageSize;
const pageData = csvData.value.slice(startIndex, endIndex);
// 供 rowClassName 识别全局行号(与 csvData 下标一致)
pageData.forEach((row, i) => {
(row as Record<string, unknown>).__srcRowIndex = startIndex + i;
});
return {
items: pageData,
@@ -110,14 +133,41 @@ const gridOptions: VxeGridProps<any> = {
},
};
const debouncedWizardSpecSync = useDebounceFn(() => {
importTaskWizardRef.value?.onPreviewSpecCodeCellSaved?.();
}, 400);
function rowClassNameForSpecMissing(params: { row?: Record<string, unknown> }) {
const idx = params.row?.__srcRowIndex;
if (typeof idx !== 'number') return '';
return specMissingRowIndices.value.has(idx) ? 'order-import-row--spec-missing' : '';
}
const gridEvents = {
editClosed(params: { column?: { field?: string } }) {
const field = params.column?.field;
if (!field || !specCodeCsvHeader.value) return;
if (field === specCodeCsvHeader.value) {
debouncedWizardSpecSync();
}
},
pageChange(params: { pageSize?: number; currentPage?: number }) {
if (params.pageSize && params.pageSize > 0) {
tablePageSize.value = params.pageSize;
}
},
};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
gridEvents,
});
const updateTable = () => {
gridApi.setGridOptions({
columns: gridColumns.value,
height: tableHeight.value,
rowClassName: rowClassNameForSpecMissing,
});
gridApi.reload();
};
@@ -140,11 +190,111 @@ const syncWizardOpen = () => {
importTaskWizardRef.value?.open(
[...csvHeaders.value],
currentFile.value ?? undefined,
[...csvData.value],
);
});
};
function onSpecCodeColumnChange(header: string | undefined) {
specCodeCsvHeader.value = header;
updateTable();
}
function onSpecMissingAfterPrecheck(payload: { count: number; indices: number[] }) {
specMissingCount.value = payload.count;
specMissingRowIndices.value = new Set(payload.indices);
missingCycleCursor.value = -1;
// 必须用 query 而非 reload:reload 会重置分页到第 1 页,用户在其它页补规格编码时会被突然拉回首页
if (csvData.value.length > 0) {
void gridApi.query({});
}
}
/** 取 VxeGrid 内部的 VxeTable 实例(用于 scrollToRow 等仅表格支持的方法) */
function getVxeInnerTable(grid: any) {
return grid?.$refs?.refTable ?? grid?.$refs?.xTable ?? null;
}
/** 等两帧再滚,避免 loadData 后 DOM 尚未稳定 */
function nextPaint() {
return new Promise<void>((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
});
}
/**
* 滚动到指定数据行(scrollToRow 返回 Promise;第二参为列 field 时同时横向滚到「规格编码」列)
* 虚拟滚动场景 vxe 内部会延时二次校正,这里再补一次延迟滚动。
*/
async function scrollGridToDataRow(row: Record<string, unknown>) {
const grid = gridApi.grid as any;
const field = specCodeCsvHeader.value;
const candidates = [grid, getVxeInnerTable(grid)].filter(Boolean);
for (const inst of candidates) {
if (inst && typeof inst.scrollToRow === 'function') {
try {
await inst.scrollToRow(row, field || undefined);
return;
} catch {
// 尝试下一个实例
}
}
}
}
/** 跳转到包含该全局行号的分页并滚动到该行 */
async function goToRowIndex(globalRowIndex: number) {
if (globalRowIndex < 0 || globalRowIndex >= csvData.value.length) return;
const ps = tablePageSize.value;
const targetPage = Math.floor(globalRowIndex / ps) + 1;
const grid = gridApi.grid as any;
if (!grid?.getProxyInfo || typeof grid.commitProxy !== 'function') {
message.warning('表格尚未就绪,请稍后重试');
return;
}
const row = csvData.value[globalRowIndex] as Record<string, unknown> | undefined;
if (!row) return;
try {
const proxy = grid.getProxyInfo();
if (proxy?.pager) {
proxy.pager.currentPage = targetPage;
proxy.pager.pageSize = ps;
}
await grid.commitProxy('query');
await nextTick();
await nextPaint();
await scrollGridToDataRow(row);
// 与 vxe 虚拟列表二次对齐时机接近,避免首屏未滚到位
window.setTimeout(() => {
void scrollGridToDataRow(row);
}, 400);
} catch (e) {
console.error('跳转表格分页失败:', e);
message.warning('跳转分页失败,请手动翻页查找');
}
}
function jumpToFirstSpecMissing() {
const sorted = [...specMissingRowIndices.value].sort((a, b) => a - b);
if (sorted.length === 0) {
message.info('当前没有空缺的规格编码');
return;
}
missingCycleCursor.value = 0;
void goToRowIndex(sorted[0]!);
}
function jumpToNextSpecMissing() {
const sorted = [...specMissingRowIndices.value].sort((a, b) => a - b);
if (sorted.length === 0) {
message.info('当前没有空缺的规格编码');
return;
}
missingCycleCursor.value = (missingCycleCursor.value + 1) % sorted.length;
void goToRowIndex(sorted[missingCycleCursor.value]!);
}
const handleFileUpload = async (file: File) => {
importLoading.value = true;
try {
@@ -183,6 +333,10 @@ const handleClearData = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
specCodeCsvHeader.value = undefined;
specMissingCount.value = 0;
specMissingRowIndices.value = new Set();
missingCycleCursor.value = -1;
importTaskWizardRef.value?.reset();
updateTable();
message.success('已清空数据');
@@ -192,6 +346,10 @@ const handleWizardSuccess = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
specCodeCsvHeader.value = undefined;
specMissingCount.value = 0;
specMissingRowIndices.value = new Set();
missingCycleCursor.value = -1;
updateTable();
message.success('已创建导入任务,可继续上传新文件');
};
@@ -287,9 +445,23 @@ onUnmounted(() => {
</h2>
<p class="m-0 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-sm">
共 {{ csvData.length }} 条 · 右侧配置导入任务
<template v-if="specMissingCount > 0">
·
<span class="font-medium text-amber-600 dark:text-amber-400">
规格编码待补 {{ specMissingCount }} 行(点击本表对应列表格填写)
</span>
</template>
</p>
</div>
<Button size="small" @click="handleClearData">清空数据</Button>
<div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
<template v-if="specMissingCount > 0">
<Button size="small" type="primary" @click="jumpToFirstSpecMissing">
第一处空缺
</Button>
<Button size="small" @click="jumpToNextSpecMissing">下一处空缺</Button>
</template>
<Button size="small" @click="handleClearData">清空数据</Button>
</div>
</div>
<div
ref="tableContainerRef"
@@ -306,6 +478,9 @@ onUnmounted(() => {
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
<ImportTaskWizard
ref="importTaskWizardRef"
v-model:preview-data="csvData"
@spec-code-column-change="onSpecCodeColumnChange"
@spec-missing-after-precheck="onSpecMissingAfterPrecheck"
@success="handleWizardSuccess"
/>
</div>
@@ -326,4 +501,18 @@ onUnmounted(() => {
flex: 1;
overflow: auto;
}
/* 规格编码为空的行:整行高亮,便于分页中辨认 */
:deep(tr.order-import-row--spec-missing) {
background-color: rgb(254 243 199) !important;
}
:deep(tr.order-import-row--spec-missing:hover) {
background-color: rgb(253 230 138) !important;
}
.dark :deep(tr.order-import-row--spec-missing) {
background-color: rgb(120 53 15 / 0.45) !important;
}
.dark :deep(tr.order-import-row--spec-missing:hover) {
background-color: rgb(120 53 15 / 0.6) !important;
}
</style>