@adminforth/import-export 1.1.0 → 1.2.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.
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 CHANGED
@@ -10,5 +10,5 @@ custom/package-lock.json
10
10
  custom/package.json
11
11
  custom/tsconfig.json
12
12
 
13
- sent 10,175 bytes received 115 bytes 20,580.00 bytes/sec
14
- total size is 9,761 speedup is 0.95
13
+ sent 12,494 bytes received 115 bytes 25,218.00 bytes/sec
14
+ total size is 12,074 speedup is 0.96
@@ -1,11 +1,27 @@
1
1
  <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')}}
4
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>
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="t('Import Confirmation')"
10
+ :buttons="[
11
+ { label: t('Import & Replace'), onclick: (dialog) => { confirmImport(dialog) } },
12
+ { label: t('Import New Only'), onclick: (dialog) => { confirmImportNewOnly(dialog) } },
13
+ { label: t('Cancel'), onclick: (dialog) => dialog.hide() }
14
+ ]"
15
+ >
16
+ <div v-if="importStats">
17
+ <p>{{ $t('Are you sure you want to continue?') }}</p>
18
+ <p class="mt-2">{{ $t('You are importing {count} records:', { count: importStats.total }) }}</p>
19
+ <ul class="list-disc ml-6 mt-2">
20
+ <li>{{ $t('{count} existing records will be replaced (old records will be lost)', { count: importStats.existingCount }) }}</li>
21
+ <li>{{ $t('{count} new records will be added', { count: importStats.newCount }) }}</li>
22
+ </ul>
23
+ </div>
24
+ </Dialog>
9
25
  </template>
10
26
 
11
27
  <script setup lang="ts">
@@ -13,32 +29,54 @@ import { ref, Ref } from 'vue';
13
29
  import { callAdminForthApi } from '@/utils';
14
30
  import adminforth from '@/adminforth';
15
31
  import Papa from 'papaparse';
32
+ import { Dialog } from '@/afcl';
33
+ import { useI18n } from 'vue-i18n';
16
34
 
17
- const inProgress: Ref<boolean> = ref(false);
35
+ const { t } = useI18n();
18
36
 
37
+ const inProgress: Ref<boolean> = ref(false);
38
+ const confirmDialog = ref(null);
39
+ const importStats = ref(null);
40
+ const pendingData = ref(null);
19
41
  const props = defineProps({
20
42
  meta: Object,
21
43
  record: Object,
22
44
  });
23
45
 
24
- async function postData(data: Record<string, string[]>) {
25
- console.log('postData 1 ', data);
46
+ async function confirmImport(dialog) {
47
+ dialog.hide();
48
+ await postData(pendingData.value);
49
+ }
50
+
51
+ async function checkRecords(data: Record<string, string[]>) {
52
+ const resp = await callAdminForthApi({
53
+ path: `/plugin/${props.meta.pluginInstanceId}/check-records`,
54
+ method: 'POST',
55
+ body: { data }
56
+ });
57
+
58
+ return resp;
59
+ }
60
+
61
+ async function confirmImportNewOnly(dialog) {
62
+ dialog.hide();
63
+ await postDataNewOnly(pendingData.value);
64
+ }
26
65
 
66
+ async function postData(data: Record<string, string[]>, skipDuplicates: boolean = false) {
27
67
  const resp = await callAdminForthApi({
28
68
  path: `/plugin/${props.meta.pluginInstanceId}/import-csv`,
29
69
  method: 'POST',
30
- body: {
31
- data
32
- }
70
+ body: { data }
33
71
  });
34
72
 
35
73
  inProgress.value = false;
36
74
 
37
- if (resp.importedCount > 0) {
75
+ if (resp.importedCount > 0 || resp.updatedCount > 0) {
38
76
  adminforth.list.refresh();
39
77
  }
40
78
  adminforth.alert({
41
- message: `Imported count ${resp.importedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
79
+ message: `Imported ${resp.importedCount || 0} records. Updated ${resp.updatedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
42
80
  variant: resp.errors?.length ? (
43
81
  resp.importedCount ? 'warning' : 'danger'
44
82
  ) : 'success'
@@ -47,8 +85,26 @@ async function postData(data: Record<string, string[]>) {
47
85
  adminforth.list.closeThreeDotsDropdown();
48
86
  }
49
87
 
88
+ async function postDataNewOnly(data: Record<string, string[]>) {
89
+ const resp = await callAdminForthApi({
90
+ path: `/plugin/${props.meta.pluginInstanceId}/import-csv-new-only`,
91
+ method: 'POST',
92
+ body: { data }
93
+ });
94
+
95
+ inProgress.value = false;
96
+ if (resp.importedCount > 0) {
97
+ adminforth.list.refresh();
98
+ }
99
+ adminforth.alert({
100
+ message: `Imported ${resp.importedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
101
+ variant: resp.errors?.length ? 'warning' : 'success'
102
+ });
103
+
104
+ adminforth.list.closeThreeDotsDropdown();
105
+ }
106
+
50
107
  async function importCsv() {
51
- // create file input and open it (with csv type)
52
108
  inProgress.value = false;
53
109
  const fileInput = document.createElement('input');
54
110
 
@@ -63,7 +119,6 @@ async function importCsv() {
63
119
  inProgress.value = false;
64
120
  return;
65
121
  }
66
-
67
122
  const reader = new FileReader();
68
123
  reader.onload = async (e) => {
69
124
  try {
@@ -72,6 +127,7 @@ async function importCsv() {
72
127
  Papa.parse(text, {
73
128
  header: true,
74
129
  skipEmptyLines: true,
130
+
75
131
  complete: async (results) => {
76
132
  if (results.errors.length > 0) {
77
133
  throw new Error(`CSV parsing errors: ${results.errors.map(e => e.message).join(', ')}`);
@@ -86,7 +142,14 @@ async function importCsv() {
86
142
  data[column] = rows.map(row => row[column]);
87
143
  });
88
144
 
89
- await postData(data);
145
+ // Store data for later use
146
+ pendingData.value = data;
147
+
148
+ // Check records and show confirmation
149
+ const stats = await checkRecords(data);
150
+ importStats.value = stats;
151
+ confirmDialog.value?.open();
152
+ inProgress.value = false;
90
153
  },
91
154
  error: (error) => {
92
155
  throw new Error(`Failed to parse CSV: ${error.message}`);
@@ -1,11 +1,27 @@
1
1
  <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')}}
4
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>
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="t('Import Confirmation')"
10
+ :buttons="[
11
+ { label: t('Import & Replace'), onclick: (dialog) => { confirmImport(dialog) } },
12
+ { label: t('Import New Only'), onclick: (dialog) => { confirmImportNewOnly(dialog) } },
13
+ { label: t('Cancel'), onclick: (dialog) => dialog.hide() }
14
+ ]"
15
+ >
16
+ <div v-if="importStats">
17
+ <p>{{ $t('Are you sure you want to continue?') }}</p>
18
+ <p class="mt-2">{{ $t('You are importing {count} records:', { count: importStats.total }) }}</p>
19
+ <ul class="list-disc ml-6 mt-2">
20
+ <li>{{ $t('{count} existing records will be replaced (old records will be lost)', { count: importStats.existingCount }) }}</li>
21
+ <li>{{ $t('{count} new records will be added', { count: importStats.newCount }) }}</li>
22
+ </ul>
23
+ </div>
24
+ </Dialog>
9
25
  </template>
10
26
 
11
27
  <script setup lang="ts">
@@ -13,32 +29,54 @@ import { ref, Ref } from 'vue';
13
29
  import { callAdminForthApi } from '@/utils';
14
30
  import adminforth from '@/adminforth';
15
31
  import Papa from 'papaparse';
32
+ import { Dialog } from '@/afcl';
33
+ import { useI18n } from 'vue-i18n';
16
34
 
17
- const inProgress: Ref<boolean> = ref(false);
35
+ const { t } = useI18n();
18
36
 
37
+ const inProgress: Ref<boolean> = ref(false);
38
+ const confirmDialog = ref(null);
39
+ const importStats = ref(null);
40
+ const pendingData = ref(null);
19
41
  const props = defineProps({
20
42
  meta: Object,
21
43
  record: Object,
22
44
  });
23
45
 
24
- async function postData(data: Record<string, string[]>) {
25
- console.log('postData 1 ', data);
46
+ async function confirmImport(dialog) {
47
+ dialog.hide();
48
+ await postData(pendingData.value);
49
+ }
50
+
51
+ async function checkRecords(data: Record<string, string[]>) {
52
+ const resp = await callAdminForthApi({
53
+ path: `/plugin/${props.meta.pluginInstanceId}/check-records`,
54
+ method: 'POST',
55
+ body: { data }
56
+ });
57
+
58
+ return resp;
59
+ }
60
+
61
+ async function confirmImportNewOnly(dialog) {
62
+ dialog.hide();
63
+ await postDataNewOnly(pendingData.value);
64
+ }
26
65
 
66
+ async function postData(data: Record<string, string[]>, skipDuplicates: boolean = false) {
27
67
  const resp = await callAdminForthApi({
28
68
  path: `/plugin/${props.meta.pluginInstanceId}/import-csv`,
29
69
  method: 'POST',
30
- body: {
31
- data
32
- }
70
+ body: { data }
33
71
  });
34
72
 
35
73
  inProgress.value = false;
36
74
 
37
- if (resp.importedCount > 0) {
75
+ if (resp.importedCount > 0 || resp.updatedCount > 0) {
38
76
  adminforth.list.refresh();
39
77
  }
40
78
  adminforth.alert({
41
- message: `Imported count ${resp.importedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
79
+ message: `Imported ${resp.importedCount || 0} records. Updated ${resp.updatedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
42
80
  variant: resp.errors?.length ? (
43
81
  resp.importedCount ? 'warning' : 'danger'
44
82
  ) : 'success'
@@ -47,8 +85,26 @@ async function postData(data: Record<string, string[]>) {
47
85
  adminforth.list.closeThreeDotsDropdown();
48
86
  }
49
87
 
88
+ async function postDataNewOnly(data: Record<string, string[]>) {
89
+ const resp = await callAdminForthApi({
90
+ path: `/plugin/${props.meta.pluginInstanceId}/import-csv-new-only`,
91
+ method: 'POST',
92
+ body: { data }
93
+ });
94
+
95
+ inProgress.value = false;
96
+ if (resp.importedCount > 0) {
97
+ adminforth.list.refresh();
98
+ }
99
+ adminforth.alert({
100
+ message: `Imported ${resp.importedCount || 0} records. ${resp.errors?.length ? `Errors: ${resp.errors.join(', ')}` : ''}`,
101
+ variant: resp.errors?.length ? 'warning' : 'success'
102
+ });
103
+
104
+ adminforth.list.closeThreeDotsDropdown();
105
+ }
106
+
50
107
  async function importCsv() {
51
- // create file input and open it (with csv type)
52
108
  inProgress.value = false;
53
109
  const fileInput = document.createElement('input');
54
110
 
@@ -63,7 +119,6 @@ async function importCsv() {
63
119
  inProgress.value = false;
64
120
  return;
65
121
  }
66
-
67
122
  const reader = new FileReader();
68
123
  reader.onload = async (e) => {
69
124
  try {
@@ -72,6 +127,7 @@ async function importCsv() {
72
127
  Papa.parse(text, {
73
128
  header: true,
74
129
  skipEmptyLines: true,
130
+
75
131
  complete: async (results) => {
76
132
  if (results.errors.length > 0) {
77
133
  throw new Error(`CSV parsing errors: ${results.errors.map(e => e.message).join(', ')}`);
@@ -86,7 +142,14 @@ async function importCsv() {
86
142
  data[column] = rows.map(row => row[column]);
87
143
  });
88
144
 
89
- await postData(data);
145
+ // Store data for later use
146
+ pendingData.value = data;
147
+
148
+ // Check records and show confirmation
149
+ const stats = await checkRecords(data);
150
+ importStats.value = stats;
151
+ confirmDialog.value?.open();
152
+ inProgress.value = false;
90
153
  },
91
154
  error: (error) => {
92
155
  throw new Error(`Failed to parse CSV: ${error.message}`);
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators } from "adminforth";
10
+ import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators, Filters } from "adminforth";
11
11
  export default class ImportExport extends AdminForthPlugin {
12
12
  constructor(options) {
13
13
  super(options, import.meta.url);
@@ -107,8 +107,6 @@ export default class ImportExport extends AdminForthPlugin {
107
107
  noAuth: true,
108
108
  handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body }) {
109
109
  const { data } = body;
110
- // data is in format {[columnName]: [value1, value2, value3...], [columnName2]: [value1, value2, value3...]}
111
- // we need to convert it to [{columnName: value1, columnName2: value1}, {columnName: value2, columnName2: value2}...]
112
110
  const rows = [];
113
111
  const columns = Object.keys(data);
114
112
  // check column names are valid
@@ -122,6 +120,7 @@ export default class ImportExport extends AdminForthPlugin {
122
120
  if (errors.length > 0) {
123
121
  return { ok: false, errors };
124
122
  }
123
+ const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
125
124
  const columnValues = Object.values(data);
126
125
  for (let i = 0; i < columnValues[0].length; i++) {
127
126
  const row = {};
@@ -131,8 +130,67 @@ export default class ImportExport extends AdminForthPlugin {
131
130
  rows.push(row);
132
131
  }
133
132
  let importedCount = 0;
133
+ let updatedCount = 0;
134
134
  yield Promise.all(rows.map((row) => __awaiter(this, void 0, void 0, function* () {
135
135
  try {
136
+ if (primaryKeyColumn && row[primaryKeyColumn.name]) {
137
+ const existingRecord = yield this.adminforth.resource(this.resourceConfig.resourceId)
138
+ .list([Filters.EQ(primaryKeyColumn.name, row[primaryKeyColumn.name])]);
139
+ if (existingRecord.length > 0) {
140
+ yield this.adminforth.resource(this.resourceConfig.resourceId)
141
+ .update(row[primaryKeyColumn.name], row);
142
+ updatedCount++;
143
+ return;
144
+ }
145
+ }
146
+ yield this.adminforth.resource(this.resourceConfig.resourceId).create(row);
147
+ importedCount++;
148
+ }
149
+ catch (e) {
150
+ errors.push(e.message);
151
+ }
152
+ })));
153
+ return { ok: true, importedCount, updatedCount, errors };
154
+ })
155
+ });
156
+ server.endpoint({
157
+ method: 'POST',
158
+ path: `/plugin/${this.pluginInstanceId}/import-csv-new-only`,
159
+ noAuth: true,
160
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body }) {
161
+ const { data } = body;
162
+ const rows = [];
163
+ const columns = Object.keys(data);
164
+ // check column names are valid
165
+ const errors = [];
166
+ columns.forEach((col) => {
167
+ if (!this.resourceConfig.columns.some((c) => c.name === col)) {
168
+ const similar = suggestIfTypo(this.resourceConfig.columns.map((c) => c.name), col);
169
+ 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:[]'}`);
170
+ }
171
+ });
172
+ if (errors.length > 0) {
173
+ return { ok: false, errors };
174
+ }
175
+ const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
176
+ const columnValues = Object.values(data);
177
+ for (let i = 0; i < columnValues[0].length; i++) {
178
+ const row = {};
179
+ for (let j = 0; j < columns.length; j++) {
180
+ row[columns[j]] = columnValues[j][i];
181
+ }
182
+ rows.push(row);
183
+ }
184
+ let importedCount = 0;
185
+ yield Promise.all(rows.map((row) => __awaiter(this, void 0, void 0, function* () {
186
+ try {
187
+ if (primaryKeyColumn && row[primaryKeyColumn.name]) {
188
+ const existingRecord = yield this.adminforth.resource(this.resourceConfig.resourceId)
189
+ .list([Filters.EQ(primaryKeyColumn.name, row[primaryKeyColumn.name])]);
190
+ if (existingRecord.length > 0) {
191
+ return;
192
+ }
193
+ }
136
194
  yield this.adminforth.resource(this.resourceConfig.resourceId).create(row);
137
195
  importedCount++;
138
196
  }
@@ -143,5 +201,35 @@ export default class ImportExport extends AdminForthPlugin {
143
201
  return { ok: true, importedCount, errors };
144
202
  })
145
203
  });
204
+ server.endpoint({
205
+ method: 'POST',
206
+ path: `/plugin/${this.pluginInstanceId}/check-records`,
207
+ noAuth: true,
208
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body }) {
209
+ const { data } = body;
210
+ const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
211
+ const rows = [];
212
+ const columns = Object.keys(data);
213
+ const columnValues = Object.values(data);
214
+ for (let i = 0; i < columnValues[0].length; i++) {
215
+ const row = {};
216
+ for (let j = 0; j < columns.length; j++) {
217
+ row[columns[j]] = columnValues[j][i];
218
+ }
219
+ rows.push(row);
220
+ }
221
+ const primaryKeys = rows
222
+ .map(row => row[primaryKeyColumn.name])
223
+ .filter(key => key !== undefined && key !== null && key !== '');
224
+ const records = yield this.adminforth.resource(this.resourceConfig.resourceId).list([]);
225
+ const existingRecords = records.filter((record) => primaryKeys.includes(record[primaryKeyColumn.name]));
226
+ return {
227
+ ok: true,
228
+ total: rows.length,
229
+ existingCount: existingRecords.length,
230
+ newCount: rows.length - existingRecords.length
231
+ };
232
+ })
233
+ });
146
234
  }
147
235
  }
package/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators } from "adminforth";
1
+ import { AdminForthPlugin, suggestIfTypo, AdminForthFilterOperators, Filters } from "adminforth";
2
2
  import type { IAdminForth, IHttpServer, AdminForthResourceColumn, AdminForthComponentDeclaration, AdminForthResource } from "adminforth";
3
3
  import type { PluginOptions } from './types.js';
4
4
 
@@ -114,8 +114,6 @@ export default class ImportExport extends AdminForthPlugin {
114
114
  noAuth: true,
115
115
  handler: async ({ body }) => {
116
116
  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}...]
119
117
  const rows = [];
120
118
  const columns = Object.keys(data);
121
119
 
@@ -133,6 +131,8 @@ export default class ImportExport extends AdminForthPlugin {
133
131
  return { ok: false, errors };
134
132
  }
135
133
 
134
+ const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
135
+
136
136
  const columnValues: any[] = Object.values(data);
137
137
  for (let i = 0; i < columnValues[0].length; i++) {
138
138
  const row = {};
@@ -143,21 +143,124 @@ export default class ImportExport extends AdminForthPlugin {
143
143
  }
144
144
 
145
145
  let importedCount = 0;
146
+ let updatedCount = 0;
147
+
146
148
  await Promise.all(rows.map(async (row) => {
147
149
  try {
148
- await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
149
- importedCount++;
150
+ if (primaryKeyColumn && row[primaryKeyColumn.name]) {
151
+ const existingRecord = await this.adminforth.resource(this.resourceConfig.resourceId)
152
+ .list([Filters.EQ(primaryKeyColumn.name, row[primaryKeyColumn.name])]);
153
+
154
+ if (existingRecord.length > 0) {
155
+ await this.adminforth.resource(this.resourceConfig.resourceId)
156
+ .update(row[primaryKeyColumn.name], row);
157
+ updatedCount++;
158
+ return;
159
+ }
160
+ }
161
+ await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
162
+ importedCount++;
150
163
  } catch (e) {
151
- errors.push(e.message);
164
+ errors.push(e.message);
152
165
  }
153
166
  }));
154
167
 
168
+ return { ok: true, importedCount, updatedCount, errors };
169
+ }
170
+ });
171
+
172
+ server.endpoint({
173
+ method: 'POST',
174
+ path: `/plugin/${this.pluginInstanceId}/import-csv-new-only`,
175
+ noAuth: true,
176
+ handler: async ({ body }) => {
177
+ const { data } = body;
178
+ const rows = [];
179
+ const columns = Object.keys(data);
180
+
181
+ // check column names are valid
182
+ const errors: string[] = [];
183
+ columns.forEach((col) => {
184
+ if (!this.resourceConfig.columns.some((c) => c.name === col)) {
185
+ const similar = suggestIfTypo(this.resourceConfig.columns.map((c) => c.name), col);
186
+ errors.push(`Column '${col}' defined in CSV not found in resource '${this.resourceConfig.resourceId}'. ${
187
+ similar ? `If you mean '${similar}', rename it in CSV` : 'If column is in database but not in resource configuration, add it with showIn:[]'}`
188
+ );
189
+ }
190
+ });
191
+ if (errors.length > 0) {
192
+ return { ok: false, errors };
193
+ }
194
+
195
+ const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
196
+ const columnValues: any[] = Object.values(data);
197
+ for (let i = 0; i < columnValues[0].length; i++) {
198
+ const row = {};
199
+ for (let j = 0; j < columns.length; j++) {
200
+ row[columns[j]] = columnValues[j][i];
201
+ }
202
+ rows.push(row);
203
+ }
204
+
205
+ let importedCount = 0;
155
206
 
156
- return { ok: true, importedCount, errors};
207
+ await Promise.all(rows.map(async (row) => {
208
+ try {
209
+ if (primaryKeyColumn && row[primaryKeyColumn.name]) {
210
+ const existingRecord = await this.adminforth.resource(this.resourceConfig.resourceId)
211
+ .list([Filters.EQ(primaryKeyColumn.name, row[primaryKeyColumn.name])]);
212
+
213
+ if (existingRecord.length > 0) {
214
+ return;
215
+ }
216
+ }
217
+ await this.adminforth.resource(this.resourceConfig.resourceId).create(row);
218
+ importedCount++;
219
+ } catch (e) {
220
+ errors.push(e.message);
221
+ }
222
+ }));
157
223
 
224
+ return { ok: true, importedCount, errors };
158
225
  }
159
226
  });
160
227
 
228
+ server.endpoint({
229
+ method: 'POST',
230
+ path: `/plugin/${this.pluginInstanceId}/check-records`,
231
+ noAuth: true,
232
+ handler: async ({ body }) => {
233
+ const { data } = body;
234
+
235
+ const primaryKeyColumn = this.resourceConfig.columns.find(col => col.primaryKey);
236
+
237
+ const rows = [];
238
+ const columns = Object.keys(data);
239
+ const columnValues = Object.values(data);
240
+ for (let i = 0; i < (columnValues[0] as any[]).length; i++) {
241
+ const row = {};
242
+ for (let j = 0; j < columns.length; j++) {
243
+ row[columns[j]] = columnValues[j][i];
244
+ }
245
+ rows.push(row);
246
+ }
247
+
248
+ const primaryKeys = rows
249
+ .map(row => row[primaryKeyColumn.name])
250
+ .filter(key => key !== undefined && key !== null && key !== '');
251
+
252
+ const records = await this.adminforth.resource(this.resourceConfig.resourceId).list([])
253
+
254
+ const existingRecords = records.filter((record) => primaryKeys.includes(record[primaryKeyColumn.name]));
255
+
256
+ return {
257
+ ok: true,
258
+ total: rows.length,
259
+ existingCount: existingRecords.length,
260
+ newCount: rows.length - existingRecords.length
261
+ };
262
+ }
263
+ });
161
264
  }
162
265
 
163
266
  }
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "@adminforth/import-export",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
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
9
  "build": "tsc && rsync -av --exclude 'node_modules' custom dist/",
9
10
  "prepare": "npm link adminforth"