wip: 开发订单导入功能

This commit is contained in:
ah--desktop
2025-11-24 00:33:54 +08:00
parent 0921ff9fc5
commit 6776a5badc
26 changed files with 687 additions and 36 deletions
@@ -0,0 +1,460 @@
<script setup lang="ts">
import type { ImportFieldDefVO } from '#/api/ecommerce/import-field-def';
import type { ImportTaskDTO } from '#/api/ecommerce/import-task';
import type { ShopVO } from '#/api/shop/shop/types';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Button, Form, message, Select, Spin, Steps } from 'ant-design-vue';
import { getFieldDefsByTypeApi } from '#/api/ecommerce/import-field-def';
import { createImportTaskApi } from '#/api/ecommerce/import-task';
import { uploadFileApi } from '#/api/media/file';
import { getShopPageApi } from '#/api/shop/shop';
defineOptions({ name: 'CreateImportTaskModal' });
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[800px]',
showCancelButton: false,
showConfirmButton: false,
onCancel() {
handleCancel();
},
});
// 响应式数据
const currentStep = ref(0);
const loading = ref(false);
const csvHeaders = ref<string[]>([]);
const selectedFile = ref<File | null>(null);
// 第一步:店铺选择
const shopList = ref<ShopVO.Info[]>([]);
const selectedShopId = ref<number | undefined>();
const shopLoading = ref(false);
const shopPage = ref(1);
const shopPageSize = ref(20);
const shopHasMore = ref(true);
const shopSearchValue = ref('');
// 第二步:字段映射
const fieldDefs = ref<ImportFieldDefVO.ImportFieldDefInfoVO[]>([]);
const fieldMappings = ref<
Record<
number,
{
fieldDef: ImportFieldDefVO.ImportFieldDefInfoVO;
mappedHeader?: string;
}
>
>({});
// 表单引用
const formRef = ref();
// 计算属性:必填字段是否都已绑定
const canGoToNextStep = computed(() => {
if (currentStep.value === 0) {
return selectedShopId.value !== undefined;
}
if (currentStep.value === 1) {
const requiredFields = fieldDefs.value.filter((f) => f.required);
return requiredFields.every((field) => {
const mapping = fieldMappings.value[field.id];
return mapping && mapping.mappedHeader;
});
}
return true;
});
// 初始化字段映射
const initFieldMappings = () => {
const mappings: typeof fieldMappings.value = {};
fieldDefs.value.forEach((fieldDef) => {
let mappedHeader: string | undefined;
// 如果字段有默认的 fileFieldName,尝试匹配 CSV 表头
if (fieldDef.fileFieldName) {
const matched = csvHeaders.value.find(
(header) => header === fieldDef.fileFieldName,
);
if (matched) {
mappedHeader = matched;
}
}
mappings[fieldDef.id] = {
fieldDef,
mappedHeader,
};
});
fieldMappings.value = mappings;
};
// 获取店铺列表
const fetchShopList = async (reset = false) => {
if (shopLoading.value) return;
try {
shopLoading.value = true;
if (reset) {
shopList.value = [];
shopPage.value = 1;
shopHasMore.value = true;
}
const result = await getShopPageApi({
page: shopPage.value,
pageSize: shopPageSize.value,
filters: {
name: shopSearchValue.value || undefined,
},
});
if (reset) {
shopList.value = result.records || [];
} else {
shopList.value.push(...(result.records || []));
}
// 判断是否还有更多数据
shopHasMore.value = (result.records?.length || 0) === shopPageSize.value;
if (shopHasMore.value) {
shopPage.value++;
}
} catch (error) {
console.error('获取店铺列表失败:', error);
message.error('获取店铺列表失败');
} finally {
shopLoading.value = false;
}
};
// 店铺搜索
const handleShopSearch = (value: string) => {
shopSearchValue.value = value;
fetchShopList(true);
};
// 店铺下拉框滚动加载更多
const handleShopScroll = (e: any) => {
const { target } = e;
if (
target.scrollTop + target.offsetHeight === target.scrollHeight &&
shopHasMore.value &&
!shopLoading.value
) {
fetchShopList();
}
};
// 获取字段定义
const fetchFieldDefs = async () => {
try {
loading.value = true;
const result = await getFieldDefsByTypeApi('order');
fieldDefs.value = result || [];
initFieldMappings();
} catch (error) {
console.error('获取字段定义失败:', error);
message.error('获取字段定义失败');
} finally {
loading.value = false;
}
};
// 下一步
const handleNext = () => {
if (currentStep.value === 0) {
if (!selectedShopId.value) {
message.warning('请选择店铺');
return;
}
currentStep.value = 1;
if (fieldDefs.value.length === 0) {
fetchFieldDefs();
}
} else if (currentStep.value === 1) {
// 验证必填字段
const requiredFields = fieldDefs.value.filter((f) => f.required);
const unMappedFields = requiredFields.filter((field) => {
const mapping = fieldMappings.value[field.id];
return !mapping || !mapping.mappedHeader;
});
if (unMappedFields.length > 0) {
message.warning(
`请先绑定必填字段:${unMappedFields.map((f) => f.fieldLabel).join('、')}`,
);
return;
}
currentStep.value = 2;
}
};
// 上一步
const handlePrev = () => {
if (currentStep.value > 0) {
currentStep.value--;
}
};
// 取消
const handleCancel = () => {
// 保持所有状态:步骤、店铺选择、字段映射
modalApi.close();
};
// 创建导入任务
const handleCreateTask = async () => {
if (!selectedFile.value) {
message.error('文件信息丢失,请重新上传');
return;
}
try {
loading.value = true;
// 先上传文件
message.loading('正在上传文件...', 0);
const fileInfo = await uploadFileApi(selectedFile.value);
message.destroy();
// 构建字段映射 JSON
const mapping: Record<string, string> = {};
Object.values(fieldMappings.value).forEach((m) => {
if (m.mappedHeader) {
mapping[m.fieldDef.fieldName] = m.mappedHeader;
}
});
const createData: ImportTaskDTO.CreateImportTaskDTO = {
shopId: selectedShopId.value!,
type: 'order',
fileName: selectedFile.value.name,
filePath: fileInfo.url,
mapping: JSON.stringify(mapping),
};
await createImportTaskApi(createData);
message.success('创建导入任务成功');
// 创建成功后,重置状态并关闭
currentStep.value = 0;
selectedShopId.value = undefined;
fieldMappings.value = {};
csvHeaders.value = [];
selectedFile.value = null;
modalApi.close();
} catch (error: any) {
message.destroy();
console.error('创建导入任务失败:', error);
message.error(error?.message || '创建导入任务失败');
} finally {
loading.value = false;
}
};
// 暴露给父组件的方法
function open(headers: string[], file?: File) {
const headersChanged =
JSON.stringify(csvHeaders.value) !== JSON.stringify(headers);
csvHeaders.value = headers;
selectedFile.value = file || null;
// 步骤保持不变,不清空
// 如果 CSV 表头变化了,需要重新初始化字段映射
if (headersChanged) {
fieldMappings.value = {};
// 如果已有字段定义,重新初始化映射
if (fieldDefs.value.length > 0) {
initFieldMappings();
}
// 表头变化时,重置到第一步
currentStep.value = 0;
}
// 店铺选择保持不变,不清空
// 只在首次打开或列表为空时加载店铺列表
if (shopList.value.length === 0) {
shopSearchValue.value = '';
shopPage.value = 1;
shopHasMore.value = true;
fetchShopList(true);
}
modalApi.open();
}
// 暴露方法给父组件
defineExpose({
open,
});
// 店铺选项
const shopOptions = computed(() => {
return shopList.value.map((shop: ShopVO.Info) => ({
label: shop.platform ? `${shop.name} (${shop.platform})` : shop.name,
value: shop.id,
}));
});
</script>
<template>
<Modal title="创建导入任务" :loading="loading">
<div class="space-y-6">
<!-- 步骤条 -->
<Steps :current="currentStep">
<Steps.Step title="选择店铺" />
<Steps.Step title="字段映射" />
<Steps.Step title="确认信息" />
</Steps>
<!-- 第一步:选择店铺 -->
<div v-if="currentStep === 0" class="py-4">
<Form
ref="formRef"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="选择店铺" required>
<Select
v-model:value="selectedShopId"
placeholder="请选择店铺"
show-search
:filter-option="false"
:loading="shopLoading"
@search="handleShopSearch"
@popup-scroll="handleShopScroll"
>
<template #notFoundContent>
<div v-if="shopLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400">
暂无数据
</div>
</template>
<Select.Option
v-for="option in shopOptions"
:key="option.value"
:value="option.value"
:label="option.label"
>
{{ option.label }}
</Select.Option>
</Select>
</Form.Item>
</Form>
</div>
<!-- 第二步:字段映射 -->
<div v-if="currentStep === 1" class="py-4">
<div class="mb-4 text-sm text-gray-600">
请为每个订单字段选择对应的CSV列,必填字段必须绑定
</div>
<div class="max-h-[400px] space-y-4 overflow-y-auto">
<div
v-for="fieldDef in fieldDefs"
:key="fieldDef.id"
class="flex items-center space-x-4 rounded border p-3"
:class="{
'border-red-300 bg-red-50':
fieldDef.required && !fieldMappings[fieldDef.id]?.mappedHeader,
}"
>
<div class="flex-1">
<div class="flex items-center space-x-2">
<span class="font-medium">{{ fieldDef.fieldLabel }}</span>
<span v-if="fieldDef.required" class="text-xs text-red-500">
(必填)
</span>
</div>
<div class="mt-1 text-xs text-gray-500">
字段名: {{ fieldDef.fieldName }}
</div>
</div>
<Select
v-if="fieldMappings[fieldDef.id]"
v-model:value="fieldMappings[fieldDef.id]!.mappedHeader"
placeholder="请选择CSV列"
class="w-[200px]"
show-search
allow-clear
:options="
csvHeaders.map((h) => ({
label: h,
value: h,
}))
"
/>
</div>
</div>
</div>
<!-- 第三步:确认信息 -->
<div v-if="currentStep === 2" class="py-4">
<div class="space-y-4">
<div class="rounded bg-gray-50 p-4">
<div class="mb-2 font-medium">店铺信息</div>
<div class="text-gray-700">
{{
shopList.find((s: ShopVO.Info) => s.id === selectedShopId)
?.name ?? '-'
}}
</div>
</div>
<div class="rounded bg-gray-50 p-4">
<div class="mb-2 font-medium">字段映射</div>
<div class="space-y-2">
<div
v-for="mapping in Object.values(fieldMappings).filter(
(m) => m.mappedHeader,
)"
:key="mapping.fieldDef.id"
class="flex justify-between text-sm"
>
<span class="text-gray-600">
{{ mapping.fieldDef.fieldLabel }}:
</span>
<span class="font-medium">{{ mapping.mappedHeader }}</span>
</div>
</div>
</div>
</div>
</div>
<!-- 操作按钮 -->
<div class="flex justify-between border-t pt-4">
<Button @click="handleCancel">取消</Button>
<div class="space-x-2">
<Button v-if="currentStep > 0" @click="handlePrev">上一步</Button>
<Button
v-if="currentStep < 2"
type="primary"
:disabled="!canGoToNextStep"
@click="handleNext"
>
下一步
</Button>
<Button
v-if="currentStep === 2"
type="primary"
:loading="loading"
@click="handleCreateTask"
>
创建导入任务
</Button>
</div>
</div>
</div>
</Modal>
</template>
<style scoped>
/* 自定义样式 */
</style>
@@ -0,0 +1,169 @@
<script setup lang="ts">
import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Spin } from 'ant-design-vue';
defineOptions({ name: 'FileUploadArea' });
const props = withDefaults(
defineProps<{
loading?: boolean;
}>(),
{
loading: false,
},
);
const emit = defineEmits<Emits>();
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload');
const LoaderIcon = createIconifyIcon('lucide:loader-2');
// Emits
interface Emits {
(e: 'fileSelected', file: File): void;
}
// 响应式数据
const isDragOver = ref(false);
const fileInputRef = ref<HTMLInputElement>();
// 文件验证
const validateFile = (file: File): boolean => {
const isCSV = file.type === 'text/csv' || file.name.endsWith('.csv');
if (!isCSV) {
message.error('只能上传CSV格式的文件!');
return false;
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('文件大小不能超过10MB!');
return false;
}
return true;
};
// 处理文件
const processFile = (file: File) => {
if (props.loading) return;
if (!validateFile(file)) return;
emit('fileSelected', file);
};
// 拖拽处理
const handleDragOver = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = true;
};
const handleDragLeave = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
};
const handleDrop = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
const files = e.dataTransfer?.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
};
// 文件选择处理
const triggerFileInput = () => {
fileInputRef.value?.click();
};
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement;
const files = target.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
// 清空input值,允许重复选择同一文件
target.value = '';
};
</script>
<template>
<Spin :spinning="loading" tip="正在解析文件...">
<div
class="rounded-lg border-2 border-dashed border-gray-300 p-8 text-center transition-colors"
:class="{
'border-blue-500 bg-blue-50': isDragOver && !loading,
'cursor-not-allowed opacity-60': loading,
}"
@dragover.prevent="!loading && handleDragOver($event)"
@dragleave.prevent="!loading && handleDragLeave($event)"
@drop.prevent="!loading && handleDrop($event)"
>
<div class="space-y-4">
<div class="relative mx-auto h-12 w-12">
<UploadIcon
v-if="!loading"
class="h-12 w-12 text-gray-400"
:class="{ 'text-blue-500': isDragOver }"
/>
<LoaderIcon v-else class="h-12 w-12 animate-spin text-blue-500" />
</div>
<div>
<p
class="text-lg font-medium"
:class="loading ? 'text-gray-500' : 'text-gray-700'"
>
{{
loading
? '正在解析文件,请稍候...'
: '拖拽CSV文件到此处或点击上传'
}}
</p>
<p v-if="!loading" class="text-sm text-gray-500">
支持.csv格式,最大10MB
</p>
</div>
<Button
@click="triggerFileInput"
type="primary"
ghost
:disabled="loading"
:loading="loading"
>
选择文件
</Button>
</div>
<input
ref="fileInputRef"
type="file"
accept=".csv"
style="display: none"
:disabled="loading"
@change="handleFileSelect"
/>
</div>
</Spin>
</template>
<style scoped>
/* 拖拽区域样式 */
.border-dashed {
transition: all 0.3s ease;
}
.border-dashed:hover {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
</style>
@@ -0,0 +1,178 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import CreateImportTaskModal from './components/CreateImportTaskModal.vue';
import FileUploadArea from './components/FileUploadArea.vue';
import { parseCSVToRawData } from './utils/csvParser';
defineOptions({ name: 'DataImport' });
// 响应式数据
const csvData = ref<any[]>([]);
const csvHeaders = ref<string[]>([]);
const importLoading = ref(false);
const currentFile = ref<File | null>(null);
// 动态生成Grid列配置
const gridColumns = computed(() => {
if (csvHeaders.value.length === 0) {
return [];
}
// 序号列
const columns: VxeGridProps<any>['columns'] = [
{
type: 'seq' as const,
title: '序号',
width: 80,
fixed: 'left' as const,
},
];
// 根据CSV表头动态生成列
csvHeaders.value.forEach((header) => {
columns.push({
field: header,
title: header,
minWidth: 150,
showOverflow: 'tooltip' as const,
});
});
return columns;
});
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [],
height: 'auto',
border: true,
stripe: true,
showOverflow: true,
size: 'small',
data: [],
pagerConfig: {
enabled: true,
pageSize: 50,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
});
// 更新表格数据和列
const updateTable = () => {
gridApi.setGridOptions({
columns: gridColumns.value,
data: csvData.value,
});
};
// 处理文件上传
const handleFileUpload = async (file: File) => {
importLoading.value = true;
try {
const result = await parseCSVToRawData(file);
if (result.errors.length > 0) {
message.warning(result.errors.join('; '));
}
if (result.data.length === 0) {
message.error('CSV文件没有有效数据');
return;
}
csvData.value = result.data;
csvHeaders.value = result.headers;
currentFile.value = file;
// 更新表格
updateTable();
message.success(`成功解析 ${result.data.length} 条数据`);
} catch (error: any) {
message.error(`文件读取失败: ${error.message}`);
} finally {
importLoading.value = false;
}
};
// 创建导入任务模态框引用
const createImportTaskModalRef =
ref<InstanceType<typeof CreateImportTaskModal>>();
// 创建导入任务按钮处理
const handleCreateImportTask = () => {
if (csvHeaders.value.length === 0) {
message.warning('请先上传CSV文件');
return;
}
createImportTaskModalRef.value?.open(
csvHeaders.value,
currentFile.value ?? undefined,
);
};
</script>
<template>
<Page auto-content-height>
<!-- 顶部栏 -->
<template #extra>
<Button
type="primary"
:disabled="csvHeaders.length === 0"
@click="handleCreateImportTask"
>
创建导入任务
</Button>
</template>
<!-- 主体内容区域 -->
<div
v-if="csvData.length === 0"
class="flex h-full items-center justify-center"
>
<FileUploadArea
:loading="importLoading"
@file-selected="handleFileUpload"
/>
</div>
<Grid v-else />
<CreateImportTaskModal ref="createImportTaskModalRef" />
</Page>
</template>
<style scoped>
/* 自定义样式 */
</style>
@@ -0,0 +1,84 @@
/**
* CSV数据解析工具
* 完全动态解析,不预设任何字段
*/
import Papa from 'papaparse';
export interface CSVParseResult {
/** 解析成功的数据 */
data: any[];
/** 解析错误 */
errors: string[];
/** 表头(保持CSV文件中的顺序) */
headers: string[];
}
/**
* 解析CSV文件为原始数据(完全动态,保持字段顺序)
*/
export async function parseCSVToRawData(file: File): Promise<CSVParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
// 尝试多种编码格式
const encodings = ['GBK', 'utf8', 'GB2312'];
let result: null | Papa.ParseResult<any> = null;
for (const encoding of encodings) {
try {
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
Papa.parse(file, {
header: true,
skipEmptyLines: true,
encoding: encoding as any,
complete: (results) => {
resolve(results);
},
error: (error) => {
reject(error);
},
});
});
// 检查是否成功解析出中文内容
if (result.data && result.data.length > 0) {
const firstRow = result.data[0];
const hasChineseContent = Object.values(firstRow).some(
(value) => typeof value === 'string' && /[\u4E00-\u9FA5]/.test(value),
);
if (hasChineseContent) {
break;
}
}
} catch {
continue;
}
}
if (!result) {
errors.push('无法解析CSV文件,请检查文件格式和编码');
return { data, errors, headers };
}
if (result.errors.length > 0) {
errors.push(
`CSV解析错误: ${result.errors.map((e) => e.message).join(', ')}`,
);
}
if (!result.data || result.data.length === 0) {
errors.push('CSV文件为空或没有有效数据');
return { data, errors, headers };
}
// 获取表头(保持CSV文件中的顺序)
headers = result.meta.fields || [];
// 直接使用原始数据,完全保持CSV文件的字段顺序和数据顺序
data.push(...result.data);
return { data, errors, headers };
}