@adminforth/import-export 1.0.0 → 1.0.1-next.1

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,13 @@
1
+
2
+ #!/bin/bash
3
+
4
+ # write npm run output both to console and to build.log
5
+ npm run build 2>&1 | tee build.log
6
+ build_status=${PIPESTATUS[0]}
7
+
8
+ # if exist status from the npm run build is not 0
9
+ # then exit with the status code from the npm run build
10
+ if [ $build_status -ne 0 ]; then
11
+ echo "Build failed. Exiting with status code $build_status"
12
+ exit $build_status
13
+ fi
@@ -0,0 +1,44 @@
1
+ #!/bin/sh
2
+
3
+ set -x
4
+
5
+ COMMIT_SHORT_SHA=$(echo $CI_COMMIT_SHA | cut -c1-8)
6
+
7
+
8
+ if [ "$CI_STEP_STATUS" = "success" ]; then
9
+ MESSAGE="Did a build without issues on \`$CI_REPO_NAME/$CI_COMMIT_BRANCH\`. Commit: _${CI_COMMIT_MESSAGE}_ (<$CI_COMMIT_URL|$COMMIT_SHORT_SHA>)"
10
+
11
+ curl -s -X POST -H "Content-Type: application/json" -d '{
12
+ "username": "'"$CI_COMMIT_AUTHOR"'",
13
+ "icon_url": "'"$CI_COMMIT_AUTHOR_AVATAR"'",
14
+ "attachments": [
15
+ {
16
+ "mrkdwn_in": ["text", "pretext"],
17
+ "color": "#36a64f",
18
+ "text": "'"$MESSAGE"'"
19
+ }
20
+ ]
21
+ }' "$DEVELOPERS_SLACK_WEBHOOK"
22
+ exit 0
23
+ fi
24
+ export BUILD_LOG=$(cat ./build.log)
25
+
26
+ BUILD_LOG=$(echo $BUILD_LOG | sed 's/"/\\"/g')
27
+
28
+ MESSAGE="Broke \`$CI_REPO_NAME/$CI_COMMIT_BRANCH\` with commit _${CI_COMMIT_MESSAGE}_ (<$CI_COMMIT_URL|$COMMIT_SHORT_SHA>)"
29
+ CODE_BLOCK="\`\`\`$BUILD_LOG\n\`\`\`"
30
+
31
+ echo "Sending slack message to developers $MESSAGE"
32
+ # Send the message
33
+ curl -sS -X POST -H "Content-Type: application/json" -d '{
34
+ "username": "'"$CI_COMMIT_AUTHOR"'",
35
+ "icon_url": "'"$CI_COMMIT_AUTHOR_AVATAR"'",
36
+ "attachments": [
37
+ {
38
+ "mrkdwn_in": ["text", "pretext"],
39
+ "color": "#8A1C12",
40
+ "text": "'"$CODE_BLOCK"'",
41
+ "pretext": "'"$MESSAGE"'"
42
+ }
43
+ ]
44
+ }' "$DEVELOPERS_SLACK_WEBHOOK" 2>&1
@@ -0,0 +1,44 @@
1
+ clone:
2
+ git:
3
+ image: woodpeckerci/plugin-git
4
+ settings:
5
+ partial: false
6
+ depth: 5
7
+
8
+ steps:
9
+ init-secrets:
10
+ when:
11
+ - event: push
12
+ image: infisical/cli
13
+ environment:
14
+ INFISICAL_TOKEN:
15
+ from_secret: VAULT_TOKEN
16
+ commands:
17
+ - infisical export --domain https://vault.devforth.io/api --format=dotenv-export --env="prod" > /woodpecker/deploy.vault.env
18
+ secrets:
19
+ - VAULT_TOKEN
20
+
21
+ release:
22
+ image: node:20
23
+ when:
24
+ - event: push
25
+ volumes:
26
+ - /var/run/docker.sock:/var/run/docker.sock
27
+ commands:
28
+ - apt update && apt install -y rsync
29
+ - export $(cat /woodpecker/deploy.vault.env | xargs)
30
+ - npm clean-install
31
+ - /bin/bash ./.woodpecker/buildRelease.sh
32
+ - npm audit signatures
33
+ - npx semantic-release
34
+
35
+ slack-on-failure:
36
+ when:
37
+ - event: push
38
+ status: [failure, success]
39
+ - event: push
40
+ image: curlimages/curl
41
+ commands:
42
+ - export $(cat /woodpecker/deploy.vault.env | xargs)
43
+ - /bin/sh ./.woodpecker/buildSlackNotify.sh
44
+
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+
2
+ # Changelog
3
+
4
+ The complete changelog is available on the [GitHub Releases page](https://github.com/devforth/adminforth-import-export/releases).
5
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Devforth.io
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # AdminForth ImportExport Plugin
2
+
3
+ <img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT" /> <img src="https://woodpecker.devforth.io/api/badges/3848/status.svg" alt="Build Status" /> <a href="https://www.npmjs.com/package/@adminforth/import-export"> <img src="https://img.shields.io/npm/dt/@adminforth/import-export" alt="npm downloads" /></a> <a href="https://www.npmjs.com/package/@adminforth/import-export"><img src="https://img.shields.io/npm/v/@adminforth/import-export" alt="npm version" /></a> <a href="https://www.npmjs.com/package/@adminforth/import-export">
4
+
5
+ Allows to add import/export to csv options to an adminforth table.
6
+
7
+ ## For usage, see [AdminForth ImportExport Documentation](https://adminforth.dev/docs/tutorial/Plugins/import-export/)
package/build.log ADDED
@@ -0,0 +1,12 @@
1
+
2
+ > @adminforth/import-export@1.0.4 build
3
+ > tsc && rsync -av --exclude 'node_modules' custom dist/
4
+
5
+ sending incremental file list
6
+ custom/
7
+ custom/ExportCsv.vue
8
+ custom/ImportCsv.vue
9
+ custom/tsconfig.json
10
+
11
+ sent 7,103 bytes received 77 bytes 14,360.00 bytes/sec
12
+ total size is 6,822 speedup is 0.95
@@ -1,6 +1,6 @@
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>
@@ -15,6 +15,7 @@ import { onMounted, ref } from 'vue';
15
15
  import { useCoreStore } from '@/stores/core';
16
16
  import { callAdminForthApi, loadFile } from '@/utils';
17
17
  import { useFiltersStore } from '@/stores/filters';
18
+ import adminforth from '@/adminforth';
18
19
 
19
20
 
20
21
  const filtersStore = useFiltersStore();
@@ -55,15 +56,16 @@ async function exportCsv() {
55
56
  });
56
57
  inProgress.value = false;
57
58
  if (resp.error) {
58
- window.adminforth.alert({
59
+ adminforth.alert({
59
60
  message: resp.error,
60
61
  })
61
62
  } else {
62
63
  loadFile(resp.data, `export-${coreStore.resource.resourceId}-${new Date().toISOString()}.csv`);
63
- window.adminforth.alert({
64
- message: 'Exported successfully. Check your downloads folder',
64
+ adminforth.alert({
65
+ message: `Exported ${resp.exportedCount} item${resp.exportedCount > 1 ? 's' : ''} successfully. Check your downloads folder`,
65
66
  })
66
67
  }
68
+ adminforth.list.closeThreeDotsDropdown();
67
69
  }
68
70
 
69
71
 
@@ -1,6 +1,6 @@
1
1
  <template>
2
2
  <div @click="importCsv" class="cursor-pointer flex gap-2 items-center">
3
- Import from CSV
3
+ {{$t('Import from 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>
@@ -11,6 +11,7 @@
11
11
  <script setup lang="ts">
12
12
  import { ref, Ref } from 'vue';
13
13
  import { callAdminForthApi } from '@/utils';
14
+ import adminforth from '@/adminforth';
14
15
 
15
16
  const inProgress: Ref<boolean> = ref(false);
16
17
 
@@ -31,13 +32,18 @@ async function postData(data: Record<string, string[]>) {
31
32
  });
32
33
 
33
34
  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 ? (
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 ? (
38
42
  resp.importedCount ? 'warning' : 'danger'
39
43
  ) : 'success'
40
44
  });
45
+
46
+ adminforth.list.closeThreeDotsDropdown();
41
47
  }
42
48
 
43
49
  async function importCsv() {
@@ -63,7 +69,6 @@ async function importCsv() {
63
69
  const reader = new FileReader();
64
70
  reader.onload = async (e) => {
65
71
  const text = e.target.result as string;
66
- console.log('fileInput.onchange 3 ', text);
67
72
 
68
73
  const lines = text.split('\n');
69
74
  const columns = lines[0].split(',');
@@ -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
+ }
@@ -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>
@@ -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>
@@ -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 ADDED
@@ -0,0 +1,123 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { AdminForthPlugin, suggestIfTypo } from "adminforth";
11
+ export default class ImportExport extends AdminForthPlugin {
12
+ constructor(options) {
13
+ super(options, import.meta.url);
14
+ this.options = options;
15
+ }
16
+ modifyResourceConfig(adminforth, resourceConfig) {
17
+ const _super = Object.create(null, {
18
+ modifyResourceConfig: { get: () => super.modifyResourceConfig }
19
+ });
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ _super.modifyResourceConfig.call(this, adminforth, resourceConfig);
22
+ if (!resourceConfig.options.pageInjections) {
23
+ resourceConfig.options.pageInjections = {};
24
+ }
25
+ if (!resourceConfig.options.pageInjections.list) {
26
+ resourceConfig.options.pageInjections.list = {};
27
+ }
28
+ if (!resourceConfig.options.pageInjections.list.threeDotsDropdownItems) {
29
+ resourceConfig.options.pageInjections.list.threeDotsDropdownItems = [];
30
+ }
31
+ resourceConfig.options.pageInjections.list.threeDotsDropdownItems.push({
32
+ file: this.componentPath('ExportCsv.vue'),
33
+ meta: { pluginInstanceId: this.pluginInstanceId, select: 'all' }
34
+ }, {
35
+ file: this.componentPath('ExportCsv.vue'),
36
+ meta: { pluginInstanceId: this.pluginInstanceId, select: 'filtered' }
37
+ }, {
38
+ file: this.componentPath('ImportCsv.vue'),
39
+ meta: { pluginInstanceId: this.pluginInstanceId }
40
+ });
41
+ // simply modify resourceConfig or adminforth.config. You can get access to plugin options via this.options;
42
+ });
43
+ }
44
+ validateConfigAfterDiscover(adminforth, resourceConfig) {
45
+ // optional method where you can safely check field types after database discovery was performed
46
+ }
47
+ instanceUniqueRepresentation(pluginOptions) {
48
+ // optional method to return unique string representation of plugin instance.
49
+ // Needed if plugin can have multiple instances on one resource
50
+ return `${this.pluginInstanceId}`;
51
+ }
52
+ setupEndpoints(server) {
53
+ server.endpoint({
54
+ method: 'POST',
55
+ path: `/plugin/${this.pluginInstanceId}/export-csv`,
56
+ noAuth: true,
57
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body }) {
58
+ const { filters, sort } = body;
59
+ const data = yield this.adminforth.connectors[this.resourceConfig.dataSource].getData({
60
+ resource: this.resourceConfig,
61
+ limit: 1e6,
62
+ offset: 0,
63
+ filters: this.adminforth.connectors[this.resourceConfig.dataSource].validateAndNormalizeInputFilters(filters),
64
+ sort,
65
+ getTotals: true,
66
+ });
67
+ // csv export
68
+ const columns = this.resourceConfig.columns.filter((col) => !col.virtual);
69
+ let csv = data.data.map((row) => {
70
+ return columns.map((col) => {
71
+ return row[col.name];
72
+ }).join(',');
73
+ }).join('\n');
74
+ // add headers
75
+ const headers = columns.map((col) => col.name).join(',');
76
+ csv = `${headers}\n${csv}`;
77
+ return { data: csv, exportedCount: data.total, ok: true };
78
+ })
79
+ });
80
+ server.endpoint({
81
+ method: 'POST',
82
+ path: `/plugin/${this.pluginInstanceId}/import-csv`,
83
+ noAuth: true,
84
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body }) {
85
+ const { data } = body;
86
+ // data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
87
+ // we need to convert it to [{columnName: value1, columnName2: value1}, {columnName: value2, columnName2: value2}...]
88
+ const rows = [];
89
+ const columns = Object.keys(data);
90
+ // check column names are valid
91
+ const errors = [];
92
+ columns.forEach((col) => {
93
+ if (!this.resourceConfig.columns.some((c) => c.name === col)) {
94
+ const similar = suggestIfTypo(this.resourceConfig.columns.map((c) => c.name), col);
95
+ 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:[]'}`);
96
+ }
97
+ });
98
+ if (errors.length > 0) {
99
+ return { ok: false, errors };
100
+ }
101
+ const columnValues = Object.values(data);
102
+ for (let i = 0; i < columnValues[0].length; i++) {
103
+ const row = {};
104
+ for (let j = 0; j < columns.length; j++) {
105
+ row[columns[j]] = columnValues[j][i];
106
+ }
107
+ rows.push(row);
108
+ }
109
+ let importedCount = 0;
110
+ yield Promise.all(rows.map((row) => __awaiter(this, void 0, void 0, function* () {
111
+ try {
112
+ yield this.adminforth.resource(this.resourceConfig.resourceId).create(row);
113
+ importedCount++;
114
+ }
115
+ catch (e) {
116
+ errors.push(e.message);
117
+ }
118
+ })));
119
+ return { ok: true, importedCount, errors };
120
+ })
121
+ });
122
+ }
123
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- import AdminForth, { AdminForthPlugin, Filters, suggestIfTypo, AdminForthFilterOperators } from "adminforth";
1
+ import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators } from "adminforth";
2
2
  import type { IAdminForth, IHttpServer, AdminForthResourceColumn, AdminForthComponentDeclaration, AdminForthResource } from "adminforth";
3
3
  import type { PluginOptions } from './types.js';
4
4
 
@@ -57,29 +57,11 @@ export default class ImportExport extends AdminForthPlugin {
57
57
  handler: async ({ body }) => {
58
58
  const { filters, sort } = body;
59
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
60
  const data = await this.adminforth.connectors[this.resourceConfig.dataSource].getData({
79
61
  resource: this.resourceConfig,
80
62
  limit: 1e6,
81
63
  offset: 0,
82
- filters,
64
+ filters: this.adminforth.connectors[this.resourceConfig.dataSource].validateAndNormalizeInputFilters(filters),
83
65
  sort,
84
66
  getTotals: true,
85
67
  });
@@ -97,7 +79,7 @@ export default class ImportExport extends AdminForthPlugin {
97
79
  const headers = columns.map((col) => col.name).join(',');
98
80
  csv = `${headers}\n${csv}`;
99
81
 
100
- return { data: csv, total: data.total, ok: true };
82
+ return { data: csv, exportedCount: data.total, ok: true };
101
83
 
102
84
  }
103
85
  });
@@ -112,6 +94,21 @@ export default class ImportExport extends AdminForthPlugin {
112
94
  // we need to convert it to [{columnName: value1, columnName2: value1}, {columnName: value2, columnName2: value2}...]
113
95
  const rows = [];
114
96
  const columns = Object.keys(data);
97
+
98
+ // check column names are valid
99
+ const errors: string[] = [];
100
+ columns.forEach((col) => {
101
+ if (!this.resourceConfig.columns.some((c) => c.name === col)) {
102
+ const similar = suggestIfTypo(this.resourceConfig.columns.map((c) => c.name), col);
103
+ errors.push(`Column '${col}' defined in CSV not found in resource '${this.resourceConfig.resourceId}'. ${
104
+ similar ? `If you mean '${similar}', rename it in CSV` : 'If column is in database but not in resource configuration, add it with showIn:[]'}`
105
+ );
106
+ }
107
+ });
108
+ if (errors.length > 0) {
109
+ return { ok: false, errors };
110
+ }
111
+
115
112
  const columnValues: any[] = Object.values(data);
116
113
  for (let i = 0; i < columnValues[0].length; i++) {
117
114
  const row = {};
@@ -121,7 +118,6 @@ export default class ImportExport extends AdminForthPlugin {
121
118
  rows.push(row);
122
119
  }
123
120
 
124
- const errors: string[] = [];
125
121
  let importedCount = 0;
126
122
  await Promise.all(rows.map(async (row) => {
127
123
  try {
package/package.json CHANGED
@@ -1,22 +1,56 @@
1
1
  {
2
2
  "name": "@adminforth/import-export",
3
- "version": "1.0.0",
3
+ "version": "1.0.1-next.1",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
7
+ "homepage": "https://adminforth.dev/docs/tutorial/Plugins/import-export/",
7
8
  "scripts": {
8
- "build": "tsc && rsync -av --exclude 'node_modules' custom dist/ && npm version patch",
9
- "rollout": "npm publish --access public"
9
+ "build": "tsc && rsync -av --exclude 'node_modules' custom dist/",
10
+ "prepare": "npm link adminforth"
10
11
  },
11
- "keywords": [],
12
- "author": "",
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/devforth/adminforth-import-export.git"
15
+ },
16
+ "keywords": [
17
+ "adminforth",
18
+ "import",
19
+ "export",
20
+ "csv"
21
+ ],
22
+ "author": "devforth",
13
23
  "license": "ISC",
14
- "description": "",
24
+ "description": "CSV import/export plugin for adminforth",
25
+ "dependencies": {},
15
26
  "devDependencies": {
16
- "@types/node": "^22.6.1",
17
- "adminforth": "file:../..",
18
- "typescript": "^5.6.2"
27
+ "@types/node": "^22.10.7",
28
+ "semantic-release": "^24.2.1",
29
+ "semantic-release-slack-bot": "^4.0.2",
30
+ "typescript": "^5.7.3"
19
31
  },
20
- "dependencies": {
32
+ "release": {
33
+ "plugins": [
34
+ "@semantic-release/commit-analyzer",
35
+ "@semantic-release/release-notes-generator",
36
+ "@semantic-release/npm",
37
+ "@semantic-release/github",
38
+ [
39
+ "semantic-release-slack-bot",
40
+ {
41
+ "notifyOnSuccess": true,
42
+ "notifyOnFail": true,
43
+ "slackIcon": ":package:",
44
+ "markdownReleaseNotes": true
45
+ }
46
+ ]
47
+ ],
48
+ "branches": [
49
+ "main",
50
+ {
51
+ "name": "next",
52
+ "prerelease": true
53
+ }
54
+ ]
21
55
  }
22
56
  }