Skip to content

Commit f447857

Browse files
authored
Merge pull request #4 from devforth/import-csv
feat: add support for importing new records only and updating existin…
2 parents 7e8c745 + f867b36 commit f447857

File tree

2 files changed

+194
-24
lines changed

2 files changed

+194
-24
lines changed

custom/ImportCsv.vue

Lines changed: 77 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,79 @@
11
<template>
2-
<div @click="importCsv" class="cursor-pointer flex gap-2 items-center">
3-
{{$t('Import from CSV')}}
2+
<div @click="importCsv" class="cursor-pointer flex gap-2 items-center">
3+
{{$t('Import from CSV')}}
44

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-
8-
</div>
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="Import Confirmation"
10+
:buttons="[
11+
{ label: 'Import & Replace', onclick: (dialog) => { confirmImport(dialog) } },
12+
{ label: 'Import New Only', onclick: (dialog) => { confirmImportNewOnly(dialog) } },
13+
{ label: 'Cancel', onclick: (dialog) => dialog.hide() }
14+
]"
15+
>
16+
<div v-if="importStats">
17+
<p>Are you sure you want to continue?</p>
18+
<p class="mt-2">You are importing {{ importStats.total }} records:</p>
19+
<ul class="list-disc ml-6 mt-2">
20+
<li>{{ importStats.existingCount }} existing records will be replaced</li>
21+
<li>{{ importStats.newCount }} new records will be added</li>
22+
</ul>
23+
</div>
24+
</Dialog>
925
</template>
1026

1127
<script setup lang="ts">
1228
import { ref, Ref } from 'vue';
1329
import { callAdminForthApi } from '@/utils';
1430
import adminforth from '@/adminforth';
1531
import Papa from 'papaparse';
32+
import { Dialog } from '@/afcl';
1633
1734
const inProgress: Ref<boolean> = ref(false);
18-
35+
const confirmDialog = ref(null);
36+
const importStats = ref(null);
37+
const pendingData = ref(null);
1938
const props = defineProps({
2039
meta: Object,
2140
record: Object,
2241
});
2342
24-
async function postData(data: Record<string, string[]>) {
25-
console.log('postData 1 ', data);
43+
async function confirmImport(dialog) {
44+
dialog.hide();
45+
await postData(pendingData.value);
46+
}
2647
48+
async function checkRecords(data: Record<string, string[]>) {
49+
const resp = await callAdminForthApi({
50+
path: `/plugin/${props.meta.pluginInstanceId}/check-records`,
51+
method: 'POST',
52+
body: { data }
53+
});
54+
55+
return resp;
56+
}
57+
58+
async function confirmImportNewOnly(dialog) {
59+
dialog.hide();
60+
await postDataNewOnly(pendingData.value);
61+
}
62+
63+
async function postData(data: Record<string, string[]>, skipDuplicates: boolean = false) {
2764
const resp = await callAdminForthApi({
2865
path: `/plugin/${props.meta.pluginInstanceId}/import-csv`,
2966
method: 'POST',
30-
body: {
31-
data
32-
}
67+
body: { data }
3368
});
3469
3570
inProgress.value = false;
3671
37-
if (resp.importedCount > 0) {
72+
if (resp.importedCount > 0 || resp.updatedCount > 0) {
3873
adminforth.list.refresh();
3974
}
4075
adminforth.alert({
41-
message: `Imported count ${resp.importedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
76+
message: `Imported ${resp.importedCount || 0} records. Updated ${resp.updatedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
4277
variant: resp.errors?.length ? (
4378
resp.importedCount ? 'warning' : 'danger'
4479
) : 'success'
@@ -47,8 +82,26 @@ async function postData(data: Record<string, string[]>) {
4782
adminforth.list.closeThreeDotsDropdown();
4883
}
4984
85+
async function postDataNewOnly(data: Record<string, string[]>) {
86+
const resp = await callAdminForthApi({
87+
path: `/plugin/${props.meta.pluginInstanceId}/import-csv-new-only`,
88+
method: 'POST',
89+
body: { data }
90+
});
91+
92+
inProgress.value = false;
93+
if (resp.importedCount > 0) {
94+
adminforth.list.refresh();
95+
}
96+
adminforth.alert({
97+
message: `Imported ${resp.importedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
98+
variant: resp.errors?.length ? 'warning' : 'success'
99+
});
100+
101+
adminforth.list.closeThreeDotsDropdown();
102+
}
103+
50104
async function importCsv() {
51-
// create file input and open it (with csv type)
52105
inProgress.value = false;
53106
const fileInput = document.createElement('input');
54107
@@ -63,7 +116,6 @@ async function importCsv() {
63116
inProgress.value = false;
64117
return;
65118
}
66-
67119
const reader = new FileReader();
68120
reader.onload = async (e) => {
69121
try {
@@ -72,6 +124,7 @@ async function importCsv() {
72124
Papa.parse(text, {
73125
header: true,
74126
skipEmptyLines: true,
127+
75128
complete: async (results) => {
76129
if (results.errors.length > 0) {
77130
throw new Error(`CSV parsing errors: ${results.errors.map(e => e.message).join(', ')}`);
@@ -86,7 +139,14 @@ async function importCsv() {
86139
data[column] = rows.map(row => row[column]);
87140
});
88141
89-
await postData(data);
142+
// Store data for later use
143+
pendingData.value = data;
144+
145+
// Check records and show confirmation
146+
const stats = await checkRecords(data);
147+
importStats.value = stats;
148+
confirmDialog.value?.open();
149+
inProgress.value = false;
90150
},
91151
error: (error) => {
92152
throw new Error(`Failed to parse CSV: ${error.message}`);

index.ts

Lines changed: 117 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators } from "adminforth";
1+
import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators, Filters } from "adminforth";
22
import type { IAdminForth, IHttpServer, AdminForthResourceColumn, AdminForthComponentDeclaration, AdminForthResource } from "adminforth";
33
import type { PluginOptions } from './types.js';
44

@@ -114,8 +114,6 @@ export default class ImportExport extends AdminForthPlugin {
114114
noAuth: true,
115115
handler: async ({ body }) => {
116116
const { data } = body;
117-
// data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
118-
// we need to convert it to [{columnName: value1, columnName2: value1}, {columnName: value2, columnName2: value2}...]
119117
const rows = [];
120118
const columns = Object.keys(data);
121119

@@ -143,21 +141,133 @@ export default class ImportExport extends AdminForthPlugin {
143141
}
144142

145143
let importedCount = 0;
144+
let updatedCount = 0;
145+
const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
146+
146147
await Promise.all(rows.map(async (row) => {
147148
try {
148-
await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
149-
importedCount++;
149+
if (primaryKeyColumn && row[primaryKeyColumn.name]) {
150+
const existingRecord = await this.adminforth.resource(this.resourceConfig.resourceId)
151+
.list([Filters.EQ(primaryKeyColumn.name, row[primaryKeyColumn.name])]);
152+
153+
if (existingRecord.length > 0) {
154+
await this.adminforth.resource(this.resourceConfig.resourceId)
155+
.update(row[primaryKeyColumn.name], row);
156+
updatedCount++;
157+
return;
158+
}
159+
}
160+
await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
161+
importedCount++;
150162
} catch (e) {
151-
errors.push(e.message);
163+
errors.push(e.message);
152164
}
153165
}));
154166

167+
return { ok: true, importedCount, updatedCount, errors };
168+
}
169+
});
170+
171+
server.endpoint({
172+
method: 'POST',
173+
path: `/plugin/${this.pluginInstanceId}/import-csv-new-only`,
174+
noAuth: true,
175+
handler: async ({ body }) => {
176+
const { data } = body;
177+
const rows = [];
178+
const columns = Object.keys(data);
179+
180+
// check column names are valid
181+
const errors: string[] = [];
182+
columns.forEach((col) => {
183+
if (!this.resourceConfig.columns.some((c) => c.name === col)) {
184+
const similar = suggestIfTypo(this.resourceConfig.columns.map((c) => c.name), col);
185+
errors.push(`Column '${col}' defined in CSV not found in resource '${this.resourceConfig.resourceId}'. ${
186+
similar ? `If you mean '${similar}', rename it in CSV` : 'If column is in database but not in resource configuration, add it with showIn:[]'}`
187+
);
188+
}
189+
});
190+
if (errors.length > 0) {
191+
return { ok: false, errors };
192+
}
155193

156-
return { ok: true, importedCount, errors};
194+
const columnValues: any[] = Object.values(data);
195+
for (let i = 0; i < columnValues[0].length; i++) {
196+
const row = {};
197+
for (let j = 0; j < columns.length; j++) {
198+
row[columns[j]] = columnValues[j][i];
199+
}
200+
rows.push(row);
201+
}
157202

203+
let importedCount = 0;
204+
const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
205+
206+
await Promise.all(rows.map(async (row) => {
207+
try {
208+
if (primaryKeyColumn && row[primaryKeyColumn.name]) {
209+
const existingRecord = await this.adminforth.resource(this.resourceConfig.resourceId)
210+
.list([Filters.EQ(primaryKeyColumn.name, row[primaryKeyColumn.name])]);
211+
212+
if (existingRecord.length > 0) {
213+
return;
214+
}
215+
}
216+
await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
217+
importedCount++;
218+
} catch (e) {
219+
errors.push(e.message);
220+
}
221+
}));
222+
223+
return { ok: true, importedCount, errors };
158224
}
159225
});
160226

227+
server.endpoint({
228+
method: 'POST',
229+
path: `/plugin/${this.pluginInstanceId}/check-records`,
230+
noAuth: true,
231+
handler: async ({ body }) => {
232+
const { data } = body;
233+
234+
const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
235+
if (!primaryKeyColumn) {
236+
return {
237+
ok: true,
238+
total: Object.values(data)[0].length,
239+
existingCount: 0,
240+
newCount: Object.values(data)[0].length
241+
};
242+
}
243+
244+
const rows = [];
245+
const columns = Object.keys(data);
246+
const columnValues = Object.values(data);
247+
for (let i = 0; i < columnValues[0].length; i++) {
248+
const row = {};
249+
for (let j = 0; j < columns.length; j++) {
250+
row[columns[j]] = columnValues[j][i];
251+
}
252+
rows.push(row);
253+
}
254+
255+
const primaryKeys = rows
256+
.map(row => row[primaryKeyColumn.name])
257+
.filter(key => key !== undefined && key !== null && key !== '');
258+
259+
const records = await this.adminforth.resource(this.resourceConfig.resourceId).list([])
260+
261+
const existingRecords = records.filter((record) => primaryKeys.includes(record[primaryKeyColumn.name]));
262+
263+
return {
264+
ok: true,
265+
total: rows.length,
266+
existingCount: existingRecords.length,
267+
newCount: rows.length - existingRecords.length
268+
};
269+
}
270+
});
161271
}
162272

163273
}

0 commit comments

Comments
 (0)