-
Notifications
You must be signed in to change notification settings - Fork 2
/
TestDataService.ts
1929 lines (1644 loc) · 64.5 KB
/
TestDataService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createRandomImage } from './ImageHelper';
import { getPromotionWithDiscount } from './ShopwareDataHelpers';
import type { AdminApiContext } from './AdminApiContext';
import type { IdProvider } from './IdProvider';
import type {
Product,
PropertyGroup,
Category,
Media,
Tag,
Rule,
Order,
Currency,
Customer,
CustomerAddress,
PaymentMethod,
ShippingMethod,
StateMachine,
StateMachineState,
Promotion,
SalesChannel,
Manufacturer,
OrderDelivery,
OrderLineItem,
PropertyGroupOption,
DeliveryTime,
CmsPage,
} from '../types/ShopwareTypes';
import { expect } from '@playwright/test';
export interface CreatedRecord {
resource: string;
payload: Record<string, string>;
}
export interface SimpleLineItem {
product: Product | Promotion;
quantity?: number;
position?: number;
overrides?: Partial<OrderLineItem>;
}
export interface SyncApiOperation {
entity: string;
action: 'upsert' | 'delete';
payload: Record<string, unknown>[];
}
export interface DataServiceOptions {
namePrefix?: string;
nameSuffix?: string;
defaultSalesChannel: SalesChannel;
defaultTaxId: string;
defaultCurrencyId: string;
defaultCategoryId: string;
defaultLanguageId: string;
defaultCountryId: string;
defaultCustomerGroupId: string;
}
export class TestDataService {
public readonly AdminApiClient: AdminApiContext;
public readonly IdProvider: IdProvider;
public readonly namePrefix: string = 'Test-';
public readonly nameSuffix: string = '';
public readonly defaultSalesChannel: SalesChannel;
public readonly defaultTaxId: string;
public readonly defaultCurrencyId: string;
public readonly defaultCategoryId: string;
public readonly defaultLanguageId: string;
public readonly defaultCountryId: string;
public readonly defaultCustomerGroupId: string;
/**
* Configures if an automated cleanup of the data should be executed.
*
* @private
*/
private shouldCleanUp = true;
/**
* Configuration of higher priority entities for the cleanup operation.
* These entities will be deleted before others.
* This will prevent restricted delete operations of associated entities.
*
* @private
*/
private highPriorityEntities = ['order', 'product'];
/**
* A registry of all created records.
*
* @private
*/
private createdRecords: CreatedRecord[] = [];
constructor(AdminApiClient: AdminApiContext, IdProvider: IdProvider, options: DataServiceOptions) {
this.AdminApiClient = AdminApiClient;
this.IdProvider = IdProvider;
this.defaultSalesChannel = options.defaultSalesChannel;
this.defaultTaxId = options.defaultTaxId;
this.defaultCurrencyId = options.defaultCurrencyId;
this.defaultCategoryId = options.defaultCategoryId;
this.defaultLanguageId = options.defaultLanguageId;
this.defaultCountryId = options.defaultCountryId;
this.defaultCustomerGroupId = options.defaultCustomerGroupId;
if (options.namePrefix) {
this.namePrefix = options.namePrefix;
}
if (options.nameSuffix) {
this.nameSuffix = options.nameSuffix;
}
}
/**
* Creates a basic product without images or other special configuration.
* The product will be added to the default sales channel category if configured.
*
* @param overrides - Specific data overrides that will be applied to the product data struct.
* @param taxId - The uuid of the tax rule to use for the product pricing.
* @param currencyId - The uuid of the currency to use for the product pricing.
*/
async createBasicProduct(
overrides: Partial<Product> = {},
taxId = this.defaultTaxId,
currencyId = this.defaultCurrencyId,
): Promise<Product> {
if (!taxId) {
return Promise.reject('Missing tax ID for creating product.');
}
if (!currencyId) {
return Promise.reject('Missing currency ID for creating product.');
}
const basicProduct = this.getBasicProductStruct(taxId, currencyId, overrides);
const productResponse = await this.AdminApiClient.post('./product?_response=detail', {
data: basicProduct,
});
expect(productResponse.ok()).toBeTruthy();
const { data: product } = (await productResponse.json()) as { data: Product };
this.addCreatedRecord('product', product.id);
return product;
}
/**
* Creates a basic product with one randomly generated image.
* The product will be added to the default sales channel category if configured.
*
* @param overrides - Specific data overrides that will be applied to the product data struct.
* @param taxId - The uuid of the tax rule to use for the product pricing.
* @param currencyId - The uuid of the currency to use for the product pricing.
*/
async createProductWithImage(
overrides: Partial<Product> = {},
taxId = this.defaultTaxId,
currencyId = this.defaultCurrencyId,
): Promise<Product> {
const product = await this.createBasicProduct(overrides, taxId, currencyId);
const media = await this.createMediaPNG();
await this.assignProductMedia(product.id, media.id);
return product;
}
/**
* Creates a digital product with a text file as its download.
* The product will be added to the default sales channel category if configured.
*
* @param content - The content of the text file for the product download.
* @param overrides - Specific data overrides that will be applied to the product data struct.
* @param taxId - The uuid of the tax rule to use for the product pricing.
* @param currencyId - The uuid of the currency to use for the product pricing.
*/
async createDigitalProduct(
content = 'Lorem ipsum dolor',
overrides: Partial<Product> = {},
taxId = this.defaultTaxId,
currencyId = this.defaultCurrencyId,
): Promise<Product> {
const product = await this.createBasicProduct(overrides, taxId, currencyId);
const media = await this.createMediaTXT(content);
await this.assignProductDownload(product.id, media.id);
return product;
}
/**
* Creates a basic product with a price range matrix.
* The product will be added to the default sales channel category if configured.
*
* @param overrides - Specific data overrides that will be applied to the product data struct.
* @param taxId - The uuid of the tax rule to use for the product pricing.
* @param currencyId - The uuid of the currency to use for the product pricing.
*/
async createProductWithPriceRange(
overrides: Partial<Product> = {},
taxId = this.defaultTaxId,
currencyId = this.defaultCurrencyId,
): Promise<Product> {
if (!currencyId) {
return Promise.reject('Missing currency ID for creating product.');
}
const rule = await this.getRule('Always valid (Default)');
const priceRange = this.getProductPriceRangeStruct(currencyId, rule.id);
const productOverrides = Object.assign({}, priceRange, overrides);
return this.createBasicProduct(productOverrides, taxId, currencyId);
}
/**
* Creates a basic manufacturer without images or other special configuration.
*
* @param overrides - Specific data overrides that will be applied to the manufacturer data struct.
*/
async createBasicManufacturer(
overrides: Partial<Manufacturer> = {},
): Promise<Manufacturer> {
const basicManufacturer = this.getBasicManufacturerStruct(overrides);
const manufacturerResponse = await this.AdminApiClient.post('./product-manufacturer?_response=detail', {
data: basicManufacturer,
});
expect(manufacturerResponse.ok()).toBeTruthy();
const { data: manufacturer } = (await manufacturerResponse.json()) as { data: Manufacturer };
this.addCreatedRecord('product_manufacturer', manufacturer.id);
return manufacturer;
}
/**
* Creates a basic manufacturer with one randomly generated image.
*
* @param overrides - Specific data overrides that will be applied to the manufacturer data struct.
*/
async createManufacturerWithImage(
overrides: Partial<Manufacturer> = {},
): Promise<Manufacturer> {
const manufacturer = await this.createBasicManufacturer(overrides);
const media = await this.createMediaPNG();
await this.assignManufacturerMedia(manufacturer.id, media.id);
return manufacturer;
}
/**
* Creates a basic product category to assign products to.
*
* @param parentId - The uuid of the parent category.
* @param overrides - Specific data overrides that will be applied to the category data struct.
*/
async createCategory(
overrides: Partial<Category> = {},
parentId = this.defaultCategoryId,
): Promise<Category> {
const basicCategory = this.getBasicCategoryStruct(overrides, parentId);
const response = await this.AdminApiClient.post('category?_response=detail', {
data: basicCategory,
});
expect(response.ok()).toBeTruthy();
const { data: category } = (await response.json()) as { data: Category };
this.addCreatedRecord('category', category.id);
return category;
}
/**
* Creates a new media resource containing a random generated PNG image.
*
* @param width - The width of the image in pixel. Default is 800.
* @param height - The height of the image in pixel. Default is 600.
*/
async createMediaPNG(
width = 800,
height = 600,
): Promise<Media> {
const image = createRandomImage(width, height);
const media = await this.createMediaResource();
const filename = `${this.namePrefix}Media-${media.id}${this.nameSuffix}`;
const response = await this.AdminApiClient.post(`_action/media/${media.id}/upload?extension=png&fileName=${filename}`, {
data: Buffer.from(image.toBuffer()),
headers: { 'content-type': 'image/png' },
});
expect(response.ok()).toBeTruthy();
this.addCreatedRecord('media', media.id);
return media;
}
/**
* Creates a new media resource containing a text file.
*
* @param content - The content of the text file.
*/
async createMediaTXT(
content = 'Lorem ipsum dolor',
): Promise<Media> {
const media = await this.createMediaResource();
const filename = `${this.namePrefix}Media-${media.id}${this.nameSuffix}`;
const response = await this.AdminApiClient.post(`_action/media/${media.id}/upload?extension=txt&fileName=${filename}`, {
data: content,
headers: { 'content-type': 'application/octet-stream' },
});
expect(response.ok()).toBeTruthy();
this.addCreatedRecord('media', media.id);
return media;
}
/**
* Creates a new empty media resource.
* This method is mostly used to combine it with a certain file upload.
*/
async createMediaResource(): Promise<Media> {
const id = this.IdProvider.getIdPair().id;
const mediaResponse = await this.AdminApiClient.post('media?_response=detail', {
data: {
private: false,
alt: `Alt-${id}`,
title: `Title-${id}`,
},
});
expect(mediaResponse.ok()).toBeTruthy();
const { data: media } = (await mediaResponse.json()) as { data: Media };
return media;
}
/**
* Creates a new property group with color type options.
*
* @param overrides - Specific data overrides that will be applied to the property group data struct.
*/
async createColorPropertyGroup(
overrides: Partial<PropertyGroup> = {},
): Promise<PropertyGroup> {
const id = this.IdProvider.getIdPair().id;
const colorPropertyGroup = {
name: `${this.namePrefix}Color-${id}${this.nameSuffix}`,
description: 'Color',
displayType: 'color',
sortingType: 'name',
options: [{
name: 'Blue',
colorHexCode: '#2148d6',
}, {
name: 'Red',
colorHexCode: '#bf0f2a',
}, {
name: 'Green',
colorHexCode: '#12bf0f',
}],
};
const propertyGroupResponse = await this.AdminApiClient.post('property-group?_response=detail', {
data: Object.assign({}, colorPropertyGroup, overrides),
});
expect(propertyGroupResponse.ok()).toBeTruthy();
const { data: propertyGroup } = (await propertyGroupResponse.json()) as { data: PropertyGroup };
this.addCreatedRecord('property_group', propertyGroup.id);
return propertyGroup;
}
/**
* Creates a new property group with text type options.
*
* @param overrides - Specific data overrides that will be applied to the property group data struct.
*/
async createTextPropertyGroup(
overrides: Partial<PropertyGroup> = {},
): Promise<PropertyGroup> {
const id = this.IdProvider.getIdPair().id;
const textPropertyGroup = {
name: `${this.namePrefix}Size-${id}${this.nameSuffix}`,
description: 'Size',
displayType: 'text',
sortingType: 'name',
options: [{
name: 'Small',
}, {
name: 'Medium',
}, {
name: 'Large',
}],
};
const propertyGroupResponse = await this.AdminApiClient.post('property-group?_response=detail', {
data: Object.assign({}, textPropertyGroup, overrides),
});
expect(propertyGroupResponse.ok()).toBeTruthy();
const { data: propertyGroup } = (await propertyGroupResponse.json()) as { data: PropertyGroup };
this.addCreatedRecord('property_group', propertyGroup.id);
return propertyGroup;
}
/**
* Creates a new tag which can be assigned to other entities.
*
* @param tagName - The name of the tag.
*/
async createTag(
tagName: string,
): Promise<Tag> {
const response = await this.AdminApiClient.post('tag?_response=detail', {
data: {
id: this.IdProvider.getIdPair().uuid,
name: tagName,
},
});
expect(response.ok()).toBeTruthy();
const { data: tag } = (await response.json()) as { data: Tag };
this.addCreatedRecord('tag', tag.id);
return tag;
}
/**
* Creates a new shop customer.
*
* @param overrides - Specific data overrides that will be applied to the customer data struct.
* @param salutationKey - The key of the salutation that should be used for the customer. Default is "mr".
* @param salesChannel - The sales channel for which the customer should be registered.
*/
async createCustomer(
overrides: Partial<Customer> = {},
salutationKey = 'mr',
salesChannel: SalesChannel = this.defaultSalesChannel,
): Promise<Customer> {
const salutation = await this.getSalutation(salutationKey);
const basicCustomerStruct = this.getBasicCustomerStruct(
salesChannel.id,
salesChannel.customerGroupId,
salesChannel.languageId,
salesChannel.countryId,
salesChannel.paymentMethodId,
salutation.id,
overrides
);
const response = await this.AdminApiClient.post('customer?_response=detail', {
data: basicCustomerStruct,
});
expect(response.ok()).toBeTruthy();
const customerData = (await response.json()) as { data: Customer };
let customer: Customer;
if (typeof basicCustomerStruct.password !== 'string') {
customer = { ...customerData.data };
} else {
customer = { ...customerData.data, password: basicCustomerStruct.password };
}
this.addCreatedRecord('customer', customer.id);
return customer;
}
/**
* Creates a new order. This order is created on pure data and prices are not guaranteed to be calculated correctly.
*
* @param lineItems - Products that should be added to the order.
* @param customer - The customer to which the order should be assigned.
* @param overrides - Specific data overrides that will be applied to the order data struct.
* @param salesChannel - The sales channel in which the order should be created.
*/
async createOrder(
lineItems: SimpleLineItem[],
customer: Customer,
overrides: Partial<Order> = {},
salesChannel: SalesChannel = this.defaultSalesChannel,
): Promise<Order> {
const orderStateMachine = await this.getOrderStateMachine();
const deliveryStateMachine = await this.getDeliveryStateMachine();
const transactionStateMachine = await this.getTransactionStateMachine();
const orderState = await this.getStateMachineState(orderStateMachine.id);
const deliveryState = await this.getStateMachineState(deliveryStateMachine.id);
const transactionState = await this.getStateMachineState(transactionStateMachine.id);
const currencyResponse = await this.AdminApiClient.get(`currency/${salesChannel.currencyId}`);
const { data: currency } = (await currencyResponse.json()) as { data: Currency };
const shippingMethod = await this.getShippingMethod();
const paymentMethod = await this.getPaymentMethod();
const customerAddress = await this.getCustomerAddress(customer.defaultBillingAddressId);
const basicOrder = this.getBasicOrderStruct(
lineItems,
salesChannel.languageId,
currency,
paymentMethod,
shippingMethod,
orderState,
deliveryState,
transactionState,
customer,
customerAddress,
salesChannel.id,
overrides,
);
const orderResponse = await this.AdminApiClient.post('order?_response=detail', {
data: basicOrder,
});
expect(orderResponse.ok()).toBeTruthy();
const { data: order } = (await orderResponse.json()) as { data: Order };
this.addCreatedRecord('order', order.id);
return order;
}
/**
* Creates a new promotion with a promotion code and only single discount option.
*
* @param overrides - Specific data overrides that will be applied to the promotion data struct.
* @param salesChannelId - The uuid of the sales channel in which the promotion should be active.
*/
async createPromotionWithCode(
overrides: Partial<Promotion> = {},
salesChannelId = this.defaultSalesChannel.id,
): Promise<Promotion> {
const basicPromotion = this.getBasicPromotionStruct(salesChannelId, overrides);
// Create a new promotion with code via admin API context
const promotionResponse = await this.AdminApiClient.post('promotion?_response=detail', {
data: basicPromotion,
});
expect(promotionResponse.ok()).toBeTruthy();
const { data: promotion } = (await promotionResponse.json()) as { data: Promotion };
const promotionWithDiscount = await getPromotionWithDiscount(promotion.id, this.AdminApiClient);
this.addCreatedRecord('promotion', promotion.id);
return promotionWithDiscount;
}
/**
* Creates a new basic payment method.
*
* @param overrides - Specific data overrides that will be applied to the payment method data struct.
*/
async createBasicPaymentMethod(
overrides: Partial<PaymentMethod> = {}
): Promise<PaymentMethod> {
const basicPaymentMethod = this.getBasicPaymentMethodStruct(overrides);
const paymentMethodResponse = await this.AdminApiClient.post('payment-method?_response=detail', {
data: basicPaymentMethod,
});
expect(paymentMethodResponse.ok()).toBeTruthy();
const { data: paymentMethod } = (await paymentMethodResponse.json()) as { data: PaymentMethod };
this.addCreatedRecord('payment_method', paymentMethod.id);
return paymentMethod;
}
/**
* Creates a new basic rule with the condition cart amount >= 1.
*
* @param overrides - Specific data overrides that will be applied to the payment method data struct.
*/
async createBasicRule(
overrides: Partial<Rule> = {}
): Promise<Rule> {
const basicRule = this.getBasicRuleStruct(overrides);
const ruleResponse = await this.AdminApiClient.post('rule?_response=detail', {
data: basicRule,
});
expect(ruleResponse.ok()).toBeTruthy();
const { data: rule } = (await ruleResponse.json()) as { data: Rule };
this.addCreatedRecord('rule', rule.id);
return rule;
}
/**
* Creates a new basic page layout.
*
* @param cmsPageType - The type of the cms page layout (page/landingpage/product_detail/product_list).
* @param overrides - Specific data overrides that will be applied to the cms page layout data struct.
*/
async createBasicPageLayout(cmsPageType: string, overrides: Partial<CmsPage> = {}): Promise<CmsPage> {
const basicLayout = this.getBasicCmsStruct(cmsPageType, overrides);
const layoutResponse = await this.AdminApiClient.post('cms-page?_response=detail', {
data: basicLayout,
});
expect(layoutResponse.ok()).toBeTruthy();
const { data: layout } = (await layoutResponse.json()) as { data: CmsPage };
this.addCreatedRecord('cms_page', layout.id);
return layout;
}
/**
* Creates a payment method with one randomly generated image.
*
* @param overrides - Specific data overrides that will be applied to the payment method data struct.
*/
async createPaymentMethodWithImage(
overrides: Partial<PaymentMethod> = {},
): Promise<PaymentMethod> {
const paymentMethod = await this.createBasicPaymentMethod(overrides);
const media = await this.createMediaPNG();
await this.assignPaymentMethodMedia(paymentMethod.id, media.id);
return paymentMethod;
}
/**
* Creates basic variant products based on property group.
*
* @param parentProduct Parent product of the variants
* @param propertyGroups Property group collection which contain options
* @param overrides - Specific data overrides that will be applied to the variant data struct.
*/
async createVariantProducts(
parentProduct: Product,
propertyGroups: PropertyGroup[],
overrides: Partial<Product> = {},
): Promise<Product[]> {
const productVariantCandidates: Record<string, string>[][] = [];
for (const propertyGroup of propertyGroups) {
const propertyGroupOptions = await this.getPropertyGroupOptions(propertyGroup.id);
const propertyGroupOptionsCollection: Record<string, string>[] = [];
for (const propertyGroupOption of propertyGroupOptions) {
propertyGroupOptionsCollection.push({ id: propertyGroupOption.id })
const productConfiguratorResponse = await this.AdminApiClient.post('product-configurator-setting?_response=detail', {
data: {
id: this.IdProvider.getIdPair().uuid,
productId: parentProduct.id,
optionId: propertyGroupOption.id,
},
});
expect(productConfiguratorResponse.ok()).toBeTruthy();
}
productVariantCandidates.push(propertyGroupOptionsCollection);
}
const productVariantCombinations = this.combineAll(productVariantCandidates);
const variantProducts: Product[] = [];
let index = 1;
for (const productVariantCombination of productVariantCombinations) {
const variantOverrides = {
parentId: parentProduct.id,
productNumber: parentProduct.productNumber + '.' + index,
options: productVariantCombination,
};
const overrideCollection = Object.assign({}, overrides, variantOverrides);
variantProducts.push(await this.createBasicProduct(overrideCollection));
index++;
}
await this.AdminApiClient.post('_action/indexing/product.indexer?_response=detail', {
data: {
offset: 0,
},
});
return variantProducts;
}
/**
* Creates a shipping method with one randomly generated image.
*
* @param overrides - Specific data overrides that will be applied to the shipping method data struct.
*/
async createShippingMethodWithImage(
overrides: Partial<ShippingMethod> = {},
): Promise<ShippingMethod> {
const shippingMethod = await this.createBasicShippingMethod(overrides);
const media = await this.createMediaPNG();
await this.assignShippingMethodMedia(shippingMethod.id, media.id);
return shippingMethod;
}
/**
* Creates a new basic shipping method with random delivery time.
*
* @param overrides - Specific data overrides that will be applied to the shipping method data struct.
*/
async createBasicShippingMethod(
overrides: Partial<ShippingMethod> = {},
): Promise<ShippingMethod> {
const deliveryTime = await this.getAllDeliveryTimeResources()
overrides.availabilityRuleId ??= (await this.getRule('Always valid (Default)')).id
const basicShippingMethod = this.getBasicShippingMethodStruct(
deliveryTime[0].id,
overrides
);
const shippingMethodResponse = await this.AdminApiClient.post('shipping-method?_response=detail', {
data: basicShippingMethod,
});
expect(shippingMethodResponse.ok()).toBeTruthy();
const { data: shippingMethod } = (await shippingMethodResponse.json()) as { data: ShippingMethod };
this.addCreatedRecord('shipping_method', shippingMethod.id);
return shippingMethod;
}
/**
* Function that generates combinations from n number of arrays
* with m number of elements in them.
* @param array
*/
combineAll = (array: Record<string, string>[][]) => {
const result: Record<string, string>[][] = [];
const max = array.length - 1;
const helper = (tmpArray: Record<string, string>[], i: number) => {
for (let j = 0, l = array[i].length; j < l; j++) {
const copy = tmpArray.slice(0);
copy.push(array[i][j]);
if (i == max)
result.push(copy);
else
helper(copy, i + 1);
}
};
helper([], 0);
return result;
};
/**
* Assigns a media resource to a payment method as a logo.
*
* @param paymentMethodId - The uuid of the payment method.
* @param mediaId - The uuid of the media resource.
*/
async assignPaymentMethodMedia(paymentMethodId: string, mediaId: string) {
const paymentMethodResponse = await this.AdminApiClient.patch(`payment-method/${paymentMethodId}?_response=basic`, {
data: {
mediaId: mediaId,
},
});
expect(paymentMethodResponse.ok()).toBeTruthy();
const { data: paymentMethodMedia } = await paymentMethodResponse.json();
return paymentMethodMedia;
}
/**
* Assigns a media resource as the download of a digital product.
*
* @param productId - The uuid of the product.
* @param mediaId - The uuid of the media resource.
*/
async assignProductDownload(productId: string, mediaId: string) {
const downloadResponse = await this.AdminApiClient.post(`product-download?_response=basic`, {
data: {
productId: productId,
mediaId: mediaId,
},
});
expect(downloadResponse.ok()).toBeTruthy();
const { data: productDownload } = await downloadResponse.json();
return productDownload;
}
/**
* Assigns a media resource to a product as the product image.
*
* @param productId - The uuid of the product.
* @param mediaId - The uuid of the media resource.
*/
async assignProductMedia(productId: string, mediaId: string) {
const productMediaId = this.IdProvider.getIdPair().uuid;
const mediaResponse = await this.AdminApiClient.patch(`product/${productId}?_response=basic`, {
data: {
coverId: productMediaId,
media: [
{
id: productMediaId,
media: {
id: mediaId,
},
},
],
},
});
expect(mediaResponse.ok()).toBeTruthy();
const { data: productMedia } = await mediaResponse.json();
return productMedia;
}
/**
* Assigns a media resource to a manufacturer as a logo.
*
* @param manufacturerId - The uuid of the manufacturer.
* @param mediaId - The uuid of the media resource.
*/
async assignManufacturerMedia(manufacturerId: string, mediaId: string) {
const mediaResponse = await this.AdminApiClient.patch(`product-manufacturer/${manufacturerId}?_response=basic`, {
data: {
mediaId: mediaId,
},
});
expect(mediaResponse.ok()).toBeTruthy();
const { data: manufacturerMedia } = await mediaResponse.json();
return manufacturerMedia;
}
/**
* Assigns a manufacturer to a product.
*
* @param manufacturerId - The uuid of the manufacturer.
* @param productId - The uuid of the product.
*/
async assignManufacturerProduct(manufacturerId: string, productId: string) {
await this.AdminApiClient.patch(`product/${productId}?_response=basic`, {
data: {
manufacturerId: manufacturerId,
},
});
}
/**
* Assigns a product to a category.
*
* @param productId - The uuid of the product.
* @param categoryId - The uuid of the category.
*/
async assignProductCategory(productId: string, categoryId: string) {
return await this.AdminApiClient.patch(`product/${productId}?_response=basic`, {
data: {
categories: [{
id: categoryId,
}],
},
});
}
/**
* Assigns a tag to a product.
*
* @param productId - The uuid of the product.
* @param tagId - The uuid of the tag.
*/
async assignProductTag(productId: string, tagId: string) {
return await this.AdminApiClient.patch(`product/${productId}?_response=basic`, {
data: {
tags: [{
id: tagId,
}],
},
});
}
/**
* Retrieves a currency based on its ISO code.
*
* @param isoCode - The ISO code of the currency, for example "EUR".
*/
async getCurrency(isoCode: string): Promise<Currency> {
const currencyResponse = await this.AdminApiClient.post('search/currency', {
data: {
limit: 1,
filter: [{
type: 'equals',
field: 'isoCode',
value: isoCode,
}],
},
});
expect(currencyResponse.ok()).toBeTruthy();
const { data: result } = (await currencyResponse.json()) as { data: Currency[] };
return result[0];
}
/**
* Retrieves a rule based on its name.
*
* @param name - The name of the rule.
*/
async getRule(name: string): Promise<Rule> {
const response = await this.AdminApiClient.post('search/rule', {
data: {
limit: 1,
filter: [{
type: 'equals',
field: 'name',
value: name,
}],
},
});
expect(response.ok()).toBeTruthy();
const { data: result } = (await response.json()) as { data: Rule[] };
return result[0];
}
/**
* Retrieves a shipping method by its name.
*
* @param name - The name of the shipping method. Default is "Standard".
*/
async getShippingMethod(name = 'Standard'): Promise<ShippingMethod> {
const response = await this.AdminApiClient.post('search/shipping-method', {
data: {
limit: 1,
filter: [{
type: 'equals',
field: 'name',
value: name,
}],
},