refactor: 下线废弃的 EC 手动文件导入(ImportTask)能力

This commit is contained in:
2026-09-18 14:21:42 +08:00
parent 17397f5347
commit 0d9b5a21c2
84 changed files with 86 additions and 12036 deletions
@@ -1,53 +0,0 @@
import type { ImportMappingDTO, ImportMappingVO } from './types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import { requestClient } from '#/api/request';
/**
* 导入映射管理API
*/
/**
* 创建导入映射模板
*/
export async function createImportMappingApi(
data: ImportMappingDTO.CreateImportMappingDTO,
) {
return requestClient.post<ImportMappingVO.ImportMappingInfoVO>(
'/ec/import/mapping/create',
data,
);
}
/**
* 更新导入映射模板
*/
export async function updateImportMappingApi(
id: number,
data: ImportMappingDTO.UpdateImportMappingDTO,
) {
return requestClient.put<ImportMappingVO.ImportMappingInfoVO>(
`/ec/import/mapping/update/${id}`,
data,
);
}
/**
* 删除导入映射
*/
export async function deleteImportMappingApi(id: number) {
return requestClient.delete(`/ec/import/mapping/delete/${id}`);
}
/**
* 分页获取导入映射列表
*/
export async function getImportMappingPageApi(
params: PageQueryDTO<ImportMappingDTO.ImportMappingFilterDTO>,
) {
return requestClient.post<PageResultVO<ImportMappingVO.ImportMappingInfoVO>>(
'/ec/import/mapping/list',
params,
);
}
@@ -1,6 +0,0 @@
/**
* 导入映射模块API导出
*/
export * from './apis';
export * from './types';
@@ -1,7 +0,0 @@
/**
* 导入映射模块类型定义导出
*/
export * from './types.dto';
export * from './types.vo';
export * from './types.enum';
@@ -1,33 +0,0 @@
import type { ImportMappingType } from './types.enum';
/**
* 导入映射模块DTO类型定义
*/
export namespace ImportMappingDTO {
/** 创建导入映射参数 */
export interface CreateImportMappingDTO {
/** 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态) */
type: ImportMappingType;
/** 映射名称 */
name: string;
/** 字段映射(JSON格式) */
mapping: string;
}
/** 更新导入映射参数 */
export interface UpdateImportMappingDTO {
/** 映射名称 */
name?: string;
/** 字段映射(JSON格式) */
mapping: string;
}
/** 导入映射过滤条件 */
export interface ImportMappingFilterDTO {
/** 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态) */
type?: ImportMappingType;
/** 映射名称(模糊查询) */
name?: string;
}
}
@@ -1,32 +0,0 @@
/**
* 导入映射类型枚举
*/
export enum ImportMappingType {
/** 商品 */
PRODUCT = 'PRODUCT',
/** 订单 */
ORDER = 'ORDER',
/** 订单状态 */
ORDER_STATUS = 'ORDER_STATUS',
/** 推广费 */
PROMOTION_FEE = 'PROMOTION_FEE',
}
/**
* 导入映射类型选项配置
*/
export const IMPORT_MAPPING_TYPE_OPTIONS = [
{ label: '商品', value: ImportMappingType.PRODUCT },
{ label: '订单', value: ImportMappingType.ORDER },
{ label: '订单状态', value: ImportMappingType.ORDER_STATUS },
{ label: '推广费', value: ImportMappingType.PROMOTION_FEE },
];
/**
* 根据导入映射类型枚举值获取中文名称
*/
export function getImportMappingTypeName(type: ImportMappingType): string {
const option = IMPORT_MAPPING_TYPE_OPTIONS.find((opt) => opt.value === type);
return option?.label || '未知类型';
}
@@ -1,29 +0,0 @@
import type { ImportMappingType } from './types.enum';
/**
* 导入映射模块VO类型定义
*/
export namespace ImportMappingVO {
/** 导入映射信息 */
export interface ImportMappingInfoVO {
/** 映射ID */
id: number;
/** 所属公司ID */
companyId?: number;
/** 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态) */
type: ImportMappingType;
/** 映射名称 */
name: string;
/** 字段映射(JSON格式) */
mapping: string;
/** 创建时间 */
createTime: string;
/** 更新时间 */
updateTime: string;
/** 创建人ID */
createBy?: number;
/** 更新人ID */
updateBy?: number;
}
}
@@ -1,33 +0,0 @@
import type { ImportTaskDTO, ImportTaskVO } from './types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import { requestClient } from '#/api/request';
/**
* 导入任务管理API
*/
/**
* 创建导入任务
*/
export async function createImportTaskApi(
data: ImportTaskDTO.CreateImportTaskDTO,
) {
return requestClient.post<ImportTaskVO.ImportTaskInfoVO>(
'/ec/import/task/create',
data,
);
}
/**
* 分页获取导入任务列表
*/
export async function getImportTaskPageApi(
params: PageQueryDTO<ImportTaskDTO.ImportTaskFilterDTO>,
) {
return requestClient.post<PageResultVO<ImportTaskVO.ImportTaskInfoVO>>(
'/ec/import/task/list',
params,
);
}
@@ -1,6 +0,0 @@
/**
* 导入任务模块API导出
*/
export * from './apis';
export * from './types';
@@ -1,6 +0,0 @@
/**
* 导入任务模块类型定义导出
*/
export * from './types.dto';
export * from './types.vo';
@@ -1,31 +0,0 @@
/**
* 导入任务模块DTO类型定义
*/
export namespace ImportTaskDTO {
/** 创建导入任务参数 */
export interface CreateImportTaskDTO {
/** 所属店铺ID */
shopId: number;
/** 导入类型(product-商品 order-订单) */
type: string;
/** 原始文件名 */
fileName: string;
/** 关联文件ID */
fileId: number;
/** 字段映射记录(JSON字符串) */
mapping?: string;
}
/** 导入任务过滤条件 */
export interface ImportTaskFilterDTO {
/** 所属店铺ID */
shopId?: number;
/** 导入类型(product-商品 order-订单) */
type?: string;
/** 任务状态 */
status?: string;
/** 文件名(模糊查询) */
fileName?: string;
}
}
@@ -1,43 +0,0 @@
/**
* 导入任务模块VO类型定义
*/
export namespace ImportTaskVO {
/** 导入任务信息 */
export interface ImportTaskInfoVO {
/** 主键ID */
id: number;
/** 所属公司ID */
companyId?: number;
/** 所属店铺ID */
shopId?: number;
/** 所属店铺名称 */
shopName?: string;
/** 导入类型(product-商品 order-订单) */
type: string;
/** 原始文件名 */
fileName: string;
/** 关联文件ID */
fileId?: number;
/** 任务状态 */
status: string;
/** 总行数 */
totalCount?: number;
/** 成功行数 */
successCount?: number;
/** 失败行数 */
failCount?: number;
/** 字段映射记录(JSON字符串) */
mapping?: string;
/** 错误信息或备注 */
message?: string;
/** 创建时间 */
createTime: string;
/** 更新时间 */
updateTime: string;
/** 创建人ID */
createBy?: number;
/** 更新人ID */
updateBy?: number;
}
}
@@ -1,4 +1,4 @@
import type { BatchImportResultVO, OrderDTO, OrderFieldVO, OrderVO } from './types';
import type { OrderDTO, OrderFieldVO, OrderVO } from './types';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
@@ -53,16 +53,6 @@ export async function getOrderByIdApi(id: number) {
return requestClient.get<OrderVO.Info>(`/ec/order/detail/${id}`);
}
/**
* 批量导入订单
*/
export async function batchImportOrdersApi(data: OrderDTO.BatchImport) {
return requestClient.post<BatchImportResultVO.Info>(
'/ec/order/batch-import',
data,
);
}
/**
* 获取订单字段信息列表
*/
@@ -121,12 +121,6 @@ export namespace OrderDTO {
productId?: number;
}
/** 批量导入订单参数 */
export interface BatchImport {
/** 订单列表 */
orders: Create[];
}
/** 批量删除订单参数 */
export interface BatchDelete {
/** 订单 ID 列表 */
@@ -164,21 +164,3 @@ export namespace OrderFieldVO {
dataType?: string;
}
}
/**
* 批量导入结果相关 VO 类型定义
*/
export namespace BatchImportResultVO {
/** 批量导入结果 */
export interface Info {
/** 总数量 */
totalCount: number;
/** 成功数量 */
successCount: number;
/** 失败数量 */
failureCount: number;
/** 失败详情 */
failureDetails: string[];
}
}
@@ -7,8 +7,6 @@ const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
export const RealtimeSseEvent = {
CONNECTED: 'message',
PING: 'ping',
IMPORT_TASK_PROGRESS: 'import_task_progress',
IMPORT_ALL_TASKS_COMPLETED: 'import_all_tasks_completed',
PDD_ORDER_FULL_SYNC_PROGRESS: 'pdd_order_full_sync_progress',
} as const;
@@ -1,39 +0,0 @@
<script setup lang="ts">
import { computed } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button } from 'ant-design-vue';
import { useImportTaskStore } from '#/store';
import ImportTaskDropdown from './ImportTaskDropdown.vue';
defineOptions({ name: 'ImportTaskButton' });
// 创建下载图标组件
const DownloadIcon = createIconifyIcon('lucide:download');
const importTaskStore = useImportTaskStore();
// 计算属性:是否有进行中的任务
const hasActiveTasks = computed(() => importTaskStore.hasActiveTasks);
</script>
<template>
<ImportTaskDropdown>
<template #trigger>
<div class="flex-center mr-2 h-full">
<Button type="text" shape="circle" class="relative">
<template #icon>
<DownloadIcon class="size-4" />
</template>
<span
v-if="hasActiveTasks"
class="bg-primary absolute right-0.5 top-0.5 h-2 w-2 rounded"
></span>
</Button>
</div>
</template>
</ImportTaskDropdown>
</template>
@@ -1,243 +0,0 @@
<script setup lang="ts">
import type { ImportTaskVO } from '#/api/ec/import/task';
import { computed, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { useToggle } from '@vueuse/core';
import { Button, Empty, List, Popover, Progress, Tag } from 'ant-design-vue';
import { useImportTaskStore } from '#/store';
defineOptions({ name: 'ImportTaskDropdown' });
const importTaskStore = useImportTaskStore();
const [open] = useToggle();
// 监听 store 中的 shouldOpenDropdown 状态,自动打开下拉菜单
watch(
() => importTaskStore.shouldOpenDropdown,
(shouldOpen) => {
if (shouldOpen) {
open.value = true;
// 重置状态,避免重复触发
importTaskStore.closeDropdown();
}
},
);
// 创建消息详情模态框
const [MessageModal, messageModalApi] = useVbenModal({
draggable: true,
class: 'w-[700px]',
title: '任务消息详情',
showCancelButton: false,
showConfirmButton: false,
footer: false,
});
// 当前要显示的消息
const currentMessage = ref<string>('');
// 计算属性:任务列表(按创建时间倒序)
const taskList = computed(() => {
return [...importTaskStore.tasks].sort(
(a, b) =>
new Date(b.createTime).getTime() - new Date(a.createTime).getTime(),
);
});
// 获取任务状态标签
function getStatusTag(status: string) {
const statusMap: Record<string, { color: string; text: string }> = {
pending: { color: 'default', text: '等待中' },
processing: { color: 'processing', text: '处理中' },
success: { color: 'success', text: '成功' },
failed: { color: 'error', text: '失败' },
};
return statusMap[status] || { color: 'default', text: status };
}
// 获取任务进度百分比
function getProgress(task: ImportTaskVO.ImportTaskInfoVO): number {
if (!task.totalCount || task.totalCount === 0) {
return 0;
}
const processed = (task.successCount || 0) + (task.failCount || 0);
return Math.round((processed / task.totalCount) * 100);
}
// 获取任务进度文本
function getProgressText(task: ImportTaskVO.ImportTaskInfoVO): string {
if (!task.totalCount || task.totalCount === 0) {
return '等待开始';
}
const processed = (task.successCount || 0) + (task.failCount || 0);
return `${processed}/${task.totalCount}`;
}
// 打开消息详情模态框
function openMessageModal(message: string) {
currentMessage.value = message;
messageModalApi.open();
}
// 格式化时间
function formatTime(time: string): string {
return new Date(time).toLocaleString();
}
</script>
<template>
<Popover
v-model:open="open"
trigger="click"
:overlay-style="{ width: '400px', padding: 0 }"
placement="bottomRight"
>
<template #content>
<div class="relative">
<div class="flex items-center justify-between border-b p-4 py-3">
<div class="font-medium">导入任务管理</div>
<Button
v-if="taskList.length > 0"
size="small"
type="text"
@click="importTaskStore.fetchTasks(true)"
>
刷新
</Button>
</div>
<div v-if="taskList.length > 0" class="max-h-[400px] overflow-y-auto">
<List :data-source="taskList" item-layout="vertical">
<template #renderItem="{ item }">
<List.Item class="border-b px-4 py-3">
<div class="flex w-full flex-col gap-2">
<!-- 任务标题和状态 -->
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<span class="text-sm font-medium">{{
item.fileName
}}</span>
<Tag
:color="getStatusTag(item.status).color"
size="small"
>
{{ getStatusTag(item.status).text }}
</Tag>
</div>
<span class="text-xs text-gray-500">
{{ formatTime(item.createTime) }}
</span>
</div>
<!-- 进度条 -->
<div v-if="item.status === 'processing'" class="space-y-1">
<Progress
:percent="getProgress(item)"
:show-info="true"
size="small"
:status="
item.status === 'failed' ? 'exception' : 'active'
"
/>
<div class="flex justify-between text-xs text-gray-500">
<span>已处理: {{ getProgressText(item) }}</span>
<span>
成功: {{ item.successCount || 0 }} / 失败:
{{ item.failCount || 0 }}
</span>
</div>
</div>
<!-- 完成信息 -->
<div
v-if="item.status === 'success' || item.status === 'failed'"
class="flex justify-between text-xs text-gray-500"
>
<span>总行数: {{ item.totalCount || 0 }}</span>
<span>
成功: {{ item.successCount || 0 }} / 失败:
{{ item.failCount || 0 }}
</span>
</div>
<!-- 任务详情信息(失败任务) -->
<div
v-if="item.status === 'failed' && item.message"
class="flex items-center gap-2 rounded bg-red-50 p-2 dark:bg-red-950"
>
<div
class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-xs text-red-600 dark:text-red-400"
>
{{ item.message }}
</div>
<Button
type="link"
size="small"
class="h-auto p-0 text-xs"
@click="openMessageModal(item.message)"
>
查看
</Button>
</div>
<!-- 任务详情信息(成功任务) -->
<div
v-if="item.status === 'success' && item.message"
class="flex items-center gap-2 rounded bg-green-50 p-2 dark:bg-green-950"
>
<div
class="flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-xs text-green-600 dark:text-green-400"
>
{{ item.message }}
</div>
<Button
type="link"
size="small"
class="h-auto p-0 text-xs"
@click="openMessageModal(item.message)"
>
查看
</Button>
</div>
<!-- 任务类型和店铺 -->
<div class="flex items-center gap-3 text-xs text-gray-400">
<span>类型: {{ item.type === 'order' ? '订单导入' : '商品导入' }}</span>
<span v-if="item.shopName">店铺: {{ item.shopName }}</span>
</div>
</div>
</List.Item>
</template>
</List>
</div>
<Empty v-else description="暂无导入任务" class="min-h-[150px]" />
</div>
</template>
<template #default>
<slot name="trigger"></slot>
</template>
</Popover>
<!-- 消息详情模态框 -->
<MessageModal>
<div class="max-h-[500px] overflow-y-auto">
<div
class="whitespace-pre-wrap break-words rounded bg-gray-50 p-4 text-sm dark:bg-gray-800"
>
{{ currentMessage }}
</div>
</div>
<!-- 底部操作栏 -->
<div class="mt-4 flex justify-end border-t pt-4">
<Button @click="messageModalApi.close()">关闭</Button>
</div>
</MessageModal>
</template>
+2 -8
View File
@@ -16,10 +16,9 @@ import {
import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
import ImportTaskButton from '#/components/ImportTaskButton.vue';
import SwitchAccountModal from '#/components/SwitchAccountModal.vue';
import SwitchCompanyModal from '#/components/SwitchCompanyModal.vue';
import { useAuthStore, useImportTaskStore, useRealtimeStore } from '#/store';
import { useAuthStore, useRealtimeStore } from '#/store';
import LoginForm from '#/views/_core/authentication/login.vue';
const router = useRouter();
@@ -58,20 +57,18 @@ const notifications = ref<NotificationItem[]>([
const userStore = useUserStore();
const authStore = useAuthStore();
const accessStore = useAccessStore();
const importTaskStore = useImportTaskStore();
const realtimeStore = useRealtimeStore();
const { destroyWatermark, updateWatermark } = useWatermark();
const showDot = computed(() =>
notifications.value.some((item) => !item.isRead),
);
// 登录布局挂载:已登录才建 SSE 与导入任务
// 登录布局挂载:已登录才建 SSE
onMounted(() => {
if (!accessStore.accessToken) {
return;
}
realtimeStore.start();
importTaskStore.init();
});
// 切换账户模态框引用
@@ -209,9 +206,6 @@ watch(
@logout="handleLogout"
/>
</template>
<template #header-right-90>
<ImportTaskButton />
</template>
<template #notification>
<Notification
:dot="showDot"
@@ -1,160 +0,0 @@
import type { ImportTaskVO } from '#/api/ec/import/task';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { useAccessStore } from '@vben/stores';
import { defineStore } from 'pinia';
import { getImportTaskPageApi } from '#/api/ec/import/task';
import { RealtimeSseEvent } from '#/api/notify/sse';
import { useRealtimeStore } from '#/store/realtime';
/**
* 导入任务管理 Store(进度通过全局 realtime SSE 订阅)
*/
export const useImportTaskStore = defineStore('import-task', () => {
const tasks = ref<ImportTaskVO.ImportTaskInfoVO[]>([]);
const pagination = ref({
current: 1,
pageSize: 10,
total: 0,
});
const loading = ref(false);
const shouldOpenDropdown = ref(false);
let unsubProgress: (() => void) | null = null;
let unsubAllDone: (() => void) | null = null;
const hasActiveTasks = computed(() => {
return tasks.value.some(
(task) => task.status === 'pending' || task.status === 'processing',
);
});
const activeTaskCount = computed(() => {
return tasks.value.filter(
(task) => task.status === 'pending' || task.status === 'processing',
).length;
});
async function fetchTasks(reset = false) {
if (loading.value) return;
try {
loading.value = true;
if (reset) {
pagination.value.current = 1;
}
const params: PageQueryDTO = {
page: pagination.value.current,
pageSize: pagination.value.pageSize,
filters: {},
};
const result = await getImportTaskPageApi(params);
if (reset) {
tasks.value = result.records || [];
} else {
tasks.value.push(...(result.records || []));
}
pagination.value.total = result.total || 0;
} catch (error) {
console.error('获取导入任务列表失败:', error);
throw error;
} finally {
loading.value = false;
}
}
function updateTask(task: ImportTaskVO.ImportTaskInfoVO) {
const index = tasks.value.findIndex((t) => t.id === task.id);
if (index === -1) {
tasks.value.unshift(task);
} else {
tasks.value[index] = task;
}
}
function subscribeRealtime() {
if (unsubProgress) {
return;
}
const realtime = useRealtimeStore();
unsubProgress = realtime.on(
RealtimeSseEvent.IMPORT_TASK_PROGRESS,
(event) => {
try {
const data = JSON.parse(event.data);
if (data.task) {
updateTask(data.task);
}
} catch (error) {
console.error('解析导入任务进度失败:', error);
}
},
);
unsubAllDone = realtime.on(
RealtimeSseEvent.IMPORT_ALL_TASKS_COMPLETED,
() => {
fetchTasks(true).catch(() => {});
},
);
}
function unsubscribeRealtime() {
unsubProgress?.();
unsubAllDone?.();
unsubProgress = null;
unsubAllDone = null;
}
/** 登录后才拉任务列表并订阅 SSE */
async function init() {
if (!useAccessStore().accessToken) {
return;
}
subscribeRealtime();
await fetchTasks(true);
}
function $reset() {
unsubscribeRealtime();
tasks.value = [];
pagination.value = {
current: 1,
pageSize: 10,
total: 0,
};
loading.value = false;
}
function openDropdown() {
shouldOpenDropdown.value = true;
}
function closeDropdown() {
shouldOpenDropdown.value = false;
}
return {
tasks,
pagination,
loading,
shouldOpenDropdown,
hasActiveTasks,
activeTaskCount,
fetchTasks,
updateTask,
init,
openDropdown,
closeDropdown,
$reset,
};
});
@@ -1,5 +1,4 @@
export * from './auth';
export * from './app-config';
export * from './col-sidebar-layout';
export * from './import-task';
export * from './realtime';
@@ -1,206 +0,0 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { ImportMappingVO } from '#/api/ec/import/mapping';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteImportMappingApi,
getImportMappingPageApi,
} from '#/api/ec/import/mapping';
import { PermissionGate } from '#/components/permission';
import {
syncVxeGridColumns,
useActionColumnVisible,
} from '#/composables/use-vxe-action-column';
import { ImportMappingType } from '#/api/ec/import/mapping/types/types.enum';
import ImportMappingFormModal from '../import-mapping/components/ImportMappingFormModal.vue';
defineOptions({ name: 'FieldMappingConfig' });
const PlusIcon = createIconifyIcon('lucide:plus');
const loading = ref(false);
const formModalRef = ref();
const mappingActionCodes = [
'data:import-mapping:create',
'data:import-mapping:update',
'data:import-mapping:delete',
];
const showActionColumn = useActionColumnVisible(mappingActionCodes);
const mappingTableBaseColumns: VxeGridProps<any>['columns'] = [
{ type: 'seq', width: 80, title: '序号' },
{
field: 'name',
title: '模板名称',
minWidth: 'auto',
showOverflow: 'tooltip',
},
{ field: 'type', title: '类型', width: 120, slots: { default: 'type' } },
{
title: '映射字段数',
width: 120,
slots: { default: 'mappingCount' },
},
{ field: 'createTime', title: '创建时间', width: 180 },
{ field: 'updateTime', title: '更新时间', width: 180 },
];
const mappingActionColumn: NonNullable<VxeGridProps<any>['columns']>[number] = {
title: '操作',
width: 160,
fixed: 'right',
slots: { default: 'action' },
};
const mappingTableColumns = computed(() =>
showActionColumn.value
? [...(mappingTableBaseColumns ?? []), mappingActionColumn]
: (mappingTableBaseColumns ?? []),
);
const gridOptions: VxeGridProps<any> = {
columns: mappingTableColumns.value,
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: { enabled: false },
proxyConfig: {
ajax: {
query: async () => {
try {
loading.value = true;
const result = await getImportMappingPageApi({
page: 1,
pageSize: 100,
filters: { type: ImportMappingType.ORDER },
});
return { items: result.records || [], total: result.total || 0 };
} catch {
message.error('获取字段映射模板列表失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
}
},
},
},
};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
showSearchForm: false,
tableTitle: '字段映射模板',
});
syncVxeGridColumns(gridApi, mappingTableColumns);
function refresh() {
gridApi?.reload();
}
function handleAdd() {
formModalRef.value?.open(true);
}
function handleEdit(row: ImportMappingVO.ImportMappingInfoVO) {
formModalRef.value?.open(false, row);
}
async function handleDelete(row: ImportMappingVO.ImportMappingInfoVO) {
try {
await deleteImportMappingApi(row.id);
message.success('删除成功');
refresh();
} catch {
message.error('删除失败');
}
}
function getMappingCount(mapping: string): number {
try {
const arr = JSON.parse(mapping);
return Array.isArray(arr) ? arr.length : 0;
} catch {
return 0;
}
}
function getTypeName(type: ImportMappingType): string {
const map: Record<string, string> = {
[ImportMappingType.ORDER]: '订单字段',
[ImportMappingType.ORDER_STATUS]: '订单状态',
[ImportMappingType.PRODUCT]: '商品字段',
};
return map[type] || type;
}
</script>
<template>
<Page title="字段映射模板" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理订单导入时的字段映射模板,支持创建、编辑和删除
</div>
</template>
<Grid :loading="loading">
<template #toolbar-tools>
<Space>
<PermissionGate code="data:import-mapping:create">
<Button type="primary" @click="handleAdd">
<PlusIcon />
新建模板
</Button>
</PermissionGate>
</Space>
</template>
<template #type="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }">
<Tag color="blue">{{ getTypeName(row.type) }}</Tag>
</template>
<template
#mappingCount="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }"
>
<Tag color="green">{{ getMappingCount(row.mapping) }} 个字段</Tag>
</template>
<template v-if="showActionColumn" #action="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }">
<Space>
<PermissionGate code="data:import-mapping:update">
<Button size="small" @click="handleEdit(row)">编辑</Button>
</PermissionGate>
<PermissionGate code="data:import-mapping:delete">
<Popconfirm title="确定删除该模板?" @confirm="handleDelete(row)">
<Button size="small" danger>删除</Button>
</Popconfirm>
</PermissionGate>
</Space>
</template>
</Grid>
<ImportMappingFormModal
ref="formModalRef"
:type="ImportMappingType.ORDER"
@success="refresh"
/>
</Page>
</template>
@@ -1,284 +0,0 @@
<script setup lang="ts">
import type { OrderFieldVO } from '#/api/ec/order/types';
import type { ImportMappingVO } from '#/api/ec/import/mapping';
import type { ImportMappingType } from '#/api/ec/import/mapping/types/types.enum';
import type { OrderStatusVO } from '#/api/ec/order/status';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Form, Input, message, Select } from 'ant-design-vue';
import { getOrderFieldsApi } from '#/api/ec/order';
import {
createImportMappingApi,
updateImportMappingApi,
} from '#/api/ec/import/mapping';
import { ImportMappingType as MappingTypeEnum } from '#/api/ec/import/mapping/types/types.enum';
import { getAllOrderStatusListApi } from '#/api/ec/order/status';
defineOptions({ name: 'ImportMappingFormModal' });
// Props: 传入模板类型
const props = defineProps<{
type: ImportMappingType;
}>();
const emit = defineEmits<{
success: [];
}>();
// 弹窗
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[700px]',
showCancelButton: true,
showConfirmButton: true,
onConfirm: handleConfirm,
onCancel() {
resetForm();
modalApi.close();
},
});
// 状态
const loading = ref(false);
const isEdit = ref(false);
const editId = ref<number | undefined>();
const templateName = ref('');
// 字段映射相关(ORDER 类型)
interface FieldMappingItem {
fieldName: string;
fieldLabel: string;
fileFieldName?: string;
required: boolean;
}
const fieldDefs = ref<OrderFieldVO.Info[]>([]);
const fieldMappings = ref<Record<string, string>>({});
// 订单状态映射相关(ORDER_STATUS 类型)
interface StatusMappingItem {
csvStatus: string;
mappedStatusCode: string;
}
const orderStatusList = ref<OrderStatusVO.Meta[]>([]);
const statusMappings = ref<StatusMappingItem[]>([]);
// 获取字段定义
async function fetchFieldDefs() {
try {
if (props.type === MappingTypeEnum.ORDER) {
fieldDefs.value = (await getOrderFieldsApi()) || [];
} else {
fieldDefs.value = [];
}
} catch (error) {
console.error('获取字段定义失败:', error);
}
}
// 获取订单状态列表(仅 ORDER_STATUS 类型)
async function fetchOrderStatuses() {
try {
const result = await getAllOrderStatusListApi();
orderStatusList.value = result || [];
} catch (error) {
console.error('获取订单状态列表失败:', error);
}
}
// 打开弹窗
async function open(
isNew: boolean,
record?: ImportMappingVO.ImportMappingInfoVO,
) {
isEdit.value = !isNew;
editId.value = record?.id;
modalApi.open();
await (props.type === MappingTypeEnum.ORDER_STATUS
? fetchOrderStatuses()
: fetchFieldDefs());
if (isNew) {
// 新建:初始化空映射
templateName.value = '';
if (props.type === MappingTypeEnum.ORDER_STATUS) {
statusMappings.value = [];
} else {
fieldMappings.value = {};
}
} else if (record) {
// 编辑:解析现有映射
templateName.value = record.name;
try {
const mappingArr = JSON.parse(record.mapping);
if (props.type === MappingTypeEnum.ORDER_STATUS) {
statusMappings.value = mappingArr || [];
} else {
const mapping: Record<string, string> = {};
(mappingArr || []).forEach((item: FieldMappingItem) => {
mapping[item.fieldName] = item.fileFieldName || '';
});
fieldMappings.value = mapping;
}
} catch {
if (props.type === MappingTypeEnum.ORDER_STATUS) {
statusMappings.value = [];
} else {
fieldMappings.value = {};
}
}
}
}
// 重置表单
function resetForm() {
templateName.value = '';
fieldMappings.value = {};
statusMappings.value = [];
fieldDefs.value = [];
orderStatusList.value = [];
}
// 确认保存
async function handleConfirm() {
if (!templateName.value.trim()) {
message.warning('请输入模板名称');
return;
}
loading.value = true;
try {
let mappingJson = '[]';
if (props.type === MappingTypeEnum.ORDER_STATUS) {
// 过滤掉未映射的
const validMappings = statusMappings.value.filter(
(m) => m.mappedStatusCode,
);
mappingJson = JSON.stringify(validMappings);
} else {
const items: FieldMappingItem[] = fieldDefs.value
.filter((f) => fieldMappings.value[f.fieldName])
.map((f) => ({
fieldName: f.fieldName,
fieldLabel: f.fieldLabel,
fileFieldName: fieldMappings.value[f.fieldName],
required: f.required,
}));
mappingJson = JSON.stringify(items);
}
if (isEdit.value && editId.value) {
await updateImportMappingApi(editId.value, {
name: templateName.value.trim(),
mapping: mappingJson,
});
message.success('更新成功');
} else {
await createImportMappingApi({
type: props.type,
name: templateName.value.trim(),
mapping: mappingJson,
});
message.success('创建成功');
}
emit('success');
resetForm();
modalApi.close();
} catch (error: any) {
message.error(error?.message || '保存失败');
} finally {
loading.value = false;
}
}
// 暴露方法
defineExpose({ open });
</script>
<template>
<Modal
:loading="loading"
:title="isEdit ? '编辑映射模板' : '新建映射模板'"
:confirm-text="isEdit ? '保存' : '创建'"
>
<Form :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
<Form.Item label="模板名称" required>
<Input
v-model:value="templateName"
placeholder="请输入模板名称"
:maxlength="50"
show-count
/>
</Form.Item>
<!-- 订单状态映射编辑 -->
<Form.Item
v-if="type === MappingTypeEnum.ORDER_STATUS"
label="状态映射"
:wrapper-col="{ span: 20 }"
>
<div class="max-h-[400px] space-y-2 overflow-y-auto">
<div
v-for="(item, idx) in statusMappings"
:key="idx"
class="flex items-center space-x-2 rounded border p-2"
>
<span class="w-[200px] truncate text-gray-600">{{
item.csvStatus
}}</span>
<span class="text-gray-400">→</span>
<Select
v-model:value="item.mappedStatusCode"
placeholder="选择订单状态"
class="flex-1"
show-search
allow-clear
:options="
orderStatusList.map((s) => ({
label: s.label,
value: s.code,
}))
"
/>
</div>
<div
v-if="statusMappings.length === 0"
class="py-4 text-center text-gray-400"
>
暂无映射数据
</div>
</div>
</Form.Item>
<!-- 字段映射编辑(只读展示) -->
<Form.Item v-else label="字段映射" :wrapper-col="{ span: 20 }">
<div class="max-h-[400px] space-y-2 overflow-y-auto">
<div
v-for="field in fieldDefs"
:key="field.fieldName"
class="flex items-center space-x-2 rounded border p-2"
:class="{
'border-red-200 bg-red-50':
field.required && !fieldMappings[field.fieldName],
}"
>
<span class="w-[140px]">
{{ field.fieldLabel }}
<span v-if="field.required" class="text-red-500">*</span>
</span>
<Input
v-model:value="fieldMappings[field.fieldName]"
placeholder="CSV列名(如:商品名称)"
class="flex-1"
/>
</div>
</div>
</Form.Item>
</Form>
</Modal>
</template>
@@ -1,206 +0,0 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { ImportMappingVO } from '#/api/ec/import/mapping';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteImportMappingApi,
getImportMappingPageApi,
} from '#/api/ec/import/mapping';
import { PermissionGate } from '#/components/permission';
import {
syncVxeGridColumns,
useActionColumnVisible,
} from '#/composables/use-vxe-action-column';
import { ImportMappingType } from '#/api/ec/import/mapping/types/types.enum';
import ImportMappingFormModal from '../import-mapping/components/ImportMappingFormModal.vue';
defineOptions({ name: 'OrderStatusMappingConfig' });
const PlusIcon = createIconifyIcon('lucide:plus');
const loading = ref(false);
const formModalRef = ref();
const mappingActionCodes = [
'data:import-mapping:create',
'data:import-mapping:update',
'data:import-mapping:delete',
];
const showActionColumn = useActionColumnVisible(mappingActionCodes);
const mappingTableBaseColumns: VxeGridProps<any>['columns'] = [
{ type: 'seq', width: 80, title: '序号' },
{
field: 'name',
title: '模板名称',
minWidth: 'auto',
showOverflow: 'tooltip',
},
{ field: 'type', title: '类型', width: 120, slots: { default: 'type' } },
{
title: '映射状态数',
width: 120,
slots: { default: 'mappingCount' },
},
{ field: 'createTime', title: '创建时间', width: 180 },
{ field: 'updateTime', title: '更新时间', width: 180 },
];
const mappingActionColumn: NonNullable<VxeGridProps<any>['columns']>[number] = {
title: '操作',
width: 160,
fixed: 'right',
slots: { default: 'action' },
};
const mappingTableColumns = computed(() =>
showActionColumn.value
? [...(mappingTableBaseColumns ?? []), mappingActionColumn]
: (mappingTableBaseColumns ?? []),
);
const gridOptions: VxeGridProps<any> = {
columns: mappingTableColumns.value,
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: { enabled: false },
proxyConfig: {
ajax: {
query: async () => {
try {
loading.value = true;
const result = await getImportMappingPageApi({
page: 1,
pageSize: 100,
filters: { type: ImportMappingType.ORDER_STATUS },
});
return { items: result.records || [], total: result.total || 0 };
} catch {
message.error('获取订单状态映射模板列表失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
}
},
},
},
};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
showSearchForm: false,
tableTitle: '订单状态映射模板',
});
syncVxeGridColumns(gridApi, mappingTableColumns);
function refresh() {
gridApi?.reload();
}
function handleAdd() {
formModalRef.value?.open(true);
}
function handleEdit(row: ImportMappingVO.ImportMappingInfoVO) {
formModalRef.value?.open(false, row);
}
async function handleDelete(row: ImportMappingVO.ImportMappingInfoVO) {
try {
await deleteImportMappingApi(row.id);
message.success('删除成功');
refresh();
} catch {
message.error('删除失败');
}
}
function getMappingCount(mapping: string): number {
try {
const arr = JSON.parse(mapping);
return Array.isArray(arr) ? arr.length : 0;
} catch {
return 0;
}
}
function getTypeName(type: ImportMappingType): string {
const map: Record<string, string> = {
[ImportMappingType.ORDER]: '订单字段',
[ImportMappingType.ORDER_STATUS]: '订单状态',
[ImportMappingType.PRODUCT]: '商品字段',
};
return map[type] || type;
}
</script>
<template>
<Page title="订单状态映射模板" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理订单导入时的订单状态映射模板,支持创建、编辑和删除
</div>
</template>
<Grid :loading="loading">
<template #toolbar-tools>
<Space>
<PermissionGate code="data:import-mapping:create">
<Button type="primary" @click="handleAdd">
<PlusIcon />
新建模板
</Button>
</PermissionGate>
</Space>
</template>
<template #type="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }">
<Tag color="orange">{{ getTypeName(row.type) }}</Tag>
</template>
<template
#mappingCount="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }"
>
<Tag color="green">{{ getMappingCount(row.mapping) }} 个状态</Tag>
</template>
<template v-if="showActionColumn" #action="{ row }: { row: ImportMappingVO.ImportMappingInfoVO }">
<Space>
<PermissionGate code="data:import-mapping:update">
<Button size="small" @click="handleEdit(row)">编辑</Button>
</PermissionGate>
<PermissionGate code="data:import-mapping:delete">
<Popconfirm title="确定删除该模板?" @confirm="handleDelete(row)">
<Button size="small" danger>删除</Button>
</Popconfirm>
</PermissionGate>
</Space>
</template>
</Grid>
<ImportMappingFormModal
ref="formModalRef"
:type="ImportMappingType.ORDER_STATUS"
@success="refresh"
/>
</Page>
</template>
@@ -1,163 +0,0 @@
<script setup lang="ts">
import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { message, Spin } from 'ant-design-vue';
defineOptions({ name: 'AdFeeFileUploadArea' });
const props = withDefaults(
defineProps<{
loading?: boolean;
}>(),
{
loading: false,
},
);
const emit = defineEmits<Emits>();
const UploadIcon = createIconifyIcon('lucide:upload');
const LoaderIcon = createIconifyIcon('lucide:loader-2');
interface Emits {
(e: 'fileSelected', file: File): void;
}
const isDragOver = ref(false);
const fileInputRef = ref<HTMLInputElement>();
const validateFile = (file: File): boolean => {
const ext = file.name.toLowerCase().split('.').pop() || '';
const allowedExts = ['csv', 'xlsx', 'xls'];
if (!allowedExts.includes(ext)) {
message.error('只能上传 CSV 或 Excel 格式的文件!');
return false;
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('文件大小不能超过10MB!');
return false;
}
return true;
};
const processFile = (file: File) => {
if (props.loading) return;
if (!validateFile(file)) return;
emit('fileSelected', file);
};
const handleDragOver = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = true;
};
const handleDragLeave = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
};
const handleDrop = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
const files = e.dataTransfer?.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
};
const triggerFileInput = () => {
fileInputRef.value?.click();
};
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement;
const files = target.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
target.value = '';
};
</script>
<template>
<Spin :spinning="loading" tip="正在解析文件...">
<div
class="rounded-lg border-2 border-dashed border-gray-300 dark:border-[hsl(240deg_3.7%_22%)] p-8 text-center transition-colors cursor-pointer"
:class="{
'border-blue-500 bg-blue-50 dark:bg-[hsl(240deg_3.7%_15.9%/20%)]': isDragOver && !loading,
'cursor-not-allowed opacity-60': loading,
}"
@dragover.prevent="!loading && handleDragOver($event)"
@dragleave.prevent="!loading && handleDragLeave($event)"
@drop.prevent="!loading && handleDrop($event)"
@click="!loading && triggerFileInput()"
>
<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 dark:text-[hsl(240deg_5%_64.9%)]"
: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 dark:text-[hsl(240deg_5%_64.9%)]' : 'text-gray-700 dark:text-[hsl(0deg_0%_95%)]'"
>
{{
loading
? '正在解析文件,请稍候...'
: '拖拽 CSV 或 Excel 文件到此处或点击上传'
}}
</p>
<p v-if="!loading" class="text-sm text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]">
支持 .csv / .xlsx / .xls 格式,最大 10MB
</p>
</div>
</div>
<input
ref="fileInputRef"
type="file"
accept=".csv,.xlsx,.xls"
style="display: none"
:disabled="loading"
@change="handleFileSelect"
/>
</div>
</Spin>
</template>
<style scoped>
.border-dashed {
transition: all 0.3s ease;
}
.border-dashed:hover {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
:deep(.border-dashed:hover) {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
html.dark .border-dashed:hover {
border-color: hsl(240deg 3.7% 40%) !important;
background-color: hsl(240deg 3.7% 15.9% / 15%) !important;
}
</style>
@@ -1,850 +0,0 @@
<script setup lang="ts">
import type { AdFeeFieldVO } from '#/api/ec/shop/ad-fee/types';
import type { ImportMappingVO } from '#/api/ec/import/mapping';
import type { ImportTaskDTO } from '#/api/ec/import/task';
import type { ShopVO } from '#/api/ec/shop/types';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Button, DatePicker, Form, Input, message, Select, Spin, Steps } from 'ant-design-vue';
import {
createImportMappingApi,
getImportMappingPageApi,
ImportMappingType,
updateImportMappingApi,
} from '#/api/ec/import/mapping';
import { getAdFeeFieldsApi } from '#/api/ec/shop/ad-fee/apis';
import { getShopPageApi } from '#/api/ec/shop';
import { createImportTaskApi } from '#/api/ec/import/task';
import { useImportTaskStore } from '#/store';
import { PermissionGate } from '#/components/permission';
import { FileCategory } from '#/constants/file-category';
import { uploadFile } from '#/utils/upload-file';
import dayjs from 'dayjs';
interface FieldMappingItem {
fieldName: string;
fieldLabel: string;
fileFieldName?: string;
required: boolean;
}
defineOptions({ name: 'AdFeeImportTaskWizard' });
const emit = defineEmits<{
success: [];
}>();
const currentStep = ref(0);
const fieldDefsLoading = ref(false);
const createTaskSubmitting = ref(false);
const csvHeaders = ref<string[]>([]);
const previewData = defineModel<any[]>('previewData', { default: () => [] });
const originalImportFile = ref<File | null>(null);
const selectedFile = ref<File | null>(null);
const shopList = ref<ShopVO.Info[]>([]);
const selectedShopId = ref<number | undefined>();
const shopLoading = ref(false);
const shopPage = ref(1);
const shopPageSize = ref(20);
const shopHasMore = ref(true);
const shopSearchValue = ref('');
const feeDate = ref<any>(undefined);
const fieldDefs = ref<AdFeeFieldVO.Info[]>([]);
const fieldMappings = ref<
Record<string, { fieldDef: AdFeeFieldVO.Info; mappedHeader?: string }>
>({});
const mappingTemplates = ref<ImportMappingVO.ImportMappingInfoVO[]>([]);
const selectedTemplateId = ref<number | undefined>();
const selectedTemplateName = ref('');
const templateLoading = ref(false);
const savingTemplate = ref(false);
const templateName = ref('');
const savingFieldToTemplate = ref<null | string>(null);
const currentTemplateMappings = ref<FieldMappingItem[]>([]);
const [SaveTemplateModal, saveTemplateModalApi] = useVbenModal({
draggable: true,
class: 'w-[500px]',
title: '保存映射模板',
showCancelButton: true,
showConfirmButton: true,
confirmText: '保存',
cancelText: '取消',
onConfirm: handleConfirmSaveTemplate,
onCancel() {
templateName.value = '';
saveTemplateModalApi.close();
},
});
const importTaskStore = useImportTaskStore();
const canGoToNextStep = computed(() => {
if (currentStep.value === 0) {
const requiredFields = fieldDefs.value.filter((f) => f.required);
return requiredFields.every((field) => {
const mapping = fieldMappings.value[field.fieldName];
return mapping && mapping.mappedHeader;
});
}
return false;
});
const isMappingFromTemplate = (fieldDefId: string): boolean => {
if (!selectedTemplateId.value || currentTemplateMappings.value.length === 0) return false;
const fieldDef = fieldDefs.value.find((f) => f.fieldName === fieldDefId);
if (!fieldDef) return false;
const templateItem = currentTemplateMappings.value.find(
(item) => item.fieldName === fieldDef.fieldName,
);
if (!templateItem) return false;
const currentMapping = fieldMappings.value[fieldDef.fieldName];
return currentMapping?.mappedHeader === templateItem.fileFieldName;
};
const isMappingChangedFromTemplate = (fieldDefId: string): boolean => {
if (!selectedTemplateId.value || currentTemplateMappings.value.length === 0) return false;
const fieldDef = fieldDefs.value.find((f) => f.fieldName === fieldDefId);
if (!fieldDef) return false;
const templateItem = currentTemplateMappings.value.find(
(item) => item.fieldName === fieldDef.fieldName,
);
if (!templateItem) return false;
const currentMapping = fieldMappings.value[fieldDef.fieldName];
if (templateItem.fileFieldName && currentMapping?.mappedHeader !== templateItem.fileFieldName) return true;
return false;
};
const initFieldMappings = () => {
const mappings: typeof fieldMappings.value = {};
fieldDefs.value.forEach((fieldDef) => {
let mappedHeader: string | undefined;
if (fieldDef.fileFieldName) {
const matched = csvHeaders.value.find((h) => h === fieldDef.fileFieldName);
if (matched) mappedHeader = matched;
}
mappings[fieldDef.fieldName] = { fieldDef, mappedHeader };
});
fieldMappings.value = mappings;
};
const fetchShopList = async (reset = false) => {
if (shopLoading.value) return;
try {
shopLoading.value = true;
if (reset) {
shopList.value = [];
shopPage.value = 1;
shopHasMore.value = true;
}
const result = await getShopPageApi({
page: shopPage.value,
pageSize: shopPageSize.value,
filters: { name: shopSearchValue.value || undefined },
});
if (reset) {
shopList.value = result.records || [];
} else {
shopList.value.push(...(result.records || []));
}
shopHasMore.value = (result.records?.length || 0) === shopPageSize.value;
if (shopHasMore.value) shopPage.value++;
} catch (error) {
console.error('获取店铺列表失败:', error);
message.error('获取店铺列表失败');
} finally {
shopLoading.value = false;
}
};
const handleShopSearch = (value: string) => {
shopSearchValue.value = value;
fetchShopList(true);
};
const handleShopScroll = (e: any) => {
const { target } = e;
if (target.scrollTop + target.offsetHeight === target.scrollHeight && shopHasMore.value && !shopLoading.value) {
fetchShopList();
}
};
const fetchFieldDefs = async () => {
try {
fieldDefsLoading.value = true;
const result = await getAdFeeFieldsApi();
fieldDefs.value = (result || []) as unknown as AdFeeFieldVO.Info[];
initFieldMappings();
} catch (error) {
console.error('获取字段定义失败:', error);
message.error('获取字段定义失败');
} finally {
fieldDefsLoading.value = false;
}
};
const fetchMappingTemplates = async () => {
try {
templateLoading.value = true;
const result = await getImportMappingPageApi({
page: 1,
pageSize: 100,
filters: { type: ImportMappingType.PROMOTION_FEE },
});
mappingTemplates.value = result.records || [];
if (mappingTemplates.value.length > 0 && !selectedTemplateId.value) {
const firstTemplate = mappingTemplates.value[0];
if (firstTemplate?.id) {
selectedTemplateId.value = firstTemplate.id;
await handleSelectTemplate(firstTemplate.id);
}
}
} catch (error) {
console.error('获取映射模板列表失败:', error);
message.error('获取映射模板列表失败');
} finally {
templateLoading.value = false;
}
};
const handleSelectTemplate = async (value: any) => {
const templateId = typeof value === 'number' ? value : undefined;
if (!templateId) {
selectedTemplateName.value = '';
currentTemplateMappings.value = [];
if (fieldDefs.value.length > 0) initFieldMappings();
return;
}
if (fieldDefs.value.length === 0) return;
const template = mappingTemplates.value.find((t) => t.id === templateId);
if (!template) return;
try {
const mappingItems: FieldMappingItem[] = JSON.parse(template.mapping);
selectedTemplateName.value = template.name;
currentTemplateMappings.value = mappingItems;
const mappings: typeof fieldMappings.value = {};
fieldDefs.value.forEach((fieldDef) => {
const templateItem = mappingItems.find((item) => item.fieldName === fieldDef.fieldName);
let mappedHeader: string | undefined;
if (templateItem?.fileFieldName) {
const matched = csvHeaders.value.find((h) => h === templateItem.fileFieldName);
if (matched) mappedHeader = matched;
}
mappings[fieldDef.fieldName] = { fieldDef, mappedHeader };
});
fieldMappings.value = mappings;
message.success('已应用映射模板');
} catch (error) {
console.error('应用映射模板失败:', error);
message.error('应用映射模板失败,模板格式可能不正确');
}
};
const handleAddFieldToTemplate = async (fieldDefId: string) => {
if (!selectedTemplateId.value) {
message.warning('请先选择一个模板');
return;
}
const mapping = fieldMappings.value[fieldDefId];
if (!mapping || !mapping.mappedHeader) {
message.warning('请先完成该字段的映射');
return;
}
const fieldDef = mapping.fieldDef;
const fieldItem: FieldMappingItem = {
fieldName: fieldDef.fieldName,
fieldLabel: fieldDef.fieldLabel,
fileFieldName: mapping.mappedHeader,
required: fieldDef.required,
};
try {
savingFieldToTemplate.value = fieldDefId;
const template = mappingTemplates.value.find((t) => t.id === selectedTemplateId.value);
if (!template) {
message.error('模板不存在');
return;
}
let mappingItems: FieldMappingItem[] = [];
try {
mappingItems = JSON.parse(template.mapping);
} catch {
mappingItems = [];
}
const existingIdx = mappingItems.findIndex((item) => item.fieldName === fieldDef.fieldName);
if (existingIdx === -1) {
mappingItems.push(fieldItem);
} else {
mappingItems[existingIdx] = fieldItem;
}
const mappingJson = JSON.stringify(mappingItems);
await updateImportMappingApi(selectedTemplateId.value, {
name: template.name,
mapping: mappingJson,
});
template.mapping = mappingJson;
currentTemplateMappings.value = mappingItems;
message.success(`已将「${fieldDef.fieldLabel}」映射添加到模板`);
} catch (error: any) {
console.error('添加到模板失败:', error);
message.error(error?.message || '添加到模板失败');
} finally {
savingFieldToTemplate.value = null;
}
};
const handleSaveTemplate = () => {
if (selectedTemplateId.value) {
message.info('已有模板选中,请使用每行「添加到模板」按钮单独更新字段映射');
return;
}
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
.filter((m) => m.mappedHeader)
.map((m) => ({
fieldName: m.fieldDef.fieldName,
fieldLabel: m.fieldDef.fieldLabel,
fileFieldName: m.mappedHeader,
required: m.fieldDef.required,
}));
if (mappingItems.length === 0) {
message.warning('请先完成字段映射');
return;
}
templateName.value = '';
saveTemplateModalApi.open();
};
async function handleConfirmSaveTemplate() {
if (!templateName.value.trim()) {
message.warning('请输入模板名称');
return;
}
const requiredFields = fieldDefs.value.filter((f) => f.required);
const unMappedFields = requiredFields.filter((field) => {
const mapping = fieldMappings.value[field.fieldName];
return !mapping || !mapping.mappedHeader;
});
if (unMappedFields.length > 0) {
message.warning(`请先绑定所有必填字段:${unMappedFields.map((f) => f.fieldLabel).join('、')}`);
return;
}
try {
savingTemplate.value = true;
saveTemplateModalApi.lock();
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
.filter((m) => m.mappedHeader)
.map((m) => ({
fieldName: m.fieldDef.fieldName,
fieldLabel: m.fieldDef.fieldLabel,
fileFieldName: m.mappedHeader,
required: m.fieldDef.required,
}));
await createImportMappingApi({
type: ImportMappingType.PROMOTION_FEE,
name: templateName.value.trim(),
mapping: JSON.stringify(mappingItems),
});
message.success('保存映射模板成功');
templateName.value = '';
saveTemplateModalApi.close();
await fetchMappingTemplates();
} catch (error: any) {
console.error('保存映射模板失败:', error);
message.error(error?.message || '保存映射模板失败');
} finally {
savingTemplate.value = false;
saveTemplateModalApi.unlock();
}
}
const handleNext = async () => {
if (currentStep.value !== 0) return;
const requiredFields = fieldDefs.value.filter((f) => f.required);
const unMappedFields = requiredFields.filter((field) => {
const mapping = fieldMappings.value[field.fieldName];
return !mapping || !mapping.mappedHeader;
});
if (unMappedFields.length > 0) {
message.warning(`请先绑定必填字段:${unMappedFields.map((f) => f.fieldLabel).join('、')}`);
return;
}
if (shopList.value.length === 0) {
shopSearchValue.value = '';
shopPage.value = 1;
shopHasMore.value = true;
await fetchShopList(true);
}
currentStep.value = 1;
};
const handlePrev = () => {
if (currentStep.value > 0) currentStep.value--;
};
const buildPatchedCsv = (): File => {
const headers = [...csvHeaders.value, 'productId'];
const rows = previewData.value.map((row: any) =>
headers.map((h: string) => {
if (h === 'productId') return row._productId ?? '';
return row[h] ?? '';
}),
);
const csvContent = `\uFEFF${[
headers.join(','),
...rows.map((r: any[]) => r.map((v: any) => `"${String(v).replace(/"/g, '""')}"`).join(',')),
].join('\n')}`;
return new File([csvContent], buildPatchedFileName(originalImportFile.value?.name || 'data.csv'), {
type: 'text/csv;charset=utf-8',
});
};
const buildPatchedFileName = (_original: string): string => {
return 'ad_fee_import_patched.csv';
};
const handleCreateTask = async () => {
if (!selectedFile.value && !originalImportFile.value) {
message.error('文件信息丢失,请重新上传');
return;
}
if (selectedShopId.value === undefined) {
message.warning('请选择店铺');
return;
}
if (!feeDate.value) {
message.warning('请选择广告费发生日期');
return;
}
try {
createTaskSubmitting.value = true;
message.loading('正在上传文件...', 0);
const patchedFile = buildPatchedCsv();
const fileInfo = await uploadFile(patchedFile, {
category: FileCategory.FILE,
errorMessage: '文件上传失败,请重试',
});
message.destroy();
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
.filter((m) => m.mappedHeader)
.map((m) => ({
fieldName: m.fieldDef.fieldName,
fieldLabel: m.fieldDef.fieldLabel,
fileFieldName: m.mappedHeader,
required: m.fieldDef.required,
}));
const fullMapping = {
fieldMapping: mappingItems,
feeDate: dayjs(feeDate.value).format('YYYY-MM-DD'),
};
const createData: ImportTaskDTO.CreateImportTaskDTO = {
shopId: selectedShopId.value!,
type: 'promotion_record',
fileName: patchedFile.name,
fileId: fileInfo.id,
mapping: JSON.stringify(fullMapping),
};
const task = await createImportTaskApi(createData);
message.success('创建导入任务成功');
importTaskStore.updateTask(task);
await importTaskStore.fetchTasks(true);
importTaskStore.openDropdown();
currentStep.value = 0;
selectedShopId.value = undefined;
feeDate.value = undefined;
fieldMappings.value = {};
csvHeaders.value = [];
previewData.value = [];
selectedFile.value = null;
originalImportFile.value = null;
selectedTemplateId.value = undefined;
emit('success');
} catch (error: any) {
message.destroy();
console.error('创建导入任务失败:', error);
message.error(error?.message || '创建导入任务失败');
} finally {
createTaskSubmitting.value = false;
}
};
async function open(headers: string[], file?: File) {
csvHeaders.value = headers;
originalImportFile.value = file ?? null;
selectedFile.value = file ?? null;
currentStep.value = 0;
fieldMappings.value = {};
if (shopList.value.length === 0) {
shopSearchValue.value = '';
shopPage.value = 1;
shopHasMore.value = true;
void fetchShopList(true);
}
if (fieldDefs.value.length === 0) {
await fetchFieldDefs();
} else {
initFieldMappings();
}
if (mappingTemplates.value.length === 0) {
await fetchMappingTemplates();
} else if (selectedTemplateId.value) {
await handleSelectTemplate(selectedTemplateId.value);
} else {
const firstTemplate = mappingTemplates.value[0];
if (firstTemplate?.id) {
selectedTemplateId.value = firstTemplate.id;
await handleSelectTemplate(firstTemplate.id);
}
}
}
function reset() {
currentStep.value = 0;
selectedShopId.value = undefined;
feeDate.value = undefined;
fieldMappings.value = {};
csvHeaders.value = [];
previewData.value = [];
selectedFile.value = null;
originalImportFile.value = null;
selectedTemplateId.value = undefined;
}
defineExpose({ open, reset });
const shopOptions = computed(() => {
return shopList.value.map((shop: ShopVO.Info) => ({
label: shop.platformName ? `${shop.name} (${shop.platformName})` : shop.name,
value: shop.id,
}));
});
</script>
<template>
<div
class="import-task-wizard flex h-full min-h-0 w-full flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<div class="shrink-0 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]">
<div class="text-base font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
创建导入任务
</div>
<p
v-if="selectedFile"
class="mb-0 mt-1 truncate text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
{{ selectedFile.name }} · {{ previewData.length }} 条
</p>
</div>
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
<div
class="import-task-wizard-main grid min-h-0 min-w-0 w-full flex-1 grid-rows-[auto_minmax(0,1fr)] gap-3 overflow-hidden px-3 py-3"
>
<div class="min-w-0 shrink-0">
<Steps :current="currentStep">
<Steps.Step title="字段映射" />
<Steps.Step title="确认信息" />
</Steps>
</div>
<div class="flex h-full min-h-0 min-w-0 flex-col overflow-hidden">
<div
v-if="currentStep === 0"
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden py-2"
>
<div class="mb-3 flex shrink-0 flex-wrap items-center justify-between gap-2 gap-y-3">
<div class="text-sm text-gray-600 dark:text-gray-300">
请为每个广告费字段选择对应的CSV列,必填字段必须绑定
</div>
<div class="flex items-center space-x-2">
<Select
v-model:value="selectedTemplateId"
placeholder="选择已有模板"
class="w-[200px]"
:loading="templateLoading"
allow-clear
@change="handleSelectTemplate"
>
<template #notFoundContent>
<div v-if="templateLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400 dark:text-gray-500">
暂无模板
</div>
</template>
<Select.Option
v-for="template in mappingTemplates"
:key="template.id"
:value="template.id"
>
{{ template.name }}
<span class="ml-2 text-xs text-gray-400 dark:text-gray-500">
({{ new Date(template.createTime).toLocaleDateString() }})
</span>
</Select.Option>
</Select>
<PermissionGate code="data:import-mapping:create">
<Button
:disabled="selectedTemplateId !== undefined"
@click="handleSaveTemplate"
>
保存为模板
</Button>
</PermissionGate>
</div>
</div>
<template v-if="fieldDefsLoading">
<div class="flex min-h-[200px] flex-1 items-center justify-center text-gray-500 dark:text-gray-400">
<Spin size="large" />
<span class="ml-3 text-sm">加载字段定义中…</span>
</div>
</template>
<div
v-else
class="min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-y-contain pr-0.5"
>
<div
v-for="fieldDef in fieldDefs"
:key="fieldDef.fieldName"
class="flex min-w-0 flex-col overflow-hidden rounded-lg border p-0"
:class="
fieldDef.required && !fieldMappings[fieldDef.fieldName]?.mappedHeader
? 'border-red-300 dark:border-red-700'
: isMappingChangedFromTemplate(fieldDef.fieldName)
? 'border-yellow-200 dark:border-yellow-700'
: isMappingFromTemplate(fieldDef.fieldName)
? 'border-blue-200 dark:border-blue-700'
: 'border-slate-200 dark:border-slate-600'
"
>
<div
class="border-b border-slate-200/90 bg-gradient-to-r to-transparent px-3 py-2.5 dark:border-slate-600"
:class="
fieldDef.required && !fieldMappings[fieldDef.fieldName]?.mappedHeader
? 'from-red-50/90 dark:from-red-950/35'
: isMappingChangedFromTemplate(fieldDef.fieldName)
? 'from-amber-50/75 dark:from-amber-950/30'
: isMappingFromTemplate(fieldDef.fieldName)
? 'from-blue-50/90 dark:from-blue-950/40'
: 'from-blue-50/95 dark:from-blue-950/35'
"
>
<div class="mb-2 flex flex-wrap items-center gap-2">
<span
class="shrink-0 rounded bg-blue-600 px-2 py-0.5 text-[11px] font-semibold text-white shadow-sm dark:bg-blue-500"
>
系统
</span>
<span class="text-xs font-medium text-slate-600 dark:text-slate-300">
广告费字段
</span>
</div>
<div class="flex flex-wrap items-center gap-x-2 gap-y-1">
<span class="font-medium leading-snug text-slate-900 dark:text-slate-100">
{{ fieldDef.fieldLabel }}
</span>
<span v-if="fieldDef.required" class="text-xs text-red-500 dark:text-red-400">
必填
</span>
<span
v-if="selectedTemplateId && isMappingFromTemplate(fieldDef.fieldName)"
class="rounded bg-blue-100 px-1.5 py-0.5 text-xs text-blue-700 dark:bg-blue-900/50 dark:text-blue-300"
>
模板映射
</span>
<span
v-if="selectedTemplateId && isMappingChangedFromTemplate(fieldDef.fieldName)"
class="rounded bg-amber-100 px-1.5 py-0.5 text-xs text-amber-800 dark:bg-amber-900/40 dark:text-amber-200"
>
已变更
</span>
</div>
</div>
<div
class="bg-gradient-to-r from-amber-50/90 to-transparent px-3 py-2.5 dark:from-amber-950/25"
>
<div class="mb-2 flex flex-wrap items-center gap-2">
<span
class="shrink-0 rounded bg-amber-600 px-2 py-0.5 text-[11px] font-semibold text-white shadow-sm dark:bg-amber-600"
>
文件
</span>
<span class="text-xs font-medium text-slate-600 dark:text-slate-300">
CSV 列
</span>
</div>
<div class="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:gap-2">
<Select
v-if="fieldMappings[fieldDef.fieldName]"
v-model:value="fieldMappings[fieldDef.fieldName]!.mappedHeader"
placeholder="选择该字段对应的 CSV 列"
class="w-full min-w-0 sm:flex-1"
show-search
allow-clear
:options="csvHeaders.map((h) => ({ label: h, value: h }))"
/>
<Button
v-if="selectedTemplateId && fieldMappings[fieldDef.fieldName]?.mappedHeader"
size="small"
type="link"
class="h-auto shrink-0 self-start px-0 py-0 sm:self-center"
:disabled="isMappingFromTemplate(fieldDef.fieldName)"
:loading="savingFieldToTemplate === fieldDef.fieldName"
@click="handleAddFieldToTemplate(fieldDef.fieldName)"
>
添加到模板
</Button>
</div>
</div>
</div>
</div>
</div>
<div
v-if="currentStep === 1"
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto py-2"
>
<div class="space-y-4">
<Form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
<Form.Item label="选择店铺" required>
<Select
v-model:value="selectedShopId"
placeholder="请选择店铺"
show-search
:filter-option="false"
:loading="shopLoading"
@search="handleShopSearch"
@popup-scroll="handleShopScroll"
>
<template #notFoundContent>
<div v-if="shopLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400 dark:text-gray-500">
暂无数据
</div>
</template>
<Select.Option
v-for="option in shopOptions"
:key="option.value"
:value="option.value"
:label="option.label"
>
{{ option.label }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="发生日期" required>
<DatePicker
v-model:value="feeDate"
placeholder="选择广告费发生日期"
style="width: 100%"
/>
</Form.Item>
</Form>
<div class="rounded bg-gray-50 p-4 dark:bg-gray-800">
<div class="mb-2 font-medium">字段映射</div>
<div class="space-y-2">
<div
v-for="mapping in Object.values(fieldMappings).filter((m) => m.mappedHeader)"
:key="mapping.fieldDef.fieldName"
class="flex justify-between text-sm"
>
<span class="text-gray-600 dark:text-gray-300">{{ mapping.fieldDef.fieldLabel }}:</span>
<span class="font-medium">{{ mapping.mappedHeader }}</span>
</div>
</div>
</div>
<div class="rounded bg-gray-50 p-4 dark:bg-gray-800">
<div class="mb-2 font-medium">导入配置摘要</div>
<div class="space-y-2">
<div class="flex justify-between text-sm">
<span class="text-gray-600 dark:text-gray-300">数据行数</span>
<span class="font-medium">{{ previewData.length }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-gray-600 dark:text-gray-300">已映射字段</span>
<span class="font-medium">{{ Object.values(fieldMappings).filter((m) => m.mappedHeader).length }}/{{ fieldDefs.length }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-gray-600 dark:text-gray-300">商品</span>
<span class="font-medium text-green-600">表格中逐行设置</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="flex shrink-0 flex-wrap justify-end gap-2 border-t border-slate-100 bg-slate-50/80 px-3 py-3 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/40%)]"
>
<Button v-if="currentStep > 0" @click="handlePrev">上一步</Button>
<Button
v-if="currentStep < 1"
type="primary"
:disabled="!canGoToNextStep"
@click="handleNext"
>
下一步
</Button>
<PermissionGate code="data:import:create">
<Button
v-if="currentStep === 1"
type="primary"
:loading="createTaskSubmitting"
@click="handleCreateTask"
>
创建导入任务
</Button>
</PermissionGate>
</div>
</div>
<SaveTemplateModal :confirm-loading="savingTemplate">
<Form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
<Form.Item label="模板名称" required>
<Input
v-model:value="templateName"
placeholder="请输入模板名称"
:maxlength="50"
show-count
@press-enter="handleConfirmSaveTemplate"
/>
</Form.Item>
</Form>
</SaveTemplateModal>
</template>
<style scoped>
.import-task-wizard-main {
min-height: 0;
}
.import-task-wizard-main > :last-child {
min-height: 0;
align-self: stretch;
}
</style>
@@ -1,351 +0,0 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import ImportTaskWizard from './components/ImportTaskWizard.vue';
import FileUploadArea from './components/FileUploadArea.vue';
import { parseFileToRawData } from '#/views/ec/import/order/utils/fileParser';
import { getProductPageApi } from '#/api/ec/product/apis';
import type { ProductVO } from '#/api/ec/product/types';
defineOptions({ name: 'AdFeeImport' });
const csvData = ref<any[]>([]);
const csvHeaders = ref<string[]>([]);
const importLoading = ref(false);
const currentFile = ref<File | null>(null);
const tableContainerRef = ref<HTMLElement>();
const tableHeight = ref<number>(600);
const importTaskWizardRef = ref<InstanceType<typeof ImportTaskWizard>>();
const productList = ref<ProductVO.Info[]>([]);
const loadReferenceData = async () => {
try {
const productRes = await getProductPageApi({
page: 1,
pageSize: 9999,
filters: {},
});
productList.value = ((productRes as any).records || []) as ProductVO.Info[];
} catch (e) {
console.error('加载参考数据失败', e);
}
};
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 },
];
csvHeaders.value.forEach((header) => {
columns.push({
field: header,
title: header,
minWidth: 150,
showOverflow: 'tooltip' as const,
});
});
columns.push({
field: '_productId',
title: '商品',
width: 180,
fixed: 'right' as const,
cellRender: {
name: 'CellSelect',
props: {
options: productList.value.map((p) => ({
label: `${p.name}${p.productCode ? ` (${p.productCode})` : ''}`,
value: p.id,
})),
allowClear: true,
placeholder: '请选择商品',
showSearch: true,
filterOption: (input: string, option: any) =>
option.label.toLowerCase().includes(input.toLowerCase()),
},
},
});
return columns;
});
const gridOptions: VxeGridProps<any> = {
columns: [],
height: tableHeight.value,
border: true,
stripe: true,
rowConfig: { isHover: true, height: 44 },
showOverflow: true,
size: 'small',
data: [],
pagerConfig: {
enabled: true,
pageSize: 50,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }) => {
if (csvData.value.length === 0) {
return { items: [], total: 0 };
}
const currentPage = page.currentPage || 1;
const pageSize = page.pageSize || 50;
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
const pageData = csvData.value.slice(startIndex, endIndex);
pageData.forEach((row, i) => {
(row as Record<string, unknown>).__srcRowIndex = startIndex + i;
});
return {
items: pageData,
total: csvData.value.length,
};
},
},
},
};
const gridEvents = {};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
gridEvents,
});
const updateTable = () => {
gridApi.setGridOptions({
columns: gridColumns.value,
height: tableHeight.value,
});
gridApi.reload();
};
const syncWizardOpen = () => {
if (csvData.value.length === 0 || csvHeaders.value.length === 0) return;
nextTick(() => {
importTaskWizardRef.value?.open(
[...csvHeaders.value],
currentFile.value ?? undefined,
);
});
};
const handleFileUpload = async (file: File) => {
importLoading.value = true;
try {
const result = await parseFileToRawData(file, { preserveEmptyRows: true });
if (result.errors.length > 0) {
message.warning(result.errors.join('; '));
}
if (result.data.length === 0) {
message.error('文件没有有效数据');
return;
}
csvData.value = result.data;
csvHeaders.value = result.headers;
currentFile.value = file;
updateTable();
nextTick(() => {
calculateTableHeight();
});
syncWizardOpen();
const fileExt = file.name.toLowerCase().split('.').pop() || '';
const format = ['xlsx', 'xls'].includes(fileExt) ? 'Excel' : 'CSV';
message.success(`成功解析 ${result.data.length} 条数据(${format} 格式)`);
// 加载参考数据用于表格行内下拉选择
await loadReferenceData();
updateTable();
} catch (error: any) {
message.error(`文件读取失败: ${error.message}`);
} finally {
importLoading.value = false;
}
};
const handleClearData = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
importTaskWizardRef.value?.reset();
updateTable();
message.success('已清空数据');
};
const handleWizardSuccess = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
importTaskWizardRef.value?.reset();
updateTable();
message.success('已创建导入任务,可继续上传新文件');
};
const calculateTableHeight = () => {
nextTick(() => {
if (tableContainerRef.value) {
const rect = tableContainerRef.value.getBoundingClientRect();
const toolbarReserve = 56;
const padding = 24;
const availableHeight = rect.height - padding - toolbarReserve;
tableHeight.value = Math.max(320, availableHeight);
}
});
};
let resizeObserver: null | ResizeObserver = null;
onMounted(() => {
calculateTableHeight();
if (tableContainerRef.value) {
resizeObserver = new ResizeObserver(() => {
calculateTableHeight();
});
resizeObserver.observe(tableContainerRef.value);
}
});
onUnmounted(() => {
resizeObserver?.disconnect();
});
</script>
<template>
<Page
auto-content-height
:content-padding-class="csvData.length === 0 ? 'p-4 sm:p-6' : 'p-2 sm:p-3'"
content-class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-slate-100 dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<div
v-if="csvData.length === 0"
class="mx-auto flex min-h-0 w-full max-w-3xl flex-1 flex-col items-center justify-center py-8"
>
<div class="mb-10 shrink-0 text-center">
<h1
class="mb-2 text-3xl font-black tracking-tight text-slate-800 dark:text-[hsl(0deg_0%_95%)] sm:text-4xl"
>
广告费导入中心
</h1>
<p
class="text-sm font-medium text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-base"
>
请上传 CSV / Excel 格式的广告费原始数据
</p>
</div>
<div
class="relative w-full overflow-hidden rounded-[2rem] border border-white/50 bg-white/45 p-6 dark:border-[hsl(240deg_3.7%_22%/50%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/80%)] shadow-[0_25px_50px_-12px_rgba(0,0,0,0.1)] dark:shadow-none backdrop-blur-2xl sm:p-8"
>
<div
class="absolute -right-10 -top-10 h-32 w-32 rounded-full bg-indigo-400 opacity-10 blur-3xl"
>
</div>
<div class="relative w-full">
<FileUploadArea
:loading="importLoading"
@file-selected="handleFileUpload"
/>
</div>
</div>
</div>
<div
v-else
class="flex min-h-0 w-full min-w-0 flex-1 flex-row gap-3 overflow-hidden sm:gap-4"
>
<section
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white/90 shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/90%)]"
>
<div
class="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]"
>
<div class="min-w-0">
<h2
class="mb-0.5 text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
>
数据预览
</h2>
<p
class="m-0 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-sm"
>
共 {{ csvData.length }} 条 · 右侧配置导入任务
</p>
</div>
<div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
<Button size="small" @click="handleClearData">清空数据</Button>
</div>
</div>
<div
ref="tableContainerRef"
class="flex min-h-0 flex-1 flex-col overflow-hidden p-3 sm:p-4"
>
<Grid />
</div>
</section>
<aside
class="flex min-h-0 w-[min(100%,440px)] shrink-0 flex-col self-stretch overflow-hidden sm:w-[400px] lg:w-[440px]"
>
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
<ImportTaskWizard
ref="importTaskWizardRef"
v-model:preview-data="csvData"
@success="handleWizardSuccess"
/>
</div>
</aside>
</div>
</Page>
</template>
<style scoped>
:deep(.vxe-grid) {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
:deep(.vxe-grid--body-wrapper) {
flex: 1;
overflow: auto;
}
</style>
@@ -1,172 +0,0 @@
<script setup lang="ts">
import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { message, Spin } from 'ant-design-vue';
defineOptions({ name: 'FileUploadArea' });
const props = withDefaults(
defineProps<{
loading?: boolean;
}>(),
{
loading: false,
},
);
const emit = defineEmits<Emits>();
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload');
const LoaderIcon = createIconifyIcon('lucide:loader-2');
// Emits
interface Emits {
(e: 'fileSelected', file: File): void;
}
// 响应式数据
const isDragOver = ref(false);
const fileInputRef = ref<HTMLInputElement>();
// 文件验证
const validateFile = (file: File): boolean => {
const ext = file.name.toLowerCase().split('.').pop() || '';
const allowedExts = ['csv', 'xlsx', 'xls'];
if (!allowedExts.includes(ext)) {
message.error('只能上传 CSV 或 Excel 格式的文件!');
return false;
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('文件大小不能超过10MB!');
return false;
}
return true;
};
// 处理文件
const processFile = (file: File) => {
if (props.loading) return;
if (!validateFile(file)) return;
emit('fileSelected', file);
};
// 拖拽处理
const handleDragOver = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = true;
};
const handleDragLeave = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
};
const handleDrop = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
const files = e.dataTransfer?.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
};
// 文件选择处理
const triggerFileInput = () => {
fileInputRef.value?.click();
};
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement;
const files = target.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
// 清空input值,允许重复选择同一文件
target.value = '';
};
</script>
<template>
<Spin :spinning="loading" tip="正在解析文件...">
<div
class="rounded-lg border-2 border-dashed border-gray-300 dark:border-[hsl(240deg_3.7%_22%)] p-8 text-center transition-colors cursor-pointer"
:class="{
'border-blue-500 bg-blue-50 dark:bg-[hsl(240deg_3.7%_15.9%/20%)]': isDragOver && !loading,
'cursor-not-allowed opacity-60': loading,
}"
@dragover.prevent="!loading && handleDragOver($event)"
@dragleave.prevent="!loading && handleDragLeave($event)"
@drop.prevent="!loading && handleDrop($event)"
@click="!loading && triggerFileInput()"
>
<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 dark:text-[hsl(240deg_5%_64.9%)]"
: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 dark:text-[hsl(240deg_5%_64.9%)]' : 'text-gray-700 dark:text-[hsl(0deg_0%_95%)]'"
>
{{
loading
? '正在解析文件,请稍候...'
: '拖拽 CSV 或 Excel 文件到此处或点击上传'
}}
</p>
<p v-if="!loading" class="text-sm text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]">
支持 .csv / .xlsx / .xls 格式,最大 10MB
</p>
</div>
</div>
<input
ref="fileInputRef"
type="file"
accept=".csv,.xlsx,.xls"
style="display: none"
:disabled="loading"
@change="handleFileSelect"
/>
</div>
</Spin>
</template>
<style scoped>
/* 拖拽区域样式 */
.border-dashed {
transition: all 0.3s ease;
}
.border-dashed:hover {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
:deep(.border-dashed:hover) {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
html.dark .border-dashed:hover {
border-color: hsl(240deg 3.7% 40%) !important;
background-color: hsl(240deg 3.7% 15.9% / 15%) !important;
}
</style>
File diff suppressed because it is too large Load Diff
@@ -1,518 +0,0 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { Page } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import ImportTaskWizard from './components/ImportTaskWizard.vue';
import FileUploadArea from './components/FileUploadArea.vue';
import { parseFileToRawData } from './utils/fileParser';
defineOptions({ name: 'DataImport' });
// 响应式数据
const csvData = ref<any[]>([]);
const csvHeaders = ref<string[]>([]);
const importLoading = ref(false);
const currentFile = ref<File | null>(null);
const tableContainerRef = ref<HTMLElement>();
const tableHeight = ref<number>(600);
const importTaskWizardRef = ref<InstanceType<typeof ImportTaskWizard>>();
/** 与向导中「SKU 编码」字段映射绑定的 CSV 表头,用于左侧表格该列可编辑 */
const skuCodeCsvHeader = ref<string | undefined>();
const skuMissingCount = ref(0);
/** SKU 编码为空的行在 csvData 中的全局下标(0-based) */
const skuMissingRowIndices = ref<Set<number>>(new Set());
/** 与表格分页条 pageSize 同步,用于计算空缺所在页 */
const tablePageSize = ref(50);
/** 「下一处空缺」循环游标,-1 表示尚未开始循环 */
const missingCycleCursor = ref(-1);
// 动态生成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,
},
];
csvHeaders.value.forEach((header) => {
const isSkuCol =
!!skuCodeCsvHeader.value && header === skuCodeCsvHeader.value;
columns.push({
field: header,
title: header,
minWidth: isSkuCol ? 180 : 150,
showOverflow: 'tooltip' as const,
...(isSkuCol ? { editRender: { name: 'input' as const } } : {}),
});
});
return columns;
});
const gridOptions: VxeGridProps<any> = {
columns: [],
height: tableHeight.value,
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
data: [],
editConfig: {
mode: 'cell',
trigger: 'click',
},
pagerConfig: {
enabled: true,
pageSize: 50,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }) => {
if (csvData.value.length === 0) {
return {
items: [],
total: 0,
};
}
const currentPage = page.currentPage || 1;
const pageSize = page.pageSize || 50;
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
const pageData = csvData.value.slice(startIndex, endIndex);
// 供 rowClassName 识别全局行号(与 csvData 下标一致)
pageData.forEach((row, i) => {
(row as Record<string, unknown>).__srcRowIndex = startIndex + i;
});
return {
items: pageData,
total: csvData.value.length,
};
},
},
},
};
const debouncedWizardSpecSync = useDebounceFn(() => {
importTaskWizardRef.value?.onPreviewSpecCodeCellSaved?.();
}, 400);
function rowClassNameForSpecMissing(params: { row?: Record<string, unknown> }) {
const idx = params.row?.__srcRowIndex;
if (typeof idx !== 'number') return '';
return skuMissingRowIndices.value.has(idx) ? 'order-import-row--sku-missing' : '';
}
const gridEvents = {
editClosed(params: { column?: { field?: string } }) {
const field = params.column?.field;
if (!field || !skuCodeCsvHeader.value) return;
if (field === skuCodeCsvHeader.value) {
debouncedWizardSpecSync();
}
},
pageChange(params: { pageSize?: number; currentPage?: number }) {
if (params.pageSize && params.pageSize > 0) {
tablePageSize.value = params.pageSize;
}
},
};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
gridEvents,
});
const updateTable = () => {
gridApi.setGridOptions({
columns: gridColumns.value,
height: tableHeight.value,
rowClassName: rowClassNameForSpecMissing,
});
gridApi.reload();
};
watch(
tableHeight,
(newHeight) => {
gridApi.setGridOptions({
height: newHeight,
});
},
{ immediate: false },
);
const syncWizardOpen = () => {
if (csvData.value.length === 0 || csvHeaders.value.length === 0) {
return;
}
nextTick(() => {
importTaskWizardRef.value?.open(
[...csvHeaders.value],
currentFile.value ?? undefined,
);
});
};
function onSkuCodeColumnChange(header: string | undefined) {
skuCodeCsvHeader.value = header;
updateTable();
}
function onSkuMissingAfterPrecheck(payload: { count: number; indices: number[] }) {
skuMissingCount.value = payload.count;
skuMissingRowIndices.value = new Set(payload.indices);
missingCycleCursor.value = -1;
// 必须用 query 而非 reload:reload 会重置分页到第 1 页,用户在其它页补SKU 编码时会被突然拉回首页
if (csvData.value.length > 0) {
void gridApi.query({});
}
}
/** 取 VxeGrid 内部的 VxeTable 实例(用于 scrollToRow 等仅表格支持的方法) */
function getVxeInnerTable(grid: any) {
return grid?.$refs?.refTable ?? grid?.$refs?.xTable ?? null;
}
/** 等两帧再滚,避免 loadData 后 DOM 尚未稳定 */
function nextPaint() {
return new Promise<void>((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
});
}
/**
* 滚动到指定数据行(scrollToRow 返回 Promise;第二参为列 field 时同时横向滚到「SKU 编码」列)
* 虚拟滚动场景 vxe 内部会延时二次校正,这里再补一次延迟滚动。
*/
async function scrollGridToDataRow(row: Record<string, unknown>) {
const grid = gridApi.grid as any;
const field = skuCodeCsvHeader.value;
const candidates = [grid, getVxeInnerTable(grid)].filter(Boolean);
for (const inst of candidates) {
if (inst && typeof inst.scrollToRow === 'function') {
try {
await inst.scrollToRow(row, field || undefined);
return;
} catch {
// 尝试下一个实例
}
}
}
}
/** 跳转到包含该全局行号的分页并滚动到该行 */
async function goToRowIndex(globalRowIndex: number) {
if (globalRowIndex < 0 || globalRowIndex >= csvData.value.length) return;
const ps = tablePageSize.value;
const targetPage = Math.floor(globalRowIndex / ps) + 1;
const grid = gridApi.grid as any;
if (!grid?.getProxyInfo || typeof grid.commitProxy !== 'function') {
message.warning('表格尚未就绪,请稍后重试');
return;
}
const row = csvData.value[globalRowIndex] as Record<string, unknown> | undefined;
if (!row) return;
try {
const proxy = grid.getProxyInfo();
if (proxy?.pager) {
proxy.pager.currentPage = targetPage;
proxy.pager.pageSize = ps;
}
await grid.commitProxy('query');
await nextTick();
await nextPaint();
await scrollGridToDataRow(row);
// 与 vxe 虚拟列表二次对齐时机接近,避免首屏未滚到位
window.setTimeout(() => {
void scrollGridToDataRow(row);
}, 400);
} catch (e) {
console.error('跳转表格分页失败:', e);
message.warning('跳转分页失败,请手动翻页查找');
}
}
function jumpToFirstSpecMissing() {
const sorted = [...skuMissingRowIndices.value].sort((a, b) => a - b);
if (sorted.length === 0) {
message.info('当前没有空缺的SKU 编码');
return;
}
missingCycleCursor.value = 0;
void goToRowIndex(sorted[0]!);
}
function jumpToNextSpecMissing() {
const sorted = [...skuMissingRowIndices.value].sort((a, b) => a - b);
if (sorted.length === 0) {
message.info('当前没有空缺的SKU 编码');
return;
}
missingCycleCursor.value = (missingCycleCursor.value + 1) % sorted.length;
void goToRowIndex(sorted[missingCycleCursor.value]!);
}
const handleFileUpload = async (file: File) => {
importLoading.value = true;
try {
const result = await parseFileToRawData(file);
if (result.errors.length > 0) {
message.warning(result.errors.join('; '));
}
if (result.data.length === 0) {
message.error('CSV文件没有有效数据');
return;
}
csvData.value = result.data;
csvHeaders.value = result.headers;
currentFile.value = file;
updateTable();
nextTick(() => {
calculateTableHeight();
});
syncWizardOpen();
const fileExt = file.name.toLowerCase().split('.').pop() || '';
const format = ['xlsx', 'xls'].includes(fileExt) ? 'Excel' : 'CSV';
message.success(`成功解析 ${result.data.length} 条数据(${format} 格式)`);
} catch (error: any) {
message.error(`文件读取失败: ${error.message}`);
} finally {
importLoading.value = false;
}
};
const handleClearData = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
skuCodeCsvHeader.value = undefined;
skuMissingCount.value = 0;
skuMissingRowIndices.value = new Set();
missingCycleCursor.value = -1;
importTaskWizardRef.value?.reset();
updateTable();
message.success('已清空数据');
};
const handleWizardSuccess = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
skuCodeCsvHeader.value = undefined;
skuMissingCount.value = 0;
skuMissingRowIndices.value = new Set();
missingCycleCursor.value = -1;
updateTable();
message.success('已创建导入任务,可继续上传新文件');
};
const calculateTableHeight = () => {
nextTick(() => {
if (tableContainerRef.value) {
const rect = tableContainerRef.value.getBoundingClientRect();
const toolbarReserve = 56;
const padding = 24;
const availableHeight = rect.height - padding - toolbarReserve;
tableHeight.value = Math.max(320, availableHeight);
}
});
};
watch(
() => csvData.value.length,
(len) => {
if (len > 0) {
nextTick(() => calculateTableHeight());
}
},
);
let resizeObserver: null | ResizeObserver = null;
onMounted(() => {
calculateTableHeight();
if (tableContainerRef.value) {
resizeObserver = new ResizeObserver(() => {
calculateTableHeight();
});
resizeObserver.observe(tableContainerRef.value);
}
});
onUnmounted(() => {
resizeObserver?.disconnect();
});
</script>
<template>
<Page
auto-content-height
:content-padding-class="csvData.length === 0 ? 'p-4 sm:p-6' : 'p-2 sm:p-3'"
content-class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-slate-100 dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<!-- 未上传:居中上传 -->
<div
v-if="csvData.length === 0"
class="mx-auto flex min-h-0 w-full max-w-3xl flex-1 flex-col items-center justify-center py-8"
>
<div class="mb-10 shrink-0 text-center">
<h1
class="mb-2 text-3xl font-black tracking-tight text-slate-800 dark:text-[hsl(0deg_0%_95%)] sm:text-4xl"
>
订单导入中心
</h1>
<p class="text-sm font-medium text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-base">
请上传 CSV / Excel 格式的订单原始数据
</p>
</div>
<div
class="relative w-full overflow-hidden rounded-[2rem] border border-white/50 bg-white/45 p-6 dark:border-[hsl(240deg_3.7%_22%/50%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/80%)] shadow-[0_25px_50px_-12px_rgba(0,0,0,0.1)] dark:shadow-none backdrop-blur-2xl sm:p-8"
>
<div
class="absolute -right-10 -top-10 h-32 w-32 rounded-full bg-indigo-400 opacity-10 blur-3xl"
></div>
<div class="relative w-full">
<FileUploadArea
:loading="importLoading"
@file-selected="handleFileUpload"
/>
</div>
</div>
</div>
<!-- 已上传:左表右配置(flex-1 + min-h-0 约束在布局内容高度内,避免撑开外层滚动) -->
<div
v-else
class="flex min-h-0 w-full min-w-0 flex-1 flex-row gap-3 overflow-hidden sm:gap-4"
>
<section
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white/90 shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/90%)]"
>
<div
class="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]"
>
<div class="min-w-0">
<h2 class="mb-0.5 text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
数据预览
</h2>
<p class="m-0 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-sm">
共 {{ csvData.length }} 条 · 右侧配置导入任务
<template v-if="skuMissingCount > 0">
·
<span class="font-medium text-amber-600 dark:text-amber-400">
SKU 编码待补 {{ skuMissingCount }} 行(点击本表对应列表格填写)
</span>
</template>
</p>
</div>
<div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
<template v-if="skuMissingCount > 0">
<Button size="small" type="primary" @click="jumpToFirstSpecMissing">
第一处空缺
</Button>
<Button size="small" @click="jumpToNextSpecMissing">下一处空缺</Button>
</template>
<Button size="small" @click="handleClearData">清空数据</Button>
</div>
</div>
<div
ref="tableContainerRef"
class="flex min-h-0 flex-1 flex-col overflow-hidden p-3 sm:p-4"
>
<Grid />
</div>
</section>
<aside
class="flex min-h-0 w-[min(100%,440px)] shrink-0 flex-col self-stretch overflow-hidden sm:w-[400px] lg:w-[440px]"
>
<!-- 单独一层 flex-1,避免多根子组件时侧栏被内容撑出视口 -->
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
<ImportTaskWizard
ref="importTaskWizardRef"
v-model:preview-data="csvData"
@sku-code-column-change="onSkuCodeColumnChange"
@sku-missing-after-precheck="onSkuMissingAfterPrecheck"
@success="handleWizardSuccess"
/>
</div>
</aside>
</div>
</Page>
</template>
<style scoped>
:deep(.vxe-grid) {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
:deep(.vxe-grid--body-wrapper) {
flex: 1;
overflow: auto;
}
/* SKU 编码为空的行:整行高亮,便于分页中辨认 */
:deep(tr.order-import-row--sku-missing) {
background-color: rgb(254 243 199) !important;
}
:deep(tr.order-import-row--sku-missing:hover) {
background-color: rgb(253 230 138) !important;
}
.dark :deep(tr.order-import-row--sku-missing) {
background-color: rgb(120 53 15 / 0.45) !important;
}
.dark :deep(tr.order-import-row--sku-missing:hover) {
background-color: rgb(120 53 15 / 0.6) !important;
}
</style>
@@ -1,84 +0,0 @@
/**
* CSV数据解析工具
* 完全动态解析,不预设任何字段
*/
import Papa from 'papaparse';
export interface CSVParseResult {
/** 解析成功的数据 */
data: any[];
/** 解析错误 */
errors: string[];
/** 表头(保持CSV文件中的顺序) */
headers: string[];
}
/**
* 解析CSV文件为原始数据(完全动态,保持字段顺序)
*/
export async function parseCSVToRawData(file: File): Promise<CSVParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
// 尝试多种编码格式
const encodings = ['GBK', 'utf8', 'GB2312'];
let result: null | Papa.ParseResult<any> = null;
for (const encoding of encodings) {
try {
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
Papa.parse(file, {
header: true,
skipEmptyLines: true,
encoding: encoding as any,
complete: (results) => {
resolve(results);
},
error: (error) => {
reject(error);
},
});
});
// 检查是否成功解析出中文内容
if (result.data && result.data.length > 0) {
const firstRow = result.data[0];
const hasChineseContent = Object.values(firstRow).some(
(value) => typeof value === 'string' && /[\u4E00-\u9FA5]/.test(value),
);
if (hasChineseContent) {
break;
}
}
} catch {
continue;
}
}
if (!result) {
errors.push('无法解析CSV文件,请检查文件格式和编码');
return { data, errors, headers };
}
if (result.errors.length > 0) {
errors.push(
`CSV解析错误: ${result.errors.map((e) => e.message).join(', ')}`,
);
}
if (!result.data || result.data.length === 0) {
errors.push('CSV文件为空或没有有效数据');
return { data, errors, headers };
}
// 获取表头(保持CSV文件中的顺序)
headers = result.meta.fields || [];
// 直接使用原始数据,完全保持CSV文件的字段顺序和数据顺序
data.push(...result.data);
return { data, errors, headers };
}
@@ -1,214 +0,0 @@
/**
* 文件数据解析工具(支持 CSV 和 Excel)
*/
import Papa from 'papaparse';
import * as XLSX from 'xlsx';
export interface FileParseOptions {
/** 为 true 时保留仅部分单元格为空的行(推广费导入需统计金额为空等失败行) */
preserveEmptyRows?: boolean;
}
export interface FileParseResult {
/** 解析成功的数据 */
data: any[];
/** 解析错误 */
errors: string[];
/** 表头(保持文件中的顺序) */
headers: string[];
}
function isExcelFile(filename: string): boolean {
const ext = filename.toLowerCase().split('.').pop() || '';
return ext === 'xlsx' || ext === 'xls';
}
/**
* 解析 CSV 文件为原始数据
*/
async function parseCSVFile(
file: File,
options?: FileParseOptions,
): Promise<FileParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
// 尝试多种编码格式
const encodings = ['GBK', 'utf8', 'GB2312'];
let result: Papa.ParseResult<any> | null = null;
for (const encoding of encodings) {
try {
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
Papa.parse(file, {
header: true,
skipEmptyLines: options?.preserveEmptyRows ? false : true,
encoding: encoding as any,
complete: (results) => {
resolve(results);
},
error: (error) => {
reject(error);
},
});
});
// 检查是否成功解析出中文内容
if (result.data && result.data.length > 0) {
const firstRow = result.data[0];
const hasChineseContent = Object.values(firstRow).some(
(value) => typeof value === 'string' && /[\u4E00-\u9FA5]/.test(value),
);
if (hasChineseContent) {
break;
}
}
} catch {
continue;
}
}
if (!result) {
errors.push('无法解析 CSV 文件,请检查文件格式和编码');
return { data, errors, headers };
}
if (result.errors.length > 0) {
errors.push(
`CSV 解析错误: ${result.errors.map((e) => e.message).join(', ')}`,
);
}
if (!result.data || result.data.length === 0) {
errors.push('CSV 文件为空或没有有效数据');
return { data, errors, headers };
}
headers = result.meta.fields || [];
data.push(...result.data);
return { data, errors, headers };
}
/**
* 解析 Excel 文件为原始数据
*/
async function parseExcelFile(
file: File,
options?: FileParseOptions,
): Promise<FileParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const arrayBuffer = e.target?.result;
if (!arrayBuffer) {
errors.push('Excel 文件读取失败');
resolve({ data, errors, headers });
return;
}
const workbook = XLSX.read(arrayBuffer, { type: 'array', cellDates: true });
// 默认取第一个 sheet
const sheetName = workbook.SheetNames[0];
if (!sheetName) {
errors.push('Excel 文件中没有工作表');
resolve({ data, errors, headers });
return;
}
const sheet = workbook.Sheets[sheetName];
if (!sheet) {
errors.push('Excel 文件读取失败:未找到有效工作表');
resolve({ data, errors, headers });
return;
}
// 转换为 JSON(header: 1 表示第一行作为表头)
const jsonData = XLSX.utils.sheet_to_json(sheet, {
header: 1,
defval: '',
blankrows: false,
}) as any[][];
if (jsonData.length === 0) {
errors.push('Excel 文件为空或没有有效数据');
resolve({ data, errors, headers });
return;
}
// 第一行是表头
headers = (jsonData[0] || []).map((h) => String(h ?? '').trim());
// 其余行是数据
for (let i = 1; i < jsonData.length; i++) {
const row = jsonData[i];
if (!row) {
continue;
}
if (
!options?.preserveEmptyRows &&
row.every((cell) => cell === '' || cell == null)
) {
continue;
}
const rowData: Record<string, any> = {};
headers.forEach((header, idx) => {
let value = row[idx];
// XLSX 读取日期会返回 Date 对象,转成字符串
if (value instanceof Date) {
const y = value.getFullYear();
const m = String(value.getMonth() + 1).padStart(2, '0');
const d = String(value.getDate()).padStart(2, '0');
value = `${y}-${m}-${d}`;
}
rowData[header] = value != null ? String(value).trim() : '';
});
data.push(rowData);
}
resolve({ data, errors, headers });
} catch (err: any) {
errors.push(`Excel 解析失败: ${err?.message || '未知错误'}`);
resolve({ data, errors, headers });
}
};
reader.onerror = () => {
errors.push('Excel 文件读取失败');
resolve({ data, errors, headers });
};
reader.readAsArrayBuffer(file);
});
}
/**
* 解析文件为原始数据(自动根据扩展名选择解析器)
*/
export async function parseFileToRawData(
file: File,
options?: FileParseOptions,
): Promise<FileParseResult> {
if (isExcelFile(file.name)) {
return parseExcelFile(file, options);
}
return parseCSVFile(file, options);
}
/**
* @deprecated 请使用 parseFileToRawData
*/
export async function parseCSVToRawData(file: File): Promise<FileParseResult> {
return parseCSVFile(file);
}
@@ -1,52 +0,0 @@
import Papa from 'papaparse';
import * as XLSX from 'xlsx';
export function buildPatchedFileName(fileName: string) {
const dot = fileName.lastIndexOf('.');
if (dot < 0) return `${fileName}_patched`;
return `${fileName.slice(0, dot)}_patched${fileName.slice(dot)}`;
}
/**
* 根据 headers + rows 重建一个“补录后”的文件,并返回新的 File 对象
* - CSV:使用 papaparse 重新生成,并添加 BOM 保证中文兼容
* - Excel:使用 xlsx 生成新的 workbook(默认一个 sheet:Sheet1)
*/
export function createPatchedFile(
sourceFile: File,
headers: string[],
rows: any[],
): File {
const ext = sourceFile.name.toLowerCase().split('.').pop() || '';
const filename = buildPatchedFileName(sourceFile.name);
if (ext === 'csv') {
const csvText = Papa.unparse(rows, { columns: headers });
const blob = new Blob([`\uFEFF${csvText}`], {
type: 'text/csv;charset=utf-8',
});
return new File([blob], filename, { type: 'text/csv;charset=utf-8' });
}
const aoa = [
headers,
...rows.map((row) => headers.map((header) => row[header] ?? '')),
];
const workbook = XLSX.utils.book_new();
const worksheet = XLSX.utils.aoa_to_sheet(aoa);
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
const wbType = ext === 'xls' ? 'xls' : 'xlsx';
const buffer = XLSX.write(workbook, {
type: 'array',
bookType: wbType,
});
const blob = new Blob([buffer], {
type:
ext === 'xls'
? 'application/vnd.ms-excel'
: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
return new File([blob], filename, { type: blob.type });
}