Skip to content

Commit 34761ba

Browse files
authored
Merge pull request #2 from devforth/import-csv
feat: integrate PapaParse for CSV parsing and enhance error handling
2 parents a47820f + 1dad1ab commit 34761ba

File tree

5 files changed

+149
-61
lines changed

5 files changed

+149
-61
lines changed

custom/ExportCsv.vue

+42-35
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,27 @@
44

55
<svg v-if="inProgress"
66
aria-hidden="true" class="w-4 h-4 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="currentColor"/><path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentFill"/></svg>
7-
87
</div>
98
</template>
109

11-
1210
<script setup lang="ts">
13-
14-
import { onMounted, ref } from 'vue';
11+
import { ref } from 'vue';
1512
import { useCoreStore } from '@/stores/core';
16-
import { callAdminForthApi, loadFile } from '@/utils';
13+
import { callAdminForthApi } from '@/utils';
1714
import { useFiltersStore } from '@/stores/filters';
1815
import adminforth from '@/adminforth';
19-
16+
import Papa from 'papaparse';
2017
2118
const filtersStore = useFiltersStore();
19+
const coreStore = useCoreStore();
20+
const inProgress = ref(false);
2221
2322
const props = defineProps({
2423
meta: Object,
2524
record: Object,
26-
})
27-
28-
const inProgress = ref(false);
29-
30-
const coreStore = useCoreStore();
31-
32-
33-
onMounted(async () => {
3425
});
3526
36-
function loadFile(data, filename) {
27+
function downloadFile(data: string, filename: string) {
3728
const blob = new Blob([data], { type: 'text/csv' });
3829
const url = window.URL.createObjectURL(blob);
3930
const a = document.createElement('a');
@@ -44,30 +35,46 @@ function loadFile(data, filename) {
4435
}
4536
4637
async function exportCsv() {
47-
4838
inProgress.value = true;
49-
const resp = await callAdminForthApi({
50-
path: `/plugin/${props.meta.pluginInstanceId}/export-csv`,
51-
method: 'POST',
52-
body: {
53-
filters: props.meta.select === 'all' ? [] : filtersStore.getFilters(),
54-
sort: filtersStore.getSort(),
39+
try {
40+
const resp = await callAdminForthApi({
41+
path: `/plugin/${props.meta.pluginInstanceId}/export-csv`,
42+
method: 'POST',
43+
body: {
44+
filters: props.meta.select === 'all' ? [] : filtersStore.getFilters(),
45+
sort: filtersStore.getSort(),
46+
}
47+
});
48+
49+
if (resp.error) {
50+
throw new Error(resp.error);
5551
}
56-
});
57-
inProgress.value = false;
58-
if (resp.error) {
59-
adminforth.alert({
60-
message: resp.error,
61-
})
62-
} else {
63-
loadFile(resp.data, `export-${coreStore.resource.resourceId}-${new Date().toISOString()}.csv`);
52+
53+
// Parse the CSV data to ensure proper formatting
54+
const parsedData = Papa.parse(resp.data).data;
55+
56+
// Generate properly formatted CSV
57+
const csvContent = '\ufeff' + Papa.unparse(parsedData, {
58+
quotes: true, // Force quotes around all fields
59+
quoteChar: '"',
60+
escapeChar: '"',
61+
});
62+
63+
// Download the file
64+
const filename = `export-${coreStore.resource.resourceId}-${new Date().toISOString()}.csv`;
65+
downloadFile(csvContent, filename);
66+
6467
adminforth.alert({
6568
message: `Exported ${resp.exportedCount} item${resp.exportedCount > 1 ? 's' : ''} successfully. Check your downloads folder`,
66-
})
69+
});
70+
} catch (error) {
71+
adminforth.alert({
72+
message: error instanceof Error ? error.message : 'Export failed',
73+
variant: 'danger'
74+
});
75+
} finally {
76+
inProgress.value = false;
77+
adminforth.list.closeThreeDotsDropdown();
6778
}
68-
adminforth.list.closeThreeDotsDropdown();
6979
}
70-
71-
72-
7380
</script>

custom/ImportCsv.vue

+32-20
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import { ref, Ref } from 'vue';
1313
import { callAdminForthApi } from '@/utils';
1414
import adminforth from '@/adminforth';
15+
import Papa from 'papaparse';
1516
1617
const inProgress: Ref<boolean> = ref(false);
1718
@@ -63,32 +64,43 @@ async function importCsv() {
6364
return;
6465
}
6566
66-
// post data in format, plain json
67-
// data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
68-
const data = {};
6967
const reader = new FileReader();
7068
reader.onload = async (e) => {
71-
const text = e.target.result as string;
72-
73-
const lines = text.split('\n');
74-
const columns = lines[0].split(',');
75-
for (let i = 1; i < lines.length; i++) {
76-
const values = lines[i].split(',');
77-
for (let j = 0; j < columns.length; j++) {
78-
if (!data[columns[j]]) {
79-
data[columns[j]] = [];
69+
try {
70+
const text = e.target.result as string;
71+
72+
Papa.parse(text, {
73+
header: true,
74+
skipEmptyLines: true,
75+
complete: async (results) => {
76+
if (results.errors.length > 0) {
77+
throw new Error(`CSV parsing errors: ${results.errors.map(e => e.message).join(', ')}`);
78+
}
79+
const data: Record<string, string[]> = {};
80+
const rows = results.data as Record<string, string>[];
81+
82+
if (rows.length === 0) {
83+
throw new Error('No data rows found in CSV');
84+
}
85+
Object.keys(rows[0]).forEach(column => {
86+
data[column] = rows.map(row => row[column]);
87+
});
88+
89+
await postData(data);
90+
},
91+
error: (error) => {
92+
throw new Error(`Failed to parse CSV: ${error.message}`);
8093
}
81-
data[columns[j]].push(values[j]);
82-
}
94+
});
95+
} catch (error) {
96+
inProgress.value = false;
97+
adminforth.alert({
98+
message: `Error processing CSV: ${error.message}`,
99+
variant: 'danger'
100+
});
83101
}
84-
await postData(data);
85102
};
86103
reader.readAsText(file);
87-
88-
89-
90104
};
91-
92105
}
93-
94106
</script>

custom/package-lock.json

+47
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

custom/package.json

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "custom",
3+
"version": "1.0.0",
4+
"main": "index.js",
5+
"scripts": {
6+
"test": "echo \"Error: no test specified\" && exit 1"
7+
},
8+
"keywords": [],
9+
"author": "",
10+
"license": "ISC",
11+
"description": "",
12+
"dependencies": {
13+
"@types/papaparse": "^5.3.15",
14+
"papaparse": "^5.5.2"
15+
}
16+
}

index.ts

+12-6
Original file line numberDiff line numberDiff line change
@@ -85,20 +85,26 @@ export default class ImportExport extends AdminForthPlugin {
8585
});
8686

8787
// csv export
88-
8988
const columns = this.resourceConfig.columns.filter((col) => !col.virtual);
89+
90+
const escapeCSV = (value: any) => {
91+
if (value === null || value === undefined) return '""';
92+
const str = String(value);
93+
if (str.includes(',') || str.includes('"') || str.includes('\n')) {
94+
return `"${str.replace(/"/g, '""')}"`;
95+
}
96+
return `"${str}"`;
97+
};
98+
9099
let csv = data.data.map((row) => {
91-
return columns.map((col) => {
92-
return row[col.name];
93-
}).join(',');
100+
return columns.map((col) => escapeCSV(row[col.name])).join(',');
94101
}).join('\n');
95102

96103
// add headers
97-
const headers = columns.map((col) => col.name).join(',');
104+
const headers = columns.map((col) => escapeCSV(col.name)).join(',');
98105
csv = `${headers}\n${csv}`;
99106

100107
return { data: csv, exportedCount: data.total, ok: true };
101-
102108
}
103109
});
104110

0 commit comments

Comments
 (0)