@haus-tech/product-import-export-plugin 2.2.0-dev.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.
Files changed (52) hide show
  1. package/dist/api/plugin.controller.d.ts +8 -0
  2. package/dist/api/plugin.controller.js +49 -0
  3. package/dist/api/product-export.controller.d.ts +14 -0
  4. package/dist/api/product-export.controller.js +117 -0
  5. package/dist/api/product-import.controller.d.ts +11 -0
  6. package/dist/api/product-import.controller.js +62 -0
  7. package/dist/constants.d.ts +2 -0
  8. package/dist/constants.js +5 -0
  9. package/dist/helpers/generate-asset-hash.d.ts +2 -0
  10. package/dist/helpers/generate-asset-hash.js +15 -0
  11. package/dist/helpers/normalize-string.d.ts +1 -0
  12. package/dist/helpers/normalize-string.js +16 -0
  13. package/dist/helpers/remove-update-at-fields.d.ts +5 -0
  14. package/dist/helpers/remove-update-at-fields.js +19 -0
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +17 -0
  17. package/dist/product-import-export.plugin.d.ts +13 -0
  18. package/dist/product-import-export.plugin.js +153 -0
  19. package/dist/providers/import-providers/asset-importer.d.ts +27 -0
  20. package/dist/providers/import-providers/asset-importer.js +127 -0
  21. package/dist/providers/import-providers/import-parser.d.ts +137 -0
  22. package/dist/providers/import-providers/import-parser.js +600 -0
  23. package/dist/providers/import-providers/product-importer.d.ts +47 -0
  24. package/dist/providers/import-providers/product-importer.js +729 -0
  25. package/dist/services/extended-fast-importer.service.d.ts +41 -0
  26. package/dist/services/extended-fast-importer.service.js +418 -0
  27. package/dist/services/product-export.service.d.ts +23 -0
  28. package/dist/services/product-export.service.js +340 -0
  29. package/dist/services/product-import.service.d.ts +21 -0
  30. package/dist/services/product-import.service.js +83 -0
  31. package/dist/types.d.ts +40 -0
  32. package/dist/types.js +2 -0
  33. package/dist/ui/components/export-dialog.component.d.ts +43 -0
  34. package/dist/ui/components/export-dialog.component.html +78 -0
  35. package/dist/ui/components/export-dialog.component.js +108 -0
  36. package/dist/ui/components/export-dialog.component.ts +142 -0
  37. package/dist/ui/components/product-import.component.d.ts +55 -0
  38. package/dist/ui/components/product-import.component.html +76 -0
  39. package/dist/ui/components/product-import.component.js +398 -0
  40. package/dist/ui/components/product-import.component.ts +528 -0
  41. package/dist/ui/product-export.service.d.ts +14 -0
  42. package/dist/ui/product-export.service.js +107 -0
  43. package/dist/ui/product-export.service.ts +107 -0
  44. package/dist/ui/providers.d.ts +2 -0
  45. package/dist/ui/providers.js +49 -0
  46. package/dist/ui/providers.ts +57 -0
  47. package/dist/ui/routes.d.ts +29 -0
  48. package/dist/ui/routes.js +12 -0
  49. package/dist/ui/routes.ts +11 -0
  50. package/dist/ui/translations/en.json +44 -0
  51. package/dist/ui/translations/sv.json +44 -0
  52. package/package.json +30 -0
@@ -0,0 +1,398 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ProductImportComponent = void 0;
13
+ const core_1 = require("@vendure/admin-ui/core");
14
+ const core_2 = require("@angular/core");
15
+ const core_3 = require("@vendure/admin-ui/core");
16
+ const core_4 = require("@ngx-translate/core");
17
+ const lodash_1 = require("lodash");
18
+ let ProductImportComponent = class ProductImportComponent {
19
+ notificationService;
20
+ cd;
21
+ translate;
22
+ localStorageService;
23
+ serverPath;
24
+ validateFile = null;
25
+ selectedFile = null;
26
+ updateProductSlug = true;
27
+ selectedMainLanguage;
28
+ availableLanguages = [];
29
+ fileUploadElement;
30
+ config;
31
+ appConfig;
32
+ currentChannel;
33
+ constructor(notificationService, cd, translate, localStorageService) {
34
+ this.notificationService = notificationService;
35
+ this.cd = cd;
36
+ this.translate = translate;
37
+ this.localStorageService = localStorageService;
38
+ this.serverPath = (0, core_1.getServerLocation)();
39
+ }
40
+ async ngOnInit() {
41
+ this.appConfig = await fetch('./vendure-ui-config.json').then((res) => res.json());
42
+ this.config = await fetch(`${this.serverPath}/product-import-export/config`, {
43
+ method: 'GET',
44
+ headers: {
45
+ 'Content-Type': 'application/json',
46
+ },
47
+ })
48
+ .then((res) => res.json())
49
+ .then((data) => data.importOptions);
50
+ }
51
+ doValidation(file) {
52
+ this.validateCsvStructure(file).then(({ isValid, langCodes, clearFile = true }) => {
53
+ if (isValid) {
54
+ this.selectedFile = file;
55
+ }
56
+ else if (clearFile) {
57
+ this.clearFile();
58
+ }
59
+ if (langCodes && !this.selectedMainLanguage) {
60
+ this.availableLanguages = langCodes.filter((code) => code);
61
+ this.selectedMainLanguage =
62
+ (0, lodash_1.size)(this.availableLanguages) === 1
63
+ ? this.availableLanguages?.[0]
64
+ : undefined;
65
+ }
66
+ this.cd.detectChanges();
67
+ });
68
+ }
69
+ onMainLanguageChange() {
70
+ this.cd.detectChanges();
71
+ if (this.validateFile) {
72
+ this.doValidation(this.validateFile);
73
+ }
74
+ }
75
+ onFileSelected(event) {
76
+ const input = event.target;
77
+ if (input.files && input.files.length > 0) {
78
+ const file = input.files[0];
79
+ if (file.type !== 'text/csv') {
80
+ this.notificationService.error(this.translate.instant('product-import.notifications.invalid-file-type'));
81
+ this.clearFile();
82
+ return;
83
+ }
84
+ this.validateFile = file;
85
+ this.doValidation(file);
86
+ }
87
+ }
88
+ clearFile() {
89
+ this.fileUploadElement.nativeElement.value = '';
90
+ this.selectedFile = null;
91
+ this.validateFile = null;
92
+ this.selectedMainLanguage = undefined;
93
+ }
94
+ async validateCsvStructure(file) {
95
+ const baseColumns = ['sku'];
96
+ const optionalColumns = [
97
+ 'assets',
98
+ 'price',
99
+ 'taxCategory',
100
+ 'stockOnHand',
101
+ 'trackInventory',
102
+ 'variantAssets',
103
+ ];
104
+ const translatableBaseColumns = ['name'];
105
+ const translatableColumns = [
106
+ 'slug',
107
+ 'description',
108
+ 'facets',
109
+ 'optionGroups',
110
+ 'optionValues',
111
+ 'variantFacets',
112
+ ];
113
+ return new Promise((resolve) => {
114
+ const reader = new FileReader();
115
+ reader.onload = async (e) => {
116
+ const text = e.target?.result;
117
+ const lines = text.split('\n');
118
+ // Remove empty lines
119
+ lines.forEach((line, index) => {
120
+ if (line.trim() === '') {
121
+ lines.splice(index, 1);
122
+ }
123
+ });
124
+ if (lines.length > 0) {
125
+ const header = this.splitLines(lines[0]).map((col) => col.trim());
126
+ console.log('CSV Header:', header);
127
+ this.currentChannel = await fetch(`${this.serverPath}/product-import-export/channel`, {
128
+ method: 'GET',
129
+ headers: {
130
+ 'Content-Type': 'application/json',
131
+ ...this.getRequestHeaders(),
132
+ },
133
+ })
134
+ .then((res) => res.json())
135
+ .then((data) => data);
136
+ const availableLanguages = this.currentChannel.availableLanguageCodes;
137
+ // Extract all language codes from headers
138
+ const languageCodes = header
139
+ .map((col) => col.match(/:(\w{2})$/)?.[1])
140
+ .filter((code, index, self) => code && self.indexOf(code) === index);
141
+ console.log('Language Codes:', languageCodes);
142
+ let validationLanguage = (0, lodash_1.size)(languageCodes) === 0 ? undefined : this.selectedMainLanguage;
143
+ if (!this.selectedMainLanguage && (0, lodash_1.size)(languageCodes) < 2) {
144
+ validationLanguage = languageCodes?.[0];
145
+ }
146
+ if (!this.selectedMainLanguage && (0, lodash_1.size)(languageCodes) > 1) {
147
+ console.log('Multiple languages found in the CSV file. Please select the main language.');
148
+ resolve({ isValid: true, langCodes: languageCodes, clearFile: false });
149
+ return;
150
+ }
151
+ if (!this.selectedMainLanguage && (0, lodash_1.size)(languageCodes) === 0) {
152
+ resolve({ isValid: true, langCodes: availableLanguages, clearFile: false });
153
+ return;
154
+ }
155
+ console.log('Validation language:', validationLanguage);
156
+ // Check if csv-file includes languages that are not available in the system
157
+ const missingLanguages = languageCodes.filter((code) => !availableLanguages.includes(code));
158
+ if (missingLanguages.length > 0) {
159
+ const missingLangs = missingLanguages.join(', ');
160
+ console.log('Missing languages:', missingLangs);
161
+ this.notificationService.error(`${this.translate.instant('product-import.notifications.missing-languages')} ${missingLangs}`);
162
+ resolve({ isValid: false });
163
+ return;
164
+ }
165
+ // Validate base columns
166
+ const missingBaseColumns = baseColumns.filter((col) => !header.includes(col));
167
+ const missingTranslatableBaseColumns = translatableBaseColumns.filter((col) => !header.includes(validationLanguage ? `${col}:${validationLanguage}` : col));
168
+ const combinedMissingBaseColumns = [
169
+ ...missingBaseColumns,
170
+ ...missingTranslatableBaseColumns,
171
+ ];
172
+ if (combinedMissingBaseColumns.length > 0) {
173
+ const missingColumns = combinedMissingBaseColumns.join(', ');
174
+ console.log('Missing base columns:', missingColumns);
175
+ this.notificationService.error(`${this.translate.instant('product-import.notifications.missing-base-columns')} ${missingColumns}`);
176
+ resolve({ isValid: false });
177
+ return;
178
+ }
179
+ const nameColumn = `name:${validationLanguage}` || 'name';
180
+ // Get optionGroups and optionValues columns for the main language
181
+ const optionGroupsColumn = `optionGroups:${validationLanguage}` || 'optionGroups';
182
+ const optionValuesColumn = `optionValues:${validationLanguage}` || 'optionValues';
183
+ const optionGroupsIndex = header.indexOf(optionGroupsColumn);
184
+ const optionValuesIndex = header.indexOf(optionValuesColumn);
185
+ // if (optionGroupsIndex === -1 || optionValuesIndex === -1) {
186
+ // console.log(
187
+ // `Missing optionGroups or optionValues columns for language: ${validationLanguage}`,
188
+ // )
189
+ // this.notificationService.error(
190
+ // `${this.translate.instant(
191
+ // 'product-import.notifications.missing-option-columns',
192
+ // )} ${validationLanguage}`,
193
+ // )
194
+ // resolve({ isValid: false })
195
+ // return
196
+ // }
197
+ // Loop through each row to validate the option values
198
+ let currentOptionGroupCount = 0;
199
+ for (let i = 1; i < lines.length; i++) {
200
+ const row = this.splitLines(lines[i]).map((col) => col.trim());
201
+ // Check if it's a product row (it has a 'name' field)
202
+ const isProductRow = row[header.indexOf(nameColumn)];
203
+ if (isProductRow) {
204
+ // It's a new product row, get the option groups
205
+ const optionGroups = (row[optionGroupsIndex]?.split('|') ?? []).filter((group) => group !== '');
206
+ const optionValues = (row[optionValuesIndex]?.split('|') ?? []).filter((value) => value !== '');
207
+ currentOptionGroupCount = optionGroups.length;
208
+ // Validate that the number of option values matches the number of option groups
209
+ if (optionValues.length !== currentOptionGroupCount) {
210
+ this.notificationService.error(`${this.translate.instant('product-import.notifications.mismatched-option-values')} Row: ${i + 1}. Expected ${currentOptionGroupCount} option values but got ${optionValues.length}.`);
211
+ resolve({ isValid: false });
212
+ return;
213
+ }
214
+ }
215
+ else {
216
+ // It's a variant row, validate the option values
217
+ const optionValues = (row[optionValuesIndex]?.split('|') ?? []).filter((value) => value !== '');
218
+ // Validate that the number of option values matches the product's option groups
219
+ if (optionValues.length !== currentOptionGroupCount) {
220
+ this.notificationService.error(`${this.translate.instant('product-import.notifications.mismatched-option-values')} Row: ${i + 1}. Expected ${currentOptionGroupCount} option values but got ${optionValues.length}. ${JSON.stringify(optionValues)}`);
221
+ resolve({ isValid: false });
222
+ return;
223
+ }
224
+ }
225
+ }
226
+ console.log('All option values for the main language are valid.');
227
+ // Check if a row contains JSON, if so check if it is valid. This should be done for all columns, not just translatable ones.
228
+ for (let i = 1; i < lines.length; i++) {
229
+ const row = this.splitLines(lines[i]).map((col) => col.trim());
230
+ for (const col of header) {
231
+ const colIndex = header.indexOf(col);
232
+ if (colIndex !== -1 && row[colIndex]) {
233
+ try {
234
+ const { isJson } = this.checkifJson(row[colIndex]);
235
+ if (isJson) {
236
+ JSON.parse(row[colIndex]
237
+ .trim()
238
+ .replace(/^"/, '')
239
+ .replace(/"$/, '')
240
+ .replace(/'/g, '"')
241
+ .replace(/\s+/g, ' ')
242
+ .replace(/,\s*'/g, ", '"));
243
+ }
244
+ }
245
+ catch (error) {
246
+ console.log(`Invalid JSON in column: ${col}, row: ${i + 1}`);
247
+ this.notificationService.error(`${this.translate.instant('product-import.notifications.invalid-json')} ${col}, row: ${i + 1}`);
248
+ resolve({ isValid: false });
249
+ return;
250
+ }
251
+ }
252
+ }
253
+ }
254
+ console.log('All JSON values are valid.');
255
+ const { errorRows: missingBaseTranslatableValuesRows } = this.checkTranslatabeColumns(lines, translatableBaseColumns, header, languageCodes);
256
+ if (missingBaseTranslatableValuesRows.length > 0) {
257
+ console.log('Missing translation values in rows:', missingBaseTranslatableValuesRows);
258
+ this.notificationService.error(`${this.translate.instant('product-import.notifications.missing-main-language-name')} Rows: ${(0, lodash_1.uniq)(missingBaseTranslatableValuesRows).join(', ')}`);
259
+ resolve({ isValid: false });
260
+ return;
261
+ }
262
+ // Check if all translatable columns have values for the main language
263
+ const { errorRows, errorColumns } = this.checkTranslatabeColumns(lines, translatableColumns, header, languageCodes);
264
+ if (errorRows.length > 0) {
265
+ console.log('Missing translation values in rows:', errorRows);
266
+ this.notificationService.warning(`${this.translate.instant('product-import.notifications.missing-translation-values')} Rows: ${(0, lodash_1.uniq)(errorRows).join(', ')} Columns: ${(0, lodash_1.uniq)(errorColumns).join(', ')}`);
267
+ }
268
+ resolve({ isValid: true, langCodes: languageCodes });
269
+ }
270
+ else {
271
+ console.log('No lines in CSV file.');
272
+ this.notificationService.error(this.translate.instant('product-import.notifications.no-lines-in-file'));
273
+ resolve({ isValid: false });
274
+ }
275
+ };
276
+ reader.onerror = () => {
277
+ console.log('Error reading file.');
278
+ this.notificationService.error(this.translate.instant('product-import.notifications.file-read-error'));
279
+ resolve({ isValid: false });
280
+ };
281
+ reader.readAsText(file);
282
+ });
283
+ }
284
+ async uploadFile() {
285
+ if (this.selectedFile && this.selectedMainLanguage) {
286
+ const formData = new FormData();
287
+ formData.append('file', this.selectedFile);
288
+ formData.append('updateProductSlug', this.updateProductSlug.toString());
289
+ formData.append('mainLanguage', this.selectedMainLanguage);
290
+ try {
291
+ const res = await fetch(`${this.serverPath}/product-import/upload`, {
292
+ method: 'POST',
293
+ body: formData,
294
+ headers: this.getRequestHeaders(),
295
+ });
296
+ if (res.ok) {
297
+ this.clearFile();
298
+ this.notificationService.success(this.translate.instant('product-import.notifications.upload-success'));
299
+ this.cd.detectChanges();
300
+ }
301
+ else {
302
+ this.notificationService.error(this.translate.instant('product-import.notifications.upload-error'));
303
+ }
304
+ }
305
+ catch (error) {
306
+ this.notificationService.error(this.translate.instant('product-import.notifications.upload-error'));
307
+ }
308
+ }
309
+ else {
310
+ this.notificationService.error(this.translate.instant('product-import.notifications.no-file-selected'));
311
+ }
312
+ }
313
+ splitLines(text) {
314
+ // Split text by commas, but not if comma is inside double quotes
315
+ const splittedText = text.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
316
+ return splittedText;
317
+ }
318
+ checkifJson(text) {
319
+ // Replace starting and ending double quotes if exists
320
+ text = text.trim().replace(/^"/, '').replace(/"$/, '');
321
+ return {
322
+ startsWithJson: (0, lodash_1.startsWith)(text.trim(), '{') || (0, lodash_1.startsWith)(text.trim(), '['),
323
+ endsWithJson: (0, lodash_1.endsWith)(text.trim(), '}') || (0, lodash_1.endsWith)(text.trim(), ']'),
324
+ startChar: text.trim().charAt(0),
325
+ endChar: text.trim().charAt(text.trim().length - 1),
326
+ isJson: (0, lodash_1.startsWith)(text.trim(), '{') ||
327
+ (0, lodash_1.startsWith)(text.trim(), '[') ||
328
+ (0, lodash_1.endsWith)(text.trim(), '}') ||
329
+ (0, lodash_1.endsWith)(text.trim(), ']'),
330
+ };
331
+ }
332
+ getRequestHeaders() {
333
+ const headers = {};
334
+ const channelToken = this.localStorageService.get('activeChannelToken');
335
+ const { tokenMethod, channelTokenKey } = this.appConfig;
336
+ if (channelToken) {
337
+ headers[channelTokenKey ?? 'vendure-token'] = channelToken;
338
+ }
339
+ if (tokenMethod === 'bearer') {
340
+ const authToken = this.localStorageService.get('authToken');
341
+ if (authToken) {
342
+ headers.authorization = `Bearer ${authToken}`;
343
+ }
344
+ }
345
+ return headers;
346
+ }
347
+ checkTranslatabeColumns(lines, columns, header, languageCodes) {
348
+ let errorRows = [];
349
+ let errorColumns = [];
350
+ if ((0, lodash_1.size)(languageCodes) < 2) {
351
+ console.log('Only one language found in the file.');
352
+ return { errorRows, errorColumns };
353
+ }
354
+ for (let i = 1; i < lines.length; i++) {
355
+ const row = this.splitLines(lines[i]).map((col) => col.trim());
356
+ for (const baseColumn of columns) {
357
+ const mainLanguageColumn = `${baseColumn}:${this.selectedMainLanguage}`;
358
+ const colIndex = header.indexOf(mainLanguageColumn);
359
+ const mainLanguageValue = row[colIndex];
360
+ const mainLanguageHasValue = mainLanguageValue !== undefined && mainLanguageValue !== '';
361
+ if (mainLanguageHasValue) {
362
+ continue;
363
+ }
364
+ for (const lang of languageCodes) {
365
+ if (lang) {
366
+ // Check if lang is defined
367
+ const langSpecificColumn = `${baseColumn}:${lang}`;
368
+ const colIndex = header.indexOf(langSpecificColumn);
369
+ const colValue = row[colIndex];
370
+ const colHasValue = colValue !== undefined && colValue !== '';
371
+ if (!mainLanguageHasValue && colHasValue) {
372
+ errorRows.push(i + 1);
373
+ errorColumns.push(langSpecificColumn);
374
+ }
375
+ }
376
+ }
377
+ }
378
+ }
379
+ return { errorRows, errorColumns };
380
+ }
381
+ };
382
+ __decorate([
383
+ (0, core_2.ViewChild)('fileUpload', { static: false }),
384
+ __metadata("design:type", core_2.ElementRef)
385
+ ], ProductImportComponent.prototype, "fileUploadElement", void 0);
386
+ ProductImportComponent = __decorate([
387
+ (0, core_2.Component)({
388
+ selector: 'product-import',
389
+ templateUrl: './product-import.component.html',
390
+ standalone: true,
391
+ imports: [core_1.SharedModule],
392
+ }),
393
+ __metadata("design:paramtypes", [core_3.NotificationService,
394
+ core_2.ChangeDetectorRef,
395
+ core_4.TranslateService,
396
+ core_3.LocalStorageService])
397
+ ], ProductImportComponent);
398
+ exports.ProductImportComponent = ProductImportComponent;