Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 77 additions & 17 deletions custom/ImportCsv.vue
Original file line number Diff line number Diff line change
@@ -1,44 +1,79 @@
<template>
<div @click="importCsv" class="cursor-pointer flex gap-2 items-center">
{{$t('Import from CSV')}}
<div @click="importCsv" class="cursor-pointer flex gap-2 items-center">
{{$t('Import from CSV')}}

<svg v-if="inProgress"
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>

</div>
<svg v-if="inProgress"
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>
</div>
<Dialog ref="confirmDialog"
header="Import Confirmation"
:buttons="[
{ label: 'Import & Replace', onclick: (dialog) => { confirmImport(dialog) } },
{ label: 'Import New Only', onclick: (dialog) => { confirmImportNewOnly(dialog) } },
{ label: 'Cancel', onclick: (dialog) => dialog.hide() }
]"
>
<div v-if="importStats">
<p>Are you sure you want to continue?</p>
<p class="mt-2">You are importing {{ importStats.total }} records:</p>
<ul class="list-disc ml-6 mt-2">
<li>{{ importStats.existingCount }} existing records will be replaced</li>
<li>{{ importStats.newCount }} new records will be added</li>
</ul>
</div>
</Dialog>
</template>

<script setup lang="ts">
import { ref, Ref } from 'vue';
import { callAdminForthApi } from '@/utils';
import adminforth from '@/adminforth';
import Papa from 'papaparse';
import { Dialog } from '@/afcl';

const inProgress: Ref<boolean> = ref(false);

const confirmDialog = ref(null);
const importStats = ref(null);
const pendingData = ref(null);
const props = defineProps({
meta: Object,
record: Object,
});

async function postData(data: Record<string, string[]>) {
console.log('postData 1 ', data);
async function confirmImport(dialog) {
dialog.hide();
await postData(pendingData.value);
}

async function checkRecords(data: Record<string, string[]>) {
const resp = await callAdminForthApi({
path: `/plugin/${props.meta.pluginInstanceId}/check-records`,
method: 'POST',
body: { data }
});

return resp;
}

async function confirmImportNewOnly(dialog) {
dialog.hide();
await postDataNewOnly(pendingData.value);
}

async function postData(data: Record<string, string[]>, skipDuplicates: boolean = false) {
const resp = await callAdminForthApi({
path: `/plugin/${props.meta.pluginInstanceId}/import-csv`,
method: 'POST',
body: {
data
}
body: { data }
});

inProgress.value = false;

if (resp.importedCount > 0) {
if (resp.importedCount > 0 || resp.updatedCount > 0) {
adminforth.list.refresh();
}
adminforth.alert({
message: `Imported count ${resp.importedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
message: `Imported ${resp.importedCount || 0} records. Updated ${resp.updatedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
variant: resp.errors?.length ? (
resp.importedCount ? 'warning' : 'danger'
) : 'success'
Expand All @@ -47,8 +82,26 @@ async function postData(data: Record<string, string[]>) {
adminforth.list.closeThreeDotsDropdown();
}

async function postDataNewOnly(data: Record<string, string[]>) {
const resp = await callAdminForthApi({
path: `/plugin/${props.meta.pluginInstanceId}/import-csv-new-only`,
method: 'POST',
body: { data }
});

inProgress.value = false;
if (resp.importedCount > 0) {
adminforth.list.refresh();
}
adminforth.alert({
message: `Imported ${resp.importedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
variant: resp.errors?.length ? 'warning' : 'success'
});

adminforth.list.closeThreeDotsDropdown();
}

async function importCsv() {
// create file input and open it (with csv type)
inProgress.value = false;
const fileInput = document.createElement('input');

Expand All @@ -63,7 +116,6 @@ async function importCsv() {
inProgress.value = false;
return;
}

const reader = new FileReader();
reader.onload = async (e) => {
try {
Expand All @@ -72,6 +124,7 @@ async function importCsv() {
Papa.parse(text, {
header: true,
skipEmptyLines: true,

complete: async (results) => {
if (results.errors.length > 0) {
throw new Error(`CSV parsing errors: ${results.errors.map(e => e.message).join(', ')}`);
Expand All @@ -86,7 +139,14 @@ async function importCsv() {
data[column] = rows.map(row => row[column]);
});

await postData(data);
// Store data for later use
pendingData.value = data;

// Check records and show confirmation
const stats = await checkRecords(data);
importStats.value = stats;
confirmDialog.value?.open();
inProgress.value = false;
},
error: (error) => {
throw new Error(`Failed to parse CSV: ${error.message}`);
Expand Down
124 changes: 117 additions & 7 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators } from "adminforth";
import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators, Filters } from "adminforth";
import type { IAdminForth, IHttpServer, AdminForthResourceColumn, AdminForthComponentDeclaration, AdminForthResource } from "adminforth";
import type { PluginOptions } from './types.js';

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

Expand Down Expand Up @@ -143,21 +141,133 @@ export default class ImportExport extends AdminForthPlugin {
}

let importedCount = 0;
let updatedCount = 0;
const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);

await Promise.all(rows.map(async (row) => {
try {
await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
importedCount++;
if (primaryKeyColumn && row[primaryKeyColumn.name]) {
const existingRecord = await this.adminforth.resource(this.resourceConfig.resourceId)
.list([Filters.EQ(primaryKeyColumn.name, row[primaryKeyColumn.name])]);

if (existingRecord.length > 0) {
await this.adminforth.resource(this.resourceConfig.resourceId)
.update(row[primaryKeyColumn.name], row);
updatedCount++;
return;
}
}
await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
importedCount++;
} catch (e) {
errors.push(e.message);
errors.push(e.message);
}
}));

return { ok: true, importedCount, updatedCount, errors };
}
});

server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/import-csv-new-only`,
noAuth: true,
handler: async ({ body }) => {
const { data } = body;
const rows = [];
const columns = Object.keys(data);

// check column names are valid
const errors: string[] = [];
columns.forEach((col) => {
if (!this.resourceConfig.columns.some((c) => c.name === col)) {
const similar = suggestIfTypo(this.resourceConfig.columns.map((c) => c.name), col);
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:[]'}`
);
}
});
if (errors.length > 0) {
return { ok: false, errors };
}

return { ok: true, importedCount, errors};
const columnValues: any[] = Object.values(data);
for (let i = 0; i < columnValues[0].length; i++) {
const row = {};
for (let j = 0; j < columns.length; j++) {
row[columns[j]] = columnValues[j][i];
}
rows.push(row);
}

let importedCount = 0;
const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);

await Promise.all(rows.map(async (row) => {
try {
if (primaryKeyColumn && row[primaryKeyColumn.name]) {
const existingRecord = await this.adminforth.resource(this.resourceConfig.resourceId)
.list([Filters.EQ(primaryKeyColumn.name, row[primaryKeyColumn.name])]);

if (existingRecord.length > 0) {
return;
}
}
await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
importedCount++;
} catch (e) {
errors.push(e.message);
}
}));

return { ok: true, importedCount, errors };
}
});

server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/check-records`,
noAuth: true,
handler: async ({ body }) => {
const { data } = body;

const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
if (!primaryKeyColumn) {
return {
ok: true,
total: Object.values(data)[0].length,
existingCount: 0,
newCount: Object.values(data)[0].length
};
}

const rows = [];
const columns = Object.keys(data);
const columnValues = Object.values(data);
for (let i = 0; i < columnValues[0].length; i++) {
const row = {};
for (let j = 0; j < columns.length; j++) {
row[columns[j]] = columnValues[j][i];
}
rows.push(row);
}

const primaryKeys = rows
.map(row => row[primaryKeyColumn.name])
.filter(key => key !== undefined && key !== null && key !== '');

const records = await this.adminforth.resource(this.resourceConfig.resourceId).list([])

const existingRecords = records.filter((record) => primaryKeys.includes(record[primaryKeyColumn.name]));

return {
ok: true,
total: rows.length,
existingCount: existingRecords.length,
newCount: rows.length - existingRecords.length
};
}
});
}

}