mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 13:09:19 +08:00
189 lines
4.2 KiB
TypeScript
189 lines
4.2 KiB
TypeScript
import Papa from 'papaparse';
|
|
|
|
export interface CSVParseResult {
|
|
data: any[];
|
|
headers: string[];
|
|
errors: any[];
|
|
}
|
|
|
|
export interface FieldMapping {
|
|
csvField: string;
|
|
standardField: string;
|
|
customName?: string;
|
|
}
|
|
|
|
export interface ExportData {
|
|
metadata: {
|
|
customFieldNames: Record<string, string>;
|
|
exportTime: string;
|
|
fieldMappings: Record<string, string>;
|
|
shopName?: string;
|
|
source: string;
|
|
totalRecords: number;
|
|
};
|
|
data: any[];
|
|
}
|
|
|
|
/**
|
|
* 解析CSV文件
|
|
*/
|
|
export function parseCSV(file: File): Promise<CSVParseResult> {
|
|
return new Promise((resolve, reject) => {
|
|
Papa.parse(file, {
|
|
header: true,
|
|
skipEmptyLines: true,
|
|
encoding: 'utf8',
|
|
complete: (results) => {
|
|
resolve({
|
|
data: results.data,
|
|
headers: results.meta.fields || [],
|
|
errors: results.errors,
|
|
});
|
|
},
|
|
error: (error) => {
|
|
reject(error);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 根据字段映射转换数据
|
|
*/
|
|
export function transformDataWithMapping(
|
|
csvData: any[],
|
|
fieldMappings: Record<string, string>,
|
|
customFieldNames: Record<string, string> = {},
|
|
): any[] {
|
|
return csvData.map((row) => {
|
|
const transformedRow: any = {};
|
|
|
|
Object.entries(fieldMappings).forEach(([csvField, standardField]) => {
|
|
if (standardField && row[csvField] !== undefined) {
|
|
const fieldName = customFieldNames[csvField] || standardField;
|
|
transformedRow[fieldName] = row[csvField];
|
|
}
|
|
});
|
|
|
|
return transformedRow;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 生成导出数据
|
|
*/
|
|
export function generateExportData(
|
|
transformedData: any[],
|
|
fieldMappings: Record<string, string>,
|
|
customFieldNames: Record<string, string> = {},
|
|
shopName?: string,
|
|
): ExportData {
|
|
return {
|
|
metadata: {
|
|
source: 'CSV导入',
|
|
totalRecords: transformedData.length,
|
|
exportTime: new Date().toISOString(),
|
|
fieldMappings,
|
|
customFieldNames,
|
|
shopName,
|
|
},
|
|
data: transformedData,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 下载JSON文件
|
|
*/
|
|
export function downloadJSON(data: ExportData, filename?: string): void {
|
|
const jsonString = JSON.stringify(data, null, 2);
|
|
const blob = new Blob([jsonString], { type: 'application/json' });
|
|
const url = URL.createObjectURL(blob);
|
|
|
|
const link = document.createElement('a');
|
|
link.href = url;
|
|
link.download = filename || `ecommerce-data-${Date.now()}.json`;
|
|
document.body.append(link);
|
|
link.click();
|
|
link.remove();
|
|
URL.revokeObjectURL(url);
|
|
}
|
|
|
|
/**
|
|
* 从文件名提取店铺名称
|
|
*/
|
|
export function extractShopNameFromFilename(filename: string): string {
|
|
// 移除文件扩展名
|
|
const nameWithoutExt = filename.replace(/\.[^/.]+$/, '');
|
|
return nameWithoutExt;
|
|
}
|
|
|
|
/**
|
|
* 验证CSV数据格式
|
|
*/
|
|
export function validateCSVData(data: any[]): {
|
|
errors: string[];
|
|
isValid: boolean;
|
|
} {
|
|
const errors: string[] = [];
|
|
|
|
if (data.length === 0) {
|
|
errors.push('CSV文件为空');
|
|
}
|
|
|
|
// 检查必要字段
|
|
const requiredFields = [
|
|
'商品',
|
|
'订单号',
|
|
'订单状态',
|
|
'商品数量(件)',
|
|
'商家实收金额(元)',
|
|
];
|
|
const firstRow = data[0];
|
|
|
|
if (firstRow) {
|
|
requiredFields.forEach((field) => {
|
|
if (!(field in firstRow)) {
|
|
errors.push(`缺少必要字段: ${field}`);
|
|
}
|
|
});
|
|
}
|
|
|
|
return {
|
|
isValid: errors.length === 0,
|
|
errors,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 数据清洗和格式化
|
|
*/
|
|
export function cleanAndFormatData(data: any[]): any[] {
|
|
return data.map((row) => {
|
|
const cleanedRow: any = {};
|
|
|
|
Object.entries(row).forEach(([key, value]) => {
|
|
if (value !== null && value !== undefined) {
|
|
// 去除首尾空格
|
|
let cleanedValue = String(value).trim();
|
|
|
|
// 处理数字字段
|
|
if (key.includes('数量') || key.includes('金额')) {
|
|
cleanedValue = cleanedValue.replaceAll(/[^\d.-]/g, '');
|
|
if (cleanedValue && !Number.isNaN(Number(cleanedValue))) {
|
|
cleanedValue = Number(cleanedValue).toString();
|
|
}
|
|
}
|
|
|
|
// 处理日期字段
|
|
if (key.includes('日期') || key.includes('时间')) {
|
|
// 这里可以添加日期格式化逻辑
|
|
}
|
|
|
|
cleanedRow[key] = cleanedValue;
|
|
}
|
|
});
|
|
|
|
return cleanedRow;
|
|
});
|
|
}
|