@adminforth/import-export 1.0.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.
@@ -0,0 +1,71 @@
1
+ <template>
2
+ <div @click="exportCsv" class="cursor-pointer flex gap-2 items-center">
3
+ Export {{ meta.select === 'all' ? 'All': 'Filtered' }} 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
+
19
+
20
+ const filtersStore = useFiltersStore();
21
+
22
+ const props = defineProps({
23
+ meta: Object,
24
+ record: Object,
25
+ })
26
+
27
+ const inProgress = ref(false);
28
+
29
+ const coreStore = useCoreStore();
30
+
31
+
32
+ onMounted(async () => {
33
+ });
34
+
35
+ function loadFile(data, filename) {
36
+ const blob = new Blob([data], { type: 'text/csv' });
37
+ const url = window.URL.createObjectURL(blob);
38
+ const a = document.createElement('a');
39
+ a.href = url;
40
+ a.download = filename;
41
+ a.click();
42
+ window.URL.revokeObjectURL(url);
43
+ }
44
+
45
+ async function exportCsv() {
46
+
47
+ inProgress.value = true;
48
+ const resp = await callAdminForthApi({
49
+ path: `/plugin/${props.meta.pluginInstanceId}/export-csv`,
50
+ method: 'POST',
51
+ body: {
52
+ filters: props.meta.select === 'all' ? [] : filtersStore.getFilters(),
53
+ sort: filtersStore.getSort(),
54
+ }
55
+ });
56
+ inProgress.value = false;
57
+ if (resp.error) {
58
+ window.adminforth.alert({
59
+ message: resp.error,
60
+ })
61
+ } else {
62
+ loadFile(resp.data, `export-${coreStore.resource.resourceId}-${new Date().toISOString()}.csv`);
63
+ window.adminforth.alert({
64
+ message: 'Exported successfully. Check your downloads folder',
65
+ })
66
+ }
67
+ }
68
+
69
+
70
+
71
+ </script>
@@ -0,0 +1,89 @@
1
+ <template>
2
+ <div @click="importCsv" class="cursor-pointer flex gap-2 items-center">
3
+ 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
+
15
+ const inProgress: Ref<boolean> = ref(false);
16
+
17
+ const props = defineProps({
18
+ meta: Object,
19
+ record: Object,
20
+ });
21
+
22
+ async function postData(data: Record<string, string[]>) {
23
+ console.log('postData 1 ', data);
24
+
25
+ const resp = await callAdminForthApi({
26
+ path: `/plugin/${props.meta.pluginInstanceId}/import-csv`,
27
+ method: 'POST',
28
+ body: {
29
+ data
30
+ }
31
+ });
32
+
33
+ inProgress.value = false;
34
+
35
+ window.adminforth.alert({
36
+ message: `Imported count ${resp.importedCount} records. ${resp.errors.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
37
+ variant: resp.errors.length ? (
38
+ resp.importedCount ? 'warning' : 'danger'
39
+ ) : 'success'
40
+ });
41
+ }
42
+
43
+ async function importCsv() {
44
+ // create file input and open it (with csv type)
45
+ inProgress.value = false;
46
+ const fileInput = document.createElement('input');
47
+
48
+ fileInput.type = 'file';
49
+ fileInput.accept = '.csv';
50
+ fileInput.click();
51
+ fileInput.onchange = async (e) => {
52
+ inProgress.value = true;
53
+
54
+ const file = (e.target as HTMLInputElement).files?.[0];
55
+ if (!file) {
56
+ inProgress.value = false;
57
+ return;
58
+ }
59
+
60
+ // post data in format, plain json
61
+ // data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
62
+ const data = {};
63
+ const reader = new FileReader();
64
+ reader.onload = async (e) => {
65
+ const text = e.target.result as string;
66
+ console.log('fileInput.onchange 3 ', text);
67
+
68
+ const lines = text.split('\n');
69
+ const columns = lines[0].split(',');
70
+ for (let i = 1; i < lines.length; i++) {
71
+ const values = lines[i].split(',');
72
+ for (let j = 0; j < columns.length; j++) {
73
+ if (!data[columns[j]]) {
74
+ data[columns[j]] = [];
75
+ }
76
+ data[columns[j]].push(values[j]);
77
+ }
78
+ }
79
+ await postData(data);
80
+ };
81
+ reader.readAsText(file);
82
+
83
+
84
+
85
+ };
86
+
87
+ }
88
+
89
+ </script>
package/index.ts ADDED
@@ -0,0 +1,143 @@
1
+ import AdminForth, { AdminForthPlugin, Filters, 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, total: 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
+ const columnValues: any[] = Object.values(data);
116
+ for (let i = 0; i < columnValues[0].length; i++) {
117
+ const row = {};
118
+ for (let j = 0; j < columns.length; j++) {
119
+ row[columns[j]] = columnValues[j][i];
120
+ }
121
+ rows.push(row);
122
+ }
123
+
124
+ const errors: string[] = [];
125
+ let importedCount = 0;
126
+ await Promise.all(rows.map(async (row) => {
127
+ try {
128
+ await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
129
+ importedCount++;
130
+ } catch (e) {
131
+ errors.push(e.message);
132
+ }
133
+ }));
134
+
135
+
136
+ return { ok: true, importedCount, errors};
137
+
138
+ }
139
+ });
140
+
141
+ }
142
+
143
+ }
package/package.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "name": "@adminforth/import-export",
3
+ "version": "1.0.0",
4
+ "main": "dist/index.js",
5
+ "types": "dist/index.d.ts",
6
+ "type": "module",
7
+ "scripts": {
8
+ "build": "tsc && rsync -av --exclude 'node_modules' custom dist/ && npm version patch",
9
+ "rollout": "npm publish --access public"
10
+ },
11
+ "keywords": [],
12
+ "author": "",
13
+ "license": "ISC",
14
+ "description": "",
15
+ "devDependencies": {
16
+ "@types/node": "^22.6.1",
17
+ "adminforth": "file:../..",
18
+ "typescript": "^5.6.2"
19
+ },
20
+ "dependencies": {
21
+ }
22
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include*/
4
+ "module": "node16", /* Specify what module code is generated. */
5
+ "outDir": "./dist", /* Specify an output folder for all emitted files. */
6
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. */
7
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
8
+ "strict": false, /* Enable all strict type-checking options. */
9
+ "skipLibCheck": true, /* Skip type checking all .d.ts files. */
10
+ },
11
+ "exclude": ["node_modules", "dist", "custom"], /* Exclude files from compilation. */
12
+ }
package/types.ts ADDED
@@ -0,0 +1,3 @@
1
+ export interface PluginOptions {
2
+
3
+ }