@adminforth/import-export 1.0.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.woodpecker/buildRelease.sh +13 -0
- package/.woodpecker/buildSlackNotify.sh +44 -0
- package/.woodpecker/release.yml +44 -0
- package/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +7 -0
- package/build.log +14 -0
- package/custom/ExportCsv.vue +45 -37
- package/custom/ImportCsv.vue +116 -40
- package/custom/package-lock.json +47 -0
- package/custom/package.json +16 -0
- package/custom/tsconfig.json +19 -0
- package/dist/custom/ExportCsv.vue +45 -37
- package/dist/custom/ImportCsv.vue +116 -40
- package/dist/custom/package-lock.json +47 -0
- package/dist/custom/package.json +16 -0
- package/dist/custom/tsconfig.json +19 -0
- package/dist/index.js +103 -8
- package/index.ts +122 -13
- package/package.json +46 -7
|
@@ -1,38 +1,30 @@
|
|
|
1
1
|
<template>
|
|
2
2
|
<div @click="exportCsv" class="cursor-pointer flex gap-2 items-center">
|
|
3
|
-
Export {{ meta.select === 'all' ? 'All': 'Filtered' }} to CSV
|
|
3
|
+
{{$t("Export")}} {{ meta.select === 'all' ? $t('All'): $t('Filtered') }} {{$t('to CSV')}}
|
|
4
4
|
|
|
5
5
|
<svg v-if="inProgress"
|
|
6
6
|
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
|
-
|
|
8
7
|
</div>
|
|
9
8
|
</template>
|
|
10
9
|
|
|
11
|
-
|
|
12
10
|
<script setup lang="ts">
|
|
13
|
-
|
|
14
|
-
import { onMounted, ref } from 'vue';
|
|
11
|
+
import { ref } from 'vue';
|
|
15
12
|
import { useCoreStore } from '@/stores/core';
|
|
16
|
-
import { callAdminForthApi
|
|
13
|
+
import { callAdminForthApi } from '@/utils';
|
|
17
14
|
import { useFiltersStore } from '@/stores/filters';
|
|
18
|
-
|
|
15
|
+
import adminforth from '@/adminforth';
|
|
16
|
+
import Papa from 'papaparse';
|
|
19
17
|
|
|
20
18
|
const filtersStore = useFiltersStore();
|
|
19
|
+
const coreStore = useCoreStore();
|
|
20
|
+
const inProgress = ref(false);
|
|
21
21
|
|
|
22
22
|
const props = defineProps({
|
|
23
23
|
meta: Object,
|
|
24
24
|
record: Object,
|
|
25
|
-
})
|
|
26
|
-
|
|
27
|
-
const inProgress = ref(false);
|
|
28
|
-
|
|
29
|
-
const coreStore = useCoreStore();
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
onMounted(async () => {
|
|
33
25
|
});
|
|
34
26
|
|
|
35
|
-
function
|
|
27
|
+
function downloadFile(data: string, filename: string) {
|
|
36
28
|
const blob = new Blob([data], { type: 'text/csv' });
|
|
37
29
|
const url = window.URL.createObjectURL(blob);
|
|
38
30
|
const a = document.createElement('a');
|
|
@@ -43,30 +35,46 @@ function loadFile(data, filename) {
|
|
|
43
35
|
}
|
|
44
36
|
|
|
45
37
|
async function exportCsv() {
|
|
46
|
-
|
|
47
38
|
inProgress.value = true;
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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);
|
|
54
51
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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
|
+
|
|
67
|
+
adminforth.alert({
|
|
64
68
|
message: `Exported ${resp.exportedCount} item${resp.exportedCount > 1 ? 's' : ''} successfully. Check your downloads folder`,
|
|
65
|
-
})
|
|
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();
|
|
66
78
|
}
|
|
67
|
-
window.adminforth.list.closeThreeDotsDropdown();
|
|
68
79
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
80
|
</script>
|
|
@@ -1,52 +1,110 @@
|
|
|
1
1
|
<template>
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
2
|
+
<div @click="importCsv" class="cursor-pointer flex gap-2 items-center">
|
|
3
|
+
{{$t('Import from CSV')}}
|
|
4
|
+
|
|
5
|
+
<svg v-if="inProgress"
|
|
6
|
+
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
|
+
</div>
|
|
8
|
+
<Dialog ref="confirmDialog"
|
|
9
|
+
:header="t('Import Confirmation')"
|
|
10
|
+
:buttons="[
|
|
11
|
+
{ label: t('Import & Replace'), onclick: (dialog) => { confirmImport(dialog) } },
|
|
12
|
+
{ label: t('Import New Only'), onclick: (dialog) => { confirmImportNewOnly(dialog) } },
|
|
13
|
+
{ label: t('Cancel'), onclick: (dialog) => dialog.hide() }
|
|
14
|
+
]"
|
|
15
|
+
>
|
|
16
|
+
<div v-if="importStats">
|
|
17
|
+
<p>{{ $t('Are you sure you want to continue?') }}</p>
|
|
18
|
+
<p class="mt-2">{{ $t('You are importing {count} records:', { count: importStats.total }) }}</p>
|
|
19
|
+
<ul class="list-disc ml-6 mt-2">
|
|
20
|
+
<li>{{ $t('{count} existing records will be replaced (old records will be lost)', { count: importStats.existingCount }) }}</li>
|
|
21
|
+
<li>{{ $t('{count} new records will be added', { count: importStats.newCount }) }}</li>
|
|
22
|
+
</ul>
|
|
23
|
+
</div>
|
|
24
|
+
</Dialog>
|
|
9
25
|
</template>
|
|
10
26
|
|
|
11
27
|
<script setup lang="ts">
|
|
12
28
|
import { ref, Ref } from 'vue';
|
|
13
29
|
import { callAdminForthApi } from '@/utils';
|
|
30
|
+
import adminforth from '@/adminforth';
|
|
31
|
+
import Papa from 'papaparse';
|
|
32
|
+
import { Dialog } from '@/afcl';
|
|
33
|
+
import { useI18n } from 'vue-i18n';
|
|
14
34
|
|
|
15
|
-
const
|
|
35
|
+
const { t } = useI18n();
|
|
16
36
|
|
|
37
|
+
const inProgress: Ref<boolean> = ref(false);
|
|
38
|
+
const confirmDialog = ref(null);
|
|
39
|
+
const importStats = ref(null);
|
|
40
|
+
const pendingData = ref(null);
|
|
17
41
|
const props = defineProps({
|
|
18
42
|
meta: Object,
|
|
19
43
|
record: Object,
|
|
20
44
|
});
|
|
21
45
|
|
|
22
|
-
async function
|
|
23
|
-
|
|
46
|
+
async function confirmImport(dialog) {
|
|
47
|
+
dialog.hide();
|
|
48
|
+
await postData(pendingData.value);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function checkRecords(data: Record<string, string[]>) {
|
|
52
|
+
const resp = await callAdminForthApi({
|
|
53
|
+
path: `/plugin/${props.meta.pluginInstanceId}/check-records`,
|
|
54
|
+
method: 'POST',
|
|
55
|
+
body: { data }
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
return resp;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function confirmImportNewOnly(dialog) {
|
|
62
|
+
dialog.hide();
|
|
63
|
+
await postDataNewOnly(pendingData.value);
|
|
64
|
+
}
|
|
24
65
|
|
|
66
|
+
async function postData(data: Record<string, string[]>, skipDuplicates: boolean = false) {
|
|
25
67
|
const resp = await callAdminForthApi({
|
|
26
68
|
path: `/plugin/${props.meta.pluginInstanceId}/import-csv`,
|
|
27
69
|
method: 'POST',
|
|
28
|
-
body: {
|
|
29
|
-
data
|
|
30
|
-
}
|
|
70
|
+
body: { data }
|
|
31
71
|
});
|
|
32
72
|
|
|
33
73
|
inProgress.value = false;
|
|
34
74
|
|
|
35
|
-
if (resp.importedCount > 0) {
|
|
36
|
-
|
|
75
|
+
if (resp.importedCount > 0 || resp.updatedCount > 0) {
|
|
76
|
+
adminforth.list.refresh();
|
|
37
77
|
}
|
|
38
|
-
|
|
39
|
-
message: `Imported
|
|
78
|
+
adminforth.alert({
|
|
79
|
+
message: `Imported ${resp.importedCount || 0} records. Updated ${resp.updatedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
|
|
40
80
|
variant: resp.errors?.length ? (
|
|
41
81
|
resp.importedCount ? 'warning' : 'danger'
|
|
42
82
|
) : 'success'
|
|
43
83
|
});
|
|
44
84
|
|
|
45
|
-
|
|
85
|
+
adminforth.list.closeThreeDotsDropdown();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function postDataNewOnly(data: Record<string, string[]>) {
|
|
89
|
+
const resp = await callAdminForthApi({
|
|
90
|
+
path: `/plugin/${props.meta.pluginInstanceId}/import-csv-new-only`,
|
|
91
|
+
method: 'POST',
|
|
92
|
+
body: { data }
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
inProgress.value = false;
|
|
96
|
+
if (resp.importedCount > 0) {
|
|
97
|
+
adminforth.list.refresh();
|
|
98
|
+
}
|
|
99
|
+
adminforth.alert({
|
|
100
|
+
message: `Imported ${resp.importedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
|
|
101
|
+
variant: resp.errors?.length ? 'warning' : 'success'
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
adminforth.list.closeThreeDotsDropdown();
|
|
46
105
|
}
|
|
47
106
|
|
|
48
107
|
async function importCsv() {
|
|
49
|
-
// create file input and open it (with csv type)
|
|
50
108
|
inProgress.value = false;
|
|
51
109
|
const fileInput = document.createElement('input');
|
|
52
110
|
|
|
@@ -61,33 +119,51 @@ async function importCsv() {
|
|
|
61
119
|
inProgress.value = false;
|
|
62
120
|
return;
|
|
63
121
|
}
|
|
64
|
-
|
|
65
|
-
// post data in format, plain json
|
|
66
|
-
// data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
|
|
67
|
-
const data = {};
|
|
68
122
|
const reader = new FileReader();
|
|
69
123
|
reader.onload = async (e) => {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
124
|
+
try {
|
|
125
|
+
const text = e.target.result as string;
|
|
126
|
+
|
|
127
|
+
Papa.parse(text, {
|
|
128
|
+
header: true,
|
|
129
|
+
skipEmptyLines: true,
|
|
130
|
+
|
|
131
|
+
complete: async (results) => {
|
|
132
|
+
if (results.errors.length > 0) {
|
|
133
|
+
throw new Error(`CSV parsing errors: ${results.errors.map(e => e.message).join(', ')}`);
|
|
134
|
+
}
|
|
135
|
+
const data: Record<string, string[]> = {};
|
|
136
|
+
const rows = results.data as Record<string, string>[];
|
|
137
|
+
|
|
138
|
+
if (rows.length === 0) {
|
|
139
|
+
throw new Error('No data rows found in CSV');
|
|
140
|
+
}
|
|
141
|
+
Object.keys(rows[0]).forEach(column => {
|
|
142
|
+
data[column] = rows.map(row => row[column]);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
// Store data for later use
|
|
146
|
+
pendingData.value = data;
|
|
147
|
+
|
|
148
|
+
// Check records and show confirmation
|
|
149
|
+
const stats = await checkRecords(data);
|
|
150
|
+
importStats.value = stats;
|
|
151
|
+
confirmDialog.value?.open();
|
|
152
|
+
inProgress.value = false;
|
|
153
|
+
},
|
|
154
|
+
error: (error) => {
|
|
155
|
+
throw new Error(`Failed to parse CSV: ${error.message}`);
|
|
79
156
|
}
|
|
80
|
-
|
|
81
|
-
|
|
157
|
+
});
|
|
158
|
+
} catch (error) {
|
|
159
|
+
inProgress.value = false;
|
|
160
|
+
adminforth.alert({
|
|
161
|
+
message: `Error processing CSV: ${error.message}`,
|
|
162
|
+
variant: 'danger'
|
|
163
|
+
});
|
|
82
164
|
}
|
|
83
|
-
await postData(data);
|
|
84
165
|
};
|
|
85
166
|
reader.readAsText(file);
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
167
|
};
|
|
90
|
-
|
|
91
168
|
}
|
|
92
|
-
|
|
93
169
|
</script>
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "custom",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"lockfileVersion": 3,
|
|
5
|
+
"requires": true,
|
|
6
|
+
"packages": {
|
|
7
|
+
"": {
|
|
8
|
+
"name": "custom",
|
|
9
|
+
"version": "1.0.0",
|
|
10
|
+
"license": "ISC",
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@types/papaparse": "^5.3.15",
|
|
13
|
+
"papaparse": "^5.5.2"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"node_modules/@types/node": {
|
|
17
|
+
"version": "22.13.10",
|
|
18
|
+
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.10.tgz",
|
|
19
|
+
"integrity": "sha512-I6LPUvlRH+O6VRUqYOcMudhaIdUVWfsjnZavnsraHvpBwaEyMN29ry+0UVJhImYL16xsscu0aske3yA+uPOWfw==",
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"undici-types": "~6.20.0"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"node_modules/@types/papaparse": {
|
|
26
|
+
"version": "5.3.15",
|
|
27
|
+
"resolved": "https://registry.npmjs.org/@types/papaparse/-/papaparse-5.3.15.tgz",
|
|
28
|
+
"integrity": "sha512-JHe6vF6x/8Z85nCX4yFdDslN11d+1pr12E526X8WAfhadOeaOTx5AuIkvDKIBopfvlzpzkdMx4YyvSKCM9oqtw==",
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@types/node": "*"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"node_modules/papaparse": {
|
|
35
|
+
"version": "5.5.2",
|
|
36
|
+
"resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.5.2.tgz",
|
|
37
|
+
"integrity": "sha512-PZXg8UuAc4PcVwLosEEDYjPyfWnTEhOrUfdv+3Bx+NuAb+5NhDmXzg5fHWmdCh1mP5p7JAZfFr3IMQfcntNAdA==",
|
|
38
|
+
"license": "MIT"
|
|
39
|
+
},
|
|
40
|
+
"node_modules/undici-types": {
|
|
41
|
+
"version": "6.20.0",
|
|
42
|
+
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
|
|
43
|
+
"integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==",
|
|
44
|
+
"license": "MIT"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"baseUrl": ".", // This should point to your project root
|
|
4
|
+
"paths": {
|
|
5
|
+
"@/*": [
|
|
6
|
+
// "node_modules/adminforth/dist/spa/src/*"
|
|
7
|
+
"../../../spa/src/*"
|
|
8
|
+
],
|
|
9
|
+
"*": [
|
|
10
|
+
// "node_modules/adminforth/dist/spa/node_modules/*"
|
|
11
|
+
"../../../spa/node_modules/*"
|
|
12
|
+
],
|
|
13
|
+
"@@/*": [
|
|
14
|
+
// "node_modules/adminforth/dist/spa/src/*"
|
|
15
|
+
"."
|
|
16
|
+
]
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
7
7
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
8
|
});
|
|
9
9
|
};
|
|
10
|
-
import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators } from "adminforth";
|
|
10
|
+
import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators, Filters } from "adminforth";
|
|
11
11
|
export default class ImportExport extends AdminForthPlugin {
|
|
12
12
|
constructor(options) {
|
|
13
13
|
super(options, import.meta.url);
|
|
@@ -83,13 +83,20 @@ export default class ImportExport extends AdminForthPlugin {
|
|
|
83
83
|
});
|
|
84
84
|
// csv export
|
|
85
85
|
const columns = this.resourceConfig.columns.filter((col) => !col.virtual);
|
|
86
|
+
const escapeCSV = (value) => {
|
|
87
|
+
if (value === null || value === undefined)
|
|
88
|
+
return '""';
|
|
89
|
+
const str = String(value);
|
|
90
|
+
if (str.includes(',') || str.includes('"') || str.includes('\n')) {
|
|
91
|
+
return `"${str.replace(/"/g, '""')}"`;
|
|
92
|
+
}
|
|
93
|
+
return `"${str}"`;
|
|
94
|
+
};
|
|
86
95
|
let csv = data.data.map((row) => {
|
|
87
|
-
return columns.map((col) =>
|
|
88
|
-
return row[col.name];
|
|
89
|
-
}).join(',');
|
|
96
|
+
return columns.map((col) => escapeCSV(row[col.name])).join(',');
|
|
90
97
|
}).join('\n');
|
|
91
98
|
// add headers
|
|
92
|
-
const headers = columns.map((col) => col.name).join(',');
|
|
99
|
+
const headers = columns.map((col) => escapeCSV(col.name)).join(',');
|
|
93
100
|
csv = `${headers}\n${csv}`;
|
|
94
101
|
return { data: csv, exportedCount: data.total, ok: true };
|
|
95
102
|
})
|
|
@@ -98,10 +105,8 @@ export default class ImportExport extends AdminForthPlugin {
|
|
|
98
105
|
method: 'POST',
|
|
99
106
|
path: `/plugin/${this.pluginInstanceId}/import-csv`,
|
|
100
107
|
noAuth: true,
|
|
101
|
-
handler: (
|
|
108
|
+
handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body }) {
|
|
102
109
|
const { data } = body;
|
|
103
|
-
// data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
|
|
104
|
-
// we need to convert it to [{columnName: value1, columnName2: value1}, {columnName: value2, columnName2: value2}...]
|
|
105
110
|
const rows = [];
|
|
106
111
|
const columns = Object.keys(data);
|
|
107
112
|
// check column names are valid
|
|
@@ -115,6 +120,7 @@ export default class ImportExport extends AdminForthPlugin {
|
|
|
115
120
|
if (errors.length > 0) {
|
|
116
121
|
return { ok: false, errors };
|
|
117
122
|
}
|
|
123
|
+
const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
|
|
118
124
|
const columnValues = Object.values(data);
|
|
119
125
|
for (let i = 0; i < columnValues[0].length; i++) {
|
|
120
126
|
const row = {};
|
|
@@ -124,8 +130,67 @@ export default class ImportExport extends AdminForthPlugin {
|
|
|
124
130
|
rows.push(row);
|
|
125
131
|
}
|
|
126
132
|
let importedCount = 0;
|
|
133
|
+
let updatedCount = 0;
|
|
127
134
|
yield Promise.all(rows.map((row) => __awaiter(this, void 0, void 0, function* () {
|
|
128
135
|
try {
|
|
136
|
+
if (primaryKeyColumn && row[primaryKeyColumn.name]) {
|
|
137
|
+
const existingRecord = yield this.adminforth.resource(this.resourceConfig.resourceId)
|
|
138
|
+
.list([Filters.EQ(primaryKeyColumn.name, row[primaryKeyColumn.name])]);
|
|
139
|
+
if (existingRecord.length > 0) {
|
|
140
|
+
yield this.adminforth.resource(this.resourceConfig.resourceId)
|
|
141
|
+
.update(row[primaryKeyColumn.name], row);
|
|
142
|
+
updatedCount++;
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
yield this.adminforth.resource(this.resourceConfig.resourceId).create(row);
|
|
147
|
+
importedCount++;
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
errors.push(e.message);
|
|
151
|
+
}
|
|
152
|
+
})));
|
|
153
|
+
return { ok: true, importedCount, updatedCount, errors };
|
|
154
|
+
})
|
|
155
|
+
});
|
|
156
|
+
server.endpoint({
|
|
157
|
+
method: 'POST',
|
|
158
|
+
path: `/plugin/${this.pluginInstanceId}/import-csv-new-only`,
|
|
159
|
+
noAuth: true,
|
|
160
|
+
handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body }) {
|
|
161
|
+
const { data } = body;
|
|
162
|
+
const rows = [];
|
|
163
|
+
const columns = Object.keys(data);
|
|
164
|
+
// check column names are valid
|
|
165
|
+
const errors = [];
|
|
166
|
+
columns.forEach((col) => {
|
|
167
|
+
if (!this.resourceConfig.columns.some((c) => c.name === col)) {
|
|
168
|
+
const similar = suggestIfTypo(this.resourceConfig.columns.map((c) => c.name), col);
|
|
169
|
+
errors.push(`Column '${col}' defined in CSV not found in resource '${this.resourceConfig.resourceId}'. ${similar ? `If you mean '${similar}', rename it in CSV` : 'If column is in database but not in resource configuration, add it with showIn:[]'}`);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
if (errors.length > 0) {
|
|
173
|
+
return { ok: false, errors };
|
|
174
|
+
}
|
|
175
|
+
const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
|
|
176
|
+
const columnValues = Object.values(data);
|
|
177
|
+
for (let i = 0; i < columnValues[0].length; i++) {
|
|
178
|
+
const row = {};
|
|
179
|
+
for (let j = 0; j < columns.length; j++) {
|
|
180
|
+
row[columns[j]] = columnValues[j][i];
|
|
181
|
+
}
|
|
182
|
+
rows.push(row);
|
|
183
|
+
}
|
|
184
|
+
let importedCount = 0;
|
|
185
|
+
yield Promise.all(rows.map((row) => __awaiter(this, void 0, void 0, function* () {
|
|
186
|
+
try {
|
|
187
|
+
if (primaryKeyColumn && row[primaryKeyColumn.name]) {
|
|
188
|
+
const existingRecord = yield this.adminforth.resource(this.resourceConfig.resourceId)
|
|
189
|
+
.list([Filters.EQ(primaryKeyColumn.name, row[primaryKeyColumn.name])]);
|
|
190
|
+
if (existingRecord.length > 0) {
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
129
194
|
yield this.adminforth.resource(this.resourceConfig.resourceId).create(row);
|
|
130
195
|
importedCount++;
|
|
131
196
|
}
|
|
@@ -136,5 +201,35 @@ export default class ImportExport extends AdminForthPlugin {
|
|
|
136
201
|
return { ok: true, importedCount, errors };
|
|
137
202
|
})
|
|
138
203
|
});
|
|
204
|
+
server.endpoint({
|
|
205
|
+
method: 'POST',
|
|
206
|
+
path: `/plugin/${this.pluginInstanceId}/check-records`,
|
|
207
|
+
noAuth: true,
|
|
208
|
+
handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body }) {
|
|
209
|
+
const { data } = body;
|
|
210
|
+
const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
|
|
211
|
+
const rows = [];
|
|
212
|
+
const columns = Object.keys(data);
|
|
213
|
+
const columnValues = Object.values(data);
|
|
214
|
+
for (let i = 0; i < columnValues[0].length; i++) {
|
|
215
|
+
const row = {};
|
|
216
|
+
for (let j = 0; j < columns.length; j++) {
|
|
217
|
+
row[columns[j]] = columnValues[j][i];
|
|
218
|
+
}
|
|
219
|
+
rows.push(row);
|
|
220
|
+
}
|
|
221
|
+
const primaryKeys = rows
|
|
222
|
+
.map(row => row[primaryKeyColumn.name])
|
|
223
|
+
.filter(key => key !== undefined && key !== null && key !== '');
|
|
224
|
+
const records = yield this.adminforth.resource(this.resourceConfig.resourceId).list([]);
|
|
225
|
+
const existingRecords = records.filter((record) => primaryKeys.includes(record[primaryKeyColumn.name]));
|
|
226
|
+
return {
|
|
227
|
+
ok: true,
|
|
228
|
+
total: rows.length,
|
|
229
|
+
existingCount: existingRecords.length,
|
|
230
|
+
newCount: rows.length - existingRecords.length
|
|
231
|
+
};
|
|
232
|
+
})
|
|
233
|
+
});
|
|
139
234
|
}
|
|
140
235
|
}
|