@infrab4a/connect-angular 5.0.0-beta.69 → 5.0.0-beta.7

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 (40) hide show
  1. package/angular-connect.module.d.ts +8 -13
  2. package/angular-firestore.module.d.ts +2 -1
  3. package/consts/index.d.ts +0 -2
  4. package/esm2022/angular-connect.module.mjs +5 -38
  5. package/esm2022/angular-firestore.module.mjs +28 -39
  6. package/esm2022/angular-hasura-graphql.module.mjs +8 -52
  7. package/esm2022/consts/index.mjs +1 -3
  8. package/esm2022/index.mjs +1 -2
  9. package/esm2022/services/cart.service.mjs +32 -44
  10. package/esm2022/services/catalog/adapters/new-category-structure.adapter.mjs +4 -6
  11. package/esm2022/services/catalog/catalog.service.mjs +47 -157
  12. package/esm2022/services/catalog/category.service.mjs +4 -4
  13. package/esm2022/services/catalog/wishlist.service.mjs +22 -142
  14. package/esm2022/services/checkout-subscription.service.mjs +21 -18
  15. package/esm2022/services/checkout.service.mjs +16 -13
  16. package/esm2022/services/coupon.service.mjs +29 -74
  17. package/esm2022/services/home-shop.service.mjs +4 -4
  18. package/fesm2022/infrab4a-connect-angular.mjs +200 -623
  19. package/fesm2022/infrab4a-connect-angular.mjs.map +1 -1
  20. package/index.d.ts +0 -1
  21. package/package.json +6 -6
  22. package/services/cart.service.d.ts +0 -1
  23. package/services/catalog/catalog.service.d.ts +4 -11
  24. package/services/catalog/category.service.d.ts +1 -6
  25. package/services/catalog/wishlist.service.d.ts +4 -16
  26. package/services/checkout-subscription.service.d.ts +4 -5
  27. package/services/checkout.service.d.ts +4 -8
  28. package/services/coupon.service.d.ts +2 -6
  29. package/angular-vertex-search.module.d.ts +0 -9
  30. package/consts/persistence.const.d.ts +0 -1
  31. package/consts/vertex-config.const.d.ts +0 -1
  32. package/esm2022/angular-vertex-search.module.mjs +0 -34
  33. package/esm2022/consts/persistence.const.mjs +0 -2
  34. package/esm2022/consts/vertex-config.const.mjs +0 -2
  35. package/esm2022/persistence/cookie-data-persistence.mjs +0 -22
  36. package/esm2022/persistence/data-persistence.mjs +0 -2
  37. package/esm2022/persistence/index.mjs +0 -3
  38. package/persistence/cookie-data-persistence.d.ts +0 -10
  39. package/persistence/data-persistence.d.ts +0 -6
  40. package/persistence/index.d.ts +0 -2
@@ -2,18 +2,18 @@ import * as i0 from '@angular/core';
2
2
  import { NgModule, InjectionToken, PLATFORM_ID, Injectable, Inject } from '@angular/core';
3
3
  import * as i1$4 from '@angular/fire/app';
4
4
  import { FirebaseApp, provideFirebaseApp, getApp, initializeApp } from '@angular/fire/app';
5
- import * as i2 from '@angular/fire/storage';
6
- import { Storage, provideStorage, getStorage } from '@angular/fire/storage';
7
5
  import * as i1$2 from '@infrab4a/connect';
8
- import { ProductsIndex, AxiosAdapter, Authentication, AuthenticationFirebaseAuthService, Register, RegisterFirebaseAuthService, SignOut, RecoveryPassword, ConnectFirestoreService, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, CampaignHashtagFirestoreRepository, CampaignDashboardFirestoreRepository, SubscriptionEditionFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, ShopSettingsFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, SubscriptionMaterializationFirestoreRepository, SubscriptionSummaryFirestoreRepository, ProductVariantFirestoreRepository, OrderBlockedFirestoreRepository, LogFirestoreRepository, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository, ProductReviewsHasuraGraphQLRepository, VariantHasuraGraphQLRepository, ProductStockNotificationHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryProductHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, ProductsVertexSearch, VertexAxiosAdapter, Where, Shops, CheckoutTypes, CouponTypes, Exclusivities, OrderStatus, isNil, NotFoundError, Checkout, pick, LineItem, RoundProductPricesHelper, set, InvalidArgumentError, isEmpty, Category, PersonTypes, WishlistLogType, Wishlist, CheckoutSubscription, Product, RequiredArgumentError, add, Order, UpdateUserImage, FirebaseFileUploaderService } from '@infrab4a/connect';
6
+ import { ProductsIndex, AxiosAdapter, Authentication, AuthenticationFirebaseAuthService, Register, RegisterFirebaseAuthService, SignOut, RecoveryPassword, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, CampaignHashtagFirestoreRepository, CampaignDashboardFirestoreRepository, SubscriptionEditionFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, ShopSettingsFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, SubscriptionMaterializationFirestoreRepository, SubscriptionSummaryFirestoreRepository, ProductVariantFirestoreRepository, FirebaseFileUploaderService, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository, ProductReviewsHasuraGraphQLRepository, VariantHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, Where, Shops, CheckoutTypes, CouponTypes, Exclusivities, isNil, NotFoundError, Checkout, pick, LineItem, RoundProductPricesHelper, set, InvalidArgumentError, Category, Wishlist, CheckoutSubscription, Product, RequiredArgumentError, add, Order, UpdateUserImage } from '@infrab4a/connect';
9
7
  import * as i1 from '@angular/fire/auth';
10
8
  import { Auth, provideAuth, getAuth, getIdToken, authState } from '@angular/fire/auth';
11
9
  import { isPlatformBrowser, isPlatformServer } from '@angular/common';
12
10
  import * as i1$1 from '@angular/fire/firestore';
13
- import { Firestore, provideFirestore, initializeFirestore, memoryLocalCache, docSnapshots, doc } from '@angular/fire/firestore';
14
- import cookie from 'js-cookie';
15
- import { of, from, combineLatest, throwError, Subject, iif, forkJoin } from 'rxjs';
11
+ import { Firestore, provideFirestore, getFirestore, initializeFirestore, memoryLocalCache, docSnapshots, doc } from '@angular/fire/firestore';
12
+ import * as i2 from '@angular/fire/storage';
13
+ import { Storage, provideStorage, getStorage } from '@angular/fire/storage';
14
+ import { combineLatest, from, of, throwError, Subject, iif, forkJoin } from 'rxjs';
16
15
  import { map, mergeMap, catchError, concatMap, tap } from 'rxjs/operators';
16
+ import cookie from 'js-cookie';
17
17
  import { __decorate, __metadata } from 'tslib';
18
18
  import { Type } from 'class-transformer';
19
19
  import * as i1$3 from '@angular/common/http';
@@ -61,10 +61,6 @@ const FIREBASE_OPTIONS = new InjectionToken('firebaseOptions');
61
61
 
62
62
  const HASURA_OPTIONS = 'HASURA_OPTIONS';
63
63
 
64
- const PERSISTENCE_PROVIDER = 'PERSISTENCE_PROVIDER';
65
-
66
- const VERTEX_CONFIG = 'VERTEX_CONFIG';
67
-
68
64
  class AngularFirebaseAuthModule {
69
65
  static initializeApp(options, nameOrConfig) {
70
66
  return {
@@ -173,6 +169,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
173
169
  }]
174
170
  }] });
175
171
 
172
+ const STORAGE_BASE_URL = 'STORAGE_BASE_URL';
173
+
176
174
  class MobileOperationSystemCheckerHelper {
177
175
  static isAppleDevice() {
178
176
  return (['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator?.platform) ||
@@ -192,12 +190,12 @@ class AngularFirestoreModule {
192
190
  };
193
191
  }
194
192
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularFirestoreModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
195
- static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularFirestoreModule, imports: [AngularElasticSeachModule, i1$1.FirestoreModule] }); }
193
+ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularFirestoreModule, imports: [AngularElasticSeachModule, i1$1.FirestoreModule, i2.StorageModule] }); }
196
194
  static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularFirestoreModule, providers: [
197
195
  {
198
196
  provide: 'FirestoreOptions',
199
197
  useFactory: (firestore, platformId) => ({
200
- firestore: new ConnectFirestoreService(firestore),
198
+ firestore,
201
199
  interceptors: {
202
200
  request: (request) => {
203
201
  if (isPlatformBrowser(platformId))
@@ -406,33 +404,26 @@ class AngularFirestoreModule {
406
404
  deps: ['FirestoreOptions', ProductFirestoreRepository],
407
405
  },
408
406
  {
409
- provide: 'OrderBlockedRepository',
410
- useFactory: (options) => {
411
- return new OrderBlockedFirestoreRepository(options);
412
- },
413
- deps: ['FirestoreOptions'],
414
- },
415
- {
416
- provide: 'LogRepository',
417
- useFactory: (options) => {
418
- return new LogFirestoreRepository(options);
407
+ provide: 'FileUploaderService',
408
+ useFactory: (storage, baseUrl) => {
409
+ return new FirebaseFileUploaderService(storage, baseUrl);
419
410
  },
420
- deps: ['FirestoreOptions'],
411
+ deps: [Storage, STORAGE_BASE_URL],
421
412
  },
422
413
  ], imports: [AngularElasticSeachModule,
423
414
  provideFirestore((injector) => {
424
415
  const platformId = injector.get(PLATFORM_ID);
425
- if (isPlatformServer(platformId) || !MobileOperationSystemCheckerHelper.isAppleDevice())
426
- return initializeFirestore(injector.get(FirebaseApp), {
427
- ignoreUndefinedProperties: true,
428
- });
416
+ if (isPlatformServer(platformId))
417
+ return getFirestore(injector.get(FirebaseApp));
418
+ if (!MobileOperationSystemCheckerHelper.isAppleDevice())
419
+ return getFirestore(injector.get(FirebaseApp));
429
420
  const firestore = initializeFirestore(injector.get(FirebaseApp), {
430
421
  experimentalForceLongPolling: true,
431
- ignoreUndefinedProperties: true,
432
422
  localCache: memoryLocalCache(),
433
423
  });
434
424
  return firestore;
435
- })] }); }
425
+ }),
426
+ provideStorage(() => getStorage())] }); }
436
427
  }
437
428
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularFirestoreModule, decorators: [{
438
429
  type: NgModule,
@@ -441,23 +432,23 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
441
432
  AngularElasticSeachModule,
442
433
  provideFirestore((injector) => {
443
434
  const platformId = injector.get(PLATFORM_ID);
444
- if (isPlatformServer(platformId) || !MobileOperationSystemCheckerHelper.isAppleDevice())
445
- return initializeFirestore(injector.get(FirebaseApp), {
446
- ignoreUndefinedProperties: true,
447
- });
435
+ if (isPlatformServer(platformId))
436
+ return getFirestore(injector.get(FirebaseApp));
437
+ if (!MobileOperationSystemCheckerHelper.isAppleDevice())
438
+ return getFirestore(injector.get(FirebaseApp));
448
439
  const firestore = initializeFirestore(injector.get(FirebaseApp), {
449
440
  experimentalForceLongPolling: true,
450
- ignoreUndefinedProperties: true,
451
441
  localCache: memoryLocalCache(),
452
442
  });
453
443
  return firestore;
454
444
  }),
445
+ provideStorage(() => getStorage()),
455
446
  ],
456
447
  providers: [
457
448
  {
458
449
  provide: 'FirestoreOptions',
459
450
  useFactory: (firestore, platformId) => ({
460
- firestore: new ConnectFirestoreService(firestore),
451
+ firestore,
461
452
  interceptors: {
462
453
  request: (request) => {
463
454
  if (isPlatformBrowser(platformId))
@@ -666,18 +657,11 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
666
657
  deps: ['FirestoreOptions', ProductFirestoreRepository],
667
658
  },
668
659
  {
669
- provide: 'OrderBlockedRepository',
670
- useFactory: (options) => {
671
- return new OrderBlockedFirestoreRepository(options);
672
- },
673
- deps: ['FirestoreOptions'],
674
- },
675
- {
676
- provide: 'LogRepository',
677
- useFactory: (options) => {
678
- return new LogFirestoreRepository(options);
660
+ provide: 'FileUploaderService',
661
+ useFactory: (storage, baseUrl) => {
662
+ return new FirebaseFileUploaderService(storage, baseUrl);
679
663
  },
680
- deps: ['FirestoreOptions'],
664
+ deps: [Storage, STORAGE_BASE_URL],
681
665
  },
682
666
  ],
683
667
  }]
@@ -760,17 +744,6 @@ class AngularHasuraGraphQLModule {
760
744
  },
761
745
  deps: ['HasuraConfig'],
762
746
  },
763
- {
764
- provide: 'ProductStockNotificationRepository',
765
- useExisting: ProductStockNotificationHasuraGraphQLRepository,
766
- },
767
- {
768
- provide: ProductStockNotificationHasuraGraphQLRepository,
769
- useFactory: (hasuraConfig) => {
770
- return new ProductStockNotificationHasuraGraphQLRepository(hasuraConfig);
771
- },
772
- deps: ['HasuraConfig'],
773
- },
774
747
  {
775
748
  provide: 'CategoryFilterRepository',
776
749
  useExisting: CategoryFilterHasuraGraphQLRepository,
@@ -813,23 +786,12 @@ class AngularHasuraGraphQLModule {
813
786
  provide: 'CategoryCollectionChildrenRepository',
814
787
  useExisting: CategoryCollectionChildrenHasuraGraphQLRepository,
815
788
  },
816
- {
817
- provide: CategoryProductHasuraGraphQLRepository,
818
- useFactory: (options) => {
819
- return new CategoryProductHasuraGraphQLRepository(options);
820
- },
821
- deps: ['HasuraConfig'],
822
- },
823
- {
824
- provide: 'CategoryProductRepository',
825
- useExisting: CategoryProductHasuraGraphQLRepository,
826
- },
827
789
  {
828
790
  provide: WishlistHasuraGraphQLRepository,
829
- useFactory: (options, categoryProductRepository) => {
830
- return new WishlistHasuraGraphQLRepository(options, categoryProductRepository);
791
+ useFactory: (options, categoryFilterRepository) => {
792
+ return new WishlistHasuraGraphQLRepository(options, categoryFilterRepository);
831
793
  },
832
- deps: ['HasuraConfig', CategoryProductHasuraGraphQLRepository],
794
+ deps: ['HasuraConfig', CategoryFilterHasuraGraphQLRepository],
833
795
  },
834
796
  {
835
797
  provide: 'WishlistRepository',
@@ -908,17 +870,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
908
870
  },
909
871
  deps: ['HasuraConfig'],
910
872
  },
911
- {
912
- provide: 'ProductStockNotificationRepository',
913
- useExisting: ProductStockNotificationHasuraGraphQLRepository,
914
- },
915
- {
916
- provide: ProductStockNotificationHasuraGraphQLRepository,
917
- useFactory: (hasuraConfig) => {
918
- return new ProductStockNotificationHasuraGraphQLRepository(hasuraConfig);
919
- },
920
- deps: ['HasuraConfig'],
921
- },
922
873
  {
923
874
  provide: 'CategoryFilterRepository',
924
875
  useExisting: CategoryFilterHasuraGraphQLRepository,
@@ -961,23 +912,12 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
961
912
  provide: 'CategoryCollectionChildrenRepository',
962
913
  useExisting: CategoryCollectionChildrenHasuraGraphQLRepository,
963
914
  },
964
- {
965
- provide: CategoryProductHasuraGraphQLRepository,
966
- useFactory: (options) => {
967
- return new CategoryProductHasuraGraphQLRepository(options);
968
- },
969
- deps: ['HasuraConfig'],
970
- },
971
- {
972
- provide: 'CategoryProductRepository',
973
- useExisting: CategoryProductHasuraGraphQLRepository,
974
- },
975
915
  {
976
916
  provide: WishlistHasuraGraphQLRepository,
977
- useFactory: (options, categoryProductRepository) => {
978
- return new WishlistHasuraGraphQLRepository(options, categoryProductRepository);
917
+ useFactory: (options, categoryFilterRepository) => {
918
+ return new WishlistHasuraGraphQLRepository(options, categoryFilterRepository);
979
919
  },
980
- deps: ['HasuraConfig', CategoryProductHasuraGraphQLRepository],
920
+ deps: ['HasuraConfig', CategoryFilterHasuraGraphQLRepository],
981
921
  },
982
922
  {
983
923
  provide: 'WishlistRepository',
@@ -987,55 +927,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
987
927
  }]
988
928
  }] });
989
929
 
990
- class AngularVertexSeachModule {
991
- static initializeApp(options) {
992
- return {
993
- ngModule: AngularVertexSeachModule,
994
- providers: [{ provide: VERTEX_CONFIG, useValue: options }],
995
- };
996
- }
997
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
998
- static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule }); }
999
- static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule, providers: [
1000
- {
1001
- provide: ProductsVertexSearch,
1002
- useFactory: (configuration) => new ProductsVertexSearch(new VertexAxiosAdapter(configuration)),
1003
- deps: [VERTEX_CONFIG],
1004
- },
1005
- ] }); }
1006
- }
1007
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule, decorators: [{
1008
- type: NgModule,
1009
- args: [{
1010
- providers: [
1011
- {
1012
- provide: ProductsVertexSearch,
1013
- useFactory: (configuration) => new ProductsVertexSearch(new VertexAxiosAdapter(configuration)),
1014
- deps: [VERTEX_CONFIG],
1015
- },
1016
- ],
1017
- }]
1018
- }] });
1019
-
1020
- const STORAGE_BASE_URL = 'STORAGE_BASE_URL';
1021
-
1022
- class CookieDataPersistence {
1023
- get(key) {
1024
- return of(cookie.get(key));
1025
- }
1026
- remove(key) {
1027
- return of(cookie.remove(key));
1028
- }
1029
- set(key, value) {
1030
- return from(cookie.set(key, value)).pipe(map(() => { }));
1031
- }
1032
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CookieDataPersistence, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1033
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CookieDataPersistence }); }
1034
- }
1035
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CookieDataPersistence, decorators: [{
1036
- type: Injectable
1037
- }] });
1038
-
1039
930
  class AuthService {
1040
931
  constructor(angularFireAuth, userRepository) {
1041
932
  this.angularFireAuth = angularFireAuth;
@@ -1116,11 +1007,11 @@ class CouponService {
1116
1007
  throw 'Limite de uso atingido';
1117
1008
  }
1118
1009
  if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
1119
- const ordersCoupon = await this.getOrdersWithCoupon(coupon);
1120
- if (!couponUseLimits.unlimited && couponUseLimits.total && ordersCoupon.length >= couponUseLimits.total)
1010
+ const orders = await this.getOrdersWithCoupon(coupon);
1011
+ if (!couponUseLimits.unlimited && couponUseLimits.total && orders.length >= couponUseLimits.total)
1121
1012
  throw 'Limite de uso atingido.';
1122
1013
  if (couponUseLimits.limitedPerUser) {
1123
- const ordersWithUser = this.countOrdersWithUser(ordersCoupon, checkout.user.email);
1014
+ const ordersWithUser = this.countOrdersWithUser(orders, checkout.user.email);
1124
1015
  if (ordersWithUser > 0)
1125
1016
  throw 'Limite de uso por usuário atingido.';
1126
1017
  }
@@ -1129,12 +1020,8 @@ class CouponService {
1129
1020
  if (!hasProductCategories)
1130
1021
  throw 'Seu carrinho não possui produtos elegíveis para desconto.';
1131
1022
  const hasMinSubTotal = await this.hasMinSubTotal(coupon, checkout);
1132
- if (!hasMinSubTotal) {
1133
- if (coupon.productsCategories?.length) {
1134
- throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido na(s) categoria(s) elegíveis para o desconto.`;
1135
- }
1136
- throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido.`;
1137
- }
1023
+ if (!hasMinSubTotal)
1024
+ throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido`;
1138
1025
  return coupon;
1139
1026
  }
1140
1027
  calcDiscountSubscription(coupon, checkout) {
@@ -1146,53 +1033,45 @@ class CouponService {
1146
1033
  return of(discount);
1147
1034
  }
1148
1035
  async calcDiscountShopping(coupon, checkout) {
1149
- let discountInfo = null;
1036
+ let discount = 0;
1150
1037
  if (checkout.user.isSubscriber && coupon.discount.subscriber.value) {
1151
- discountInfo = await this.calcDiscountByType(coupon.discount.subscriber.type, coupon.discount.subscriber.value, coupon.productsCategories, checkout);
1038
+ discount = await this.calcDiscountByType(coupon.discount.subscriber.type, coupon.discount.subscriber.value, coupon.productsCategories, checkout);
1152
1039
  }
1153
1040
  else {
1154
- discountInfo = await this.calcDiscountByType(coupon.discount.non_subscriber.type, coupon.discount.non_subscriber.value, coupon.productsCategories, checkout);
1041
+ discount = await this.calcDiscountByType(coupon.discount.non_subscriber.type, coupon.discount.non_subscriber.value, coupon.productsCategories, checkout);
1155
1042
  }
1156
- return { discount: discountInfo.discount, lineItems: discountInfo.lineItems };
1043
+ return discount;
1157
1044
  }
1158
1045
  async calcDiscountByType(type, value, categories, checkout) {
1159
1046
  let discount = 0;
1160
- if (type == CouponTypes.SHIPPING) {
1161
- const subTotal = checkout.shipping.ShippingPrice;
1162
- const discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2);
1163
- return { discount, lineItems: checkout.lineItems };
1164
- }
1165
- let lineItensElegibleForDiscount = await this.getLineItensEligebleForDiscount(categories, checkout);
1166
- const subTotal = this.calcCheckoutSubtotal(lineItensElegibleForDiscount, checkout.user);
1047
+ let lineItensDiscount = await this.getLineItensEligebleForDiscount(categories, checkout);
1048
+ const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user, checkout.shop);
1167
1049
  if (type == CouponTypes.ABSOLUTE) {
1168
1050
  discount = value > subTotal ? subTotal : value;
1169
1051
  }
1170
1052
  else {
1171
- discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2);
1053
+ discount = subTotal * (value / 100);
1172
1054
  }
1173
- const lineItems = this.calcLineItenDiscount(type, lineItensElegibleForDiscount, value, subTotal);
1174
- return { discount, lineItems };
1055
+ return discount;
1175
1056
  }
1176
1057
  async hasMinSubTotal(coupon, checkout) {
1177
1058
  if (!coupon.minSubTotalValue)
1178
1059
  return true;
1179
1060
  let lineItensDiscount = await this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
1180
- const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user);
1061
+ const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user, checkout.shop);
1181
1062
  if (coupon.minSubTotalValue <= subTotal)
1182
1063
  return true;
1183
1064
  return false;
1184
1065
  }
1185
1066
  async hasProductCategories(coupon, checkout) {
1186
- if (!coupon.productsCategories || !coupon.productsCategories?.length) {
1067
+ if (!coupon.productsCategories || !coupon.productsCategories.length) {
1187
1068
  return true;
1188
1069
  }
1189
1070
  const couponCategories = await this.getCouponCategoriesId(coupon.productsCategories);
1190
- const hasCategories = checkout.lineItems?.filter((item) => {
1191
- if (item.isGift)
1192
- return false;
1193
- if (!item.categories || !item.categories?.length)
1071
+ const hasCategories = checkout.lineItems?.filter((i) => {
1072
+ if (!i.categories || !i.categories?.length)
1194
1073
  return true;
1195
- return item.categories.some((c) => couponCategories.some((cat) => cat == c));
1074
+ return i.categories.some((c) => couponCategories.some((cat) => cat == c));
1196
1075
  });
1197
1076
  return hasCategories.length ? true : false;
1198
1077
  }
@@ -1235,24 +1114,20 @@ class CouponService {
1235
1114
  let lineItensDiscount = [];
1236
1115
  const couponCategories = await this.getCouponCategoriesId(productsCategories);
1237
1116
  if (productsCategories && productsCategories.length) {
1238
- lineItensDiscount = checkout.lineItems?.filter((item) => {
1239
- if (item.isGift)
1240
- return false;
1241
- if (item.categories?.length) {
1242
- return item.categories.some((c) => couponCategories.some((cat) => cat == c));
1117
+ lineItensDiscount = checkout.lineItems?.filter((i) => {
1118
+ if (i.categories?.length) {
1119
+ return i.categories.some((c) => couponCategories.some((cat) => cat == c));
1243
1120
  }
1244
1121
  return true;
1245
1122
  });
1246
1123
  }
1247
1124
  else {
1248
- lineItensDiscount = checkout.lineItems.filter((item) => !item.isGift);
1125
+ lineItensDiscount = checkout.lineItems;
1249
1126
  }
1250
1127
  return lineItensDiscount;
1251
1128
  }
1252
- calcCheckoutSubtotal(lineItens, user) {
1253
- return (lineItens
1254
- ?.filter((item) => !item.isGift)
1255
- .reduce((acc, curr) => user?.isSubscriber && curr.price.subscriberPrice
1129
+ calcCheckoutSubtotal(lineItens, user, shop) {
1130
+ return (lineItens?.reduce((acc, curr) => user?.isSubscriber && curr.price.subscriberPrice
1256
1131
  ? acc + curr.price?.subscriberPrice * curr.quantity
1257
1132
  : acc + curr.pricePaid * curr.quantity, 0) || 0);
1258
1133
  }
@@ -1261,7 +1136,7 @@ class CouponService {
1261
1136
  .find({
1262
1137
  filters: {
1263
1138
  coupon: { id: coupon.id },
1264
- status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1139
+ payment: { status: 'paid' },
1265
1140
  },
1266
1141
  })
1267
1142
  .then((result) => result.data);
@@ -1271,7 +1146,7 @@ class CouponService {
1271
1146
  .find({
1272
1147
  filters: {
1273
1148
  user: { email: { operator: Where.EQUALS, value: email } },
1274
- status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1149
+ payment: { status: 'paid' },
1275
1150
  },
1276
1151
  })
1277
1152
  .then((result) => result.data);
@@ -1282,42 +1157,13 @@ class CouponService {
1282
1157
  getCouponUseLimits(coupon, checkoutType, user) {
1283
1158
  let couponUseLimits;
1284
1159
  if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
1285
- if (coupon.exclusivityType.length === 1 &&
1286
- (coupon.exclusivityType.at(0) === Exclusivities.SPECIFIC_USER ||
1287
- coupon.exclusivityType.at(0) === Exclusivities.COLLABORATORS))
1288
- couponUseLimits = coupon.useLimits.non_subscriber;
1289
- else
1290
- couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
1160
+ couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
1291
1161
  }
1292
1162
  else {
1293
1163
  couponUseLimits = coupon.useLimits.subscription;
1294
1164
  }
1295
1165
  return couponUseLimits;
1296
1166
  }
1297
- calcLineItenDiscount(type, lineItems, couponDiscount, subTotal) {
1298
- let lineItemsDiscount = [];
1299
- if (type === CouponTypes.ABSOLUTE) {
1300
- const couponDiscountMax = couponDiscount > subTotal ? subTotal : couponDiscount;
1301
- lineItemsDiscount = lineItems.map((item) => {
1302
- const totalItemPercentage = item.pricePaid / subTotal;
1303
- const discountItem = couponDiscountMax * totalItemPercentage;
1304
- return {
1305
- ...item,
1306
- discount: Number(discountItem.toFixed(2)),
1307
- };
1308
- });
1309
- }
1310
- else {
1311
- lineItemsDiscount = lineItems.map((item) => {
1312
- const discountItem = item.pricePaid * (couponDiscount / 100);
1313
- return {
1314
- ...item,
1315
- discount: Number(discountItem.toFixed(2)),
1316
- };
1317
- });
1318
- }
1319
- return lineItemsDiscount;
1320
- }
1321
1167
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CouponService, deps: [{ token: 'CouponRepository' }, { token: DEFAULT_SHOP }, { token: 'OrderRepository' }, { token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable }); }
1322
1168
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CouponService, providedIn: 'root' }); }
1323
1169
  }
@@ -1341,17 +1187,18 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
1341
1187
  }] }] });
1342
1188
 
1343
1189
  class CheckoutService {
1344
- constructor(couponService, checkoutRepository, userRepository, defaultShop, dataPersistence) {
1190
+ constructor(couponService, checkoutRepository, orderRepository, userRepository, defaultShop) {
1345
1191
  this.couponService = couponService;
1346
1192
  this.checkoutRepository = checkoutRepository;
1193
+ this.orderRepository = orderRepository;
1347
1194
  this.userRepository = userRepository;
1348
1195
  this.defaultShop = defaultShop;
1349
- this.dataPersistence = dataPersistence;
1350
1196
  }
1351
1197
  getCheckout(checkoutData) {
1352
- return this.dataPersistence
1353
- .get('checkoutId')
1354
- .pipe(concatMap((id) => (!isNil(id) ? this.checkoutRepository.get({ id }) : this.createCheckout(checkoutData))));
1198
+ const checkoutId = cookie.get('checkoutId');
1199
+ if (!isNil(checkoutId))
1200
+ return from(this.checkoutRepository.get({ id: checkoutId }));
1201
+ return from(this.createCheckout(checkoutData));
1355
1202
  }
1356
1203
  getUserByCheckout(checkoutId) {
1357
1204
  return from(this.checkoutRepository.get({ id: checkoutId })).pipe(concatMap((checkout) => checkout?.user?.id ? of(checkout.user) : from(this.userRepository.get({ id: checkout.user.id }))), concatMap((user) => of(user) || throwError(() => new NotFoundError('User is not found'))));
@@ -1363,7 +1210,8 @@ class CheckoutService {
1363
1210
  return from(this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, user: checkout.user })));
1364
1211
  }
1365
1212
  clearCheckoutFromSession() {
1366
- return this.dataPersistence.remove('checkoutId');
1213
+ cookie.remove('checkoutId');
1214
+ return of();
1367
1215
  }
1368
1216
  calcDiscount(coupon) {
1369
1217
  return this.getCheckout().pipe(concatMap(async (checkout) => await this.couponService.calcDiscountShopping(coupon, checkout)));
@@ -1377,10 +1225,10 @@ class CheckoutService {
1377
1225
  ...Checkout.toInstance(pick(checkoutData, ['user', 'shop'])).toPlain(),
1378
1226
  shop: checkoutData?.shop || this.defaultShop,
1379
1227
  });
1380
- await this.dataPersistence.set('checkoutId', checkout.id).toPromise();
1228
+ cookie.set('checkoutId', checkout.id);
1381
1229
  return checkout;
1382
1230
  }
1383
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutService, deps: [{ token: CouponService }, { token: 'CheckoutRepository' }, { token: 'UserRepository' }, { token: DEFAULT_SHOP }, { token: PERSISTENCE_PROVIDER }], target: i0.ɵɵFactoryTarget.Injectable }); }
1231
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutService, deps: [{ token: CouponService }, { token: 'CheckoutRepository' }, { token: 'OrderRepository' }, { token: 'UserRepository' }, { token: DEFAULT_SHOP }], target: i0.ɵɵFactoryTarget.Injectable }); }
1384
1232
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutService }); }
1385
1233
  }
1386
1234
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutService, decorators: [{
@@ -1388,15 +1236,15 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
1388
1236
  }], ctorParameters: () => [{ type: CouponService }, { type: undefined, decorators: [{
1389
1237
  type: Inject,
1390
1238
  args: ['CheckoutRepository']
1239
+ }] }, { type: undefined, decorators: [{
1240
+ type: Inject,
1241
+ args: ['OrderRepository']
1391
1242
  }] }, { type: undefined, decorators: [{
1392
1243
  type: Inject,
1393
1244
  args: ['UserRepository']
1394
1245
  }] }, { type: i1$2.Shops, decorators: [{
1395
1246
  type: Inject,
1396
1247
  args: [DEFAULT_SHOP]
1397
- }] }, { type: undefined, decorators: [{
1398
- type: Inject,
1399
- args: [PERSISTENCE_PROVIDER]
1400
1248
  }] }] });
1401
1249
 
1402
1250
  class CartService {
@@ -1412,11 +1260,9 @@ class CartService {
1412
1260
  this.updateLineItemInCart = (lineItem, quantity, checkout) => (isNil(checkout) ? this.checkoutService.getCheckout() : of(checkout)).pipe(concatMap((checkoutLoaded) => {
1413
1261
  const items = [];
1414
1262
  const index = checkoutLoaded.lineItems?.map((checkoutItem) => checkoutItem.id).indexOf(lineItem.id);
1415
- const isGift = checkoutLoaded.lineItems?.[index]?.isGift;
1416
1263
  if (index > -1) {
1417
1264
  checkoutLoaded.lineItems[index].quantity += quantity;
1418
- checkoutLoaded.lineItems[index].pricePaid = isGift ? 0 : lineItem.pricePaid;
1419
- checkoutLoaded.lineItems[index].price = lineItem.price;
1265
+ checkoutLoaded.lineItems[index].pricePaid = lineItem.pricePaid;
1420
1266
  }
1421
1267
  else
1422
1268
  checkoutLoaded.lineItems = items.concat(checkoutLoaded.lineItems ? checkoutLoaded.lineItems.concat([lineItem]) : [lineItem]);
@@ -1434,20 +1280,17 @@ class CartService {
1434
1280
  this.buildLineItem = async ({ checkout, item, quantity, }) => {
1435
1281
  const product = await this.getProductData(item.id);
1436
1282
  item.quantity = item?.quantity || checkout?.lineItems?.find((lineItem) => lineItem.id === item.id)?.quantity || 0;
1437
- if (this.checkMaxStock(product.stock.quantity, item.quantity || 0, quantity || 0))
1438
- throw new Error('Desculpe! Temos apenas ' + product.stock?.quantity + ' em estoque.');
1283
+ if (this.checkMaxStock(item, quantity || 0))
1284
+ throw new Error('Desculpe! Temos apenas ' + item.stock?.quantity + ' em estoque.');
1439
1285
  const image = item.image || item.images?.shift();
1440
- const { id, name, EAN, slug, weight, sku, type } = item;
1441
- const isGift = item?.isGift || null;
1442
- const pricePaid = isGift
1443
- ? 0
1444
- : this.getProductPrice({
1445
- product: LineItem.toInstance(product),
1446
- shop: checkout.shop || this.defaultShop,
1447
- isSubscriber: checkout.user?.isSubscriber,
1448
- });
1286
+ const { id, name, EAN, slug, stock, price, weight, sku, type } = item;
1287
+ const isGift = item.isGift || null;
1288
+ const pricePaid = this.getProductPrice({
1289
+ product: item,
1290
+ shop: checkout.shop || this.defaultShop,
1291
+ isSubscriber: checkout.user?.isSubscriber,
1292
+ });
1449
1293
  RoundProductPricesHelper.roundProductPrices(item);
1450
- RoundProductPricesHelper.roundProductPrices(product);
1451
1294
  return {
1452
1295
  checkout,
1453
1296
  lineItem: LineItem.toInstance({
@@ -1457,19 +1300,16 @@ class CartService {
1457
1300
  brand: product.brand,
1458
1301
  slug: slug ?? product.slug,
1459
1302
  sku: sku ?? product.sku,
1460
- stock: product.stock,
1461
- price: this.roundPrice(product.price),
1303
+ stock,
1304
+ price: this.roundPrice(price),
1462
1305
  image,
1463
1306
  weight: weight ?? product.weight,
1464
1307
  quantity: (item.quantity || 0) + (quantity || 0),
1465
1308
  pricePaid,
1466
- discount: 0,
1467
- categories: product.categories || product.category?.id ? [product.category?.id, ...product.categories] : [],
1468
- category: product.category,
1309
+ categories: product.categories ?? [],
1469
1310
  isGift: isGift ?? null,
1470
- costPrice: isGift ? 0 : product.costPrice ?? 0,
1311
+ costPrice: product.costPrice ?? 0,
1471
1312
  type,
1472
- label: product.label,
1473
1313
  }),
1474
1314
  };
1475
1315
  };
@@ -1481,10 +1321,10 @@ class CartService {
1481
1321
  ? Number(info.subscriberPrice.toFixed(2))
1482
1322
  : Number(info.price.toFixed(2));
1483
1323
  };
1484
- this.checkMaxStock = (currentStock, currentItemQtd, quantityToAdd) => {
1485
- const maxStock = currentStock || 0;
1486
- const currentItemAmount = currentItemQtd || 0;
1487
- return currentItemAmount + quantityToAdd > maxStock;
1324
+ this.checkMaxStock = (item, quantity) => {
1325
+ const maxStock = item.stock?.quantity || 0;
1326
+ const currentItemAmount = item.quantity || 0;
1327
+ return currentItemAmount + quantity > maxStock;
1488
1328
  };
1489
1329
  }
1490
1330
  addItem(item, quantity = 1) {
@@ -1517,14 +1357,14 @@ class CartService {
1517
1357
  }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1518
1358
  }
1519
1359
  updateUserCart(user) {
1520
- return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user }))), concatMap(async (checkout) => await this.checkoutService
1360
+ return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user }))), concatMap(async (checkout) => this.checkoutService
1521
1361
  .updateCheckoutLineItems(Checkout.toInstance({
1522
1362
  ...checkout.toPlain(),
1523
1363
  lineItems: checkout.lineItems?.length
1524
1364
  ? await Promise.all(checkout.lineItems?.map(async (item) => (await this.buildLineItem({ checkout, item })).lineItem))
1525
1365
  : [],
1526
1366
  }))
1527
- .toPromise()), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => (this.user = user)), tap((cart) => this.cartSubject.next(cart)));
1367
+ .toPromise()), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1528
1368
  }
1529
1369
  clearCart() {
1530
1370
  return this.checkoutService.getCheckout().pipe(map((checkout) => {
@@ -1569,13 +1409,15 @@ class CartService {
1569
1409
  const notGiftItems = checkout.lineItems ? checkout.lineItems.filter((item) => !item.isGift) : [];
1570
1410
  if (!notGiftItems.length)
1571
1411
  return { ...checkout, lineItems: [] };
1412
+ const cartTotal = notGiftItems.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1572
1413
  const campaigns = await this.buy2WinRepository
1573
1414
  .find({
1574
1415
  filters: {
1575
1416
  active: { operator: Where.EQUALS, value: true },
1417
+ shop: { operator: Where.EQUALS, value: this.defaultShop },
1576
1418
  },
1577
1419
  })
1578
- .then((data) => data.data.filter((campaign) => campaign.shop === Shops.ALL || campaign.shop === this.defaultShop));
1420
+ .then((data) => data.data);
1579
1421
  if (!campaigns.length)
1580
1422
  return { ...checkout, lineItems: notGiftItems };
1581
1423
  const elegibleCampaigns = [];
@@ -1591,27 +1433,22 @@ class CartService {
1591
1433
  categoriesCampaingFullTree.push(id, ...children.map((c) => c.id.toString()));
1592
1434
  }
1593
1435
  const categoriesCampaingTree = [...new Set(categoriesCampaingFullTree)];
1594
- const filterProductsCategories = notGiftItems.filter((l) => {
1436
+ const filterProductsCategories = checkout.lineItems.filter((l) => {
1595
1437
  if (!l.categories || !l.categories?.length)
1596
1438
  return true;
1597
1439
  return l.categories.some((c) => categoriesCampaingTree.some((cat) => cat == c));
1598
1440
  });
1599
1441
  if (filterProductsCategories.length) {
1600
- const cartValuelWithCategories = filterProductsCategories.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1601
- const cartItensQuantityWithCategories = filterProductsCategories.reduce((a, b) => a + b.quantity, 0);
1602
- const hasMinValue = campaign.cartValueMin && cartValuelWithCategories >= campaign.cartValueMin;
1603
- const hasMinQuantity = campaign.cartItensQuantityMin && cartItensQuantityWithCategories >= campaign.cartItensQuantityMin;
1604
- if (hasMinQuantity || hasMinValue)
1442
+ const cartTotalCategories = filterProductsCategories.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1443
+ if (cartTotalCategories >= campaign.cartValueMin)
1605
1444
  elegibleCampaigns.push(campaign);
1606
1445
  }
1607
1446
  }
1608
1447
  else {
1609
- const cartTotal = notGiftItems.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1610
- const cartItensQuantity = notGiftItems.reduce((a, b) => a + b.quantity, 0);
1611
- const hasMinValue = campaign.cartValue && campaign.cartValue > 0 && campaign.cartValue <= cartTotal;
1612
- const hasMinQuantity = campaign.cartItensQuantityMin && cartItensQuantity >= campaign.cartItensQuantityMin;
1613
- if (hasMinQuantity || hasMinValue)
1614
- elegibleCampaigns.push(campaign);
1448
+ if (campaign.cartValue && campaign.cartValue > 0) {
1449
+ if (campaign.cartValue <= cartTotal)
1450
+ elegibleCampaigns.push(campaign);
1451
+ }
1615
1452
  }
1616
1453
  }
1617
1454
  if (!elegibleCampaigns.length)
@@ -1638,12 +1475,11 @@ class CartService {
1638
1475
  }
1639
1476
  giftToLineItems(items) {
1640
1477
  return items.map((item) => {
1641
- const { brand, categories, category, id, name, price, sku, slug, stock, weight, EAN } = item;
1478
+ const { brand, categories, id, name, price, sku, slug, stock, weight, EAN } = item;
1642
1479
  const image = item?.miniatures?.length ? item.miniatures[0] : item.images[0];
1643
1480
  return LineItem.toInstance({
1644
1481
  brand,
1645
1482
  categories,
1646
- category,
1647
1483
  id: id.toString(),
1648
1484
  name,
1649
1485
  price,
@@ -1705,11 +1541,9 @@ class NewCategoryStructureAdapter {
1705
1541
  .then((categories) => categories.map((category) => category.id.toString()));
1706
1542
  }
1707
1543
  async getCategory(category) {
1708
- const collectionCategory = category.isCollection ||
1709
- (isNil(category.isCollection) && !category.products?.length) ||
1710
- category.isWishlist ||
1711
- category.brandCategory;
1712
- return collectionCategory ? this.categoryRepository.get({ id: category.id }) : category;
1544
+ return isNil(category.isCollection) || (category.isCollection && !category.products?.length)
1545
+ ? this.categoryRepository.get({ id: category.id })
1546
+ : category;
1713
1547
  }
1714
1548
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: NewCategoryStructureAdapter, deps: [{ token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable }); }
1715
1549
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: NewCategoryStructureAdapter }); }
@@ -1742,15 +1576,13 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
1742
1576
  }] }] });
1743
1577
 
1744
1578
  class CatalogService {
1745
- constructor(productRepository, productStockNotificationRepository, categoryRepository, categoryStructureAdapter, shop, productSearch) {
1579
+ constructor(productRepository, categoryRepository, categoryStructureAdapter, shop, productIndex) {
1746
1580
  this.productRepository = productRepository;
1747
- this.productStockNotificationRepository = productStockNotificationRepository;
1748
1581
  this.categoryRepository = categoryRepository;
1749
1582
  this.categoryStructureAdapter = categoryStructureAdapter;
1750
1583
  this.shop = shop;
1751
- this.productSearch = productSearch;
1584
+ this.productIndex = productIndex;
1752
1585
  this.productsByTerm = {};
1753
- this.brandsList = {};
1754
1586
  this.buildFilterQuery = ({ clubDiscount, brands, prices, gender, tags, rate, customOptions, }) => {
1755
1587
  const filters = {};
1756
1588
  if (clubDiscount?.length)
@@ -1776,22 +1608,17 @@ class CatalogService {
1776
1608
  if (!sort || sort === 'most-relevant')
1777
1609
  return {};
1778
1610
  if (sort === 'best-sellers')
1779
- return {
1780
- shoppingCount: 'desc',
1781
- rate: 'desc',
1782
- stock: 'desc',
1783
- name: 'asc',
1784
- };
1611
+ return { shoppingCount: 'desc' };
1785
1612
  if (sort === 'biggest-price')
1786
- return { subscriberPrice: 'desc', rate: 'desc', shoppingCount: 'desc' };
1613
+ return { subscriberPrice: 'desc' };
1787
1614
  if (sort === 'lowest-price')
1788
- return { subscriberPrice: 'asc', rate: 'desc', shoppingCount: 'desc' };
1615
+ return { subscriberPrice: 'asc' };
1789
1616
  if (sort === 'best-rating')
1790
- return { rate: 'desc', shoppingCount: 'desc', stock: 'desc', name: 'asc' };
1617
+ return { rate: 'desc' };
1791
1618
  if (sort === 'news')
1792
1619
  return { createdAt: 'desc' };
1793
1620
  if (sort === 'biggest-discount')
1794
- return { subscriberDiscountPercentage: 'desc', rate: 'desc', shoppingCount: 'desc' };
1621
+ return { subscriberDiscountPercentage: 'desc' };
1795
1622
  };
1796
1623
  this.buildLimitQuery = (options) => {
1797
1624
  const limit = options?.perPage || 20;
@@ -1803,15 +1630,6 @@ class CatalogService {
1803
1630
  this.hasProfile = (options) => 'profile' in options;
1804
1631
  this.hasTerm = (options) => 'term' in options;
1805
1632
  this.hasCategory = (options) => 'category' in options;
1806
- this.buildIndexBrands = (options) => {
1807
- if (this.hasCategory(options))
1808
- return `category-${options.category.id}`;
1809
- if (this.hasTerm(options))
1810
- return `term-${options.term}`;
1811
- if (this.hasProfile(options))
1812
- return `profile-${options.profile.join(',')}`;
1813
- return '';
1814
- };
1815
1633
  }
1816
1634
  async fetchProducts(options) {
1817
1635
  const limits = this.buildLimitQuery(options);
@@ -1821,42 +1639,29 @@ class CatalogService {
1821
1639
  throw new InvalidArgumentError(`It couldn't filled tags when profile is given`);
1822
1640
  if (this.hasTerm(options) && options.filters?.customOptions)
1823
1641
  throw new InvalidArgumentError(`It couldn't filled customOptions when term is given`);
1824
- return await this.findCatalog(options, limits).then(async ({ data, count: total, maximum, minimal, distinct }) => {
1825
- await this.setBrandsList(options, distinct?.brand);
1826
- return {
1827
- products: { data: data.map((product) => RoundProductPricesHelper.roundProductPrices(product)), total },
1828
- pages: Math.ceil(total / limits.limit),
1829
- prices: {
1830
- price: { min: +minimal?.price?.price?.toFixed(2), max: +maximum?.price?.price?.toFixed(2) },
1831
- subscriberPrice: {
1832
- min: +minimal?.price?.subscriberPrice?.toFixed(2),
1833
- max: +maximum?.price?.subscriberPrice?.toFixed(2),
1834
- },
1642
+ return await this.findCatalog(options, limits).then(({ data, count: total, maximum, minimal, distinct }) => ({
1643
+ products: { data: data.map((product) => RoundProductPricesHelper.roundProductPrices(product)), total },
1644
+ pages: Math.ceil(total / limits.limit),
1645
+ prices: {
1646
+ price: { min: +minimal?.price?.price?.toFixed(2), max: +maximum?.price?.price?.toFixed(2) },
1647
+ subscriberPrice: {
1648
+ min: +minimal?.price?.subscriberPrice?.toFixed(2),
1649
+ max: +maximum?.price?.subscriberPrice?.toFixed(2),
1835
1650
  },
1836
- brands: this.brandsList[this.buildIndexBrands(options)],
1837
- };
1838
- });
1839
- }
1840
- async addCustomerToStockNotification(shop, productId, name, email) {
1841
- return this.productStockNotificationRepository.addCustomerEmail(shop, productId, name, email);
1651
+ },
1652
+ brands: distinct?.brand,
1653
+ }));
1842
1654
  }
1843
1655
  async findCatalog(options, limits) {
1844
1656
  if (this.hasTerm(options) && options.sort === 'most-relevant') {
1845
- const productsIds = await this.findCatalogIdsBySearch(options.term);
1846
- return this.findCatalogAndSortByMostRevelantByTerm(productsIds, options, limits);
1657
+ const productsIds = await this.findCatalogIdsByElasticSearch(options.term);
1658
+ return this.findCatalogAndSortByMostRevelant(productsIds, options, limits);
1847
1659
  }
1848
1660
  if (this.hasCategory(options) && options.sort === 'most-relevant') {
1849
- const mostRelevant = options.category.isWishlist ? [] : options.category.getMostRelevantByShop(this.shop);
1850
- const productsIds = await this.productRepository
1851
- .findCatalog({
1852
- fields: ['id'],
1853
- filters: {
1854
- ...(await this.buildMainFilter(options)),
1855
- ...this.buildFilterQuery(options?.filters || {}),
1856
- },
1857
- })
1858
- .then((products) => products.data.map((product) => product.id));
1859
- return this.findCatalogAndSortByMostRevelant(mostRelevant, productsIds, options, limits);
1661
+ const productsIds = options.category.products?.length
1662
+ ? options.category.products
1663
+ : await this.categoryRepository.get({ id: options.category.id }).then((categoryFound) => categoryFound.products);
1664
+ return this.findCatalogAndSortByMostRevelant(productsIds, options, limits);
1860
1665
  }
1861
1666
  const repoParams = {
1862
1667
  filters: {
@@ -1868,9 +1673,7 @@ class CatalogService {
1868
1673
  options: {
1869
1674
  minimal: ['price'],
1870
1675
  maximum: ['price'],
1871
- ...(!this.brandsList[this.buildIndexBrands(options)] && isEmpty(options.filters?.brands)
1872
- ? { distinct: ['brand'] }
1873
- : {}),
1676
+ ...(!this.hasCategory(options) ? { distinct: ['brand'] } : {}),
1874
1677
  },
1875
1678
  };
1876
1679
  if (['biggest-price', 'lowest-price', 'biggest-discount', 'best-rating'].includes(options.sort))
@@ -1883,72 +1686,27 @@ class CatalogService {
1883
1686
  if (profile)
1884
1687
  return { tags: { operator: Where.LIKE, value: profile } };
1885
1688
  if (term)
1886
- return this.productSearch
1887
- .search(term, 999, this.shop == Shops.GLAMSHOP ? 'female' : 'male')
1888
- .then((data) => ({ id: { operator: Where.IN, value: data.map((_source) => _source.id) } }));
1889
- }
1890
- async findCatalogAndSortByMostRevelant(mostRelevants, productIds, options, limits) {
1891
- const brandsList = this.brandsList[this.buildIndexBrands(options)];
1892
- const mostRelevantProductsIds = [...new Set(mostRelevants.concat(productIds))];
1893
- const totalResult = await this.productRepository.findCatalog({
1894
- filters: {
1895
- id: { operator: Where.IN, value: mostRelevantProductsIds },
1896
- ...this.buildFilterQuery(options?.filters || {}),
1897
- },
1898
- orderBy: this.buildSortQuery('best-sellers'),
1899
- options: {
1900
- minimal: ['price'],
1901
- maximum: ['price'],
1902
- ...(!brandsList && isEmpty(options.filters?.brands) ? { distinct: ['brand'] } : {}),
1903
- },
1904
- }, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female');
1905
- const mostRelevantWithouyStock = totalResult.data.filter((product) => mostRelevants.includes(product.id) && product.stock.quantity <= 0);
1906
- const firstProducts = totalResult.data
1907
- .filter((product) => mostRelevants.includes(product.id) && product.stock.quantity > 0)
1908
- .sort((a, b) => mostRelevants.indexOf(a.id) - mostRelevants.indexOf(b.id));
1909
- const lastProducts = totalResult.data
1910
- .filter((product) => !mostRelevants.includes(product.id))
1911
- .concat(mostRelevantWithouyStock);
1912
- const categoryMostRelevants = firstProducts.concat(lastProducts);
1913
- const resultFinal = categoryMostRelevants.slice(limits.offset, limits.offset + limits.limit);
1914
- await this.setBrandsList(options, totalResult.distinct?.brand);
1915
- return {
1916
- data: resultFinal,
1917
- count: totalResult.count,
1918
- maximum: totalResult.maximum,
1919
- minimal: totalResult.minimal,
1920
- distinct: {
1921
- ...totalResult.distinct,
1922
- brand: this.brandsList[this.buildIndexBrands(options)],
1923
- },
1924
- };
1689
+ return this.productIndex
1690
+ .search(term, 999, this.shop)
1691
+ .then((data) => ({ id: { operator: Where.IN, value: data.hits.map(({ _source }) => _source.id) } }));
1925
1692
  }
1926
- async findCatalogAndSortByMostRevelantByTerm(productIds, options, limits) {
1927
- const brandsList = this.brandsList[this.buildIndexBrands(options)];
1693
+ async findCatalogAndSortByMostRevelant(productIds, options, limits) {
1928
1694
  const totalResult = await this.productRepository.findCatalog({
1929
- fields: ['id', 'stock', 'gender'],
1695
+ fields: ['id', 'stock'],
1930
1696
  filters: {
1931
1697
  id: { operator: Where.IN, value: productIds },
1932
- published: { operator: Where.EQUALS, value: true },
1933
1698
  ...this.buildFilterQuery(options?.filters || {}),
1934
1699
  },
1935
1700
  options: {
1936
1701
  minimal: ['price'],
1937
1702
  maximum: ['price'],
1938
- ...(!brandsList && isEmpty(options.filters?.brands) ? { distinct: ['brand'] } : {}),
1703
+ distinct: ['brand'],
1939
1704
  },
1940
1705
  }, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female');
1941
- const defaultGender = options?.filters?.gender
1942
- ? options?.filters?.gender.at(0)
1943
- : this.shop === Shops.GLAMSHOP
1944
- ? 'female'
1945
- : 'male';
1946
1706
  const stockData = totalResult.data.filter((product) => product.stock.quantity > 0);
1947
1707
  const stockOut = totalResult.data.filter((product) => product.stock.quantity <= 0);
1948
- const productIdsStockGender = productIds.filter((product) => stockData.some((result) => result.id === product && (result.gender?.includes(defaultGender) || result.gender?.includes('unisex'))));
1949
- const productIdsStockNotGender = productIds.filter((product) => stockData.some((result) => result.id === product && !result.gender?.includes(defaultGender) && !result.gender?.includes('unisex')));
1950
- const productIdsStock = productIdsStockGender.concat(productIdsStockNotGender);
1951
- const productIdsStockOut = productIds.filter((product) => stockOut.some((result) => result.id === product));
1708
+ const productIdsStock = productIds.filter((product) => stockData.some((result) => result.id == product));
1709
+ const productIdsStockOut = productIds.filter((product) => stockOut.some((result) => result.id == product));
1952
1710
  const limitedProductId = productIdsStock
1953
1711
  .concat(productIdsStockOut)
1954
1712
  .slice(limits.offset, limits.offset + limits.limit);
@@ -1958,55 +1716,27 @@ class CatalogService {
1958
1716
  id: { operator: Where.IN, value: orderedId },
1959
1717
  },
1960
1718
  });
1961
- await this.setBrandsList(options, totalResult.distinct?.brand);
1962
1719
  return {
1963
1720
  data: limitedProductId.map((id) => productResult.data.find((product) => product.id === id)).filter(Boolean),
1964
1721
  count: totalResult.count,
1965
1722
  maximum: totalResult.maximum,
1966
1723
  minimal: totalResult.minimal,
1967
- distinct: {
1968
- ...totalResult.distinct,
1969
- brand: this.brandsList[this.buildIndexBrands(options)],
1970
- },
1724
+ distinct: totalResult.distinct,
1971
1725
  };
1972
1726
  }
1973
- async findCatalogIdsBySearch(term, preview = false) {
1727
+ async findCatalogIdsByElasticSearch(term) {
1974
1728
  if (this.productsByTerm[term])
1975
1729
  return this.productsByTerm[term];
1976
- return (this.productsByTerm[term] = await this.productSearch
1977
- .search(term, 999, this.shop == Shops.GLAMSHOP ? 'female' : 'male')
1978
- .then((products) => [...new Set(products.map((product) => product.id))]));
1979
- }
1980
- async fetchBrandsOnly(options, productIds = []) {
1981
- return this.productRepository
1982
- .findCatalog({
1983
- fields: ['id'],
1984
- filters: {
1985
- ...(!isEmpty(productIds) ? { id: { operator: Where.IN, value: productIds } } : {}),
1986
- published: { operator: Where.EQUALS, value: true },
1987
- ...this.buildFilterQuery(options?.filters || {}),
1988
- },
1989
- options: {
1990
- distinct: ['brand'],
1991
- },
1992
- }, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female')
1993
- .then((result) => {
1994
- return result.distinct.brand;
1995
- });
1996
- }
1997
- async setBrandsList(options, brands) {
1998
- const filterBrands = options.filters?.brands;
1999
- if (isEmpty(brands))
2000
- delete options.filters?.brands;
2001
- this.brandsList[this.buildIndexBrands(options)] =
2002
- this.brandsList[this.buildIndexBrands(options)] || brands || (await this.fetchBrandsOnly(options));
2003
- this.brandsList[this.buildIndexBrands(options)] = this.brandsList[this.buildIndexBrands(options)].filter(Boolean);
2004
- options.filters = {
2005
- ...options.filters,
2006
- brands: filterBrands,
2007
- };
1730
+ return (this.productsByTerm[term] = await this.productIndex
1731
+ .search(term, 999, this.shop)
1732
+ .then(({ hits: products }) => {
1733
+ const withStock = products.filter(({ _source }) => _source.stock.quantity > 0);
1734
+ const withOutStock = products.filter(({ _source }) => _source.stock.quantity <= 0);
1735
+ const sorted = [...withStock, ...withOutStock];
1736
+ return [...new Set(sorted.map(({ _source }) => _source.id))];
1737
+ }));
2008
1738
  }
2009
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CatalogService, deps: [{ token: 'ProductRepository' }, { token: 'ProductStockNotificationRepository' }, { token: 'CategoryRepository' }, { token: CATEGORY_STRUCTURE }, { token: DEFAULT_SHOP }, { token: 'ProductSearch' }], target: i0.ɵɵFactoryTarget.Injectable }); }
1739
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CatalogService, deps: [{ token: 'ProductRepository' }, { token: 'CategoryRepository' }, { token: CATEGORY_STRUCTURE }, { token: DEFAULT_SHOP }, { token: i1$2.ProductsIndex }], target: i0.ɵɵFactoryTarget.Injectable }); }
2010
1740
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CatalogService }); }
2011
1741
  }
2012
1742
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CatalogService, decorators: [{
@@ -2014,9 +1744,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2014
1744
  }], ctorParameters: () => [{ type: undefined, decorators: [{
2015
1745
  type: Inject,
2016
1746
  args: ['ProductRepository']
2017
- }] }, { type: undefined, decorators: [{
2018
- type: Inject,
2019
- args: ['ProductStockNotificationRepository']
2020
1747
  }] }, { type: undefined, decorators: [{
2021
1748
  type: Inject,
2022
1749
  args: ['CategoryRepository']
@@ -2026,10 +1753,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2026
1753
  }] }, { type: i1$2.Shops, decorators: [{
2027
1754
  type: Inject,
2028
1755
  args: [DEFAULT_SHOP]
2029
- }] }, { type: undefined, decorators: [{
2030
- type: Inject,
2031
- args: ['ProductSearch']
2032
- }] }] });
1756
+ }] }, { type: i1$2.ProductsIndex }] });
2033
1757
 
2034
1758
  class CategoryService {
2035
1759
  constructor(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop) {
@@ -2039,15 +1763,15 @@ class CategoryService {
2039
1763
  this.categoryStructureAdapter = categoryStructureAdapter;
2040
1764
  this.shop = shop;
2041
1765
  }
2042
- async fetchBrands(category, options) {
1766
+ async fetchBrands(category, mainGender) {
2043
1767
  const brands = await this.productRepository
2044
1768
  .findCatalog({
2045
1769
  filters: await this.categoryStructureAdapter.buildProductFilterByCategory(category),
2046
1770
  fields: ['brand'],
2047
- }, options?.mainGender ? options?.mainGender : this.shop === Shops.MENSMARKET ? 'male' : 'female')
1771
+ }, mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female')
2048
1772
  .then(({ data }) => Object.keys(data.map((product) => product.brand).reduce((brands, brand) => ({ ...brands, [brand]: true }), {})));
2049
1773
  return this.categoryRepository
2050
- .find({ filters: { brandCategory: true, shop: options?.shop || this.shop }, orderBy: { name: 'asc' } })
1774
+ .find({ filters: { brandCategory: true, shop: this.shop }, orderBy: { name: 'asc' } })
2051
1775
  .then(({ data }) => data.filter((category) => brands.includes(category.conditions.brand)));
2052
1776
  }
2053
1777
  async fetchFilterOptions(category) {
@@ -2096,14 +1820,11 @@ __decorate([
2096
1820
  ], CategoryWithTree.prototype, "children", void 0);
2097
1821
 
2098
1822
  class WishlistService {
2099
- constructor(wishlistRepository, shop, productRepository, categoryFilterRepository, categoryRepository, productStockNotificationRepository, productSearch, logRepository) {
1823
+ constructor(wishlistRepository, shop, productRepository, categoryFilterRepository, categoryRepository, productIndex) {
2100
1824
  this.wishlistRepository = wishlistRepository;
2101
1825
  this.shop = shop;
2102
- this.productRepository = productRepository;
2103
- this.productSearch = productSearch;
2104
- this.logRepository = logRepository;
2105
1826
  const categoryStructureAdapter = new NewCategoryStructureAdapter(wishlistRepository);
2106
- this.catalogService = new CatalogService(productRepository, productStockNotificationRepository, categoryRepository, categoryStructureAdapter, shop, productSearch);
1827
+ this.catalogService = new CatalogService(productRepository, categoryRepository, categoryStructureAdapter, shop, productIndex);
2107
1828
  this.categoryService = new CategoryService(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop);
2108
1829
  }
2109
1830
  getCatalogService() {
@@ -2112,76 +1833,46 @@ class WishlistService {
2112
1833
  getCategoryService() {
2113
1834
  return this.categoryService;
2114
1835
  }
2115
- async create({ personId, title, description, published, userFullName, userPhoto, theme, bannerUrl, personType, personIsSubscriber, }) {
1836
+ async create({ personId, title, description, userFullName, userPhoto, theme, bannerUrl, }) {
2116
1837
  const data = {
2117
1838
  slug: '',
2118
1839
  name: title,
2119
1840
  description,
2120
- metadatas: [
2121
- {
2122
- shop: this.shop,
2123
- title: `${userFullName} - ${title}`,
2124
- description: `${userFullName} - ${description}`,
2125
- },
2126
- ],
1841
+ metadata: {
1842
+ title: `${userFullName} - ${title}`,
1843
+ description: `${userFullName} - ${description}`,
1844
+ },
2127
1845
  shop: this.shop,
2128
1846
  shops: [this.shop],
2129
1847
  personId,
2130
1848
  personName: userFullName,
2131
1849
  personPhoto: userPhoto,
2132
1850
  brandCategory: false,
2133
- published,
1851
+ published: true,
2134
1852
  theme,
2135
1853
  bannerUrl,
2136
- personType: personType ?? PersonTypes.NONE,
2137
- personIsSubscriber: personIsSubscriber ?? false,
2138
1854
  };
2139
- const hasWishlist = await this.wishlistRepository
2140
- .find({
2141
- filters: {
2142
- personId,
2143
- },
2144
- options: {
2145
- enableCount: false,
2146
- },
2147
- orderBy: {
2148
- id: 'asc',
2149
- },
2150
- })
2151
- .then((res) => res.data);
2152
- await this.createWishlistLog(WishlistLogType.CREATE, data);
2153
- if (hasWishlist.length)
2154
- return hasWishlist.at(0);
2155
1855
  const newWishlist = await this.wishlistRepository.create(data);
2156
1856
  await this.wishlistRepository.update({ id: newWishlist.id, slug: newWishlist.id });
2157
1857
  return Wishlist.toInstance({ ...newWishlist.toPlain(), slug: newWishlist.id });
2158
1858
  }
2159
- async update({ id, title, description, published, userFullName, userPhoto, theme, bannerUrl, personType, personIsSubscriber, }) {
1859
+ update({ id, title, description, userFullName, userPhoto, theme, bannerUrl, }) {
2160
1860
  const data = {
2161
1861
  id,
2162
1862
  name: title,
2163
1863
  description,
2164
- published,
2165
- metadatas: [
2166
- {
2167
- shop: this.shop,
2168
- title: `${userFullName} - ${title}`,
2169
- description: `${userFullName} - ${description}`,
2170
- },
2171
- ],
1864
+ metadata: {
1865
+ title: `${userFullName} - ${title}`,
1866
+ description: `${userFullName} - ${description}`,
1867
+ },
2172
1868
  personName: userFullName,
2173
1869
  personPhoto: userPhoto,
2174
1870
  theme,
2175
1871
  bannerUrl,
2176
- personType: personType ?? PersonTypes.NONE,
2177
- personIsSubscriber: personIsSubscriber ?? false,
2178
1872
  };
2179
- await this.createWishlistLog(WishlistLogType.UPDATE, data);
2180
1873
  return this.wishlistRepository.update(data);
2181
1874
  }
2182
- async delete(wishlistId) {
2183
- const wishlist = await this.findById(wishlistId);
2184
- await this.createWishlistLog(WishlistLogType.DELETE, wishlist);
1875
+ delete(wishlistId) {
2185
1876
  return this.wishlistRepository.delete({ id: wishlistId });
2186
1877
  }
2187
1878
  getWishlistBySlug(slug) {
@@ -2196,12 +1887,9 @@ class WishlistService {
2196
1887
  async addProduct(wishlistId, productId) {
2197
1888
  const wishlist = await this.wishlistRepository.get({ id: wishlistId });
2198
1889
  const hasProduct = wishlist.products.some((p) => p == productId);
2199
- const wishlistData = await this.findById(wishlistId);
2200
- const productData = await this.findProductById(productId);
2201
- await this.createWishlistLog(WishlistLogType.ADD_PRODUCT, wishlistData, productData);
2202
1890
  if (!hasProduct) {
2203
1891
  wishlist.products = [...wishlist.products, productId];
2204
- await this.wishlistRepository.addProduct(wishlistId, productId);
1892
+ return this.wishlistRepository.update({ id: wishlistId, products: wishlist.products });
2205
1893
  }
2206
1894
  return wishlist;
2207
1895
  }
@@ -2210,88 +1898,13 @@ class WishlistService {
2210
1898
  const productIndex = wishlist.products.findIndex((p) => p == productId);
2211
1899
  if (productIndex != -1) {
2212
1900
  wishlist.products.splice(productIndex, 1);
2213
- const wishlistData = await this.findById(wishlistId);
2214
- const productData = await this.findProductById(productId);
2215
- await this.createWishlistLog(WishlistLogType.REMOVE_PRODUCT, wishlistData, productData);
2216
- await this.wishlistRepository.removeProduct(wishlistId, productId);
1901
+ if (!wishlist.products.length)
1902
+ return this.wishlistRepository.update({ id: wishlistId, products: { action: 'remove' } });
1903
+ return this.wishlistRepository.update({ id: wishlistId, products: wishlist.products });
2217
1904
  }
2218
1905
  return wishlist;
2219
1906
  }
2220
- async findById(id) {
2221
- return this.wishlistRepository
2222
- .find({
2223
- fields: ['id', 'name', 'description', 'personId', 'personIsSubscriber', 'personType', 'personName'],
2224
- filters: {
2225
- id,
2226
- },
2227
- })
2228
- .then((res) => res.data.at(0));
2229
- }
2230
- async findProductById(id) {
2231
- return this.productRepository
2232
- .find({
2233
- fields: ['id', 'sku', 'EAN', 'name', 'brand'],
2234
- filters: {
2235
- id,
2236
- },
2237
- })
2238
- .then((res) => res.data.at(0));
2239
- }
2240
- async createWishlistLog(type, wishlist, product) {
2241
- switch (type) {
2242
- case WishlistLogType.CREATE:
2243
- case WishlistLogType.UPDATE:
2244
- case WishlistLogType.DELETE:
2245
- await this.logRepository.create({
2246
- collection: 'wishlist',
2247
- date: new Date(),
2248
- operation: WishlistLogType.CREATE ? 'CREATE' : WishlistLogType.UPDATE ? 'UPDATE' : 'DELETE',
2249
- documentId: wishlist.id,
2250
- document: {
2251
- id: wishlist.id,
2252
- shop: this.shop,
2253
- name: wishlist.name,
2254
- description: wishlist.description,
2255
- published: wishlist.published,
2256
- type: type,
2257
- personType: wishlist.personType,
2258
- personId: wishlist.personId,
2259
- personName: wishlist.personName,
2260
- personIsSubscriber: wishlist.personIsSubscriber,
2261
- },
2262
- });
2263
- break;
2264
- case WishlistLogType.ADD_PRODUCT:
2265
- case WishlistLogType.REMOVE_PRODUCT:
2266
- await this.logRepository.create({
2267
- collection: 'wishlist',
2268
- date: new Date(),
2269
- operation: 'UPDATE',
2270
- documentId: wishlist.id,
2271
- document: {
2272
- id: wishlist.id,
2273
- shop: this.shop,
2274
- name: wishlist.name,
2275
- description: wishlist.description,
2276
- published: wishlist.published,
2277
- type: type,
2278
- personType: wishlist.personType,
2279
- personId: wishlist.personId,
2280
- personName: wishlist.personName,
2281
- personIsSubscriber: wishlist.personIsSubscriber,
2282
- productId: product.id,
2283
- productEAN: product.EAN,
2284
- productSKU: product.sku,
2285
- productName: product.name,
2286
- productBrand: product.brand,
2287
- },
2288
- });
2289
- break;
2290
- default:
2291
- break;
2292
- }
2293
- }
2294
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: WishlistService, deps: [{ token: 'WishlistRepository' }, { token: DEFAULT_SHOP }, { token: 'ProductRepository' }, { token: 'CategoryFilterRepository' }, { token: 'CategoryRepository' }, { token: 'ProductStockNotificationRepository' }, { token: 'ProductSearch' }, { token: 'LogRepository' }], target: i0.ɵɵFactoryTarget.Injectable }); }
1907
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: WishlistService, deps: [{ token: 'WishlistRepository' }, { token: DEFAULT_SHOP }, { token: 'ProductRepository' }, { token: 'CategoryFilterRepository' }, { token: 'CategoryRepository' }, { token: i1$2.ProductsIndex }], target: i0.ɵɵFactoryTarget.Injectable }); }
2295
1908
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: WishlistService }); }
2296
1909
  }
2297
1910
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: WishlistService, decorators: [{
@@ -2311,30 +1924,31 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2311
1924
  }] }, { type: undefined, decorators: [{
2312
1925
  type: Inject,
2313
1926
  args: ['CategoryRepository']
2314
- }] }, { type: undefined, decorators: [{
2315
- type: Inject,
2316
- args: ['ProductStockNotificationRepository']
2317
- }] }, { type: undefined, decorators: [{
2318
- type: Inject,
2319
- args: ['ProductSearch']
2320
- }] }, { type: undefined, decorators: [{
2321
- type: Inject,
2322
- args: ['LogRepository']
2323
- }] }] });
1927
+ }] }, { type: i1$2.ProductsIndex }] });
2324
1928
 
2325
1929
  class CheckoutSubscriptionService {
2326
- constructor(checkoutSubscriptionRepository, dataPersistence, couponService) {
1930
+ constructor(checkoutSubscriptionRepository, subscriptionRepository, couponService) {
2327
1931
  this.checkoutSubscriptionRepository = checkoutSubscriptionRepository;
2328
- this.dataPersistence = dataPersistence;
1932
+ this.subscriptionRepository = subscriptionRepository;
2329
1933
  this.couponService = couponService;
2330
1934
  }
2331
1935
  getCheckoutSubscription(checkoutData) {
2332
- return this.dataPersistence
2333
- .get('checkoutSubscriptionId')
2334
- .pipe(concatMap((id) => !isNil(id) ? this.checkoutSubscriptionRepository.get({ id }) : this.createCheckoutSubscription(checkoutData)));
1936
+ const checkoutId = cookie.get('checkoutSubscriptionId');
1937
+ if (!isNil(checkoutId))
1938
+ return from(this.checkoutSubscriptionRepository.get({ id: checkoutId }));
1939
+ return from(this.createCheckoutSubscription(checkoutData));
1940
+ }
1941
+ async createCheckoutSubscription(checkoutData) {
1942
+ const checkout = await this.checkoutSubscriptionRepository.create({
1943
+ createdAt: new Date(),
1944
+ ...CheckoutSubscription.toInstance(pick(checkoutData, ['user', 'shop'])).toPlain(),
1945
+ });
1946
+ cookie.set('checkoutSubscriptionId', checkout.id);
1947
+ return checkout;
2335
1948
  }
2336
1949
  clearCheckoutSubscriptionFromSession() {
2337
- return this.dataPersistence.remove('checkoutSubscriptionId');
1950
+ cookie.remove('checkoutSubscriptionId');
1951
+ return of();
2338
1952
  }
2339
1953
  checkCoupon(nickname, userEmail) {
2340
1954
  return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService
@@ -2344,15 +1958,7 @@ class CheckoutSubscriptionService {
2344
1958
  calcDiscountSubscription(coupon) {
2345
1959
  return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService.calcDiscountSubscription(coupon, checkout).pipe()));
2346
1960
  }
2347
- async createCheckoutSubscription(checkoutData) {
2348
- const checkout = await this.checkoutSubscriptionRepository.create({
2349
- createdAt: new Date(),
2350
- ...CheckoutSubscription.toInstance(pick(checkoutData, ['user', 'shop'])).toPlain(),
2351
- });
2352
- await this.dataPersistence.set('checkoutSubscriptionId', checkout.id).toPromise();
2353
- return checkout;
2354
- }
2355
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutSubscriptionService, deps: [{ token: 'CheckoutSubscriptionRepository' }, { token: PERSISTENCE_PROVIDER }, { token: CouponService }], target: i0.ɵɵFactoryTarget.Injectable }); }
1961
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutSubscriptionService, deps: [{ token: 'CheckoutSubscriptionRepository' }, { token: 'SubscriptionRepository' }, { token: CouponService }], target: i0.ɵɵFactoryTarget.Injectable }); }
2356
1962
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutSubscriptionService }); }
2357
1963
  }
2358
1964
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutSubscriptionService, decorators: [{
@@ -2362,7 +1968,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2362
1968
  args: ['CheckoutSubscriptionRepository']
2363
1969
  }] }, { type: undefined, decorators: [{
2364
1970
  type: Inject,
2365
- args: [PERSISTENCE_PROVIDER]
1971
+ args: ['SubscriptionRepository']
2366
1972
  }] }, { type: CouponService }] });
2367
1973
 
2368
1974
  class UtilHelper {
@@ -2447,10 +2053,10 @@ class HomeShopService {
2447
2053
  return this.getHomeConfiguration().pipe(map((home) => home.minValueForFreeShipping));
2448
2054
  }
2449
2055
  getDiscoverProducts(gender) {
2450
- return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.discoverCategories, this.defaultShop)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
2056
+ return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.discoverCategories, undefined, gender)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
2451
2057
  }
2452
2058
  getFeaturedProducts(gender) {
2453
- return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.featuredCategories, this.defaultShop)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
2059
+ return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.featuredCategories, undefined, gender)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
2454
2060
  }
2455
2061
  getVerticalProducts(gender) {
2456
2062
  return this.getHomeConfiguration().pipe(concatMap((home) => forkJoin(home.verticalCarousels.filter(Boolean).map((id) => from(this.categoryRepository.get({ id })).pipe(concatMap((category) => from(this.productRepository.find({
@@ -2620,12 +2226,10 @@ class AngularConnectModule {
2620
2226
  ? OldCategoryStructureAdapter
2621
2227
  : NewCategoryStructureAdapter,
2622
2228
  },
2623
- { provide: PERSISTENCE_PROVIDER, useClass: options?.persistenceProvider || CookieDataPersistence },
2624
2229
  ...(isNil(defaultShop) ? [] : [{ provide: DEFAULT_SHOP, useValue: defaultShop }]),
2625
2230
  ...(isNil(options?.firebase) ? [] : [{ provide: FIREBASE_OPTIONS, useValue: options?.firebase }]),
2626
2231
  ...(isNil(options?.firebase) ? [] : [{ provide: FIREBASE_APP_NAME, useValue: nameOrConfig }]),
2627
2232
  ...(isNil(options?.elasticSearch) ? [] : [{ provide: ES_CONFIG, useValue: options.elasticSearch }]),
2628
- ...(isNil(options?.vertexConfig) ? [] : [{ provide: VERTEX_CONFIG, useValue: options.vertexConfig }]),
2629
2233
  ...(isNil(options?.hasura) ? [] : [{ provide: HASURA_OPTIONS, useValue: options.hasura }]),
2630
2234
  ...(isNil(options?.backendUrl) ? [] : [{ provide: BACKEND_URL, useValue: options.backendUrl }]),
2631
2235
  ...(isNil(options?.storageBaseUrl) ? [] : [{ provide: STORAGE_BASE_URL, useValue: options.storageBaseUrl }]),
@@ -2633,8 +2237,7 @@ class AngularConnectModule {
2633
2237
  };
2634
2238
  }
2635
2239
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularConnectModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
2636
- static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularConnectModule, imports: [i1$4.FirebaseAppModule, i2.StorageModule, AngularElasticSeachModule,
2637
- AngularVertexSeachModule,
2240
+ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularConnectModule, imports: [i1$4.FirebaseAppModule, AngularElasticSeachModule,
2638
2241
  AngularFirebaseAuthModule,
2639
2242
  AngularFirestoreModule,
2640
2243
  AngularHasuraGraphQLModule] }); }
@@ -2657,17 +2260,6 @@ class AngularConnectModule {
2657
2260
  },
2658
2261
  deps: ['UserRepository', 'FileUploaderService'],
2659
2262
  },
2660
- {
2661
- provide: 'FileUploaderService',
2662
- useFactory: (storage, baseUrl) => {
2663
- return new FirebaseFileUploaderService(storage, baseUrl);
2664
- },
2665
- deps: [Storage, STORAGE_BASE_URL],
2666
- },
2667
- {
2668
- provide: 'ProductSearch',
2669
- useExisting: ProductsVertexSearch,
2670
- },
2671
2263
  ], imports: [provideFirebaseApp((injector) => {
2672
2264
  const appName = injector.get(FIREBASE_APP_NAME) || '[DEFAULT]';
2673
2265
  try {
@@ -2677,9 +2269,7 @@ class AngularConnectModule {
2677
2269
  return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2678
2270
  }
2679
2271
  }),
2680
- provideStorage((injector) => getStorage(injector.get(FirebaseApp))),
2681
2272
  AngularElasticSeachModule,
2682
- AngularVertexSeachModule,
2683
2273
  AngularFirebaseAuthModule,
2684
2274
  AngularFirestoreModule,
2685
2275
  AngularHasuraGraphQLModule] }); }
@@ -2697,9 +2287,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2697
2287
  return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2698
2288
  }
2699
2289
  }),
2700
- provideStorage((injector) => getStorage(injector.get(FirebaseApp))),
2701
2290
  AngularElasticSeachModule,
2702
- AngularVertexSeachModule,
2703
2291
  AngularFirebaseAuthModule,
2704
2292
  AngularFirestoreModule,
2705
2293
  AngularHasuraGraphQLModule,
@@ -2723,17 +2311,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2723
2311
  },
2724
2312
  deps: ['UserRepository', 'FileUploaderService'],
2725
2313
  },
2726
- {
2727
- provide: 'FileUploaderService',
2728
- useFactory: (storage, baseUrl) => {
2729
- return new FirebaseFileUploaderService(storage, baseUrl);
2730
- },
2731
- deps: [Storage, STORAGE_BASE_URL],
2732
- },
2733
- {
2734
- provide: 'ProductSearch',
2735
- useExisting: ProductsVertexSearch,
2736
- },
2737
2314
  ],
2738
2315
  }]
2739
2316
  }] });
@@ -2742,5 +2319,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2742
2319
  * Generated bundle index. Do not edit.
2743
2320
  */
2744
2321
 
2745
- export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CookieDataPersistence, CouponService, HomeShopService, NewCategoryStructureAdapter, OldCategoryStructureAdapter, OrderService, ProductSorts, ShippingService, UtilHelper, WishlistService };
2322
+ export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CouponService, HomeShopService, NewCategoryStructureAdapter, OldCategoryStructureAdapter, OrderService, ProductSorts, ShippingService, UtilHelper, WishlistService };
2746
2323
  //# sourceMappingURL=infrab4a-connect-angular.mjs.map