wip: 订单导入

This commit is contained in:
ah--desktop
2025-11-18 00:05:35 +08:00
parent 8547e0714a
commit 0921ff9fc5
20 changed files with 196 additions and 3229 deletions
@@ -42,12 +42,6 @@ public class CreateOrderDTO {
@NotNull(message = "商家实收金额不能为空")
private BigDecimal receivedAmount;
/**
* 运费
*/
@Schema(description = "运费", example = "10.00")
private BigDecimal shippingFee;
/**
* 下单时间
*/
@@ -102,11 +96,4 @@ public class CreateOrderDTO {
@Schema(description = "成本价", example = "8000.00", required = true)
@NotNull(message = "成本价不能为空")
private BigDecimal costPrice;
/**
* 成本小计
*/
@Schema(description = "成本小计", example = "8000.00", required = true)
@NotNull(message = "成本小计不能为空")
private BigDecimal costTotal;
}
@@ -40,12 +40,6 @@ public class UpdateOrderDTO {
@NotNull(message = "商家实收金额不能为空")
private BigDecimal receivedAmount;
/**
* 运费
*/
@Schema(description = "运费", example = "10.00")
private BigDecimal shippingFee;
/**
* 下单时间
*/
@@ -94,10 +88,4 @@ public class UpdateOrderDTO {
*/
@Schema(description = "成本价", example = "8000.00")
private BigDecimal costPrice;
/**
* 成本小计
*/
@Schema(description = "成本小计", example = "8000.00")
private BigDecimal costTotal;
}
@@ -87,24 +87,12 @@ public class OrderPO {
@TableField("cost_price")
private BigDecimal costPrice;
/**
* 成本小计
*/
@TableField("cost_total")
private BigDecimal costTotal;
/**
* 商家实收金额
*/
@TableField("received_amount")
private BigDecimal receivedAmount;
/**
* 运费
*/
@TableField("shipping_fee")
private BigDecimal shippingFee;
/**
* 下单时间
*/
@@ -61,12 +61,6 @@ public class OrderVO {
@Schema(description = "商家实收金额", example = "9999.00")
private BigDecimal receivedAmount;
/**
* 运费
*/
@Schema(description = "运费", example = "10.00")
private BigDecimal shippingFee;
/**
* 下单时间
*/
@@ -138,10 +132,4 @@ public class OrderVO {
*/
@Schema(description = "成本价", example = "8000.00")
private BigDecimal costPrice;
/**
* 成本小计
*/
@Schema(description = "成本小计", example = "8000.00")
private BigDecimal costTotal;
}
@@ -106,9 +106,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
order.setQuantity(createOrderDTO.getQuantity());
order.setUnitPrice(createOrderDTO.getUnitPrice());
order.setCostPrice(createOrderDTO.getCostPrice());
order.setCostTotal(createOrderDTO.getCostTotal());
order.setReceivedAmount(createOrderDTO.getReceivedAmount());
order.setShippingFee(createOrderDTO.getShippingFee() != null ? createOrderDTO.getShippingFee() : java.math.BigDecimal.ZERO);
order.setOrderDate(createOrderDTO.getOrderDate());
order.setCreateBy(currentUserContext.getCurrentUserId());
@@ -96,18 +96,16 @@ CREATE TABLE `ec_order` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '订单ID',
`company_id` BIGINT UNSIGNED NOT NULL COMMENT '公司ID',
`shop_id` BIGINT UNSIGNED NOT NULL COMMENT '店铺ID',
`platform_order_no` VARCHAR(100) DEFAULT NULL COMMENT '平台订单号',
`status_id` BIGINT UNSIGNED NOT NULL COMMENT '订单状态ID',
`product_id` BIGINT UNSIGNED NOT NULL COMMENT '商品ID',
`product_spec_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '商品规格ID',
`status_id` BIGINT UNSIGNED NOT NULL COMMENT '订单状态ID',
`platform_order_no` VARCHAR(100) DEFAULT NULL COMMENT '平台订单号',
`product_name` VARCHAR(255) NOT NULL COMMENT '商品名称(冗余存储)',
`spec_name` VARCHAR(200) DEFAULT NULL COMMENT '规格名称(冗余存储)',
`received_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '商家实收金额',
`quantity` INT NOT NULL DEFAULT 1 COMMENT '数量',
`unit_price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '销售单价',
`cost_price` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '成本价(下单时快照)',
`cost_total` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '成本小计',
`received_amount` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '商家实收金额',
`shipping_fee` DECIMAL(10,2) NOT NULL DEFAULT 0.00 COMMENT '运费',
`order_date` TIMESTAMP NOT NULL COMMENT '下单时间',
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
@@ -13,8 +13,6 @@ export namespace OrderDTO {
statusId: number;
/** 商家实收金额 */
receivedAmount: number;
/** 运费 */
shippingFee?: number;
/** 下单时间 */
orderDate: string;
/** 商品ID */
@@ -31,8 +29,6 @@ export namespace OrderDTO {
unitPrice: number;
/** 成本价(下单时快照) */
costPrice: number;
/** 成本小计 */
costTotal: number;
}
/** 更新订单参数 */
@@ -45,8 +41,6 @@ export namespace OrderDTO {
statusId?: number;
/** 商家实收金额 */
receivedAmount: number;
/** 运费 */
shippingFee?: number;
/** 下单时间 */
orderDate: string;
/** 商品ID */
@@ -63,22 +57,24 @@ export namespace OrderDTO {
unitPrice?: number;
/** 成本价(下单时快照) */
costPrice?: number;
/** 成本小计 */
costTotal?: number;
}
/** 订单过滤条件 */
export interface Filters {
/** 店铺ID */
shopId?: number;
/** 商品规格ID */
productSpecId?: number;
/** 平台订单号(模糊查询) */
platformOrderNo?: string;
/** 订单状态ID */
orderStatusId?: number;
/** 订单编号(模糊查询) */
orderNumber?: string;
/** 商品名称(模糊查询) */
productName?: string;
statusId?: number;
/** 实收金额范围-最小值 */
minReceivedAmount?: number;
/** 实收金额范围-最大值 */
maxReceivedAmount?: number;
/** 下单时间范围-开始时间 */
startOrderDate?: string;
/** 下单时间范围-结束时间 */
endOrderDate?: string;
}
/** 批量导入订单参数 */
@@ -21,8 +21,6 @@ export namespace OrderVO {
statusName: string;
/** 商家实收金额 */
receivedAmount: number;
/** 运费 */
shippingFee: number;
/** 下单时间 */
orderDate: string;
/** 创建时间 */
@@ -47,8 +45,6 @@ export namespace OrderVO {
unitPrice: number;
/** 成本价(下单时快照) */
costPrice: number;
/** 成本小计 */
costTotal: number;
}
}
@@ -1,301 +0,0 @@
<script lang="ts" setup>
import { ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
import ProductFormModal from '#/views/shop/product/components/ProductFormModal.vue';
import ProductSpecModal from '#/views/shop/product/components/ProductSpecModal.vue';
import ShopFormModal from '#/views/shop/shop/components/ShopFormModal.vue';
interface Props {
visible: boolean;
entitiesToCreate: {
products: string[];
shops: string[];
specs: { productName: string; specCode: string; specName?: string }[];
};
csvData?: any[]; // 传递CSV数据用于获取更多信息
}
interface Emits {
(e: 'success'): void;
(e: 'cancel'): void;
}
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[800px]',
onCancel() {
handleCancel();
},
onConfirm() {
handleSubmit();
},
});
// 监听 visible 变化
watch(
() => props.visible,
(newVal) => {
if (newVal) {
modalApi.open();
} else {
modalApi.close();
}
},
{ immediate: true },
);
// 响应式数据
const loading = ref(false);
const shopFormModalRef = ref();
const productFormModalRef = ref();
const productSpecModalRef = ref();
// 当前正在创建的实体
const currentCreatingShop = ref<string>('');
const currentCreatingProduct = ref<string>('');
const currentCreatingSpec = ref<null | {
productName: string;
specCode: string;
}>(null);
// 处理提交
function handleSubmit() {
// 检查是否还有未创建的实体
if (
props.entitiesToCreate.shops.length > 0 ||
props.entitiesToCreate.products.length > 0 ||
props.entitiesToCreate.specs.length > 0
) {
message.warning('请先创建所有缺失的实体');
return;
}
emit('success');
modalApi.close();
}
// 处理取消
function handleCancel() {
emit('cancel');
modalApi.close();
}
// 打开店铺创建模态框
function openShopModal(shopName: string) {
currentCreatingShop.value = shopName;
// 从CSV数据中获取更多店铺信息
const shopData = {
name: shopName,
description: `从CSV文件导入的店铺:${shopName}`,
// 可以根据需要添加更多默认值
};
shopFormModalRef.value?.open(false, shopData);
}
// 打开商品创建模态框
function openProductModal(productName: string) {
currentCreatingProduct.value = productName;
// 从CSV数据中获取该商品的所有规格信息
const csvSpecs =
props.csvData?.filter((row) => row.productName === productName) || [];
// 对规格进行去重处理,使用Map来去重
const specMap = new Map<string, { specCode: string; specName: string }>();
csvSpecs.forEach((row) => {
const specCode = row.specCode;
const specName = row.productSpecName;
if (specCode && !specMap.has(specCode)) {
specMap.set(specCode, {
specCode,
specName: specName || specCode, // 如果没有规格名称,使用规格编码
});
}
});
// 转换为数组
const uniqueSpecs = [...specMap.values()];
// 构建商品数据,包含规格信息
const productData = {
name: productName,
description: `从CSV文件导入的商品:${productName}`,
// 添加规格信息
specs: uniqueSpecs,
};
productFormModalRef.value?.open(false, productData);
}
// 打开商品规格创建模态框
function openProductSpecModal(spec: {
productName: string;
specCode: string;
specName?: string;
}) {
currentCreatingSpec.value = spec;
// 由于ProductSpecModal需要完整的商品对象,这里需要先创建商品
// 或者修改ProductSpecModal以支持部分数据
message.info('请先创建对应的商品,然后再创建规格');
}
// 处理店铺创建成功
function handleShopCreated() {
message.success(`店铺 "${currentCreatingShop.value}" 创建成功`);
currentCreatingShop.value = '';
// 这里可以触发重新匹配
emit('success');
}
// 处理商品创建成功
function handleProductCreated() {
message.success(`商品 "${currentCreatingProduct.value}" 创建成功`);
currentCreatingProduct.value = '';
// 这里可以触发重新匹配
emit('success');
}
// 处理商品规格创建成功
function handleProductSpecCreated() {
if (currentCreatingSpec.value) {
message.success(
`商品规格 "${currentCreatingSpec.value.productName} - ${currentCreatingSpec.value.specCode}" 创建成功`,
);
currentCreatingSpec.value = null;
// 这里可以触发重新匹配
emit('success');
}
}
</script>
<template>
<Modal title="创建缺失的实体" :confirm-loading="loading">
<div class="space-y-6">
<!-- 店铺创建 -->
<div
v-if="entitiesToCreate.shops.length > 0"
class="rounded-lg border border-gray-200 p-4"
>
<h3 class="mb-4 text-lg font-medium text-gray-900">
需要创建的店铺 ({{ entitiesToCreate.shops.length }} 个)
</h3>
<div class="space-y-3">
<div
v-for="(shopName, index) in entitiesToCreate.shops"
:key="`shop-${index}`"
class="flex items-center gap-4 rounded bg-gray-50 p-3"
>
<span class="font-medium">{{ shopName }}</span>
<Button
type="primary"
size="small"
@click="openShopModal(shopName)"
>
创建店铺
</Button>
</div>
</div>
</div>
<!-- 商品创建 -->
<div
v-if="entitiesToCreate.products.length > 0"
class="rounded-lg border border-gray-200 p-4"
>
<h3 class="mb-4 text-lg font-medium text-gray-900">
需要创建的商品 ({{ entitiesToCreate.products.length }} 个)
</h3>
<div class="space-y-3">
<div
v-for="(productName, index) in entitiesToCreate.products"
:key="`product-${index}`"
class="flex items-center gap-4 rounded bg-gray-50 p-3"
>
<span class="font-medium">{{ productName }}</span>
<Button
type="primary"
size="small"
@click="openProductModal(productName)"
>
创建商品
</Button>
</div>
</div>
</div>
<!-- 商品规格创建 -->
<div
v-if="entitiesToCreate.specs.length > 0"
class="rounded-lg border border-gray-200 p-4"
>
<h3 class="mb-4 text-lg font-medium text-gray-900">
需要创建的商品规格 ({{ entitiesToCreate.specs.length }} 个)
</h3>
<div class="space-y-3">
<div
v-for="(spec, index) in entitiesToCreate.specs"
:key="`spec-${index}`"
class="flex items-center gap-4 rounded bg-gray-50 p-3"
>
<span class="font-medium">
{{ spec.productName }} - {{ spec.specCode }}
</span>
<Button
type="primary"
size="small"
@click="openProductSpecModal(spec)"
>
创建规格
</Button>
</div>
</div>
</div>
<!-- 提示信息 -->
<div class="rounded-lg border border-blue-200 bg-blue-50 p-4">
<div class="flex items-start">
<div class="flex-shrink-0">
<svg
class="h-5 w-5 text-blue-400"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
clip-rule="evenodd"
/>
</svg>
</div>
<div class="ml-3">
<h3 class="text-sm font-medium text-blue-800">提示</h3>
<div class="mt-2 text-sm text-blue-700">
<p>
请先创建所有缺失的实体,然后再进行数据导入。创建完成后,系统将自动重新匹配数据。
</p>
</div>
</div>
</div>
</div>
</div>
</Modal>
<!-- 店铺创建模态框 -->
<ShopFormModal ref="shopFormModalRef" @success="handleShopCreated" />
<!-- 商品创建模态框 -->
<ProductFormModal ref="productFormModalRef" @success="handleProductCreated" />
<!-- 商品规格创建模态框 -->
<ProductSpecModal
ref="productSpecModalRef"
@success="handleProductSpecCreated"
/>
</template>
@@ -1,220 +0,0 @@
<script setup lang="ts">
import { computed, h, ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Table } from 'ant-design-vue';
import {
downloadJSON,
generateExportData,
transformDataWithMapping,
} from '#/utils/csv-utils';
const props = defineProps<Props>();
// Emits
const emit = defineEmits<{
cancel: [];
confirm: [data: any];
}>();
// 创建图标组件
const InfoIcon = createIconifyIcon('lucide:info');
// Props
interface Props {
csvHeaders: string[];
csvData: any[];
}
// 响应式数据
const fieldMappings = ref<Record<string, string>>({});
const customFieldNames = ref<Record<string, string>>({});
// 标准字段选项
const standardFields = [
{ value: 'product_name', label: '商品名称' },
{ value: 'order_id', label: '订单号' },
{ value: 'order_status', label: '订单状态' },
{ value: 'quantity', label: '商品数量' },
{ value: 'product_id', label: '商品ID' },
{ value: 'product_spec', label: '商品规格' },
{ value: 'after_sale_status', label: '售后状态' },
{ value: 'amount', label: '实收金额' },
{ value: 'shop_name', label: '店铺名称' },
{ value: 'order_date', label: '订单日期' },
{ value: 'customer_id', label: '客户ID' },
{ value: 'payment_method', label: '支付方式' },
{ value: 'delivery_address', label: '收货地址' },
{ value: 'remark', label: '备注' },
];
// 计算属性
const mappingData = computed(() => {
return props.csvHeaders.map((header, index) => ({
key: index,
csvField: header,
standardField: fieldMappings.value[header] || '',
customName: customFieldNames.value[header] || '',
}));
});
const mappingColumns = [
{
title: 'CSV字段',
dataIndex: 'csvField',
key: 'csvField',
width: 200,
},
{
title: '标准字段',
dataIndex: 'standardField',
key: 'standardField',
width: 200,
customRender: ({ record }: any) => {
return h('Select', {
value: record.standardField,
placeholder: '选择标准字段',
allowClear: true,
options: standardFields,
onChange: (value: string) => {
fieldMappings.value[record.csvField] = value;
},
});
},
},
{
title: '自定义字段名',
dataIndex: 'customName',
key: 'customName',
width: 200,
customRender: ({ record }: any) => {
return h('Input', {
value: record.customName,
placeholder: '可选:自定义字段名',
onChange: (e: any) => {
customFieldNames.value[record.csvField] = e.target.value;
},
});
},
},
{
title: '示例数据',
dataIndex: 'example',
key: 'example',
ellipsis: true,
customRender: ({ record }: any) => {
const exampleValue = props.csvData[0]?.[record.csvField] || '';
return (
exampleValue.toString().slice(0, 50) +
(exampleValue.toString().length > 50 ? '...' : '')
);
},
},
];
const previewData = computed(() => {
if (Object.keys(fieldMappings.value).length === 0) return [];
return transformDataWithMapping(
props.csvData,
fieldMappings.value,
customFieldNames.value,
);
});
const previewColumns = computed(() => {
const columns = Object.keys(previewData.value[0] || {}).map((field) => ({
title: field,
dataIndex: field,
key: field,
width: 150,
ellipsis: true,
}));
return columns;
});
// 监听字段映射变化,自动生成预览
watch(
[fieldMappings, customFieldNames],
() => {
// 预览数据会自动更新
},
{ deep: true },
);
// 导出JSON
const handleExport = () => {
if (previewData.value.length === 0) {
message.warning('请先配置字段映射');
return;
}
const exportData = generateExportData(
previewData.value,
fieldMappings.value,
customFieldNames.value,
);
// 使用工具函数下载JSON
downloadJSON(exportData);
message.success('JSON文件导出成功');
emit('confirm', exportData);
};
</script>
<template>
<div class="space-y-6">
<!-- 字段映射说明 -->
<div class="rounded-lg border border-blue-200 bg-blue-50 p-4">
<div class="flex items-start space-x-2">
<InfoIcon class="mt-0.5 h-5 w-5 text-blue-500" />
<div>
<p class="font-medium text-blue-800">字段映射说明</p>
<p class="mt-1 text-sm text-blue-600">
请为每个CSV字段选择对应的标准字段,未映射的字段将被忽略。您也可以自定义字段名称。
</p>
</div>
</div>
</div>
<!-- 字段映射表格 -->
<div class="rounded-lg border">
<Table
:columns="mappingColumns"
:data-source="mappingData"
:pagination="false"
size="small"
/>
</div>
<!-- 数据预览 -->
<div v-if="previewData.length > 0">
<h4 class="text-md mb-3 font-medium">映射后数据预览</h4>
<Table
:columns="previewColumns"
:data-source="previewData.slice(0, 5)"
:pagination="false"
size="small"
:scroll="{ x: 800 }"
/>
<p class="mt-2 text-sm text-gray-500">
显示前5条映射后的数据,共 {{ previewData.length }} 条记录
</p>
</div>
<!-- 操作按钮 -->
<div class="flex justify-end space-x-3 border-t pt-4">
<Button @click="$emit('cancel')"> 取消 </Button>
<Button @click="handleExport" type="primary"> 导出JSON </Button>
</div>
</div>
</template>
<style scoped>
.ant-table-tbody > tr > td {
padding: 8px 12px;
}
</style>
@@ -1,498 +0,0 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, Select } from 'ant-design-vue';
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[1200px]',
onCancel() {
handleCancel();
},
});
// 创建图标组件
const InfoIcon = createIconifyIcon('lucide:info');
const CheckIcon = createIconifyIcon('lucide:check');
const XIcon = createIconifyIcon('lucide:x');
interface SystemField {
key: string;
label: string;
description: string;
required: boolean;
dataType: string;
}
interface Props {
visible: boolean;
csvHeaders: string[];
csvData: any[];
}
interface Emits {
(e: 'update:visible', value: boolean): void;
(e: 'confirm', mappings: Record<string, string>): void;
(e: 'cancel'): void;
}
// 系统字段定义
const systemFields: SystemField[] = [
{
key: 'shopName',
label: '店铺名称',
description: '订单所属店铺名称',
required: true,
dataType: 'string',
},
{
key: 'productName',
label: '商品名称',
description: '订单商品名称',
required: true,
dataType: 'string',
},
{
key: 'productSpecName',
label: '商品规格',
description: '商品规格名称',
required: false,
dataType: 'string',
},
{
key: 'specCode',
label: '规格编码',
description: '商品规格编码',
required: false,
dataType: 'string',
},
{
key: 'orderNumber',
label: '订单编号',
description: '平台订单编号',
required: true,
dataType: 'string',
},
{
key: 'orderStatusName',
label: '订单状态',
description: '订单状态名称',
required: true,
dataType: 'string',
},
{
key: 'quantity',
label: '商品数量',
description: '订单商品数量',
required: true,
dataType: 'number',
},
{
key: 'shopActualAmount',
label: '实收金额',
description: '商家实际收到金额',
required: true,
dataType: 'number',
},
{
key: 'unitPrice',
label: '销售单价',
description: '商品销售单价',
required: false,
dataType: 'number',
},
{
key: 'costPrice',
label: '成本价',
description: '商品成本价格',
required: false,
dataType: 'number',
},
{
key: 'orderDate',
label: '下单时间',
description: '订单创建时间',
required: false,
dataType: 'date',
},
{
key: 'shippingFee',
label: '运费',
description: '订单运费',
required: false,
dataType: 'number',
},
];
// 字段映射状态
const fieldMappings = ref<Record<string, string>>({});
// CSV字段选项
const csvFieldOptions = computed(() => {
return props.csvHeaders.map((header) => ({
label: header,
value: header,
}));
});
// 已映射字段数量
const mappedFieldsCount = computed(() => {
return Object.values(fieldMappings.value).filter(Boolean).length;
});
// 未映射字段数量
const unmappedFieldsCount = computed(() => {
return systemFields.length - mappedFieldsCount.value;
});
// 监听visible变化
watch(
() => props.visible,
(newVal) => {
if (newVal) {
modalApi.open();
// 初始化字段映射
initializeFieldMappings();
} else {
modalApi.close();
}
},
{ immediate: true },
);
// 初始化字段映射
const initializeFieldMappings = () => {
const mappings: Record<string, string> = {};
// 尝试自动匹配字段
systemFields.forEach((field) => {
const matchedHeader = findBestMatch(field.label, props.csvHeaders);
if (matchedHeader) {
mappings[field.key] = matchedHeader;
}
});
fieldMappings.value = mappings;
};
// 查找最佳匹配
const findBestMatch = (
systemFieldLabel: string,
csvHeaders: string[],
): null | string => {
const systemFieldLower = systemFieldLabel.toLowerCase();
// 精确匹配
for (const header of csvHeaders) {
if (header.toLowerCase() === systemFieldLower) {
return header;
}
}
// 包含匹配
for (const header of csvHeaders) {
if (
header.toLowerCase().includes(systemFieldLower) ||
systemFieldLower.includes(header.toLowerCase())
) {
return header;
}
}
// 关键词匹配
const keywords = {
店铺名称: ['店铺', 'shop', 'store'],
商品名称: ['商品', 'product', 'item'],
商品规格: ['规格', 'spec', '规格名称'],
规格编码: ['编码', 'code', '规格编码'],
订单编号: ['订单', 'order', '编号', 'number'],
订单状态: ['状态', 'status'],
商品数量: ['数量', 'quantity', 'qty'],
实收金额: ['实收', '金额', 'amount', 'received'],
销售单价: ['单价', 'price', 'unit'],
成本价: ['成本', 'cost'],
下单时间: ['时间', 'date', 'time', '下单'],
运费: ['运费', 'shipping', 'freight'],
};
const fieldKeywords =
keywords[systemFieldLabel as keyof typeof keywords] || [];
for (const header of csvHeaders) {
for (const keyword of fieldKeywords) {
if (header.toLowerCase().includes(keyword)) {
return header;
}
}
}
return null;
};
// 下拉框搜索过滤
const filterOption = (input: string, option: any) => {
return option.label.toLowerCase().includes(input.toLowerCase());
};
// 处理字段映射变化
const handleFieldMappingChange = (
fieldKey: string,
value: string | undefined,
) => {
fieldMappings.value[fieldKey] = value || '';
};
// 获取字段数据样本
const getFieldSamples = (fieldName: string) => {
if (!fieldName || props.csvData.length === 0) return [];
return props.csvData
.slice(0, 3)
.map((row) => row[fieldName] || '')
.filter((val) => val !== '');
};
// 处理确认
const handleConfirm = () => {
if (unmappedFieldsCount.value > 0) {
return;
}
emit('confirm', { ...fieldMappings.value });
modalApi.close();
emit('update:visible', false);
};
// 处理取消
const handleCancel = () => {
modalApi.close();
emit('update:visible', false);
emit('cancel');
};
// 处理重置
const handleReset = () => {
fieldMappings.value = {};
};
</script>
<template>
<Modal title="字段匹配配置" :footer="false">
<div class="field-mapping-container">
<!-- 说明信息 -->
<div class="mb-4 rounded-lg border border-blue-200 bg-blue-50 p-3">
<div class="flex items-center space-x-2">
<InfoIcon class="h-4 w-4 text-blue-500" />
<span class="text-sm text-blue-800">
请将左侧系统字段与右侧CSV文件字段进行匹配,重新组织数据结构以正确进行实体匹配
</span>
</div>
</div>
<!-- 字段映射区域 -->
<div class="grid grid-cols-2 gap-6">
<!-- 左侧:系统字段 -->
<div class="system-fields">
<div class="mb-3">
<h3 class="text-lg font-medium text-gray-800">系统字段</h3>
<p class="text-sm text-gray-600">系统预定义的订单字段,必须映射</p>
</div>
<div class="max-h-96 space-y-3 overflow-y-auto">
<div
v-for="field in systemFields"
:key="field.key"
class="field-item rounded-lg border p-3"
:class="{
'border-green-200 bg-green-50': fieldMappings[field.key],
'border-gray-200 bg-gray-50': !fieldMappings[field.key],
}"
>
<div class="flex items-center justify-between">
<div class="flex-1">
<div class="flex items-center space-x-2">
<span class="font-medium text-gray-800">{{
field.label
}}</span>
<span v-if="field.required" class="text-xs text-red-500">
*
</span>
</div>
<div class="mt-1 text-xs text-gray-500">
{{ field.description }}
</div>
</div>
<div class="flex items-center space-x-2">
<CheckIcon
v-if="fieldMappings[field.key]"
class="h-4 w-4 text-green-500"
/>
<XIcon v-else class="h-4 w-4 text-gray-400" />
</div>
</div>
</div>
</div>
</div>
<!-- 右侧:CSV字段映射 -->
<div class="csv-fields">
<div class="mb-3">
<h3 class="text-lg font-medium text-gray-800">CSV字段映射</h3>
<p class="text-sm text-gray-600">选择CSV文件中的对应字段</p>
</div>
<div class="max-h-96 space-y-3 overflow-y-auto">
<div
v-for="field in systemFields"
:key="field.key"
class="field-mapping-item rounded-lg border p-3"
>
<div class="mb-2 flex items-center justify-between">
<div class="flex items-center space-x-2">
<span class="font-medium text-gray-800">{{
field.label
}}</span>
<span v-if="field.required" class="text-xs text-red-500">
*
</span>
</div>
<div class="flex items-center space-x-2">
<CheckIcon
v-if="fieldMappings[field.key]"
class="h-4 w-4 text-green-500"
/>
<XIcon v-else class="h-4 w-4 text-gray-400" />
</div>
</div>
<Select
v-model:value="fieldMappings[field.key]"
placeholder="请选择CSV字段"
style="width: 100%"
:options="csvFieldOptions"
:filter-option="filterOption"
show-search
allow-clear
@change="
(value: any) => handleFieldMappingChange(field.key, value)
"
>
<template #option="{ label, value }">
<div class="flex items-center justify-between">
<span>{{ label }}</span>
<span class="text-xs text-gray-500">{{ value }}</span>
</div>
</template>
</Select>
<!-- 字段预览 -->
<div v-if="fieldMappings[field.key]" class="mt-2">
<div class="mb-1 text-xs text-gray-600">数据预览:</div>
<div
class="max-h-20 overflow-y-auto rounded bg-gray-100 p-2 text-xs"
>
<div
v-for="(sample, index) in getFieldSamples(
fieldMappings[field.key] || '',
)"
:key="index"
>
{{ sample }}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 映射统计 -->
<div class="mt-6 rounded-lg border bg-gray-50 p-4">
<div class="grid grid-cols-3 gap-4 text-center">
<div>
<div class="text-2xl font-bold text-blue-600">
{{ systemFields.length }}
</div>
<div class="text-sm text-gray-600">总字段数</div>
</div>
<div>
<div class="text-2xl font-bold text-green-600">
{{ mappedFieldsCount }}
</div>
<div class="text-sm text-gray-600">已映射</div>
</div>
<div>
<div class="text-2xl font-bold text-red-600">
{{ unmappedFieldsCount }}
</div>
<div class="text-sm text-gray-600">未映射</div>
</div>
</div>
</div>
<!-- 操作按钮 -->
<div class="mt-6 flex justify-end space-x-3">
<Button @click="handleCancel"> 取消 </Button>
<Button @click="handleReset" type="default"> 重置 </Button>
<Button
type="primary"
@click="handleConfirm"
:disabled="unmappedFieldsCount > 0"
>
确认匹配 ({{ mappedFieldsCount }}/{{ systemFields.length }})
</Button>
</div>
</div>
</Modal>
</template>
<style scoped>
.field-mapping-container {
max-height: 80vh;
overflow-y: auto;
}
.field-item {
transition: all 0.2s ease;
}
.field-item:hover {
border-color: #3b82f6;
background-color: #eff6ff;
}
.field-mapping-item {
transition: all 0.2s ease;
}
.field-mapping-item:hover {
border-color: #3b82f6;
background-color: #eff6ff;
}
/* 滚动条样式 */
.overflow-y-auto::-webkit-scrollbar {
width: 6px;
}
.overflow-y-auto::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 3px;
}
.overflow-y-auto::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 3px;
}
.overflow-y-auto::-webkit-scrollbar-thumb:hover {
background: #a8a8a8;
}
</style>
@@ -3,14 +3,24 @@ import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, message } from 'ant-design-vue';
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 {
@@ -40,6 +50,7 @@ const validateFile = (file: File): boolean => {
// 处理文件
const processFile = (file: File) => {
if (props.loading) return;
if (!validateFile(file)) return;
emit('fileSelected', file);
};
@@ -88,31 +99,61 @@ const handleFileSelect = (e: Event) => {
</script>
<template>
<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 }"
@dragover.prevent="handleDragOver"
@dragleave.prevent="handleDragLeave"
@drop.prevent="handleDrop"
>
<div class="space-y-4">
<UploadIcon class="mx-auto h-12 w-12 text-gray-400" />
<div>
<p class="text-lg font-medium text-gray-700">
拖拽CSV文件到此处或点击上传
</p>
<p class="text-sm text-gray-500">支持.csv格式,最大10MB</p>
<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>
<Button @click="triggerFileInput" type="primary" ghost> 选择文件 </Button>
<input
ref="fileInputRef"
type="file"
accept=".csv"
style="display: none"
:disabled="loading"
@change="handleFileSelect"
/>
</div>
<input
ref="fileInputRef"
type="file"
accept=".csv"
style="display: none"
@change="handleFileSelect"
/>
</div>
</Spin>
</template>
<style scoped>
@@ -1,230 +0,0 @@
<script setup lang="ts">
import { ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message } from 'ant-design-vue';
defineOptions({ name: 'FileUploadModal' });
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[800px]',
onCancel() {
handleCancel();
},
});
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload');
const CheckCircleIcon = createIconifyIcon('lucide:check-circle');
// Props
interface Props {
open: boolean;
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void;
(e: 'confirm', file: File): void;
(e: 'cancel'): void;
}
// 响应式数据
const uploadedFile = ref<File | null>(null);
const isDragOver = ref(false);
const fileInputRef = ref<HTMLInputElement>();
// 监听props变化
watch(
() => props.open,
(newVal) => {
if (newVal) {
modalApi.open();
} else {
modalApi.close();
// 关闭时重置状态
uploadedFile.value = null;
isDragOver.value = false;
}
},
{ immediate: true },
);
// 文件验证
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 (!validateFile(file)) return;
uploadedFile.value = file;
message.success('文件选择成功');
};
// 拖拽处理
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 = '';
};
// 清除文件
const clearFile = () => {
uploadedFile.value = null;
};
// 确认上传
const handleConfirm = () => {
if (uploadedFile.value) {
emit('confirm', uploadedFile.value);
modalApi.close();
emit('update:open', false);
}
};
// 取消
const handleCancel = () => {
emit('cancel');
modalApi.close();
emit('update:open', false);
};
// 格式化文件大小
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
};
</script>
<template>
<Modal title="继续导入CSV文件" :footer="false">
<div class="space-y-6">
<!-- 文件拖拽上传区域 -->
<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 }"
@dragover.prevent="handleDragOver"
@dragleave.prevent="handleDragLeave"
@drop.prevent="handleDrop"
>
<div class="space-y-4">
<UploadIcon class="mx-auto h-12 w-12 text-gray-400" />
<div>
<p class="text-lg font-medium text-gray-700">
拖拽CSV文件到此处或点击上传
</p>
<p class="text-sm text-gray-500">支持.csv格式,最大10MB</p>
</div>
<Button @click="triggerFileInput" type="primary" ghost>
选择文件
</Button>
</div>
<input
ref="fileInputRef"
type="file"
accept=".csv"
style="display: none"
@change="handleFileSelect"
/>
</div>
<!-- 文件信息显示 -->
<div
v-if="uploadedFile"
class="rounded-lg border border-green-200 bg-green-50 p-4"
>
<div class="flex items-center justify-between">
<div class="flex items-center space-x-2">
<CheckCircleIcon class="h-5 w-5 text-green-500" />
<span class="font-medium text-green-800">文件上传成功</span>
</div>
<Button @click="clearFile" size="small" type="text" danger>
清除文件
</Button>
</div>
<p class="mt-1 text-sm text-green-600">
{{ uploadedFile.name }} ({{ formatFileSize(uploadedFile.size) }})
</p>
</div>
<!-- 操作按钮 -->
<div class="flex justify-end space-x-2">
<Button @click="handleCancel"> 取消 </Button>
<Button @click="handleConfirm" type="primary" :disabled="!uploadedFile">
确认导入
</Button>
</div>
</div>
</Modal>
</template>
<style scoped>
/* 拖拽区域样式 */
.border-dashed {
transition: all 0.3s ease;
}
.border-dashed:hover {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
</style>
@@ -1,446 +0,0 @@
<script setup lang="ts">
import type { MatchDetail } from '../services/EntityMatchingService';
import { ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, Select } from 'ant-design-vue';
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[600px]',
onCancel() {
handleCancel();
},
});
// 创建图标组件
const CheckIcon = createIconifyIcon('lucide:check');
const XIcon = createIconifyIcon('lucide:x');
const AlertTriangleIcon = createIconifyIcon('lucide:alert-triangle');
const InfoIcon = createIconifyIcon('lucide:info');
interface Props {
visible: boolean;
matchDetail: MatchDetail | null;
fieldType: 'orderStatus' | 'product' | 'shop' | 'spec';
sameDataCount?: number;
}
interface Emits {
(e: 'update:visible', value: boolean): void;
(e: 'applyMatch', rowIndex: number, fieldType: string, matchId: string): void;
(e: 'applyToAll', rowIndex: number, fieldType: string, matchId: string): void;
}
const selectedMatchId = ref<string>('');
watch(
() => props.visible,
(newVal) => {
if (newVal) {
modalApi.open();
if (props.matchDetail) {
// 初始化选中的匹配项
selectedMatchId.value = getCurrentMatchId() || '';
}
} else {
modalApi.close();
}
},
{ immediate: true },
);
const getStatusText = (status: string) => {
switch (status) {
case 'failed': {
return '匹配失败';
}
case 'matched': {
return '匹配成功';
}
case 'partial': {
return '部分匹配';
}
default: {
return '未知状态';
}
}
};
// 获取模态框标题
const getModalTitle = () => {
const titles = {
shop: '店铺匹配切换',
product: '商品匹配切换',
spec: '规格匹配切换',
orderStatus: '订单状态匹配切换',
};
return titles[props.fieldType] || '匹配切换';
};
// 获取字段标题
const getFieldTitle = () => {
const titles = {
shop: '店铺',
product: '商品',
spec: '规格',
orderStatus: '订单状态',
};
return titles[props.fieldType] || '字段';
};
// 获取字段名称
const getFieldName = () => {
const names = {
shop: '店铺',
product: '商品',
spec: '规格',
orderStatus: '订单状态',
};
return names[props.fieldType] || '字段';
};
// 获取字段值
const getFieldValue = () => {
if (!props.matchDetail) return '';
switch (props.fieldType) {
case 'orderStatus': {
return props.matchDetail.originalData.orderStatusName;
}
case 'product': {
return props.matchDetail.originalData.productName;
}
case 'shop': {
return props.matchDetail.originalData.shopName;
}
case 'spec': {
return props.matchDetail.originalData.productSpecName;
}
default: {
return '';
}
}
};
// 获取当前匹配信息
const getCurrentMatchInfo = () => {
if (!props.matchDetail) return null;
switch (props.fieldType) {
case 'orderStatus': {
return props.matchDetail.matchedOrderStatusId
? {
name: props.matchDetail.originalData.orderStatusName,
id: props.matchDetail.matchedOrderStatusId,
}
: null;
}
case 'product': {
return props.matchDetail.matchedProduct
? {
name: props.matchDetail.matchedProduct.name,
id: props.matchDetail.matchedProduct.id,
}
: null;
}
case 'shop': {
return props.matchDetail.matchedShop
? {
name: props.matchDetail.matchedShop.name,
id: props.matchDetail.matchedShop.id,
}
: null;
}
case 'spec': {
return props.matchDetail.matchedSpec
? {
name: props.matchDetail.matchedSpec.name,
id: props.matchDetail.matchedSpec.id,
specCode: props.matchDetail.matchedSpec.specCode,
}
: null;
}
default: {
return null;
}
}
};
// 获取当前匹配ID
const getCurrentMatchId = () => {
const matchInfo = getCurrentMatchInfo();
return matchInfo?.id?.toString() || '';
};
// 获取字段匹配状态样式
const getFieldMatchStatusClass = () => {
const matchInfo = getCurrentMatchInfo();
return matchInfo ? 'bg-green-500' : 'bg-red-500';
};
// 获取字段匹配状态文本
const getFieldMatchStatusText = () => {
const matchInfo = getCurrentMatchInfo();
return matchInfo ? '已匹配' : '未匹配';
};
// 获取匹配选项(模拟数据,实际应该从API获取)
const getMatchOptions = () => {
// 这里应该根据fieldType从API获取可选的匹配项
// 暂时返回模拟数据
const mockOptions = {
shop: [
{ label: '锐泽创意家居', value: '123' },
{ label: '其他店铺1', value: '124' },
{ label: '其他店铺2', value: '125' },
],
product: [
{ label: '创意台灯', value: '456' },
{ label: '其他商品1', value: '457' },
{ label: '其他商品2', value: '458' },
],
spec: [
{ label: '白色', value: '789' },
{ label: '黑色', value: '790' },
{ label: '红色', value: '791' },
],
orderStatus: [
{ label: '已发货,待收货', value: '1' },
{ label: '未发货,退款成功', value: '2' },
{ label: '已取消', value: '3' },
],
};
return mockOptions[props.fieldType] || [];
};
// 处理匹配选择变化
const handleMatchChange = (value: string) => {
selectedMatchId.value = value;
};
// 处理应用匹配
const handleApplyMatch = () => {
if (props.matchDetail && selectedMatchId.value) {
emit(
'applyMatch',
props.matchDetail.rowIndex,
props.fieldType,
selectedMatchId.value,
);
}
modalApi.close();
emit('update:visible', false);
};
// 处理应用到所有相同数据
const handleApplyToAll = () => {
if (props.matchDetail && selectedMatchId.value) {
emit(
'applyToAll',
props.matchDetail.rowIndex,
props.fieldType,
selectedMatchId.value,
);
}
modalApi.close();
emit('update:visible', false);
};
const handleCancel = () => {
modalApi.close();
emit('update:visible', false);
};
</script>
<template>
<Modal :title="getModalTitle()">
<div v-if="matchDetail" class="space-y-4">
<!-- 当前匹配状态 -->
<div class="mb-4 flex items-center space-x-2">
<div
class="flex h-4 w-4 items-center justify-center rounded-full"
:class="{
'bg-green-500': matchDetail.status === 'matched',
'bg-red-500': matchDetail.status === 'failed',
'bg-yellow-500': matchDetail.status === 'partial',
}"
>
<CheckIcon
v-if="matchDetail.status === 'matched'"
class="h-3 w-3 text-white"
/>
<XIcon
v-else-if="matchDetail.status === 'failed'"
class="h-3 w-3 text-white"
/>
<AlertTriangleIcon
v-else-if="matchDetail.status === 'partial'"
class="h-3 w-3 text-white"
/>
</div>
<span class="font-medium">
{{ getStatusText(matchDetail.status) }}
</span>
<span class="text-gray-500">第 {{ matchDetail.rowIndex }} 行</span>
</div>
<!-- 原始数据 -->
<div class="rounded-lg bg-gray-50 p-4">
<h4 class="mb-3 font-medium text-gray-800">原始数据</h4>
<div class="grid grid-cols-2 gap-3 text-sm">
<div>
<span class="text-gray-600">商品名称:</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.productName
}}</span>
</div>
<div>
<span class="text-gray-600">订单编号:</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.orderNumber
}}</span>
</div>
<div>
<span class="text-gray-600">商品规格:</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.productSpecName
}}</span>
</div>
<div>
<span class="text-gray-600">规格编码:</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.specCode
}}</span>
</div>
<div>
<span class="text-gray-600">店铺名称:</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.shopName
}}</span>
</div>
<div>
<span class="text-gray-600">订单状态:</span>
<span class="ml-2 font-medium">{{
matchDetail.originalData.orderStatusName
}}</span>
</div>
</div>
</div>
<!-- 当前字段匹配信息 -->
<div class="rounded-lg border p-4">
<div class="mb-3 flex items-center justify-between">
<h4 class="font-medium text-gray-800">{{ getFieldTitle() }}</h4>
<div class="flex items-center space-x-2">
<div
class="h-3 w-3 rounded-full"
:class="getFieldMatchStatusClass()"
></div>
<span class="text-sm">
{{ getFieldMatchStatusText() }}
</span>
</div>
</div>
<!-- 当前匹配信息 -->
<div
v-if="getCurrentMatchInfo()"
class="mb-3 rounded border border-green-200 bg-green-50 p-3"
>
<div class="text-sm">
<div class="font-medium text-green-800">
{{ getCurrentMatchInfo()?.name }}
</div>
<div class="text-green-600">
ID: {{ getCurrentMatchInfo()?.id }}
</div>
<div v-if="getCurrentMatchInfo()?.specCode" class="text-green-600">
编码: {{ getCurrentMatchInfo()?.specCode }}
</div>
</div>
</div>
<!-- 未匹配信息 -->
<div v-else class="mb-3 rounded border border-red-200 bg-red-50 p-3">
<div class="text-sm text-red-700">
{{ getFieldName() }} "{{ getFieldValue() }}" 未找到匹配
</div>
</div>
<!-- 匹配选项下拉框 -->
<div class="space-y-3">
<div>
<label class="mb-2 block text-sm font-medium text-gray-700">
选择匹配的{{ getFieldTitle() }}:
</label>
<Select
v-model:value="selectedMatchId"
placeholder="请选择匹配项"
style="width: 100%"
:options="getMatchOptions()"
@change="(value: any) => handleMatchChange(value)"
/>
</div>
<div
v-if="selectedMatchId"
class="rounded border border-blue-200 bg-blue-50 p-3"
>
<div class="text-sm">
<div class="font-medium text-blue-800">已选择匹配项</div>
<div class="text-blue-600">ID: {{ selectedMatchId }}</div>
</div>
</div>
</div>
</div>
<!-- 相同数据提示 -->
<div
v-if="sameDataCount && sameDataCount > 1"
class="rounded-lg border border-blue-200 bg-blue-50 p-3"
>
<div class="flex items-center space-x-2">
<InfoIcon class="h-4 w-4 text-blue-500" />
<span class="text-sm text-blue-800">
检测到
{{ sameDataCount }} 条相同数据,切换匹配将同时应用到所有相同数据
</span>
</div>
</div>
</div>
<template #footer>
<div class="flex justify-end space-x-2">
<Button @click="handleCancel">关闭</Button>
<Button
type="primary"
@click="handleApplyMatch"
:disabled="!selectedMatchId"
>
应用匹配
</Button>
<Button
v-if="sameDataCount && sameDataCount > 1"
type="primary"
@click="handleApplyToAll"
:disabled="!selectedMatchId"
>
应用到所有相同数据
</Button>
</div>
</template>
</Modal>
</template>
<style scoped>
/* 自定义样式 */
</style>
@@ -1,157 +1,65 @@
<script setup lang="ts">
import type {
EntityMatchingResult,
MatchDetail,
} from './services/EntityMatchingService';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { ref } from 'vue';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Progress, Space } from 'ant-design-vue';
import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { batchImportOrdersApi } from '#/api/ecommerce/order';
import FieldMappingModal from '#/views/ecommerce/data-import/components/FieldMappingModal.vue';
import EntityCreationModal from './components/EntityCreationModal.vue';
import FileUploadArea from './components/FileUploadArea.vue';
import FileUploadModal from './components/FileUploadModal.vue';
import MatchSwitchModal from './components/MatchSwitchModal.vue';
import { EntityMatchingService } from './services/EntityMatchingService';
import {
convertToCSVOrderData,
extractShopNameFromFilename,
parseOrderCSV,
} from './utils/csvParser';
import { parseCSVToRawData } from './utils/csvParser';
defineOptions({ name: 'DataImport' });
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload');
const CheckCircleIcon = createIconifyIcon('lucide:check-circle');
const CheckIcon = createIconifyIcon('lucide:check');
const XIcon = createIconifyIcon('lucide:x');
// 响应式数据
const uploadedFile = ref<File | null>(null);
const csvData = ref<any[]>([]);
const csvHeaders = ref<string[]>([]);
const showFieldMapping = ref(false);
const showUploadModal = ref(false);
const selectedRows = ref<any[]>([]);
// 实体匹配相关
const entityMatchingService = new EntityMatchingService();
const matchingResult = ref<EntityMatchingResult | null>(null);
const showEntityCreationModal = ref(false);
const importLoading = ref(false);
const importProgress = ref(0);
// 匹配切换相关
const showMatchSwitchModal = ref(false);
const currentMatchDetail = ref<MatchDetail | null>(null);
const currentRowData = ref<any>(null);
const currentFieldType = ref<'orderStatus' | 'product' | 'shop' | 'spec'>(
'shop',
);
// 动态生成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: [
{
type: 'checkbox' as const,
minWidth: 'auto',
fixed: 'left' as const,
},
{
type: 'seq' as const,
minWidth: 'auto',
title: '序号',
},
{
field: 'productName',
title: '商品名称',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
slots: { default: 'productName' },
},
{
field: 'orderNumber',
title: '订单编号',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
field: 'orderStatusName',
title: '订单状态',
minWidth: 'auto',
slots: { default: 'orderStatusName' },
},
{
field: 'quantity',
title: '数量',
minWidth: 'auto',
},
{
field: 'productId',
title: '商品ID',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
field: 'productSpecName',
title: '商品规格',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
slots: { default: 'productSpecName' },
},
{
field: 'specCode',
title: '规格编码',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
field: 'shopName',
title: '店铺名称',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
slots: { default: 'shopName' },
},
{
field: 'afterSaleStatus',
title: '售后状态',
minWidth: 'auto',
},
{
title: '实收金额',
minWidth: 'auto',
slots: { default: 'receivedAmount' },
},
{
title: '操作',
minWidth: 'auto',
fixed: 'right' as const,
slots: { default: 'action' },
},
],
columns: [],
height: 'auto',
border: true,
stripe: true,
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSize: 50,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
@@ -173,661 +81,74 @@ const gridOptions: VxeGridProps<any> = {
| 'Total'
)[],
},
checkboxConfig: {
labelField: 'id',
reserve: true,
highlight: true,
range: true,
},
};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
});
// 更新表格数据
const updateTableData = () => {
// 更新表格数据和列
const updateTable = () => {
gridApi.setGridOptions({
columns: gridColumns.value,
data: csvData.value,
});
};
// 处理文件
const processFile = async (file: File) => {
uploadedFile.value = file;
// 处理文件上传
const handleFileUpload = async (file: File) => {
importLoading.value = true;
try {
// 使用新的CSV解析器
const result = await parseOrderCSV(file);
const result = await parseCSVToRawData(file);
if (result.errors.length > 0) {
message.error(`CSV文件解析失败: ${result.errors.join(', ')}`);
message.warning(result.errors.join('; '));
}
if (result.data.length === 0) {
message.error('CSV文件没有有效数据');
return;
}
// 添加唯一ID并转换为表格数据
const tableData = result.data.map((item, index) => ({
...item,
id: `row_${index}`,
}));
csvData.value = tableData;
csvData.value = result.data;
csvHeaders.value = result.headers;
selectedRows.value = [];
// 更新表格数据
updateTableData();
// 更新表格
updateTable();
// 从文件名提取店铺名称
const shopName = extractShopNameFromFilename(file.name);
message.success(`成功解析 ${tableData.length} 条数据,店铺:${shopName}`);
// 自动进行实体匹配
await performEntityMatching();
message.success(`成功解析 ${result.data.length} 条数据`);
} catch (error: any) {
message.error(`文件读取失败: ${error.message}`);
}
};
// 文件上传处理
const handleFileUpload = async (file: File) => {
await processFile(file);
showUploadModal.value = false;
};
// 表格选择处理
const handleCheckboxChange = ({ records }: { records: any[] }) => {
selectedRows.value = records;
};
const handleCheckboxAll = ({ records }: { records: any[] }) => {
selectedRows.value = records;
};
// 选择操作
const selectAll = () => {
gridApi.grid?.setAllCheckboxRow(true);
};
const clearSelection = () => {
gridApi.grid?.clearCheckboxRow();
};
// 清除数据
const clearData = () => {
csvData.value = [];
csvHeaders.value = [];
selectedRows.value = [];
uploadedFile.value = null;
gridApi.grid?.clearCheckboxRow();
};
// 字段匹配处理
const handleFieldMapping = (fieldMappings: Record<string, string>) => {
showFieldMapping.value = false;
// 应用字段匹配到CSV数据
const matchedCsvData = csvData.value.map((row) => {
const matchedRow: any = {};
// 根据字段匹配重新组织数据
Object.entries(fieldMappings).forEach(([systemField, csvField]) => {
if (csvField && row[csvField] !== undefined) {
matchedRow[systemField] = row[csvField];
}
});
// 保留原始ID
matchedRow.id = row.id;
return matchedRow;
});
// 更新CSV数据
csvData.value = matchedCsvData;
// 更新表格显示
updateTableData();
// 重新进行实体匹配
performEntityMatching();
message.success(
`字段匹配完成,已匹配 ${Object.keys(fieldMappings).length} 个字段,正在重新进行实体匹配...`,
);
};
// 执行实体匹配
const performEntityMatching = async () => {
if (csvData.value.length === 0) return;
try {
// 转换为EntityMatchingService需要的格式
const shopName = uploadedFile.value
? extractShopNameFromFilename(uploadedFile.value.name)
: '未知店铺';
const orderData = convertToCSVOrderData(csvData.value as any[], shopName);
// 执行实体匹配
const result = await entityMatchingService.matchEntities(orderData);
matchingResult.value = result;
// 显示匹配结果
if (result.matchedOrders.length > 0) {
message.success(`成功匹配 ${result.matchedOrders.length} 条订单数据`);
}
if (result.failedRecords.length > 0) {
message.warning(
`${result.failedRecords.length} 条记录需要手动处理,可以在表格中操作`,
);
}
// 如果有需要创建的实体,显示创建模态框
if (
result.entitiesToCreate.shops.length > 0 ||
result.entitiesToCreate.products.length > 0 ||
result.entitiesToCreate.specs.length > 0
) {
showEntityCreationModal.value = true;
}
} catch (error) {
console.error('实体匹配失败:', error);
message.error(
`实体匹配失败: ${error instanceof Error ? error.message : '未知错误'}`,
);
}
};
// 执行数据导入
const performImport = async () => {
if (
!matchingResult.value ||
matchingResult.value.matchedOrders.length === 0
) {
message.warning('没有可导入的数据');
return;
}
try {
importLoading.value = true;
importProgress.value = 0;
// 使用 requestAnimationFrame 进行更平滑的进度更新
const updateProgress = () => {
if (importProgress.value < 90) {
importProgress.value += 10;
requestAnimationFrame(updateProgress);
}
};
// 开始进度更新
requestAnimationFrame(updateProgress);
// 调用批量导入API
const result = await batchImportOrdersApi({
orders: matchingResult.value.matchedOrders,
});
importProgress.value = 100;
message.success(
`导入完成!成功导入 ${result.successCount || 0} 条,失败 ${result.failureCount || 0} 条`,
);
// 显示失败详情
if (result.failureDetails && result.failureDetails.length > 0) {
console.warn('导入失败详情:', result.failureDetails);
}
} catch (error) {
console.error('数据导入失败:', error);
message.error(
`数据导入失败: ${error instanceof Error ? error.message : '未知错误'}`,
);
} finally {
importLoading.value = false;
importProgress.value = 0;
}
};
// 处理实体创建成功
const handleEntityCreationSuccess = async () => {
showEntityCreationModal.value = false;
message.success('实体创建成功,正在重新匹配...');
// 重新执行实体匹配
await performEntityMatching();
};
// 处理实体创建取消
const handleEntityCreationCancel = () => {
showEntityCreationModal.value = false;
};
// 处理行编辑
const handleEditRow = () => {
// 可以打开编辑模态框或内联编辑
message.info('编辑功能待实现');
};
// 处理行匹配
const handleMatchRow = () => {
// 可以打开匹配模态框,让用户手动匹配实体
message.info('匹配功能待实现');
};
// 获取匹配详情
const getMatchDetail = (row: any) => {
if (!matchingResult.value) return null;
return matchingResult.value.matchDetails.find(
(detail) =>
detail.originalData.orderNumber === row.orderNumber &&
detail.originalData.productName === row.productName,
);
};
// 店铺匹配状态
const getShopMatchStatus = (row: any): 'failed' | 'matched' | 'none' => {
const matchDetail = getMatchDetail(row);
if (!matchDetail) return 'none';
if (matchDetail.matchedShop) return 'matched';
if (matchDetail.status === 'failed' && !matchDetail.matchedShop)
return 'failed';
return 'none';
};
// 商品匹配状态
const getProductMatchStatus = (row: any): 'failed' | 'matched' | 'none' => {
const matchDetail = getMatchDetail(row);
if (!matchDetail) return 'none';
if (matchDetail.matchedProduct) return 'matched';
if (matchDetail.status === 'failed' && !matchDetail.matchedProduct)
return 'failed';
return 'none';
};
// 规格匹配状态
const getSpecMatchStatus = (row: any): 'failed' | 'matched' | 'none' => {
const matchDetail = getMatchDetail(row);
if (!matchDetail) return 'none';
if (matchDetail.matchedSpec) return 'matched';
if (matchDetail.status === 'failed' && !matchDetail.matchedSpec)
return 'failed';
return 'none';
};
// 订单状态匹配状态
const getOrderStatusMatchStatus = (row: any): 'failed' | 'matched' | 'none' => {
const matchDetail = getMatchDetail(row);
if (!matchDetail) return 'none';
if (matchDetail.matchedOrderStatusId) return 'matched';
if (matchDetail.status === 'failed' && !matchDetail.matchedOrderStatusId)
return 'failed';
return 'none';
};
// 显示匹配模态框
const showMatchModal = (
row: any,
fieldType: 'orderStatus' | 'product' | 'shop' | 'spec',
) => {
const matchDetail = getMatchDetail(row);
if (matchDetail) {
currentMatchDetail.value = matchDetail;
currentRowData.value = row;
currentFieldType.value = fieldType;
showMatchSwitchModal.value = true;
} else {
message.warning('未找到该行的匹配信息');
}
};
// 获取相同数据的数量
const getSameDataCount = (row: any) => {
if (!row || !matchingResult.value) return 1;
return matchingResult.value.matchDetails.filter(
(detail) =>
detail.originalData.productName === row.productName &&
detail.originalData.orderNumber === row.orderNumber,
).length;
};
// 处理应用匹配
const handleApplyMatch = (
rowIndex: number,
fieldType: string,
matchId: string,
) => {
message.success(
`已应用${fieldType}匹配 - 行 ${rowIndex}, 匹配ID: ${matchId}`,
);
// 这里可以实现具体的匹配应用逻辑
// 1. 更新匹配详情
// 2. 重新计算匹配状态
// 3. 更新表格显示
};
// 处理应用到所有相同数据
const handleApplyToAll = (
rowIndex: number,
fieldType: string,
matchId: string,
) => {
message.success(
`已应用${fieldType}匹配到所有相同数据 - 行 ${rowIndex}, 匹配ID: ${matchId}`,
);
// 这里可以实现应用到所有相同数据的逻辑
// 1. 找到所有相同的数据行
// 2. 批量更新匹配详情
// 3. 重新计算匹配状态
// 4. 更新表格显示
};
// 格式化文件大小
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
// 匹配向导按钮处理
const handleMatchWizard = () => {
message.info('匹配向导功能待实现');
};
</script>
<template>
<Page title="电商数据导入" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
支持CSV文件导入,自动匹配实体信息,批量导入订单数据
</div>
<Page auto-content-height>
<!-- 顶部栏 -->
<template #extra>
<Button type="primary" @click="handleMatchWizard"> 匹配向导 </Button>
</template>
<!-- 文件拖拽上传区域 - 只在没有数据时显示 -->
<FileUploadArea
<!-- 主体内容区域 -->
<div
v-if="csvData.length === 0"
@file-selected="handleFileUpload"
/>
<!-- 数据表格 -->
<Grid
v-if="csvData.length > 0"
@checkbox-change="handleCheckboxChange"
@checkbox-all="handleCheckboxAll"
class="flex h-full items-center justify-center"
>
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
<Button @click="showUploadModal = true" type="default">
<UploadIcon class="mr-1 h-4 w-4" />
继续导入
</Button>
<Button
@click="performImport"
type="primary"
:loading="importLoading"
:disabled="
!matchingResult || matchingResult.matchedOrders.length === 0
"
>
一键上传订单 ({{ matchingResult?.matchedOrders.length || 0 }})
</Button>
<Button @click="selectAll"> 全选 </Button>
<Button @click="clearSelection"> 清空选择 </Button>
<Button
@click="showFieldMapping = true"
:disabled="csvData.length === 0"
>
字段匹配
</Button>
</Space>
</template>
<FileUploadArea
:loading="importLoading"
@file-selected="handleFileUpload"
/>
</div>
<!-- 文件信息显示 -->
<template #toolbar-extra>
<div
v-if="uploadedFile"
class="mb-4 rounded-lg border border-green-200 bg-green-50 p-3"
>
<div class="flex items-center justify-between">
<div class="flex items-center space-x-2">
<CheckCircleIcon class="h-4 w-4 text-green-500" />
<span class="text-sm font-medium text-green-800">
文件上传成功
</span>
</div>
<Button @click="clearData" size="small" type="text" danger>
清除数据
</Button>
</div>
<p class="mt-1 text-xs text-green-600">
{{ uploadedFile.name }} ({{ formatFileSize(uploadedFile.size) }})
</p>
</div>
<!-- 实体匹配结果 -->
<div v-if="matchingResult" class="mb-4 space-y-3">
<div class="rounded-lg border border-blue-200 bg-blue-50 p-3">
<div class="mb-2 text-sm font-medium text-blue-800">
实体匹配结果
</div>
<div class="mb-3 grid grid-cols-3 gap-3">
<div
class="rounded border border-green-200 bg-green-50 p-2 text-center"
>
<div class="text-xs font-medium text-green-800">匹配成功</div>
<div class="text-lg font-bold text-green-600">
{{ matchingResult.matchedOrders.length }}
</div>
<div class="text-xs text-green-600">条订单</div>
</div>
<div
class="rounded border border-red-200 bg-red-50 p-2 text-center"
>
<div class="text-xs font-medium text-red-800">匹配失败</div>
<div class="text-lg font-bold text-red-600">
{{ matchingResult.failedRecords.length }}
</div>
<div class="text-xs text-red-600">条记录</div>
</div>
<div
class="rounded border border-blue-200 bg-blue-50 p-2 text-center"
>
<div class="text-xs font-medium text-blue-800">需要创建</div>
<div class="text-lg font-bold text-blue-600">
{{
matchingResult.entitiesToCreate.shops.length +
matchingResult.entitiesToCreate.products.length +
matchingResult.entitiesToCreate.specs.length
}}
</div>
<div class="text-xs text-blue-600">个实体</div>
</div>
</div>
<div class="flex items-center space-x-2">
<Button
@click="performImport"
type="primary"
size="small"
:loading="importLoading"
:disabled="matchingResult.matchedOrders.length === 0"
>
一键上传订单 ({{ matchingResult.matchedOrders.length }})
</Button>
<Button @click="performEntityMatching" size="small">
重新匹配
</Button>
</div>
<!-- 导入进度 -->
<div v-if="importLoading" class="mt-3">
<Progress :percent="importProgress" size="small" />
</div>
</div>
</div>
</template>
<!-- 商品名称列 -->
<template #productName="{ row }: { row: any }">
<div class="flex items-center space-x-2">
<div
class="flex h-4 w-4 cursor-pointer items-center justify-center rounded-full"
:class="{
'bg-green-500': getProductMatchStatus(row) === 'matched',
'bg-red-500': getProductMatchStatus(row) === 'failed',
'bg-gray-300': getProductMatchStatus(row) === 'none',
}"
@click="showMatchModal(row, 'product')"
>
<CheckIcon
v-if="getProductMatchStatus(row) === 'matched'"
class="h-2.5 w-2.5 text-white"
/>
<XIcon
v-else-if="getProductMatchStatus(row) === 'failed'"
class="h-2.5 w-2.5 text-white"
/>
</div>
<span>{{ row.productName }}</span>
</div>
</template>
<!-- 订单状态列 -->
<template #orderStatusName="{ row }: { row: any }">
<div class="flex items-center space-x-2">
<div
class="flex h-4 w-4 cursor-pointer items-center justify-center rounded-full"
:class="{
'bg-green-500': getOrderStatusMatchStatus(row) === 'matched',
'bg-red-500': getOrderStatusMatchStatus(row) === 'failed',
'bg-gray-300': getOrderStatusMatchStatus(row) === 'none',
}"
@click="showMatchModal(row, 'orderStatus')"
>
<CheckIcon
v-if="getOrderStatusMatchStatus(row) === 'matched'"
class="h-2.5 w-2.5 text-white"
/>
<XIcon
v-else-if="getOrderStatusMatchStatus(row) === 'failed'"
class="h-2.5 w-2.5 text-white"
/>
</div>
<span>{{ row.orderStatusName }}</span>
</div>
</template>
<!-- 商品规格列 -->
<template #productSpecName="{ row }: { row: any }">
<div class="flex items-center space-x-2">
<div
class="flex h-4 w-4 cursor-pointer items-center justify-center rounded-full"
:class="{
'bg-green-500': getSpecMatchStatus(row) === 'matched',
'bg-red-500': getSpecMatchStatus(row) === 'failed',
'bg-gray-300': getSpecMatchStatus(row) === 'none',
}"
@click="showMatchModal(row, 'spec')"
>
<CheckIcon
v-if="getSpecMatchStatus(row) === 'matched'"
class="h-2.5 w-2.5 text-white"
/>
<XIcon
v-else-if="getSpecMatchStatus(row) === 'failed'"
class="h-2.5 w-2.5 text-white"
/>
</div>
<span>{{ row.productSpecName }}</span>
</div>
</template>
<!-- 店铺名称列 -->
<template #shopName="{ row }: { row: any }">
<div class="flex items-center space-x-2">
<div
class="flex h-4 w-4 cursor-pointer items-center justify-center rounded-full"
:class="{
'bg-green-500': getShopMatchStatus(row) === 'matched',
'bg-red-500': getShopMatchStatus(row) === 'failed',
'bg-gray-300': getShopMatchStatus(row) === 'none',
}"
@click="showMatchModal(row, 'shop')"
>
<CheckIcon
v-if="getShopMatchStatus(row) === 'matched'"
class="h-2.5 w-2.5 text-white"
/>
<XIcon
v-else-if="getShopMatchStatus(row) === 'failed'"
class="h-2.5 w-2.5 text-white"
/>
</div>
<span>{{ row.shopName }}</span>
</div>
</template>
<!-- 实收金额列 -->
<template #receivedAmount="{ row }: { row: any }">
<span style="color: #52c41a; font-weight: bold">
¥{{ (row.shopActualAmount || 0).toFixed(2) }}
</span>
</template>
<!-- 操作列 -->
<template #action>
<Space>
<Button size="small" @click="handleEditRow()"> 编辑 </Button>
<Button size="small" type="primary" @click="handleMatchRow()">
匹配
</Button>
</Space>
</template>
</Grid>
<!-- 字段映射弹窗 -->
<FieldMappingModal
v-model:visible="showFieldMapping"
:csv-headers="csvHeaders"
:csv-data="csvData"
@confirm="handleFieldMapping"
@cancel="showFieldMapping = false"
/>
<!-- 文件上传模态框 -->
<FileUploadModal
v-model:open="showUploadModal"
@confirm="handleFileUpload"
@cancel="showUploadModal = false"
/>
<!-- 实体创建模态框 -->
<EntityCreationModal
:visible="showEntityCreationModal"
:entities-to-create="
matchingResult?.entitiesToCreate || {
shops: [],
products: [],
specs: [],
}
"
:csv-data="csvData"
@success="handleEntityCreationSuccess"
@cancel="handleEntityCreationCancel"
/>
<!-- 匹配切换模态框 -->
<MatchSwitchModal
v-model:visible="showMatchSwitchModal"
:match-detail="currentMatchDetail"
:field-type="currentFieldType"
:same-data-count="getSameDataCount(currentRowData)"
@apply-match="handleApplyMatch"
@apply-to-all="handleApplyToAll"
/>
<Grid v-else />
</Page>
</template>
@@ -1,414 +0,0 @@
/**
* 实体匹配服务
* 用于匹配CSV数据中的实体(店铺、商品、规格、订单状态)到数据库中的ID
*/
import type { OrderDTO } from '#/api/ecommerce/order';
import type { ProductVO } from '#/api/shop/product/types';
import type { ShopVO } from '#/api/shop/shop/types';
import {
getProductsByNamesApi,
getProductSpecsByProductAndSpecsApi,
} from '#/api/shop/product';
import { getShopsByNamesApi } from '#/api/shop/shop';
export interface EntityMatchingResult {
/** 匹配成功的订单数据 */
matchedOrders: OrderDTO.Create[];
/** 匹配失败的记录 */
failedRecords: FailedRecord[];
/** 需要创建的实体 */
entitiesToCreate: {
products: string[];
shops: string[];
specs: { productName: string; specCode: string }[];
};
/** 匹配详情信息 */
matchDetails: MatchDetail[];
}
export interface MatchDetail {
/** 行索引 */
rowIndex: number;
/** 原始数据 */
originalData: CSVOrderData;
/** 匹配状态 */
status: 'failed' | 'matched' | 'partial';
/** 匹配的店铺信息 */
matchedShop?: ShopVO.Info;
/** 匹配的商品信息 */
matchedProduct?: ProductVO.Info;
/** 匹配的规格信息 */
matchedSpec?: ProductVO.SpecInfo;
/** 匹配的订单状态ID */
matchedOrderStatusId?: number;
/** 失败原因 */
failureReason?: string;
/** 生成的订单数据(如果匹配成功) */
orderData?: OrderDTO.Create;
}
export interface FailedRecord {
/** 行号 */
rowIndex: number;
/** 原始数据 */
originalData: any;
/** 失败原因 */
reason: string;
}
export interface CSVOrderData {
/** 店铺名称 */
shopName: string;
/** 商品名称 */
productName: string;
/** 商品规格编码 */
specCode: string;
/** 订单状态名称 */
orderStatusName: string;
/** 商品数量 */
quantity: number;
/** 订单编号 */
orderNumber: string;
/** 商品规格名称 */
productSpecName: string;
/** 店铺实际收入 */
shopActualAmount: number;
}
export class EntityMatchingService {
private orderStatusMap: Map<string, number> = new Map();
private productCache: Map<string, ProductVO.Info> = new Map();
private shopCache: Map<string, ShopVO.Info> = new Map();
private specCache: Map<string, ProductVO.SpecInfo> = new Map();
constructor() {
this.initializeOrderStatusMap();
}
/**
* 获取订单状态ID
*/
getOrderStatusId(statusName: string): number | undefined {
return this.orderStatusMap.get(statusName);
}
/**
* 获取商品信息
*/
getProductByName(name: string): ProductVO.Info | undefined {
return this.productCache.get(name);
}
/**
* 获取商品规格信息
*/
getProductSpecByKey(
productName: string,
specCode: string,
): ProductVO.SpecInfo | undefined {
const key = `${productName}_${specCode}`;
return this.specCache.get(key);
}
/**
* 获取店铺信息
*/
getShopByName(name: string): ShopVO.Info | undefined {
return this.shopCache.get(name);
}
/**
* 匹配实体并生成订单数据
*/
async matchEntities(csvData: CSVOrderData[]): Promise<EntityMatchingResult> {
// 清空缓存
this.clearCache();
// 提取所有需要查询的实体名称
const shopNames = [...new Set(csvData.map((row) => row.shopName))];
const productNames = [...new Set(csvData.map((row) => row.productName))];
// 对规格查询进行去重处理
const specQueriesMap = new Map<
string,
{ productName: string; specCode: string }
>();
csvData.forEach((row) => {
const key = `${row.productName}_${row.specCode}`;
if (!specQueriesMap.has(key)) {
specQueriesMap.set(key, {
productName: row.productName,
specCode: row.specCode,
});
}
});
const specQueries = [...specQueriesMap.values()];
// 批量查询所有实体
await this.loadEntitiesBatch(shopNames, productNames, specQueries);
const matchedOrders: OrderDTO.Create[] = [];
const failedRecords: FailedRecord[] = [];
const matchDetails: MatchDetail[] = [];
const entitiesToCreate = {
shops: new Set<string>(),
products: new Set<string>(),
specs: new Set<{ productName: string; specCode: string }>(),
};
for (const [i, row] of csvData.entries()) {
// 检查行数据是否存在
if (!row) {
const failedRecord = {
rowIndex: i + 1,
originalData: null,
reason: '行数据为空',
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row || ({} as CSVOrderData),
status: 'failed',
failureReason: '行数据为空',
});
continue;
}
try {
// 匹配店铺
const shop = this.shopCache.get(row.shopName);
if (!shop) {
entitiesToCreate.shops.add(row.shopName);
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `店铺 "${row.shopName}" 不存在`,
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
failureReason: `店铺 "${row.shopName}" 不存在`,
});
continue;
}
// 匹配商品
const product = this.productCache.get(row.productName);
if (!product) {
entitiesToCreate.products.add(row.productName);
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `商品 "${row.productName}" 不存在`,
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
matchedShop: shop,
failureReason: `商品 "${row.productName}" 不存在`,
});
continue;
}
// 匹配商品规格
const specKey = `${row.productName}_${row.specCode}`;
const spec = this.specCache.get(specKey);
if (!spec) {
entitiesToCreate.specs.add({
productName: row.productName,
specCode: row.specCode,
});
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `商品规格 "${row.productName}" - "${row.specCode}" 不存在`,
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
matchedShop: shop,
matchedProduct: product,
failureReason: `商品规格 "${row.productName}" - "${row.specCode}" 不存在`,
});
continue;
}
// 匹配订单状态
const orderStatusId = this.orderStatusMap.get(row.orderStatusName);
if (!orderStatusId) {
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `订单状态 "${row.orderStatusName}" 不存在`,
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
matchedShop: shop,
matchedProduct: product,
matchedSpec: spec,
failureReason: `订单状态 "${row.orderStatusName}" 不存在`,
});
continue;
}
// 从订单号中提取日期信息(格式:250913-341248633251447,前6位是日期)
let orderDate = new Date().toISOString(); // 默认使用当前时间
if (row.orderNumber && row.orderNumber.length >= 6) {
try {
const dateStr = row.orderNumber.slice(0, 6); // 提取前6位
const year = `20${dateStr.slice(0, 2)}`; // 25 -> 2025
const month = dateStr.slice(2, 4); // 09
const day = dateStr.slice(4, 6); // 13
orderDate = new Date(
`${year}-${month}-${day}T00:00:00`,
).toISOString();
} catch {
console.warn(
'无法解析订单号中的日期,使用当前时间:',
row.orderNumber,
);
}
}
// 创建订单数据(新的合并结构)
const orderData: OrderDTO.Create = {
shopId: shop.id,
platformOrderNo: row.orderNumber,
statusId: orderStatusId,
receivedAmount: row.shopActualAmount,
shippingFee: 0, // 运费暂时设为0
orderDate,
productId: product.id,
productSpecId: spec.id,
productName: row.productName,
specName: row.productSpecName,
quantity: row.quantity,
unitPrice: row.shopActualAmount / row.quantity, // 根据实收金额和数量计算单价
costPrice: spec.costPrice || 0, // 使用规格的成本价
costTotal: (spec.costPrice || 0) * row.quantity, // 成本小计
};
matchedOrders.push(orderData);
// 添加匹配成功的详情
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'matched',
matchedShop: shop,
matchedProduct: product,
matchedSpec: spec,
matchedOrderStatusId: orderStatusId,
orderData,
});
} catch (error) {
const failedRecord = {
rowIndex: i + 1,
originalData: row,
reason: `处理失败: ${error instanceof Error ? error.message : '未知错误'}`,
};
failedRecords.push(failedRecord);
matchDetails.push({
rowIndex: i + 1,
originalData: row,
status: 'failed',
failureReason: `处理失败: ${error instanceof Error ? error.message : '未知错误'}`,
});
}
}
return {
matchedOrders,
failedRecords,
entitiesToCreate: {
shops: [...entitiesToCreate.shops],
products: [...entitiesToCreate.products],
specs: [...entitiesToCreate.specs],
},
matchDetails,
};
}
/**
* 清空缓存
*/
private clearCache(): void {
this.shopCache.clear();
this.productCache.clear();
this.specCache.clear();
}
/**
* 初始化订单状态映射
*/
private initializeOrderStatusMap() {
// 根据CSV文件中的订单状态,映射到对应的ID
// 这里需要根据实际的订单状态配置来设置
this.orderStatusMap.set('已发货,待收货', 1);
this.orderStatusMap.set('未发货,退款成功', 2);
this.orderStatusMap.set('已取消', 3);
this.orderStatusMap.set('退款成功', 2);
// 可以根据需要添加更多状态映射
}
/**
* 批量加载实体数据
*/
private async loadEntitiesBatch(
shopNames: string[],
productNames: string[],
specQueries: { productName: string; specCode: string }[],
): Promise<void> {
try {
// 并行查询所有实体
const [shops, products, productsWithSpecs] = await Promise.all([
shopNames.length > 0
? getShopsByNamesApi(shopNames)
: Promise.resolve([]),
productNames.length > 0
? getProductsByNamesApi(productNames)
: Promise.resolve([]),
specQueries.length > 0
? getProductSpecsByProductAndSpecsApi(specQueries)
: Promise.resolve([]),
]);
// 缓存店铺数据
shops.forEach((shop) => {
this.shopCache.set(shop.name, shop);
});
// 缓存商品数据
products.forEach((product) => {
this.productCache.set(product.name, product);
});
// 缓存包含规格信息的商品数据
productsWithSpecs.forEach((product) => {
// 更新商品缓存
this.productCache.set(product.name, product);
// 缓存该商品的规格数据
if (product.specs && product.specs.length > 0) {
product.specs.forEach((spec) => {
const key = `${product.name}_${spec.specCode || ''}`;
this.specCache.set(key, spec);
});
}
});
} catch (error) {
console.error('批量加载实体数据失败:', error);
}
}
}
@@ -1,48 +1,25 @@
/**
* CSV数据解析工具
* 专门用于解析订单导入的CSV文件
* 完全动态解析,不预设任何字段
*/
import Papa from 'papaparse';
export interface ParsedOrderData {
/** 商品名称 */
productName: string;
/** 订单编号 */
orderNumber: string;
/** 订单状态名称 */
orderStatusName: string;
/** 商品数量 */
quantity: number;
/** 商品ID */
productId: string;
/** 商品规格名称 */
productSpecName: string;
/** 规格编码 */
specCode: string;
/** 店铺名称 */
shopName: string;
/** 售后状态 */
afterSaleStatus: string;
/** 店铺实际收入 */
shopActualAmount: number;
}
export interface CSVParseResult {
/** 解析成功的数据 */
data: ParsedOrderData[];
data: any[];
/** 解析错误 */
errors: string[];
/** 表头 */
/** 表头(保持CSV文件中的顺序) */
headers: string[];
}
/**
* 解析CSV文件 - 使用papaparse库,支持多种编码
* 解析CSV文件为原始数据(完全动态,保持字段顺序)
*/
export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
export async function parseCSVToRawData(file: File): Promise<CSVParseResult> {
const errors: string[] = [];
const data: ParsedOrderData[] = [];
const data: any[] = [];
let headers: string[] = [];
// 尝试多种编码格式
@@ -97,163 +74,11 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
return { data, errors, headers };
}
// 获取表头
// 获取表头(保持CSV文件中的顺序)
headers = result.meta.fields || [];
// 验证表头 - 使用更灵活的表头匹配
const requiredHeaders = [
'商品',
'订单号',
'订单状态',
'商品数量(件)',
'商品id',
'商品规格',
'商家编码-规格维度',
'售后状态',
'商家实收金额(元)',
];
const missingHeaders = requiredHeaders.filter((requiredHeader) => {
// 检查是否有匹配的表头(支持部分匹配)
return !headers.some(
(header) =>
header.includes(requiredHeader) || requiredHeader.includes(header),
);
});
if (missingHeaders.length > 0) {
// 不再阻止导入,只是记录警告
errors.push(
`警告:缺少部分列: ${missingHeaders.join(', ')},可以在导入后手动处理`,
);
}
// 解析数据行
for (let i = 0; i < result.data.length; i++) {
try {
const row = result.data[i];
const rowData = parseOrderRowFromObject(row, i + 2); // +2 因为从第2行开始(第1行是表头)
if (rowData) {
data.push(rowData);
}
} catch (error) {
errors.push(
`第${i + 2}行解析失败: ${error instanceof Error ? error.message : '未知错误'}`,
);
}
}
// 直接使用原始数据,完全保持CSV文件的字段顺序和数据顺序
data.push(...result.data);
return { data, errors, headers };
}
/**
* 解析订单行数据 - 从papaparse对象格式
*/
function parseOrderRowFromObject(
row: any,
rowNumber: number,
): null | ParsedOrderData {
try {
// 获取字段值,支持多种可能的字段名
const getValue = (fieldNames: string[]): string => {
for (const fieldName of fieldNames) {
if (
row[fieldName] !== undefined &&
row[fieldName] !== null &&
row[fieldName] !== ''
) {
return String(row[fieldName]).trim();
}
}
return '';
};
const productName = getValue(['商品', '商品名称', 'productName']);
const orderNumber = getValue(['订单号', '订单编号', 'orderNumber']);
const orderStatusName = getValue(['订单状态', 'orderStatus', '状态']);
const quantityStr = getValue([
'商品数量(件)',
'商品数量',
'数量',
'quantity',
]);
const productId = getValue(['商品id', '商品ID', 'productId', '商品编码']);
const productSpecName = getValue([
'商品规格',
'规格',
'spec',
'productSpec',
]);
const specCode = getValue(['商家编码-规格维度', '规格编码', 'specCode']);
// 店铺名称应该从文件名获取,这里不设置shopName
const afterSaleStatus = getValue(['售后状态', '售后', 'afterSale']);
const shopActualAmountStr = getValue([
'商家实收金额(元)',
'店铺实际收入(元)',
'店铺实际收入',
'收入',
'amount',
]);
// 验证必填字段 - 只验证最核心的字段
if (!productName) {
throw new Error('商品名称不能为空');
}
if (!orderNumber) {
throw new Error('订单编号不能为空');
}
// 其他字段可以为空,在后续处理中处理
// 解析数量 - 允许为0或空
const quantity = Number.parseFloat(quantityStr) || 0;
// 解析金额 - 允许为0或空
const shopActualAmount = Number.parseFloat(shopActualAmountStr) || 0;
return {
productName,
orderNumber,
orderStatusName,
quantity,
productId,
productSpecName,
specCode,
shopName: '', // 店铺名称将从文件名获取
afterSaleStatus,
shopActualAmount,
};
} catch (error) {
throw new Error(
`第${rowNumber}行数据验证失败: ${error instanceof Error ? error.message : '未知错误'}`,
);
}
}
/**
* 从文件名提取店铺名称
*/
export function extractShopNameFromFilename(filename: string): string {
// 移除文件扩展名,整个文件名就是店铺名称
return filename.replace(/\.(csv|CSV)$/, '');
}
/**
* 转换为EntityMatchingService需要的格式
*/
export function convertToCSVOrderData(
parsedData: ParsedOrderData[],
shopName: string,
): any[] {
return parsedData.map((row) => ({
productName: row.productName,
orderNumber: row.orderNumber,
orderStatusName: row.orderStatusName,
quantity: row.quantity,
productId: row.productId,
productSpecName: row.productSpecName,
specCode: row.specCode,
shopName, // 使用从文件名提取的店铺名称
afterSaleStatus: row.afterSaleStatus,
shopActualAmount: row.shopActualAmount,
}));
}
@@ -49,7 +49,6 @@ const formData = ref<Partial<OrderDTO.Create>>({
platformOrderNo: '',
statusId: undefined,
receivedAmount: 0,
shippingFee: 0,
orderDate: dayjs().format('YYYY-MM-DD'),
productId: undefined,
productSpecId: undefined,
@@ -58,7 +57,6 @@ const formData = ref<Partial<OrderDTO.Create>>({
quantity: 1,
unitPrice: 0,
costPrice: 0,
costTotal: 0,
});
// 下拉选项数据
@@ -78,7 +76,6 @@ const rules = {
quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
unitPrice: [{ required: true, message: '请输入销售单价', trigger: 'blur' }],
costPrice: [{ required: true, message: '请输入成本价', trigger: 'blur' }],
costTotal: [{ required: true, message: '请输入成本小计', trigger: 'blur' }],
};
// 表单引用
@@ -134,7 +131,6 @@ function open(edit: boolean, record?: OrderVO.Info) {
platformOrderNo: record.platformOrderNo || '',
statusId: record.statusId,
receivedAmount: record.receivedAmount,
shippingFee: record.shippingFee || 0,
orderDate: record.orderDate
? dayjs(record.orderDate).format('YYYY-MM-DD')
: dayjs().format('YYYY-MM-DD'),
@@ -145,14 +141,12 @@ function open(edit: boolean, record?: OrderVO.Info) {
quantity: record.quantity,
unitPrice: record.unitPrice,
costPrice: record.costPrice,
costTotal: record.costTotal,
}
: {
shopId: undefined,
platformOrderNo: '',
statusId: undefined,
receivedAmount: 0,
shippingFee: 0,
orderDate: dayjs().format('YYYY-MM-DD'),
productId: undefined,
productSpecId: undefined,
@@ -161,7 +155,6 @@ function open(edit: boolean, record?: OrderVO.Info) {
quantity: 1,
unitPrice: 0,
costPrice: 0,
costTotal: 0,
};
}
@@ -185,7 +178,6 @@ async function handleSubmit() {
platformOrderNo: formData.value.platformOrderNo,
statusId: formData.value.statusId,
receivedAmount: formData.value.receivedAmount!,
shippingFee: formData.value.shippingFee,
orderDate: formData.value.orderDate!,
productId: formData.value.productId,
productSpecId: formData.value.productSpecId,
@@ -194,7 +186,6 @@ async function handleSubmit() {
quantity: formData.value.quantity,
unitPrice: formData.value.unitPrice,
costPrice: formData.value.costPrice,
costTotal: formData.value.costTotal,
};
await updateOrderApi(currentRecord.value.id, updateData);
message.success('更新订单成功');
@@ -205,7 +196,6 @@ async function handleSubmit() {
platformOrderNo: formData.value.platformOrderNo,
statusId: formData.value.statusId!,
receivedAmount: formData.value.receivedAmount!,
shippingFee: formData.value.shippingFee,
orderDate: formData.value.orderDate!,
productId: formData.value.productId!,
productSpecId: formData.value.productSpecId,
@@ -214,7 +204,6 @@ async function handleSubmit() {
quantity: formData.value.quantity!,
unitPrice: formData.value.unitPrice!,
costPrice: formData.value.costPrice!,
costTotal: formData.value.costTotal!,
};
await createOrderApi(createData);
message.success('创建订单成功');
@@ -349,37 +338,15 @@ defineExpose({
</Form.Item>
</div>
<div class="grid grid-cols-3 gap-4">
<Form.Item label="成本小计" name="costTotal">
<InputNumber
v-model:value="formData.costTotal"
placeholder="请输入成本小计"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="实收金额" name="receivedAmount">
<InputNumber
v-model:value="formData.receivedAmount"
placeholder="请输入实收金额"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="运费" name="shippingFee">
<InputNumber
v-model:value="formData.shippingFee"
placeholder="请输入运费"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
</div>
<Form.Item label="实收金额" name="receivedAmount">
<InputNumber
v-model:value="formData.receivedAmount"
placeholder="请输入实收金额"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -35,7 +35,6 @@ const orderStatusOptions = ref<{ label: string; value: number }[]>([]);
// 搜索表单
const searchForm = ref({
platformOrderNo: '',
productName: '',
shopId: undefined as number | undefined,
statusId: undefined as number | undefined,
});
@@ -75,11 +74,6 @@ const gridOptions: VxeGridProps<any> = {
minWidth: 'auto',
slots: { default: 'receivedAmount' },
},
{
title: '运费',
minWidth: 'auto',
slots: { default: 'shippingFee' },
},
{
title: '订单状态',
minWidth: 'auto',
@@ -146,10 +140,9 @@ const gridOptions: VxeGridProps<any> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
orderNumber: searchForm.value.platformOrderNo || undefined,
productName: searchForm.value.productName || undefined,
platformOrderNo: searchForm.value.platformOrderNo || undefined,
shopId: searchForm.value.shopId,
orderStatusId: searchForm.value.statusId,
statusId: searchForm.value.statusId,
},
};
const data = await getOrderPageApi(params);
@@ -183,14 +176,6 @@ const formOptions = computed(() => ({
fieldName: 'platformOrderNo',
label: '平台订单号',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入商品名称',
},
fieldName: 'productName',
label: '商品名称',
},
{
component: 'Select',
componentProps: {
@@ -349,13 +334,6 @@ onMounted(async () => {
</span>
</template>
<!-- 运费列 -->
<template #shippingFee="{ row }: { row: any }">
<span style="color: #666">
¥{{ (row.shippingFee || 0).toFixed(2) }}
</span>
</template>
<!-- 订单状态列 -->
<template #orderStatus="{ row }: { row: any }">
<Tag color="blue">
@@ -46,6 +46,7 @@ const gridOptions: VxeGridProps<any> = {
type: 'seq' as const,
minWidth: 60,
title: '序号',
dragSort: true, // 启用拖拽排序
},
{
field: 'type',
@@ -223,6 +224,7 @@ let isUpdating = false;
// 处理拖拽排序
const handleDragSort = async (_params: any) => {
// 防止重复调用
if (isUpdating) {
return;
}
@@ -234,32 +236,18 @@ const handleDragSort = async (_params: any) => {
const tableDataResult = gridApi.grid.getTableData();
const tableData = tableDataResult?.tableData || [];
// 按类型分组排序
const typeGroups: Record<string, ImportFieldDefVO.ImportFieldDefInfoVO[]> =
{};
tableData.forEach((item: ImportFieldDefVO.ImportFieldDefInfoVO) => {
const type = item.type;
if (!typeGroups[type]) {
typeGroups[type] = [];
}
typeGroups[type].push(item);
});
// 为每个类型组构建排序数据
const sortItems: ImportFieldDefDTO.FieldDefSortItem[] = [];
Object.values(typeGroups).forEach((group) => {
group.forEach((item, index) => {
sortItems.push({
fieldDefId: item.id,
sort: index + 1,
});
});
});
// 构建排序数据,直接按表格中的顺序排序
const sortItems: ImportFieldDefDTO.FieldDefSortItem[] = tableData.map(
(item: ImportFieldDefVO.ImportFieldDefInfoVO, index: number) => ({
fieldDefId: item.id,
sort: index + 1, // 排序值从1开始
}),
);
// 调用排序接口
await batchSortImportFieldDefApi({ sortItems });
message.success('排序更新成功');
// 排序成功后不需要重新加载数据,因为表格数据已经更新
} catch (error: any) {
console.error('拖拽排序失败:', error);
if (error?.message) {
@@ -267,7 +255,7 @@ const handleDragSort = async (_params: any) => {
} else {
message.error('排序更新失败');
}
// 排序失败时重新加载数据
// 排序失败时重新加载数据,恢复原始状态
gridApi.reload();
} finally {
isUpdating = false;
@@ -311,20 +299,37 @@ const [Grid, gridApi] = useVbenVxeGrid({
showSearchForm: true,
tableTitle: '字段管理',
gridEvents: {
// 拖拽排序事件
rowDragend: handleDragSort,
} as any,
});
// 在组件挂载后初始化
// 添加Grid组件的ref
const gridRef = ref();
// 在组件挂载后绑定拖拽事件
onMounted(() => {
// 组件挂载完成
// 延迟绑定,确保Grid组件完全初始化
setTimeout(() => {
if (gridRef.value) {
// 尝试直接绑定VxeTable的拖拽事件
const vxeGrid = gridRef.value;
if (vxeGrid && vxeGrid.$refs && vxeGrid.$refs.grid) {
const grid = vxeGrid.$refs.grid;
// 绑定拖拽事件
grid.on('row-drag-end', (params: any) => {
handleDragSort(params);
});
}
}
}, 1000);
});
</script>
<template>
<Page title="字段管理" auto-content-height>
<!-- VbenVxeGrid 表格 -->
<Grid :loading="loading">
<Grid ref="gridRef" :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>