<script lang="ts" setup>
|
import type { FileType } from 'ant-design-vue/es/upload/interface';
|
|
import { h, ref } from 'vue';
|
|
import { useVbenModal } from '@vben/common-ui';
|
import { downloadFileFromBlobPart } from '@vben/utils';
|
|
import { Button, message, Modal as AntModal, Upload } from 'ant-design-vue';
|
|
import { useVbenForm, z } from '#/adapter/form';
|
import { $t } from '#/locales';
|
|
/**
|
* 导入接口返回结构。
|
*
|
* 后端各模块的导入返回值不统一,这里描述可展示结果中约定明确的字段;
|
* create* / update* / failure* 等业务专用字段会在运行时统一识别。
|
*/
|
export interface ImportResultLike {
|
/** 被跳过的行:key 为 Excel 行号,value 为原因 */
|
skippedRows?: Record<string, string>;
|
/** 被跳过的行数 */
|
skippedCount?: number;
|
/** Excel 中实际有数据的行数 */
|
totalRows?: number;
|
/** 成功导入的行数 */
|
successRows?: number;
|
/** 成功导入的数量 */
|
successCount?: number;
|
/** 导入失败的数量 */
|
failureCount?: number;
|
/** 其它模块的通用字段:失败列表 */
|
failureList?: Record<string, string> | string[];
|
/** 其它模块的通用字段:失败原因 */
|
failureMessages?: Record<string, string> | string[];
|
[key: string]: unknown;
|
}
|
|
export interface ImportModalProps {
|
/** 弹窗标题,如「导入用户」 */
|
title: string;
|
/** 下载的模板文件名,如「用户导入模板.xls」 */
|
fileName: string;
|
/** 执行导入的接口函数 (file, updateSupport) => Promise */
|
importFn: (file: File, updateSupport: boolean) => Promise<unknown>;
|
/** 是否允许覆盖已有数据 */
|
allowUpdate?: boolean;
|
uploadHint?: string;
|
/** 不提供模板下载时隐藏弹窗内的下载按钮。 */
|
showTemplateDownload?: boolean;
|
/** 下载模板的接口函数 () => Promise(blob) */
|
templateFn?: () => Promise<BlobPart>;
|
}
|
|
const emit = defineEmits(['success']);
|
|
const config = ref<ImportModalProps>({
|
title: '',
|
fileName: '',
|
importFn: async () => {},
|
templateFn: () => Promise.resolve(new Blob()),
|
});
|
|
const [Form, formApi] = useVbenForm({
|
commonConfig: {
|
formItemClass: 'col-span-2',
|
labelWidth: 120,
|
},
|
layout: 'horizontal',
|
schema: [
|
{
|
fieldName: 'file',
|
label: '数据文件',
|
component: 'Upload',
|
rules: 'required',
|
help: () => config.value.uploadHint || '仅允许导入 xls、xlsx 格式文件',
|
},
|
{
|
fieldName: 'updateSupport',
|
dependencies: { triggerFields: ['file'], show: () => config.value.allowUpdate !== false },
|
label: '是否覆盖',
|
component: 'Switch',
|
componentProps: {
|
checkedChildren: '是',
|
unCheckedChildren: '否',
|
},
|
rules: z.boolean().default(false),
|
help: '是否更新已经存在的数据',
|
},
|
],
|
showDefaultActions: false,
|
});
|
|
/**
|
* 从导入接口的返回值里提取可展示的结果。
|
*
|
* 关键点:不能只看接口有没有报错就提示「操作成功」——后端可能跳过了部分行,
|
* 这些行不会抛异常,必须把跳过/失败的数量和行号明确告诉用户,否则数据无声丢失。
|
*/
|
function summarizeImportResult(raw: unknown) {
|
const result = unwrapImportResult(raw);
|
|
// 各模块分别返回 createCodes、createContractNames、updateNames 等字段,
|
// 不能把通用组件绑定到某一个业务的字段名。
|
const successRows = firstNumber(result.successRows, result.successCount)
|
?? countArrayFields(result, /^(?:create|update|success)(?!Count$)/i);
|
|
const failureEntries = collectEntries(result, /^failure(?!Count$)/i);
|
const skippedEntries = toEntries(result.skippedRows);
|
const failureRows = firstNumber(result.failureCount) ?? failureEntries.length;
|
const skippedRows = firstNumber(result.skippedCount) ?? skippedEntries.length;
|
const totalRows = firstNumber(result.totalRows);
|
const recognized = hasOutcomeFields(result);
|
|
if (failureRows > 0 && failureEntries.length === 0) {
|
failureEntries.push([`失败 ${failureRows} 条`, '后端未返回失败明细']);
|
}
|
if (skippedRows > 0 && skippedEntries.length === 0) {
|
skippedEntries.push([`跳过 ${skippedRows} 条`, '后端未返回跳过明细']);
|
}
|
|
return {
|
successRows,
|
failureRows,
|
skippedRows,
|
failureEntries,
|
skippedEntries,
|
totalRows,
|
recognized,
|
hasIssue: failureRows > 0 || skippedRows > 0,
|
};
|
}
|
|
const OUTCOME_KEY_PATTERN = /^(?:create|update|success|failure|skipped|totalRows)/i;
|
|
function hasOutcomeFields(result: ImportResultLike) {
|
return Object.keys(result).some((key) => OUTCOME_KEY_PATTERN.test(key));
|
}
|
|
/** requestClient 默认会解包 data,同时兼容 Axios / CommonResult 的嵌套 data。 */
|
function unwrapImportResult(raw: unknown): ImportResultLike {
|
let current = raw;
|
for (let depth = 0; depth < 3; depth++) {
|
if (!current || typeof current !== 'object' || Array.isArray(current)) {
|
return {};
|
}
|
const result = current as ImportResultLike;
|
if (hasOutcomeFields(result)) {
|
return result;
|
}
|
current = result.data;
|
}
|
return {};
|
}
|
|
function firstNumber(...values: unknown[]): number | undefined {
|
return values.find((value): value is number => typeof value === 'number');
|
}
|
|
/** 汇总 create* / update* / success* 数组的长度。 */
|
function countArrayFields(result: ImportResultLike, keyPattern: RegExp) {
|
return Object.entries(result).reduce(
|
(total, [key, value]) =>
|
total + (keyPattern.test(key) && Array.isArray(value) ? value.length : 0),
|
0,
|
);
|
}
|
|
/** 合并 failure* 等结果字段,保留业务单号及失败原因。 */
|
function collectEntries(result: ImportResultLike, keyPattern: RegExp) {
|
return Object.entries(result).flatMap(([key, value]) =>
|
keyPattern.test(key) ? toEntries(value) : [],
|
);
|
}
|
|
/** 把 Record / string[] / undefined 统一成 [label, reason][] */
|
function toEntries(input: unknown): Array<[string, string]> {
|
if (!input) {
|
return [];
|
}
|
if (Array.isArray(input)) {
|
return input.map((item) => [String(item), '']);
|
}
|
if (typeof input === 'object') {
|
return Object.entries(input as Record<string, string>).map(([k, v]) => [
|
k,
|
String(v ?? ''),
|
]);
|
}
|
return [];
|
}
|
|
/** 把结果拼成用户能看懂的一段话 */
|
function buildResultMessage(summary: ReturnType<typeof summarizeImportResult>) {
|
const parts: string[] = [];
|
if (summary.successRows > 0) {
|
parts.push(`成功 ${summary.successRows} 条`);
|
}
|
if (summary.skippedRows > 0) {
|
parts.push(`跳过 ${summary.skippedRows} 条`);
|
}
|
if (summary.failureRows > 0) {
|
parts.push(`失败 ${summary.failureRows} 条`);
|
}
|
if (parts.length === 0) {
|
return summary.recognized
|
? '导入完成,但没有可处理的数据'
|
: '导入请求已完成,请刷新列表确认结果';
|
}
|
const total = summary.totalRows === undefined ? '' : `(表格共 ${summary.totalRows} 行)`;
|
return `导入完成:${parts.join(',')}${total}`;
|
}
|
|
const [Modal, modalApi] = useVbenModal({
|
async onOpenChange(isOpen: boolean) {
|
if (isOpen) {
|
config.value = modalApi.getData<ImportModalProps>() ?? config.value;
|
await formApi.resetForm();
|
}
|
},
|
async onConfirm() {
|
const { valid } = await formApi.validate();
|
if (!valid) {
|
return;
|
}
|
modalApi.lock();
|
// 提交表单
|
const data = await formApi.getValues();
|
try {
|
// 统一兜底:后端各模块历史实现对 updateSupport 的来源不一致(有的从 query 读、
|
// 有的从表单读),漏传会被 @NotNull 拦下并弹出用户根本看不到对应字段的
|
// "是否支持更新不能为空"。这里强制显式传布尔值,避免任何页面因未初始化踩坑。
|
const updateSupport = data.updateSupport === true;
|
const raw = await config.value.importFn(data.file, updateSupport);
|
const summary = summarizeImportResult(raw);
|
const text = buildResultMessage(summary);
|
|
if (summary.hasIssue) {
|
// 有跳过或失败的行:保持弹窗打开,把明细展示给用户,避免数据无声丢失
|
message.warning({
|
content: text,
|
duration: 8,
|
});
|
showDetail(summary);
|
emit('success');
|
return;
|
}
|
|
await modalApi.close();
|
emit('success');
|
message.success(text);
|
} finally {
|
modalApi.unlock();
|
}
|
},
|
});
|
|
/** 用 Modal.info 展示跳过/失败明细,比 toast 更耐读 */
|
function showDetail(summary: ReturnType<typeof summarizeImportResult>) {
|
const sections: Array<{ title: string; rows: Array<[string, string]> }> = [];
|
if (summary.skippedEntries.length > 0) {
|
sections.push({ title: '被跳过的行(未导入)', rows: summary.skippedEntries });
|
}
|
if (summary.failureEntries.length > 0) {
|
sections.push({ title: '导入失败', rows: summary.failureEntries });
|
}
|
AntModal.info({
|
title: '导入结果明细',
|
width: 560,
|
content: h(
|
'div',
|
{ style: 'max-height: 360px; overflow-y: auto;' },
|
sections.map((section) =>
|
h('div', { style: 'margin-bottom: 12px;' }, [
|
h('div', { style: 'font-weight: 600; margin-bottom: 4px;' }, section.title),
|
...section.rows.map(([label, reason]) =>
|
h('div', { style: 'font-size: 13px; line-height: 20px;' }, [
|
h('span', { style: 'color: #cf1322;' }, `${label}`),
|
h('span', {}, `:${reason || '未说明原因'}`),
|
]),
|
),
|
]),
|
),
|
),
|
});
|
}
|
|
/** 上传前 */
|
function beforeUpload(file: FileType) {
|
formApi.setFieldValue('file', file);
|
return false;
|
}
|
|
/** 下载模版 */
|
async function handleDownload() {
|
if (!config.value.templateFn) return;
|
const data = await config.value.templateFn();
|
downloadFileFromBlobPart({ fileName: config.value.fileName, source: data });
|
}
|
</script>
|
|
<template>
|
<Modal :title="config.title" class="w-1/3">
|
<Form class="mx-4">
|
<template #file>
|
<div class="w-full">
|
<Upload
|
:max-count="1"
|
accept=".xls,.xlsx"
|
:before-upload="beforeUpload"
|
>
|
<Button type="primary"> 选择 Excel 文件 </Button>
|
</Upload>
|
</div>
|
</template>
|
</Form>
|
<template #prepend-footer>
|
<div v-if="config.showTemplateDownload !== false" class="flex flex-auto items-center">
|
<Button @click="handleDownload"> 下载导入模板 </Button>
|
</div>
|
</template>
|
</Modal>
|
</template>
|