prettier: 代码格式化

This commit is contained in:
ah--desktop
2025-10-31 22:42:03 +08:00
parent 91ee49f45f
commit dfc6de49e0
62 changed files with 6814 additions and 5256 deletions
@@ -1,21 +1,22 @@
<script setup lang="ts">
import { createIconifyIcon } from '@vben/icons';
import { Card } from 'ant-design-vue';
defineOptions({ name: 'DataAnalysis' });
// 创建图标组件
const BarChartIcon = createIconifyIcon('lucide:bar-chart-3');
</script>
<template>
<div class="p-6">
<Card title="数据分析" class="mb-6">
<div class="text-center py-12">
<BarChartIcon class="w-16 h-16 mx-auto text-gray-400 mb-4" />
<h3 class="text-lg font-medium text-gray-700 mb-2">数据分析功能</h3>
<div class="py-12 text-center">
<BarChartIcon class="mx-auto mb-4 h-16 w-16 text-gray-400" />
<h3 class="mb-2 text-lg font-medium text-gray-700">数据分析功能</h3>
<p class="text-gray-500">此功能正在开发中,敬请期待...</p>
</div>
</Card>
</div>
</template>
<script setup lang="ts">
import { Card } from 'ant-design-vue';
import { createIconifyIcon } from '@vben/icons';
// 创建图标组件
const BarChartIcon = createIconifyIcon('lucide:bar-chart-3');
defineOptions({ name: 'DataAnalysis' });
</script>
@@ -1,126 +1,17 @@
<template>
<Modal
:open="visible"
title="创建缺失的实体"
width="800px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<div class="space-y-6">
<!-- 店铺创建 -->
<div v-if="entitiesToCreate.shops.length > 0" class="border border-gray-200 rounded-lg p-4">
<h3 class="text-lg font-medium text-gray-900 mb-4">需要创建的店铺 ({{ 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 p-3 bg-gray-50 rounded"
>
<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="border border-gray-200 rounded-lg p-4">
<h3 class="text-lg font-medium text-gray-900 mb-4">需要创建的商品 ({{ 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 p-3 bg-gray-50 rounded"
>
<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="border border-gray-200 rounded-lg p-4">
<h3 class="text-lg font-medium text-gray-900 mb-4">需要创建的商品规格 ({{ 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 p-3 bg-gray-50 rounded"
>
<span class="font-medium">{{ spec.productName }} - {{ spec.specCode }}</span>
<Button
type="primary"
size="small"
@click="openProductSpecModal(spec)"
>
创建规格
</Button>
</div>
</div>
</div>
<!-- 提示信息 -->
<div class="bg-blue-50 border border-blue-200 rounded-lg 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>
<script lang="ts" setup>
import { ref } from 'vue';
import { Modal, Button, message } from 'ant-design-vue';
import ShopFormModal from '#/views/shop/shop/components/ShopFormModal.vue';
import { Button, message, Modal } 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: {
shops: string[];
products: string[];
shops: string[];
specs: { productName: string; specCode: string; specName?: string }[];
};
csvData?: any[]; // 传递CSV数据用于获取更多信息
@@ -143,20 +34,25 @@ const productSpecModalRef = ref();
// 当前正在创建的实体
const currentCreatingShop = ref<string>('');
const currentCreatingProduct = ref<string>('');
const currentCreatingSpec = ref<{ productName: string; specCode: string } | null>(null);
const currentCreatingSpec = ref<null | {
productName: string;
specCode: string;
}>(null);
// 处理提交
function handleSubmit() {
// 检查是否还有未创建的实体
const { entitiesToCreate } = defineProps<Props>();
if (entitiesToCreate.shops.length > 0 ||
entitiesToCreate.products.length > 0 ||
entitiesToCreate.specs.length > 0) {
if (
entitiesToCreate.shops.length > 0 ||
entitiesToCreate.products.length > 0 ||
entitiesToCreate.specs.length > 0
) {
message.warning('请先创建所有缺失的实体');
return;
}
emit('success');
}
@@ -180,40 +76,43 @@ function openShopModal(shopName: string) {
// 打开商品创建模态框
function openProductModal(productName: string) {
currentCreatingProduct.value = productName;
// 从CSV数据中获取该商品的所有规格信息
const csvSpecs = props.csvData?.filter(row => row.productName === productName) || [];
const csvSpecs =
props.csvData?.filter((row) => row.productName === productName) || [];
// 对规格进行去重处理,使用Map来去重
const specMap = new Map<string, { specCode: string; specName: string }>();
csvSpecs.forEach(row => {
csvSpecs.forEach((row) => {
const specCode = row.specCode;
const specName = row.productSpecName;
if (specCode && !specMap.has(specCode)) {
specMap.set(specCode, {
specCode: specCode,
specName: specName || specCode // 如果没有规格名称,使用规格编码
specCode,
specName: specName || specCode, // 如果没有规格名称,使用规格编码
});
}
});
// 转换为数组
const uniqueSpecs = Array.from(specMap.values());
const uniqueSpecs = [...specMap.values()];
// 构建商品数据,包含规格信息
const productData = {
name: productName,
description: `从CSV文件导入的商品:${productName}`,
// 添加规格信息
specs: uniqueSpecs
specs: uniqueSpecs,
};
console.log('商品数据:', productData);
productFormModalRef.value?.open(false, productData);
}
// 打开商品规格创建模态框
function openProductSpecModal(spec: { productName: string; specCode: string; specName?: string }) {
function openProductSpecModal(spec: {
productName: string;
specCode: string;
specName?: string;
}) {
currentCreatingSpec.value = spec;
// 由于ProductSpecModal需要完整的商品对象,这里需要先创建商品
// 或者修改ProductSpecModal以支持部分数据
@@ -239,10 +138,144 @@ function handleProductCreated() {
// 处理商品规格创建成功
function handleProductSpecCreated() {
if (currentCreatingSpec.value) {
message.success(`商品规格 "${currentCreatingSpec.value.productName} - ${currentCreatingSpec.value.specCode}" 创建成功`);
message.success(
`商品规格 "${currentCreatingSpec.value.productName} - ${currentCreatingSpec.value.specCode}" 创建成功`,
);
currentCreatingSpec.value = null;
// 这里可以触发重新匹配
emit('success');
}
}
</script>
<template>
<Modal
:open="visible"
title="创建缺失的实体"
width="800px"
:confirm-loading="loading"
@ok="handleSubmit"
@cancel="handleCancel"
>
<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,81 +1,36 @@
<template>
<div class="space-y-6">
<!-- 字段映射说明 -->
<div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
<div class="flex items-start space-x-2">
<InfoIcon class="w-5 h-5 text-blue-500 mt-0.5" />
<div>
<p class="font-medium text-blue-800">字段映射说明</p>
<p class="text-sm text-blue-600 mt-1">
请为每个CSV字段选择对应的标准字段,未映射的字段将被忽略。您也可以自定义字段名称。
</p>
</div>
</div>
</div>
<!-- 字段映射表格 -->
<div class="border rounded-lg">
<Table
:columns="mappingColumns"
:data-source="mappingData"
:pagination="false"
size="small"
/>
</div>
<!-- 数据预览 -->
<div v-if="previewData.length > 0">
<h4 class="text-md font-medium mb-3">映射后数据预览</h4>
<Table
:columns="previewColumns"
:data-source="previewData.slice(0, 5)"
:pagination="false"
size="small"
:scroll="{ x: 800 }"
/>
<p class="text-sm text-gray-500 mt-2">
显示前5条映射后的数据,共 {{ previewData.length }} 条记录
</p>
</div>
<!-- 操作按钮 -->
<div class="flex justify-end space-x-3 pt-4 border-t">
<Button @click="$emit('cancel')">
取消
</Button>
<Button @click="handleExport" type="primary">
导出JSON
</Button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, h } from 'vue'
import { message, Table, Button } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
import { transformDataWithMapping, generateExportData, downloadJSON } from '#/utils/csv-utils'
import { computed, h, ref, watch } from 'vue';
// 创建图标组件
const InfoIcon = createIconifyIcon('lucide:info')
import { createIconifyIcon } from '@vben/icons';
// Props
interface Props {
csvHeaders: string[]
csvData: any[]
}
import { Button, message, Table } from 'ant-design-vue';
const props = defineProps<Props>()
import {
downloadJSON,
generateExportData,
transformDataWithMapping,
} from '#/utils/csv-utils';
const props = defineProps<Props>();
// Emits
const emit = defineEmits<{
confirm: [data: any]
cancel: []
}>()
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 fieldMappings = ref<Record<string, string>>({});
const customFieldNames = ref<Record<string, string>>({});
// 标准字段选项
const standardFields = [
@@ -93,7 +48,7 @@ const standardFields = [
{ value: 'payment_method', label: '支付方式' },
{ value: 'delivery_address', label: '收货地址' },
{ value: 'remark', label: '备注' },
]
];
// 计算属性
const mappingData = computed(() => {
@@ -102,8 +57,8 @@ const mappingData = computed(() => {
csvField: header,
standardField: fieldMappings.value[header] || '',
customName: customFieldNames.value[header] || '',
}))
})
}));
});
const mappingColumns = [
{
@@ -124,10 +79,10 @@ const mappingColumns = [
allowClear: true,
options: standardFields,
onChange: (value: string) => {
fieldMappings.value[record.csvField] = value
}
})
}
fieldMappings.value[record.csvField] = value;
},
});
},
},
{
title: '自定义字段名',
@@ -139,10 +94,10 @@ const mappingColumns = [
value: record.customName,
placeholder: '可选:自定义字段名',
onChange: (e: any) => {
customFieldNames.value[record.csvField] = e.target.value
}
})
}
customFieldNames.value[record.csvField] = e.target.value;
},
});
},
},
{
title: '示例数据',
@@ -150,60 +105,114 @@ const mappingColumns = [
key: 'example',
ellipsis: true,
customRender: ({ record }: any) => {
const exampleValue = props.csvData[0]?.[record.csvField] || ''
return exampleValue.toString().substring(0, 50) + (exampleValue.toString().length > 50 ? '...' : '')
}
}
]
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 []
if (Object.keys(fieldMappings.value).length === 0) return [];
return transformDataWithMapping(
props.csvData,
fieldMappings.value,
customFieldNames.value
)
})
customFieldNames.value,
);
});
const previewColumns = computed(() => {
const columns = Object.keys(previewData.value[0] || {}).map(field => ({
const columns = Object.keys(previewData.value[0] || {}).map((field) => ({
title: field,
dataIndex: field,
key: field,
width: 150,
ellipsis: true,
}))
return columns
})
}));
return columns;
});
// 监听字段映射变化,自动生成预览
watch([fieldMappings, customFieldNames], () => {
// 预览数据会自动更新
}, { deep: true })
watch(
[fieldMappings, customFieldNames],
() => {
// 预览数据会自动更新
},
{ deep: true },
);
// 导出JSON
const handleExport = () => {
if (previewData.value.length === 0) {
message.warning('请先配置字段映射')
return
message.warning('请先配置字段映射');
return;
}
const exportData = generateExportData(
previewData.value,
fieldMappings.value,
customFieldNames.value
)
// 使用工具函数下载JSON
downloadJSON(exportData)
message.success('JSON文件导出成功')
emit('confirm', exportData)
}
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;
@@ -1,16 +1,291 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, Modal, Select } from 'ant-design-vue';
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建图标组件
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 visible = ref(false);
// 系统字段定义
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) => {
visible.value = newVal;
if (newVal) {
// 初始化字段映射
initializeFieldMappings();
}
},
);
watch(visible, (newVal) => {
emit('update:visible', newVal);
});
// 初始化字段映射
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 });
visible.value = false;
};
// 处理取消
const handleCancel = () => {
visible.value = false;
emit('cancel');
};
// 处理重置
const handleReset = () => {
fieldMappings.value = {};
};
</script>
<template>
<Modal
v-model:open="visible"
title="字段匹配配置"
width="1200px"
:footer="null"
@cancel="handleCancel"
>
<Modal
v-model:open="visible"
title="字段匹配配置"
width="1200px"
:footer="null"
@cancel="handleCancel"
>
<div class="field-mapping-container">
<!-- 说明信息 -->
<div class="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
<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="w-4 h-4 text-blue-500" />
<InfoIcon class="h-4 w-4 text-blue-500" />
<span class="text-sm text-blue-800">
请将左侧系统字段与右侧CSV文件字段进行匹配,重新组织数据结构以正确进行实体匹配
</span>
@@ -25,39 +300,37 @@
<h3 class="text-lg font-medium text-gray-800">系统字段</h3>
<p class="text-sm text-gray-600">系统预定义的订单字段,必须映射</p>
</div>
<div class="space-y-3 max-h-96 overflow-y-auto">
<div
v-for="field in systemFields"
<div class="max-h-96 space-y-3 overflow-y-auto">
<div
v-for="field in systemFields"
:key="field.key"
class="field-item p-3 border rounded-lg"
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]
'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-red-500 text-xs"
>
<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="text-xs text-gray-500 mt-1">{{ field.description }}</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="w-4 h-4 text-green-500"
/>
<XIcon
v-else
class="w-4 h-4 text-gray-400"
<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>
@@ -70,35 +343,31 @@
<h3 class="text-lg font-medium text-gray-800">CSV字段映射</h3>
<p class="text-sm text-gray-600">选择CSV文件中的对应字段</p>
</div>
<div class="space-y-3 max-h-96 overflow-y-auto">
<div
v-for="field in systemFields"
<div class="max-h-96 space-y-3 overflow-y-auto">
<div
v-for="field in systemFields"
:key="field.key"
class="field-mapping-item p-3 border rounded-lg"
class="field-mapping-item rounded-lg border p-3"
>
<div class="flex items-center justify-between mb-2">
<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-red-500 text-xs"
>
<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="w-4 h-4 text-green-500"
/>
<XIcon
v-else
class="w-4 h-4 text-gray-400"
<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字段"
@@ -107,7 +376,9 @@
:filter-option="filterOption"
show-search
allow-clear
@change="(value: any) => handleFieldMappingChange(field.key, value)"
@change="
(value: any) => handleFieldMappingChange(field.key, value)
"
>
<template #option="{ label, value }">
<div class="flex items-center justify-between">
@@ -116,12 +387,19 @@
</div>
</template>
</Select>
<!-- 字段预览 -->
<div v-if="fieldMappings[field.key]" class="mt-2">
<div class="text-xs text-gray-600 mb-1">数据预览:</div>
<div class="text-xs bg-gray-100 p-2 rounded max-h-20 overflow-y-auto">
<div v-for="(sample, index) in getFieldSamples(fieldMappings[field.key] || '')" :key="index">
<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>
@@ -132,33 +410,35 @@
</div>
<!-- 映射统计 -->
<div class="mt-6 p-4 bg-gray-50 border rounded-lg">
<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-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-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-2xl font-bold text-red-600">
{{ unmappedFieldsCount }}
</div>
<div class="text-sm text-gray-600">未映射</div>
</div>
</div>
</div>
<!-- 操作按钮 -->
<div class="flex justify-end space-x-3 mt-6">
<Button @click="handleCancel">
取消
</Button>
<Button @click="handleReset" type="default">
重置
</Button>
<Button
type="primary"
<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"
>
@@ -169,265 +449,6 @@
</Modal>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Modal, Button, Select } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
// 创建图标组件
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 props = defineProps<Props>()
const emit = defineEmits<Emits>()
const visible = ref(false)
// 系统字段定义
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(value => value).length
})
// 未映射字段数量
const unmappedFieldsCount = computed(() => {
return systemFields.length - mappedFieldsCount.value
})
// 监听visible变化
watch(() => props.visible, (newVal) => {
visible.value = newVal
if (newVal) {
// 初始化字段映射
initializeFieldMappings()
}
})
watch(visible, (newVal) => {
emit('update:visible', newVal)
})
// 初始化字段映射
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[]): string | null => {
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) 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 })
visible.value = false
}
// 处理取消
const handleCancel = () => {
visible.value = false
emit('cancel')
}
// 处理重置
const handleReset = () => {
fieldMappings.value = {}
}
</script>
<style scoped>
.field-mapping-container {
max-height: 80vh;
@@ -1,20 +1,109 @@
<script setup lang="ts">
import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, message } from 'ant-design-vue';
defineOptions({ name: 'FileUploadArea' });
const emit = defineEmits<Emits>();
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload');
// 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 (!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>
<div
class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center transition-colors"
<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="w-12 h-12 mx-auto text-gray-400" />
<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-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>
<Button @click="triggerFileInput" type="primary" ghost> 选择文件 </Button>
</div>
<input
ref="fileInputRef"
@@ -26,93 +115,6 @@
</div>
</template>
<script setup lang="ts">
defineOptions({ name: 'FileUploadArea' })
import { ref } from 'vue'
import { message, Button } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload')
// Emits
interface Emits {
(e: 'file-selected', file: File): void
}
const emit = defineEmits<Emits>()
// 响应式数据
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 (!validateFile(file)) return
emit('file-selected', 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>
<style scoped>
/* 拖拽区域样式 */
.border-dashed {
@@ -1,3 +1,150 @@
<script setup lang="ts">
import { ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Modal } from 'ant-design-vue';
defineOptions({ name: 'FileUploadModal' });
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建图标组件
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 visible = ref(false);
const uploadedFile = ref<File | null>(null);
const isDragOver = ref(false);
const fileInputRef = ref<HTMLInputElement>();
// 监听props变化
watch(
() => props.open,
(newVal) => {
visible.value = newVal;
if (!newVal) {
// 关闭时重置状态
uploadedFile.value = null;
isDragOver.value = false;
}
},
);
// 监听visible变化,同步到父组件
watch(visible, (newVal) => {
emit('update:open', newVal);
});
// 文件验证
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);
visible.value = false;
}
};
// 取消
const handleCancel = () => {
emit('cancel');
visible.value = 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
v-model:open="visible"
@@ -8,17 +155,19 @@
>
<div class="space-y-6">
<!-- 文件拖拽上传区域 -->
<div
class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center transition-colors"
<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="w-12 h-12 mx-auto text-gray-400" />
<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-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>
@@ -35,29 +184,28 @@
</div>
<!-- 文件信息显示 -->
<div v-if="uploadedFile" class="bg-green-50 border border-green-200 rounded-lg p-4">
<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="w-5 h-5 text-green-500" />
<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="text-sm text-green-600 mt-1">{{ uploadedFile.name }} ({{ formatFileSize(uploadedFile.size) }})</p>
<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 @click="handleCancel"> 取消 </Button>
<Button @click="handleConfirm" type="primary" :disabled="!uploadedFile">
确认导入
</Button>
</div>
@@ -65,149 +213,6 @@
</Modal>
</template>
<script setup lang="ts">
defineOptions({ name: 'FileUploadModal' })
import { ref, watch } from 'vue'
import { message, Button, Modal } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
// 创建图标组件
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 props = defineProps<Props>()
const emit = defineEmits<Emits>()
// 响应式数据
const visible = ref(false)
const uploadedFile = ref<File | null>(null)
const isDragOver = ref(false)
const fileInputRef = ref<HTMLInputElement>()
// 监听props变化
watch(() => props.open, (newVal) => {
visible.value = newVal
if (!newVal) {
// 关闭时重置状态
uploadedFile.value = null
isDragOver.value = false
}
})
// 监听visible变化,同步到父组件
watch(visible, (newVal) => {
emit('update:open', newVal)
})
// 文件验证
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)
visible.value = false
}
}
// 取消
const handleCancel = () => {
emit('cancel')
visible.value = 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 parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>
<style scoped>
/* 拖拽区域样式 */
.border-dashed {
@@ -1,3 +1,254 @@
<script setup lang="ts">
import type { MatchDetail } from '../services/EntityMatchingService';
import { computed, ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, Modal, Select } from 'ant-design-vue';
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// 创建图标组件
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>('');
// 计算属性用于双向绑定
const visible = computed({
get: () => props.visible,
set: (value) => {
emit('update:visible', value);
},
});
watch(
() => props.visible,
(newVal) => {
if (newVal && props.matchDetail) {
// 初始化选中的匹配项
selectedMatchId.value = getCurrentMatchId() || '';
}
},
);
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,
);
}
visible.value = false;
};
// 处理应用到所有相同数据
const handleApplyToAll = () => {
if (props.matchDetail && selectedMatchId.value) {
emit(
'applyToAll',
props.matchDetail.rowIndex,
props.fieldType,
selectedMatchId.value,
);
}
visible.value = false;
};
const handleCancel = () => {
visible.value = false;
};
</script>
<template>
<Modal
v-model:open="visible"
@@ -8,26 +259,26 @@
>
<div v-if="matchDetail" class="space-y-4">
<!-- 当前匹配状态 -->
<div class="flex items-center space-x-2 mb-4">
<div
class="w-4 h-4 rounded-full flex items-center justify-center"
<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'
'bg-yellow-500': matchDetail.status === 'partial',
}"
>
<CheckIcon
v-if="matchDetail.status === 'matched'"
class="w-3 h-3 text-white"
<CheckIcon
v-if="matchDetail.status === 'matched'"
class="h-3 w-3 text-white"
/>
<XIcon
v-else-if="matchDetail.status === 'failed'"
class="w-3 h-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="w-3 h-3 text-white"
<AlertTriangleIcon
v-else-if="matchDetail.status === 'partial'"
class="h-3 w-3 text-white"
/>
</div>
<span class="font-medium">
@@ -37,43 +288,55 @@
</div>
<!-- 原始数据 -->
<div class="bg-gray-50 rounded-lg p-4">
<h4 class="font-medium text-gray-800 mb-3">原始数据</h4>
<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>
<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>
<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>
<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>
<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>
<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>
<span class="ml-2 font-medium">{{
matchDetail.originalData.orderStatusName
}}</span>
</div>
</div>
</div>
<!-- 当前字段匹配信息 -->
<div class="border rounded-lg p-4">
<div class="flex items-center justify-between mb-3">
<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="w-3 h-3 rounded-full"
<div
class="h-3 w-3 rounded-full"
:class="getFieldMatchStatusClass()"
></div>
<span class="text-sm">
@@ -81,29 +344,36 @@
</span>
</div>
</div>
<!-- 当前匹配信息 -->
<div v-if="getCurrentMatchInfo()" class="bg-green-50 border border-green-200 rounded p-3 mb-3">
<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 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="bg-red-50 border border-red-200 rounded p-3 mb-3">
<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="block text-sm font-medium text-gray-700 mb-2">
<label class="mb-2 block text-sm font-medium text-gray-700">
选择匹配的{{ getFieldTitle() }}:
</label>
<Select
@@ -114,8 +384,11 @@
@change="(value: any) => handleMatchChange(value)"
/>
</div>
<div v-if="selectedMatchId" class="bg-blue-50 border border-blue-200 rounded p-3">
<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>
@@ -125,11 +398,15 @@
</div>
<!-- 相同数据提示 -->
<div v-if="sameDataCount && sameDataCount > 1" class="bg-blue-50 border border-blue-200 rounded-lg p-3">
<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="w-4 h-4 text-blue-500" />
<InfoIcon class="h-4 w-4 text-blue-500" />
<span class="text-sm text-blue-800">
检测到 {{ sameDataCount }} 条相同数据,切换匹配将同时应用到所有相同数据
检测到
{{ sameDataCount }} 条相同数据,切换匹配将同时应用到所有相同数据
</span>
</div>
</div>
@@ -138,17 +415,17 @@
<template #footer>
<div class="flex justify-end space-x-2">
<Button @click="handleCancel">关闭</Button>
<Button
type="primary"
@click="handleApplyMatch"
<Button
type="primary"
@click="handleApplyMatch"
:disabled="!selectedMatchId"
>
应用匹配
</Button>
<Button
<Button
v-if="sameDataCount && sameDataCount > 1"
type="primary"
@click="handleApplyToAll"
type="primary"
@click="handleApplyToAll"
:disabled="!selectedMatchId"
>
应用到所有相同数据
@@ -158,218 +435,6 @@
</Modal>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { Modal, Button, Select } from 'ant-design-vue'
import { createIconifyIcon } from '@vben/icons'
import type { MatchDetail } from '../services/EntityMatchingService'
// 创建图标组件
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: 'shop' | 'product' | 'spec' | 'orderStatus'
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 props = defineProps<Props>()
const emit = defineEmits<Emits>()
const visible = ref(false)
const selectedMatchId = ref<string>('')
watch(() => props.visible, (newVal) => {
visible.value = newVal
if (newVal && props.matchDetail) {
// 初始化选中的匹配项
selectedMatchId.value = getCurrentMatchId() || ''
}
})
watch(visible, (newVal) => {
emit('update:visible', newVal)
})
const getStatusText = (status: string) => {
switch (status) {
case 'matched':
return '匹配成功'
case 'failed':
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 'shop':
return props.matchDetail.originalData.shopName
case 'product':
return props.matchDetail.originalData.productName
case 'spec':
return props.matchDetail.originalData.productSpecName
case 'orderStatus':
return props.matchDetail.originalData.orderStatusName
default:
return ''
}
}
// 获取当前匹配信息
const getCurrentMatchInfo = () => {
if (!props.matchDetail) return null
switch (props.fieldType) {
case 'shop':
return props.matchDetail.matchedShop ? {
name: props.matchDetail.matchedShop.name,
id: props.matchDetail.matchedShop.id
} : null
case 'product':
return props.matchDetail.matchedProduct ? {
name: props.matchDetail.matchedProduct.name,
id: props.matchDetail.matchedProduct.id
} : null
case 'spec':
return props.matchDetail.matchedSpec ? {
name: props.matchDetail.matchedSpec.name,
id: props.matchDetail.matchedSpec.id,
specCode: props.matchDetail.matchedSpec.specCode
} : null
case 'orderStatus':
return props.matchDetail.matchedOrderStatusId ? {
name: props.matchDetail.originalData.orderStatusName,
id: props.matchDetail.matchedOrderStatusId
} : 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)
}
visible.value = false
}
// 处理应用到所有相同数据
const handleApplyToAll = () => {
if (props.matchDetail && selectedMatchId.value) {
emit('applyToAll', props.matchDetail.rowIndex, props.fieldType, selectedMatchId.value)
}
visible.value = false
}
const handleCancel = () => {
visible.value = false
}
</script>
<style scoped>
/* 自定义样式 */
</style>
File diff suppressed because it is too large Load Diff
@@ -3,11 +3,15 @@
* 用于匹配CSV数据中的实体(店铺、商品、规格、订单状态)到数据库中的ID
*/
import { getShopsByNamesApi } from '#/api/shop/shop';
import { getProductsByNamesApi, getProductSpecsByProductAndSpecsApi } from '#/api/shop/product';
import type { OrderDTO} from '#/api/ecommerce/types';
import type { ShopVO } from '#/api/shop/shop/types';
import type { OrderDTO } from '#/api/ecommerce/types';
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 {
/** 匹配成功的订单数据 */
@@ -16,8 +20,8 @@ export interface EntityMatchingResult {
failedRecords: FailedRecord[];
/** 需要创建的实体 */
entitiesToCreate: {
shops: string[];
products: string[];
shops: string[];
specs: { productName: string; specCode: string }[];
};
/** 匹配详情信息 */
@@ -30,7 +34,7 @@ export interface MatchDetail {
/** 原始数据 */
originalData: CSVOrderData;
/** 匹配状态 */
status: 'matched' | 'failed' | 'partial';
status: 'failed' | 'matched' | 'partial';
/** 匹配的店铺信息 */
matchedShop?: ShopVO.Info;
/** 匹配的商品信息 */
@@ -74,15 +78,277 @@ export interface CSVOrderData {
}
export class EntityMatchingService {
private shopCache: Map<string, ShopVO.Info> = new Map();
private productCache: Map<string, ProductVO.Info> = new Map();
private specCache: Map<string, ProductVO.SpecInfo> = new Map();
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();
}
/**
* 初始化订单状态映射
*/
@@ -96,249 +362,46 @@ export class EntityMatchingService {
// 可以根据需要添加更多状态映射
}
/**
* 匹配实体并生成订单数据
*/
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 = Array.from(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 (let i = 0; i < csvData.length; i++) {
const row = csvData[i];
// 检查行数据是否存在
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.substring(0, 6); // 提取前6位
const year = '20' + dateStr.substring(0, 2); // 25 -> 2025
const month = dateStr.substring(2, 4); // 09
const day = dateStr.substring(4, 6); // 13
orderDate = new Date(`${year}-${month}-${day}T00:00:00`).toISOString();
} catch (error) {
console.warn('无法解析订单号中的日期,使用当前时间:', row.orderNumber);
}
}
// 创建订单数据(新的合并结构)
const orderData: OrderDTO.Create = {
shopId: shop.id,
platformOrderNo: row.orderNumber,
statusId: orderStatusId,
receivedAmount: row.shopActualAmount,
shippingFee: 0, // 运费暂时设为0
orderDate: 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: 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: Array.from(entitiesToCreate.shops),
products: Array.from(entitiesToCreate.products),
specs: Array.from(entitiesToCreate.specs)
},
matchDetails
};
}
/**
* 批量加载实体数据
*/
private async loadEntitiesBatch(
shopNames: string[],
productNames: string[],
specQueries: { productName: string; specCode: string }[]
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([])
shopNames.length > 0
? getShopsByNamesApi(shopNames)
: Promise.resolve([]),
productNames.length > 0
? getProductsByNamesApi(productNames)
: Promise.resolve([]),
specQueries.length > 0
? getProductSpecsByProductAndSpecsApi(specQueries)
: Promise.resolve([]),
]);
// 缓存店铺数据
shops.forEach(shop => {
shops.forEach((shop) => {
this.shopCache.set(shop.name, shop);
});
// 缓存商品数据
products.forEach(product => {
products.forEach((product) => {
this.productCache.set(product.name, product);
});
// 缓存包含规格信息的商品数据
productsWithSpecs.forEach(product => {
productsWithSpecs.forEach((product) => {
// 更新商品缓存
this.productCache.set(product.name, product);
// 缓存该商品的规格数据
if (product.specs && product.specs.length > 0) {
product.specs.forEach(spec => {
product.specs.forEach((spec) => {
const key = `${product.name}_${spec.specCode || ''}`;
this.specCache.set(key, spec);
});
@@ -348,42 +411,4 @@ export class EntityMatchingService {
console.error('批量加载实体数据失败:', error);
}
}
/**
* 清空缓存
*/
private clearCache(): void {
this.shopCache.clear();
this.productCache.clear();
this.specCache.clear();
}
/**
* 获取店铺信息
*/
getShopByName(name: string): ShopVO.Info | undefined {
return this.shopCache.get(name);
}
/**
* 获取商品信息
*/
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);
}
/**
* 获取订单状态ID
*/
getOrderStatusId(statusName: string): number | undefined {
return this.orderStatusMap.get(statusName);
}
}
@@ -46,13 +46,11 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
let headers: string[] = [];
// 尝试多种编码格式
const encodings = ['GBK', 'UTF-8', 'GB2312'];
let result: Papa.ParseResult<any> | null = null;
const encodings = ['GBK', 'utf8', 'GB2312'];
let result: null | Papa.ParseResult<any> = null;
for (const encoding of encodings) {
try {
console.log(`尝试使用${encoding}编码解析文件...`);
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
Papa.parse(file, {
header: true,
@@ -63,24 +61,22 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
},
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)
const hasChineseContent = Object.values(firstRow).some(
(value) => typeof value === 'string' && /[\u4E00-\u9FA5]/.test(value),
);
if (hasChineseContent) {
console.log(`成功使用${encoding}编码解析文件`);
break;
}
}
} catch (error) {
console.log(`使用${encoding}编码解析失败:`, error);
} catch {
continue;
}
}
@@ -91,7 +87,9 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
}
if (result.errors.length > 0) {
errors.push(`CSV解析错误: ${result.errors.map(e => e.message).join(', ')}`);
errors.push(
`CSV解析错误: ${result.errors.map((e) => e.message).join(', ')}`,
);
}
if (!result.data || result.data.length === 0) {
@@ -101,23 +99,32 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
// 获取表头
headers = result.meta.fields || [];
console.log('解析到的表头:', headers);
// 验证表头 - 使用更灵活的表头匹配
const requiredHeaders = ['商品', '订单号', '订单状态', '商品数量(件)', '商品id', '商品规格', '商家编码-规格维度', '售后状态', '商家实收金额(元)'];
const missingHeaders = requiredHeaders.filter(requiredHeader => {
// 检查是否有匹配的表头(支持部分匹配)
return !headers.some(header =>
header.includes(requiredHeader) || requiredHeader.includes(header)
);
});
// 验证表头 - 使用更灵活的表头匹配
const requiredHeaders = [
'商品',
'订单号',
'订单状态',
'商品数量(件)',
'商品id',
'商品规格',
'商家编码-规格维度',
'售后状态',
'商家实收金额(元)',
];
const missingHeaders = requiredHeaders.filter((requiredHeader) => {
// 检查是否有匹配的表头(支持部分匹配)
return !headers.some(
(header) =>
header.includes(requiredHeader) || requiredHeader.includes(header),
);
});
if (missingHeaders.length > 0) {
console.log('缺少的列:', missingHeaders);
console.log('实际表头:', headers);
console.log('期望表头:', requiredHeaders);
// 不再阻止导入,只是记录警告
errors.push(`警告:缺少部分列: ${missingHeaders.join(', ')},可以在导入后手动处理`);
errors.push(
`警告:缺少部分列: ${missingHeaders.join(', ')},可以在导入后手动处理`,
);
}
// 解析数据行
@@ -129,8 +136,9 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
data.push(rowData);
}
} catch (error) {
errors.push(`第${i + 2}行解析失败: ${error instanceof Error ? error.message : '未知错误'}`);
console.log(`第${i + 2}行解析错误:`, error);
errors.push(
`第${i + 2}行解析失败: ${error instanceof Error ? error.message : '未知错误'}`,
);
}
}
@@ -140,12 +148,19 @@ export async function parseOrderCSV(file: File): Promise<CSVParseResult> {
/**
* 解析订单行数据 - 从papaparse对象格式
*/
function parseOrderRowFromObject(row: any, rowNumber: number): ParsedOrderData | null {
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] !== '') {
if (
row[fieldName] !== undefined &&
row[fieldName] !== null &&
row[fieldName] !== ''
) {
return String(row[fieldName]).trim();
}
}
@@ -155,13 +170,29 @@ function parseOrderRowFromObject(row: any, rowNumber: number): ParsedOrderData |
const productName = getValue(['商品', '商品名称', 'productName']);
const orderNumber = getValue(['订单号', '订单编号', 'orderNumber']);
const orderStatusName = getValue(['订单状态', 'orderStatus', '状态']);
const quantityStr = getValue(['商品数量(件)', '商品数量', '数量', 'quantity']);
const quantityStr = getValue([
'商品数量(件)',
'商品数量',
'数量',
'quantity',
]);
const productId = getValue(['商品id', '商品ID', 'productId', '商品编码']);
const productSpecName = getValue(['商品规格', '规格', 'spec', 'productSpec']);
const productSpecName = getValue([
'商品规格',
'规格',
'spec',
'productSpec',
]);
const specCode = getValue(['商家编码-规格维度', '规格编码', 'specCode']);
// 店铺名称应该从文件名获取,这里不设置shopName
const afterSaleStatus = getValue(['售后状态', '售后', 'afterSale']);
const shopActualAmountStr = getValue(['商家实收金额(元)', '店铺实际收入(元)', '店铺实际收入', '收入', 'amount']);
const shopActualAmountStr = getValue([
'商家实收金额(元)',
'店铺实际收入(元)',
'店铺实际收入',
'收入',
'amount',
]);
// 验证必填字段 - 只验证最核心的字段
if (!productName) {
@@ -170,14 +201,14 @@ function parseOrderRowFromObject(row: any, rowNumber: number): ParsedOrderData |
if (!orderNumber) {
throw new Error('订单编号不能为空');
}
// 其他字段可以为空,在后续处理中处理
// 解析数量 - 允许为0或空
const quantity = parseFloat(quantityStr) || 0;
const quantity = Number.parseFloat(quantityStr) || 0;
// 解析金额 - 允许为0或空
const shopActualAmount = parseFloat(shopActualAmountStr) || 0;
const shopActualAmount = Number.parseFloat(shopActualAmountStr) || 0;
return {
productName,
@@ -192,7 +223,9 @@ function parseOrderRowFromObject(row: any, rowNumber: number): ParsedOrderData |
shopActualAmount,
};
} catch (error) {
throw new Error(`第${rowNumber}行数据验证失败: ${error instanceof Error ? error.message : '未知错误'}`);
throw new Error(
`第${rowNumber}行数据验证失败: ${error instanceof Error ? error.message : '未知错误'}`,
);
}
}
@@ -207,8 +240,11 @@ export function extractShopNameFromFilename(filename: string): string {
/**
* 转换为EntityMatchingService需要的格式
*/
export function convertToCSVOrderData(parsedData: ParsedOrderData[], shopName: string): any[] {
return parsedData.map(row => ({
export function convertToCSVOrderData(
parsedData: ParsedOrderData[],
shopName: string,
): any[] {
return parsedData.map((row) => ({
productName: row.productName,
orderNumber: row.orderNumber,
orderStatusName: row.orderStatusName,
@@ -216,8 +252,8 @@ export function convertToCSVOrderData(parsedData: ParsedOrderData[], shopName: s
productId: row.productId,
productSpecName: row.productSpecName,
specCode: row.specCode,
shopName: shopName, // 使用从文件名提取的店铺名称
shopName, // 使用从文件名提取的店铺名称
afterSaleStatus: row.afterSaleStatus,
shopActualAmount: row.shopActualAmount
shopActualAmount: row.shopActualAmount,
}));
}