Skip to content

Commit 40f3a02

Browse files
committed
initial version
1 parent cbd0e60 commit 40f3a02

File tree

9 files changed

+415
-0
lines changed

9 files changed

+415
-0
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
node_modules
2+
custom/node_modules
3+
dist

custom/ExportCsv.vue

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
<template>
2+
<div @click="exportCsv" class="cursor-pointer flex gap-2 items-center">
3+
{{$t("Export")}} {{ meta.select === 'all' ? $t('All'): $t('Filtered') }} {{$t('to 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+
8+
</div>
9+
</template>
10+
11+
12+
<script setup lang="ts">
13+
14+
import { onMounted, ref } from 'vue';
15+
import { useCoreStore } from '@/stores/core';
16+
import { callAdminForthApi, loadFile } from '@/utils';
17+
import { useFiltersStore } from '@/stores/filters';
18+
import adminforth from '@/adminforth';
19+
20+
21+
const filtersStore = useFiltersStore();
22+
23+
const props = defineProps({
24+
meta: Object,
25+
record: Object,
26+
})
27+
28+
const inProgress = ref(false);
29+
30+
const coreStore = useCoreStore();
31+
32+
33+
onMounted(async () => {
34+
});
35+
36+
function loadFile(data, filename) {
37+
const blob = new Blob([data], { type: 'text/csv' });
38+
const url = window.URL.createObjectURL(blob);
39+
const a = document.createElement('a');
40+
a.href = url;
41+
a.download = filename;
42+
a.click();
43+
window.URL.revokeObjectURL(url);
44+
}
45+
46+
async function exportCsv() {
47+
48+
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(),
55+
}
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`);
64+
adminforth.alert({
65+
message: `Exported ${resp.exportedCount} item${resp.exportedCount > 1 ? 's' : ''} successfully. Check your downloads folder`,
66+
})
67+
}
68+
adminforth.list.closeThreeDotsDropdown();
69+
}
70+
71+
72+
73+
</script>

custom/ImportCsv.vue

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
<template>
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+
8+
</div>
9+
</template>
10+
11+
<script setup lang="ts">
12+
import { ref, Ref } from 'vue';
13+
import { callAdminForthApi } from '@/utils';
14+
import adminforth from '@/adminforth';
15+
16+
const inProgress: Ref<boolean> = ref(false);
17+
18+
const props = defineProps({
19+
meta: Object,
20+
record: Object,
21+
});
22+
23+
async function postData(data: Record<string, string[]>) {
24+
console.log('postData 1 ', data);
25+
26+
const resp = await callAdminForthApi({
27+
path: `/plugin/${props.meta.pluginInstanceId}/import-csv`,
28+
method: 'POST',
29+
body: {
30+
data
31+
}
32+
});
33+
34+
inProgress.value = false;
35+
36+
if (resp.importedCount > 0) {
37+
adminforth.list.refresh();
38+
}
39+
adminforth.alert({
40+
message: `Imported count ${resp.importedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
41+
variant: resp.errors?.length ? (
42+
resp.importedCount ? 'warning' : 'danger'
43+
) : 'success'
44+
});
45+
46+
adminforth.list.closeThreeDotsDropdown();
47+
}
48+
49+
async function importCsv() {
50+
// create file input and open it (with csv type)
51+
inProgress.value = false;
52+
const fileInput = document.createElement('input');
53+
54+
fileInput.type = 'file';
55+
fileInput.accept = '.csv';
56+
fileInput.click();
57+
fileInput.onchange = async (e) => {
58+
inProgress.value = true;
59+
60+
const file = (e.target as HTMLInputElement).files?.[0];
61+
if (!file) {
62+
inProgress.value = false;
63+
return;
64+
}
65+
66+
// post data in format, plain json
67+
// data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
68+
const data = {};
69+
const reader = new FileReader();
70+
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]] = [];
80+
}
81+
data[columns[j]].push(values[j]);
82+
}
83+
}
84+
await postData(data);
85+
};
86+
reader.readAsText(file);
87+
88+
89+
90+
};
91+
92+
}
93+
94+
</script>

custom/tsconfig.json

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
}

index.ts

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators } from "adminforth";
2+
import type { IAdminForth, IHttpServer, AdminForthResourceColumn, AdminForthComponentDeclaration, AdminForthResource } from "adminforth";
3+
import type { PluginOptions } from './types.js';
4+
5+
export default class ImportExport extends AdminForthPlugin {
6+
options: PluginOptions;
7+
emailField: AdminForthResourceColumn;
8+
authResourceId: string;
9+
adminforth: IAdminForth;
10+
11+
constructor(options: PluginOptions) {
12+
super(options, import.meta.url);
13+
this.options = options;
14+
}
15+
16+
async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
17+
super.modifyResourceConfig(adminforth, resourceConfig);
18+
if (!resourceConfig.options.pageInjections) {
19+
resourceConfig.options.pageInjections = {};
20+
}
21+
if (!resourceConfig.options.pageInjections.list) {
22+
resourceConfig.options.pageInjections.list = {};
23+
}
24+
if (!resourceConfig.options.pageInjections.list.threeDotsDropdownItems) {
25+
resourceConfig.options.pageInjections.list.threeDotsDropdownItems = [];
26+
}
27+
(resourceConfig.options.pageInjections.list.threeDotsDropdownItems as AdminForthComponentDeclaration[]).push({
28+
file: this.componentPath('ExportCsv.vue'),
29+
meta: { pluginInstanceId: this.pluginInstanceId, select: 'all' }
30+
}, {
31+
file: this.componentPath('ExportCsv.vue'),
32+
meta: { pluginInstanceId: this.pluginInstanceId, select: 'filtered' }
33+
}, {
34+
file: this.componentPath('ImportCsv.vue'),
35+
meta: { pluginInstanceId: this.pluginInstanceId }
36+
});
37+
38+
39+
// simply modify resourceConfig or adminforth.config. You can get access to plugin options via this.options;
40+
}
41+
42+
validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
43+
// optional method where you can safely check field types after database discovery was performed
44+
}
45+
46+
instanceUniqueRepresentation(pluginOptions: any) : string {
47+
// optional method to return unique string representation of plugin instance.
48+
// Needed if plugin can have multiple instances on one resource
49+
return `${this.pluginInstanceId}`;
50+
}
51+
52+
setupEndpoints(server: IHttpServer) {
53+
server.endpoint({
54+
method: 'POST',
55+
path: `/plugin/${this.pluginInstanceId}/export-csv`,
56+
noAuth: true,
57+
handler: async ({ body }) => {
58+
const { filters, sort } = body;
59+
60+
for (const filter of (filters || [])) {
61+
if (!Object.values(AdminForthFilterOperators).includes(filter.operator)) {
62+
throw new Error(`Operator '${filter.operator}' is not allowed`);
63+
}
64+
if (!this.resourceConfig.columns.some((col) => col.name === filter.field)) {
65+
throw new Error(`Field '${filter.field}' is not in resource '${this.resourceConfig.resourceId}'. Available fields: ${this.resourceConfig.columns.map((col) => col.name).join(', ')}`);
66+
}
67+
if (filter.operator === AdminForthFilterOperators.IN || filter.operator === AdminForthFilterOperators.NIN) {
68+
if (!Array.isArray(filter.value)) {
69+
throw new Error(`Value for operator '${filter.operator}' should be an array`);
70+
}
71+
}
72+
if (filter.operator === AdminForthFilterOperators.IN && filter.value.length === 0) {
73+
// nonsense
74+
return { data: [], total: 0 };
75+
}
76+
}
77+
78+
const data = await this.adminforth.connectors[this.resourceConfig.dataSource].getData({
79+
resource: this.resourceConfig,
80+
limit: 1e6,
81+
offset: 0,
82+
filters,
83+
sort,
84+
getTotals: true,
85+
});
86+
87+
// csv export
88+
89+
const columns = this.resourceConfig.columns.filter((col) => !col.virtual);
90+
let csv = data.data.map((row) => {
91+
return columns.map((col) => {
92+
return row[col.name];
93+
}).join(',');
94+
}).join('\n');
95+
96+
// add headers
97+
const headers = columns.map((col) => col.name).join(',');
98+
csv = `${headers}\n${csv}`;
99+
100+
return { data: csv, exportedCount: data.total, ok: true };
101+
102+
}
103+
});
104+
105+
server.endpoint({
106+
method: 'POST',
107+
path: `/plugin/${this.pluginInstanceId}/import-csv`,
108+
noAuth: true,
109+
handler: async ({ body }) => {
110+
const { data } = body;
111+
// data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
112+
// we need to convert it to [{columnName: value1, columnName2: value1}, {columnName: value2, columnName2: value2}...]
113+
const rows = [];
114+
const columns = Object.keys(data);
115+
116+
// check column names are valid
117+
const errors: string[] = [];
118+
columns.forEach((col) => {
119+
if (!this.resourceConfig.columns.some((c) => c.name === col)) {
120+
const similar = suggestIfTypo(this.resourceConfig.columns.map((c) => c.name), col);
121+
errors.push(`Column '${col}' defined in CSV not found in resource '${this.resourceConfig.resourceId}'. ${
122+
similar ? `If you mean '${similar}', rename it in CSV` : 'If column is in database but not in resource configuration, add it with showIn:[]'}`
123+
);
124+
}
125+
});
126+
if (errors.length > 0) {
127+
return { ok: false, errors };
128+
}
129+
130+
const columnValues: any[] = Object.values(data);
131+
for (let i = 0; i < columnValues[0].length; i++) {
132+
const row = {};
133+
for (let j = 0; j < columns.length; j++) {
134+
row[columns[j]] = columnValues[j][i];
135+
}
136+
rows.push(row);
137+
}
138+
139+
let importedCount = 0;
140+
await Promise.all(rows.map(async (row) => {
141+
try {
142+
await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
143+
importedCount++;
144+
} catch (e) {
145+
errors.push(e.message);
146+
}
147+
}));
148+
149+
150+
return { ok: true, importedCount, errors};
151+
152+
}
153+
});
154+
155+
}
156+
157+
}

package-lock.json

Lines changed: 37 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)