wangzhibo
2026-07-28 fa9b89139f34809b7bf01ca2052fbaa3d1ea64e6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
<template>
    <cl-crud ref="Crud">
        <cl-row>
            <!-- 刷新按钮 -->
            <cl-refresh-btn />
            <!-- 新增按钮 -->
            <cl-add-btn />
            <!-- 删除按钮 -->
            <cl-multi-delete-btn />
            <cl-flex1 />
            <cl-import-btn tips="导入微信交易记录" :on-config="onConfig" :on-submit="onSubmit" />
            <!-- 条件搜索 -->
            <cl-search ref="Search" />
        </cl-row>
 
        <cl-row>
            <!-- 数据表格 -->
            <cl-table ref="Table">
                <template #column-filepath="{ scope }">
                    <el-link :href="scope.row.filepath" target="_blank" type="primary">
                        {{ scope.row.filepath?.split('/').pop() }}
                    </el-link>
 
                </template>
            </cl-table>
        </cl-row>
 
        <cl-row>
            <cl-flex1 />
            <!-- 分页控件 -->
            <cl-pagination />
        </cl-row>
 
        <!-- 新增、编辑 -->
        <cl-upsert ref="Upsert" />
    </cl-crud>
</template>
 
<script lang="ts" setup>
defineOptions({
    name: "trade-record"
});
import { ElMessage } from 'element-plus';
import { useCrud, useTable, useUpsert, useSearch } from "@cool-vue/crud";
import { useCool } from "/@/cool";
import { useI18n } from "vue-i18n";
import { reactive, ref, watch, nextTick } from "vue";
 
const { service } = useCool();
const { t } = useI18n();
 
// 选项
const options = reactive({
    incomeType: [
        { label: t('收入'), value: '收入' },
        { label: t('支出'), value: '支出' },
        { label: t('其他'), value: '其他' }
    ]
});
 
// cl-upsert
 
const Upsert = useUpsert({
    items: [
        {
            label: t('交易时间'),
            prop: "transactionTime",
            component: {
                name: "el-date-picker",
                props: { type: "datetime", valueFormat: "YYYY-MM-DD HH:mm:ss" }
            },
            span: 12
        },
        {
            label: t('交易类型'),
            prop: "transactionType",
            component: { name: "el-input", props: { clearable: true } },
            span: 12
        },
        {
            label: t('交易对方'),
            prop: "opponent",
            component: { name: "el-input", props: { clearable: true } },
            span: 12
        },
        {
            label: t('商品名称'),
            prop: "goodsName",
            component: { name: "el-input", props: { clearable: true } },
            span: 12
        },
        {
            label: t('收支类型'),
            prop: "incomeType",
            component: { name: "el-radio-group", options: options.incomeType },
            value: 2,
            required: true
        },
        {
            label: t('金额'),
            prop: "amount",
            hook: "number",
            component: { name: "el-input-number", props: { min: 0 } },
            span: 12,
            required: true
        },
        {
            label: t('支付方式'),
            prop: "payMethod",
            component: { name: "el-input", props: { clearable: true } },
            span: 12
        },
        {
            label: t('当前状态'),
            prop: "status",
            component: { name: "el-input", props: { clearable: true } },
            span: 12
        },
        {
            label: t('交易单号'),
            prop: "transactionNo",
            component: { name: "el-input", props: { clearable: true } },
            span: 12
        },
        {
            label: t('商户单号'),
            prop: "merchantNo",
            component: { name: "el-input", props: { clearable: true } },
            span: 12
        },
        {
            label: t('备注'),
            prop: "remark",
            component: { name: "el-input", props: { type: "textarea", rows: 4 } }
        }
        /*{
            label: t('选择关联文件'),
            prop: "fileId",
            component: { name: "cl-upload", props: { type: "file", limit: 1 } }
        }
        */
    ]
});
 
// cl-table
const Table = useTable({
    columns: [
        { type: "selection" },
        { label: t('所属单位'), prop: "departmentName", minWidth: 120 },
        {
            label: t('交易时间'),
            prop: "transactionTime",
            minWidth: 170,
            sortable: "custom",
            component: { name: "cl-date-text" }
        },
        { label: t('交易类型'), prop: "transactionType", minWidth: 120 },
        { label: t('交易对方'), prop: "opponent", minWidth: 140 },
        { label: t('商品名称'), prop: "goodsName", minWidth: 140 },
        {
            label: t('收支类型'),
            prop: "incomeType",
            minWidth: 120,
            dict: options.incomeType
        },
        { label: t('金额'), prop: "amount", minWidth: 140, sortable: "custom" },
        { label: t('支付方式'), prop: "payMethod", minWidth: 120 },
        /*{ label: t('当前状态'), prop: "status", minWidth: 120 },
        { label: t('交易单号'), prop: "transactionNo", minWidth: 140 },
        { label: t('商户单号'), prop: "merchantNo", minWidth: 140 },
        { label: t('备注'), prop: "remark", showOverflowTooltip: true, minWidth: 200 },*/
        { label: t('文件路径'), prop: "filepath", minWidth: 140 },
 
        {
            label: t('创建时间'),
            prop: "createTime",
            minWidth: 170,
            sortable: "desc",
            component: { name: "cl-date-text" }
        },
        /*
        {
            label: t('更新时间'),
            prop: "updateTime",
            minWidth: 170,
            sortable: "custom",
            component: { name: "cl-date-text" }
        },
        { type: "op", buttons: ["edit", "delete"] }
        */
    ]
});
 
// cl-search
const Search = useSearch();
 
// cl-crud
const Crud = useCrud(
    {
        service: service.operation.traderecord
    },
    (app) => {
        app.refresh();
    }
);
 
// 刷新
function refresh(params?: any) {
    Crud.value?.refresh(params);
}
 
/**
 * 1. 扩展导入弹窗中的配置项(添加部门选择器 + 监听文件选择)
 */
function onConfig(Form: ClForm.Ref) {
    return [
        {
            label: "选择部门",
            prop: "departmentId",
            component: {
                name: "cl-dept-select",
                props: {
                    multiple: false,
                    placeholder: "请选择部门",
                    checkStrictly: true,
                    immediate: true
                }
            },
            required: true
        }
    ];
}
 
/**
 * 定义 Excel 中文表头与 Entity 字段名的对应关系字典
 */
const fieldMap: Record<string, string> = {
    交易时间: "transactionTime",
    交易类型: "transactionType",
    交易对方: "opponent",
    商品: "goodsName",
    "收/支": "incomeType",
    "金额(元)": "amount",
    支付方式: "payMethod",
    当前状态: "status",
    交易单号: "transactionNo",
    商户单号: "merchantNo",
    备注: "remark"
};
function cleanAmount(val: any): number {
    if (val === null || val === undefined || val === '') return 0;
 
    // 转为字符串,并移除所有非数字、非小数点、非负号的字符(即移除 ¥、¥、逗号、空格等)
    const cleanStr = String(val).replace(/[^\d.-]/g, '');
 
    const num = parseFloat(cleanStr);
    return isNaN(num) ? 0 : num;
}
 
/**
 * 2. 提交数据处理逻辑
 * @param data  Excel解析后的行数据数组 (5列数据)
 * @param extra 额外表单数据(departmentId 等)
 * @param helper 状态控制方法
 */
async function onSubmit(data: any, { done, close }: any) {
    try {
 
        if (!data.file) {
            ElMessage.warning("未能识别到上传的 Excel 文件");
            return done?.();
        }
 
        console.log(data.file);
        console.log(data.file instanceof File);
 
        const formData = new FormData();
        formData.append("file", data.file); // 放入文件对象
        formData.append("key", "");        // ⭐️ 传入 key,防止后端 ctx.fields 为 undefined
 
        // 2. 发送上传请求(cool-admin 的 request 模块)
        // 注意:通常基础上传接口地址是 /admin/base/comm/upload
        const fileUrl = await service.base.comm.request({
            url: "/upload",
            method: "POST",
            headers: {
                "Content-Type": "multipart/form-data"
            },
            data: formData
        });
 
        // 第二步:将 departmentId 和 file 组装到 Excel 解析的每条数据中(5列 -> 7列)
        const list = data.list.map((row) => {
            const formattedItem: Record<string, any> = {
                // 附加的第 6 列和第 7 列
                departmentId: data.departmentId,
                filepath: fileUrl
            };
 
            // 遍历 Excel 解析出来的单行数据 (例如: { "姓名": "张三", "年龄": 25 })
            Object.keys(row).forEach((excelHeader) => {
                const cleanHeader = excelHeader
                    .replace(/(/g, "(")
                    .replace(/)/g, ")")
                    .trim();
                const englishKey = fieldMap[cleanHeader];
                if (englishKey) {
                    let value = row[excelHeader];
                    // ⭐️ 针对金额字段(amount)进行强制清洗类型转换
                    if (englishKey === "amount") {
                        value = cleanAmount(value); // '¥300.00' 会变成数字 300
                    }
                    formattedItem[englishKey] = value;
                }
            });
 
            return formattedItem;
        });
 
        // 第三步:提交给后端批量保存接口(请替换 service.yourModule.yourService 为你的实际 service)
        await service.operation.traderecord.import({ list });
 
        ElMessage.success("导入成功");
 
        close();
        refresh();
 
    } catch (err: any) {
        ElMessage.error(err?.message || "导入失败,请检查文件或网络");
        done();
    }
}
 
</script>