@infrab4a/connect-angular 5.0.0-beta.68 → 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 +2 -24
  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 +18 -140
  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 +190 -593
  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, 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,
@@ -897,17 +870,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
897
870
  },
898
871
  deps: ['HasuraConfig'],
899
872
  },
900
- {
901
- provide: 'ProductStockNotificationRepository',
902
- useExisting: ProductStockNotificationHasuraGraphQLRepository,
903
- },
904
- {
905
- provide: ProductStockNotificationHasuraGraphQLRepository,
906
- useFactory: (hasuraConfig) => {
907
- return new ProductStockNotificationHasuraGraphQLRepository(hasuraConfig);
908
- },
909
- deps: ['HasuraConfig'],
910
- },
911
873
  {
912
874
  provide: 'CategoryFilterRepository',
913
875
  useExisting: CategoryFilterHasuraGraphQLRepository,
@@ -965,55 +927,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
965
927
  }]
966
928
  }] });
967
929
 
968
- class AngularVertexSeachModule {
969
- static initializeApp(options) {
970
- return {
971
- ngModule: AngularVertexSeachModule,
972
- providers: [{ provide: VERTEX_CONFIG, useValue: options }],
973
- };
974
- }
975
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
976
- static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule }); }
977
- static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule, providers: [
978
- {
979
- provide: ProductsVertexSearch,
980
- useFactory: (configuration) => new ProductsVertexSearch(new VertexAxiosAdapter(configuration)),
981
- deps: [VERTEX_CONFIG],
982
- },
983
- ] }); }
984
- }
985
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule, decorators: [{
986
- type: NgModule,
987
- args: [{
988
- providers: [
989
- {
990
- provide: ProductsVertexSearch,
991
- useFactory: (configuration) => new ProductsVertexSearch(new VertexAxiosAdapter(configuration)),
992
- deps: [VERTEX_CONFIG],
993
- },
994
- ],
995
- }]
996
- }] });
997
-
998
- const STORAGE_BASE_URL = 'STORAGE_BASE_URL';
999
-
1000
- class CookieDataPersistence {
1001
- get(key) {
1002
- return of(cookie.get(key));
1003
- }
1004
- remove(key) {
1005
- return of(cookie.remove(key));
1006
- }
1007
- set(key, value) {
1008
- return from(cookie.set(key, value)).pipe(map(() => { }));
1009
- }
1010
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CookieDataPersistence, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1011
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CookieDataPersistence }); }
1012
- }
1013
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CookieDataPersistence, decorators: [{
1014
- type: Injectable
1015
- }] });
1016
-
1017
930
  class AuthService {
1018
931
  constructor(angularFireAuth, userRepository) {
1019
932
  this.angularFireAuth = angularFireAuth;
@@ -1094,11 +1007,11 @@ class CouponService {
1094
1007
  throw 'Limite de uso atingido';
1095
1008
  }
1096
1009
  if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
1097
- const ordersCoupon = await this.getOrdersWithCoupon(coupon);
1098
- 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)
1099
1012
  throw 'Limite de uso atingido.';
1100
1013
  if (couponUseLimits.limitedPerUser) {
1101
- const ordersWithUser = this.countOrdersWithUser(ordersCoupon, checkout.user.email);
1014
+ const ordersWithUser = this.countOrdersWithUser(orders, checkout.user.email);
1102
1015
  if (ordersWithUser > 0)
1103
1016
  throw 'Limite de uso por usuário atingido.';
1104
1017
  }
@@ -1107,12 +1020,8 @@ class CouponService {
1107
1020
  if (!hasProductCategories)
1108
1021
  throw 'Seu carrinho não possui produtos elegíveis para desconto.';
1109
1022
  const hasMinSubTotal = await this.hasMinSubTotal(coupon, checkout);
1110
- if (!hasMinSubTotal) {
1111
- if (coupon.productsCategories?.length) {
1112
- 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.`;
1113
- }
1114
- throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido.`;
1115
- }
1023
+ if (!hasMinSubTotal)
1024
+ throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido`;
1116
1025
  return coupon;
1117
1026
  }
1118
1027
  calcDiscountSubscription(coupon, checkout) {
@@ -1124,53 +1033,45 @@ class CouponService {
1124
1033
  return of(discount);
1125
1034
  }
1126
1035
  async calcDiscountShopping(coupon, checkout) {
1127
- let discountInfo = null;
1036
+ let discount = 0;
1128
1037
  if (checkout.user.isSubscriber && coupon.discount.subscriber.value) {
1129
- 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);
1130
1039
  }
1131
1040
  else {
1132
- 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);
1133
1042
  }
1134
- return { discount: discountInfo.discount, lineItems: discountInfo.lineItems };
1043
+ return discount;
1135
1044
  }
1136
1045
  async calcDiscountByType(type, value, categories, checkout) {
1137
1046
  let discount = 0;
1138
- if (type == CouponTypes.SHIPPING) {
1139
- const subTotal = checkout.shipping.ShippingPrice;
1140
- const discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2);
1141
- return { discount, lineItems: checkout.lineItems };
1142
- }
1143
- let lineItensElegibleForDiscount = await this.getLineItensEligebleForDiscount(categories, checkout);
1144
- 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);
1145
1049
  if (type == CouponTypes.ABSOLUTE) {
1146
1050
  discount = value > subTotal ? subTotal : value;
1147
1051
  }
1148
1052
  else {
1149
- discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2);
1053
+ discount = subTotal * (value / 100);
1150
1054
  }
1151
- const lineItems = this.calcLineItenDiscount(type, lineItensElegibleForDiscount, value, subTotal);
1152
- return { discount, lineItems };
1055
+ return discount;
1153
1056
  }
1154
1057
  async hasMinSubTotal(coupon, checkout) {
1155
1058
  if (!coupon.minSubTotalValue)
1156
1059
  return true;
1157
1060
  let lineItensDiscount = await this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
1158
- const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user);
1061
+ const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user, checkout.shop);
1159
1062
  if (coupon.minSubTotalValue <= subTotal)
1160
1063
  return true;
1161
1064
  return false;
1162
1065
  }
1163
1066
  async hasProductCategories(coupon, checkout) {
1164
- if (!coupon.productsCategories || !coupon.productsCategories?.length) {
1067
+ if (!coupon.productsCategories || !coupon.productsCategories.length) {
1165
1068
  return true;
1166
1069
  }
1167
1070
  const couponCategories = await this.getCouponCategoriesId(coupon.productsCategories);
1168
- const hasCategories = checkout.lineItems?.filter((item) => {
1169
- if (item.isGift)
1170
- return false;
1171
- if (!item.categories || !item.categories?.length)
1071
+ const hasCategories = checkout.lineItems?.filter((i) => {
1072
+ if (!i.categories || !i.categories?.length)
1172
1073
  return true;
1173
- return item.categories.some((c) => couponCategories.some((cat) => cat == c));
1074
+ return i.categories.some((c) => couponCategories.some((cat) => cat == c));
1174
1075
  });
1175
1076
  return hasCategories.length ? true : false;
1176
1077
  }
@@ -1213,24 +1114,20 @@ class CouponService {
1213
1114
  let lineItensDiscount = [];
1214
1115
  const couponCategories = await this.getCouponCategoriesId(productsCategories);
1215
1116
  if (productsCategories && productsCategories.length) {
1216
- lineItensDiscount = checkout.lineItems?.filter((item) => {
1217
- if (item.isGift)
1218
- return false;
1219
- if (item.categories?.length) {
1220
- 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));
1221
1120
  }
1222
1121
  return true;
1223
1122
  });
1224
1123
  }
1225
1124
  else {
1226
- lineItensDiscount = checkout.lineItems.filter((item) => !item.isGift);
1125
+ lineItensDiscount = checkout.lineItems;
1227
1126
  }
1228
1127
  return lineItensDiscount;
1229
1128
  }
1230
- calcCheckoutSubtotal(lineItens, user) {
1231
- return (lineItens
1232
- ?.filter((item) => !item.isGift)
1233
- .reduce((acc, curr) => user?.isSubscriber && curr.price.subscriberPrice
1129
+ calcCheckoutSubtotal(lineItens, user, shop) {
1130
+ return (lineItens?.reduce((acc, curr) => user?.isSubscriber && curr.price.subscriberPrice
1234
1131
  ? acc + curr.price?.subscriberPrice * curr.quantity
1235
1132
  : acc + curr.pricePaid * curr.quantity, 0) || 0);
1236
1133
  }
@@ -1239,7 +1136,7 @@ class CouponService {
1239
1136
  .find({
1240
1137
  filters: {
1241
1138
  coupon: { id: coupon.id },
1242
- status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1139
+ payment: { status: 'paid' },
1243
1140
  },
1244
1141
  })
1245
1142
  .then((result) => result.data);
@@ -1249,7 +1146,7 @@ class CouponService {
1249
1146
  .find({
1250
1147
  filters: {
1251
1148
  user: { email: { operator: Where.EQUALS, value: email } },
1252
- status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1149
+ payment: { status: 'paid' },
1253
1150
  },
1254
1151
  })
1255
1152
  .then((result) => result.data);
@@ -1260,42 +1157,13 @@ class CouponService {
1260
1157
  getCouponUseLimits(coupon, checkoutType, user) {
1261
1158
  let couponUseLimits;
1262
1159
  if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
1263
- if (coupon.exclusivityType.length === 1 &&
1264
- (coupon.exclusivityType.at(0) === Exclusivities.SPECIFIC_USER ||
1265
- coupon.exclusivityType.at(0) === Exclusivities.COLLABORATORS))
1266
- couponUseLimits = coupon.useLimits.non_subscriber;
1267
- else
1268
- couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
1160
+ couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
1269
1161
  }
1270
1162
  else {
1271
1163
  couponUseLimits = coupon.useLimits.subscription;
1272
1164
  }
1273
1165
  return couponUseLimits;
1274
1166
  }
1275
- calcLineItenDiscount(type, lineItems, couponDiscount, subTotal) {
1276
- let lineItemsDiscount = [];
1277
- if (type === CouponTypes.ABSOLUTE) {
1278
- const couponDiscountMax = couponDiscount > subTotal ? subTotal : couponDiscount;
1279
- lineItemsDiscount = lineItems.map((item) => {
1280
- const totalItemPercentage = item.pricePaid / subTotal;
1281
- const discountItem = couponDiscountMax * totalItemPercentage;
1282
- return {
1283
- ...item,
1284
- discount: Number(discountItem.toFixed(2)),
1285
- };
1286
- });
1287
- }
1288
- else {
1289
- lineItemsDiscount = lineItems.map((item) => {
1290
- const discountItem = item.pricePaid * (couponDiscount / 100);
1291
- return {
1292
- ...item,
1293
- discount: Number(discountItem.toFixed(2)),
1294
- };
1295
- });
1296
- }
1297
- return lineItemsDiscount;
1298
- }
1299
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 }); }
1300
1168
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CouponService, providedIn: 'root' }); }
1301
1169
  }
@@ -1319,17 +1187,18 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
1319
1187
  }] }] });
1320
1188
 
1321
1189
  class CheckoutService {
1322
- constructor(couponService, checkoutRepository, userRepository, defaultShop, dataPersistence) {
1190
+ constructor(couponService, checkoutRepository, orderRepository, userRepository, defaultShop) {
1323
1191
  this.couponService = couponService;
1324
1192
  this.checkoutRepository = checkoutRepository;
1193
+ this.orderRepository = orderRepository;
1325
1194
  this.userRepository = userRepository;
1326
1195
  this.defaultShop = defaultShop;
1327
- this.dataPersistence = dataPersistence;
1328
1196
  }
1329
1197
  getCheckout(checkoutData) {
1330
- return this.dataPersistence
1331
- .get('checkoutId')
1332
- .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));
1333
1202
  }
1334
1203
  getUserByCheckout(checkoutId) {
1335
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'))));
@@ -1341,7 +1210,8 @@ class CheckoutService {
1341
1210
  return from(this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, user: checkout.user })));
1342
1211
  }
1343
1212
  clearCheckoutFromSession() {
1344
- return this.dataPersistence.remove('checkoutId');
1213
+ cookie.remove('checkoutId');
1214
+ return of();
1345
1215
  }
1346
1216
  calcDiscount(coupon) {
1347
1217
  return this.getCheckout().pipe(concatMap(async (checkout) => await this.couponService.calcDiscountShopping(coupon, checkout)));
@@ -1355,10 +1225,10 @@ class CheckoutService {
1355
1225
  ...Checkout.toInstance(pick(checkoutData, ['user', 'shop'])).toPlain(),
1356
1226
  shop: checkoutData?.shop || this.defaultShop,
1357
1227
  });
1358
- await this.dataPersistence.set('checkoutId', checkout.id).toPromise();
1228
+ cookie.set('checkoutId', checkout.id);
1359
1229
  return checkout;
1360
1230
  }
1361
- 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 }); }
1362
1232
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutService }); }
1363
1233
  }
1364
1234
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutService, decorators: [{
@@ -1366,15 +1236,15 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
1366
1236
  }], ctorParameters: () => [{ type: CouponService }, { type: undefined, decorators: [{
1367
1237
  type: Inject,
1368
1238
  args: ['CheckoutRepository']
1239
+ }] }, { type: undefined, decorators: [{
1240
+ type: Inject,
1241
+ args: ['OrderRepository']
1369
1242
  }] }, { type: undefined, decorators: [{
1370
1243
  type: Inject,
1371
1244
  args: ['UserRepository']
1372
1245
  }] }, { type: i1$2.Shops, decorators: [{
1373
1246
  type: Inject,
1374
1247
  args: [DEFAULT_SHOP]
1375
- }] }, { type: undefined, decorators: [{
1376
- type: Inject,
1377
- args: [PERSISTENCE_PROVIDER]
1378
1248
  }] }] });
1379
1249
 
1380
1250
  class CartService {
@@ -1390,11 +1260,9 @@ class CartService {
1390
1260
  this.updateLineItemInCart = (lineItem, quantity, checkout) => (isNil(checkout) ? this.checkoutService.getCheckout() : of(checkout)).pipe(concatMap((checkoutLoaded) => {
1391
1261
  const items = [];
1392
1262
  const index = checkoutLoaded.lineItems?.map((checkoutItem) => checkoutItem.id).indexOf(lineItem.id);
1393
- const isGift = checkoutLoaded.lineItems?.[index]?.isGift;
1394
1263
  if (index > -1) {
1395
1264
  checkoutLoaded.lineItems[index].quantity += quantity;
1396
- checkoutLoaded.lineItems[index].pricePaid = isGift ? 0 : lineItem.pricePaid;
1397
- checkoutLoaded.lineItems[index].price = lineItem.price;
1265
+ checkoutLoaded.lineItems[index].pricePaid = lineItem.pricePaid;
1398
1266
  }
1399
1267
  else
1400
1268
  checkoutLoaded.lineItems = items.concat(checkoutLoaded.lineItems ? checkoutLoaded.lineItems.concat([lineItem]) : [lineItem]);
@@ -1412,20 +1280,17 @@ class CartService {
1412
1280
  this.buildLineItem = async ({ checkout, item, quantity, }) => {
1413
1281
  const product = await this.getProductData(item.id);
1414
1282
  item.quantity = item?.quantity || checkout?.lineItems?.find((lineItem) => lineItem.id === item.id)?.quantity || 0;
1415
- if (this.checkMaxStock(product.stock.quantity, item.quantity || 0, quantity || 0))
1416
- 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.');
1417
1285
  const image = item.image || item.images?.shift();
1418
- const { id, name, EAN, slug, weight, sku, type } = item;
1419
- const isGift = item?.isGift || null;
1420
- const pricePaid = isGift
1421
- ? 0
1422
- : this.getProductPrice({
1423
- product: LineItem.toInstance(product),
1424
- shop: checkout.shop || this.defaultShop,
1425
- isSubscriber: checkout.user?.isSubscriber,
1426
- });
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
+ });
1427
1293
  RoundProductPricesHelper.roundProductPrices(item);
1428
- RoundProductPricesHelper.roundProductPrices(product);
1429
1294
  return {
1430
1295
  checkout,
1431
1296
  lineItem: LineItem.toInstance({
@@ -1435,19 +1300,16 @@ class CartService {
1435
1300
  brand: product.brand,
1436
1301
  slug: slug ?? product.slug,
1437
1302
  sku: sku ?? product.sku,
1438
- stock: product.stock,
1439
- price: this.roundPrice(product.price),
1303
+ stock,
1304
+ price: this.roundPrice(price),
1440
1305
  image,
1441
1306
  weight: weight ?? product.weight,
1442
1307
  quantity: (item.quantity || 0) + (quantity || 0),
1443
1308
  pricePaid,
1444
- discount: 0,
1445
- categories: product.categories || product.category?.id ? [product.category?.id, ...product.categories] : [],
1446
- category: product.category,
1309
+ categories: product.categories ?? [],
1447
1310
  isGift: isGift ?? null,
1448
- costPrice: isGift ? 0 : product.costPrice ?? 0,
1311
+ costPrice: product.costPrice ?? 0,
1449
1312
  type,
1450
- label: product.label,
1451
1313
  }),
1452
1314
  };
1453
1315
  };
@@ -1459,10 +1321,10 @@ class CartService {
1459
1321
  ? Number(info.subscriberPrice.toFixed(2))
1460
1322
  : Number(info.price.toFixed(2));
1461
1323
  };
1462
- this.checkMaxStock = (currentStock, currentItemQtd, quantityToAdd) => {
1463
- const maxStock = currentStock || 0;
1464
- const currentItemAmount = currentItemQtd || 0;
1465
- 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;
1466
1328
  };
1467
1329
  }
1468
1330
  addItem(item, quantity = 1) {
@@ -1495,14 +1357,14 @@ class CartService {
1495
1357
  }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1496
1358
  }
1497
1359
  updateUserCart(user) {
1498
- 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
1499
1361
  .updateCheckoutLineItems(Checkout.toInstance({
1500
1362
  ...checkout.toPlain(),
1501
1363
  lineItems: checkout.lineItems?.length
1502
1364
  ? await Promise.all(checkout.lineItems?.map(async (item) => (await this.buildLineItem({ checkout, item })).lineItem))
1503
1365
  : [],
1504
1366
  }))
1505
- .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)));
1506
1368
  }
1507
1369
  clearCart() {
1508
1370
  return this.checkoutService.getCheckout().pipe(map((checkout) => {
@@ -1547,13 +1409,15 @@ class CartService {
1547
1409
  const notGiftItems = checkout.lineItems ? checkout.lineItems.filter((item) => !item.isGift) : [];
1548
1410
  if (!notGiftItems.length)
1549
1411
  return { ...checkout, lineItems: [] };
1412
+ const cartTotal = notGiftItems.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1550
1413
  const campaigns = await this.buy2WinRepository
1551
1414
  .find({
1552
1415
  filters: {
1553
1416
  active: { operator: Where.EQUALS, value: true },
1417
+ shop: { operator: Where.EQUALS, value: this.defaultShop },
1554
1418
  },
1555
1419
  })
1556
- .then((data) => data.data.filter((campaign) => campaign.shop === Shops.ALL || campaign.shop === this.defaultShop));
1420
+ .then((data) => data.data);
1557
1421
  if (!campaigns.length)
1558
1422
  return { ...checkout, lineItems: notGiftItems };
1559
1423
  const elegibleCampaigns = [];
@@ -1569,27 +1433,22 @@ class CartService {
1569
1433
  categoriesCampaingFullTree.push(id, ...children.map((c) => c.id.toString()));
1570
1434
  }
1571
1435
  const categoriesCampaingTree = [...new Set(categoriesCampaingFullTree)];
1572
- const filterProductsCategories = notGiftItems.filter((l) => {
1436
+ const filterProductsCategories = checkout.lineItems.filter((l) => {
1573
1437
  if (!l.categories || !l.categories?.length)
1574
1438
  return true;
1575
1439
  return l.categories.some((c) => categoriesCampaingTree.some((cat) => cat == c));
1576
1440
  });
1577
1441
  if (filterProductsCategories.length) {
1578
- const cartValuelWithCategories = filterProductsCategories.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1579
- const cartItensQuantityWithCategories = filterProductsCategories.reduce((a, b) => a + b.quantity, 0);
1580
- const hasMinValue = campaign.cartValueMin && cartValuelWithCategories >= campaign.cartValueMin;
1581
- const hasMinQuantity = campaign.cartItensQuantityMin && cartItensQuantityWithCategories >= campaign.cartItensQuantityMin;
1582
- if (hasMinQuantity || hasMinValue)
1442
+ const cartTotalCategories = filterProductsCategories.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1443
+ if (cartTotalCategories >= campaign.cartValueMin)
1583
1444
  elegibleCampaigns.push(campaign);
1584
1445
  }
1585
1446
  }
1586
1447
  else {
1587
- const cartTotal = notGiftItems.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1588
- const cartItensQuantity = notGiftItems.reduce((a, b) => a + b.quantity, 0);
1589
- const hasMinValue = campaign.cartValue && campaign.cartValue > 0 && campaign.cartValue <= cartTotal;
1590
- const hasMinQuantity = campaign.cartItensQuantityMin && cartItensQuantity >= campaign.cartItensQuantityMin;
1591
- if (hasMinQuantity || hasMinValue)
1592
- elegibleCampaigns.push(campaign);
1448
+ if (campaign.cartValue && campaign.cartValue > 0) {
1449
+ if (campaign.cartValue <= cartTotal)
1450
+ elegibleCampaigns.push(campaign);
1451
+ }
1593
1452
  }
1594
1453
  }
1595
1454
  if (!elegibleCampaigns.length)
@@ -1616,12 +1475,11 @@ class CartService {
1616
1475
  }
1617
1476
  giftToLineItems(items) {
1618
1477
  return items.map((item) => {
1619
- 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;
1620
1479
  const image = item?.miniatures?.length ? item.miniatures[0] : item.images[0];
1621
1480
  return LineItem.toInstance({
1622
1481
  brand,
1623
1482
  categories,
1624
- category,
1625
1483
  id: id.toString(),
1626
1484
  name,
1627
1485
  price,
@@ -1683,11 +1541,9 @@ class NewCategoryStructureAdapter {
1683
1541
  .then((categories) => categories.map((category) => category.id.toString()));
1684
1542
  }
1685
1543
  async getCategory(category) {
1686
- const collectionCategory = category.isCollection ||
1687
- (isNil(category.isCollection) && !category.products?.length) ||
1688
- category.isWishlist ||
1689
- category.brandCategory;
1690
- 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;
1691
1547
  }
1692
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 }); }
1693
1549
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: NewCategoryStructureAdapter }); }
@@ -1720,15 +1576,13 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
1720
1576
  }] }] });
1721
1577
 
1722
1578
  class CatalogService {
1723
- constructor(productRepository, productStockNotificationRepository, categoryRepository, categoryStructureAdapter, shop, productSearch) {
1579
+ constructor(productRepository, categoryRepository, categoryStructureAdapter, shop, productIndex) {
1724
1580
  this.productRepository = productRepository;
1725
- this.productStockNotificationRepository = productStockNotificationRepository;
1726
1581
  this.categoryRepository = categoryRepository;
1727
1582
  this.categoryStructureAdapter = categoryStructureAdapter;
1728
1583
  this.shop = shop;
1729
- this.productSearch = productSearch;
1584
+ this.productIndex = productIndex;
1730
1585
  this.productsByTerm = {};
1731
- this.brandsList = {};
1732
1586
  this.buildFilterQuery = ({ clubDiscount, brands, prices, gender, tags, rate, customOptions, }) => {
1733
1587
  const filters = {};
1734
1588
  if (clubDiscount?.length)
@@ -1754,22 +1608,17 @@ class CatalogService {
1754
1608
  if (!sort || sort === 'most-relevant')
1755
1609
  return {};
1756
1610
  if (sort === 'best-sellers')
1757
- return {
1758
- shoppingCount: 'desc',
1759
- rate: 'desc',
1760
- stock: 'desc',
1761
- name: 'asc',
1762
- };
1611
+ return { shoppingCount: 'desc' };
1763
1612
  if (sort === 'biggest-price')
1764
- return { subscriberPrice: 'desc', rate: 'desc', shoppingCount: 'desc' };
1613
+ return { subscriberPrice: 'desc' };
1765
1614
  if (sort === 'lowest-price')
1766
- return { subscriberPrice: 'asc', rate: 'desc', shoppingCount: 'desc' };
1615
+ return { subscriberPrice: 'asc' };
1767
1616
  if (sort === 'best-rating')
1768
- return { rate: 'desc', shoppingCount: 'desc', stock: 'desc', name: 'asc' };
1617
+ return { rate: 'desc' };
1769
1618
  if (sort === 'news')
1770
1619
  return { createdAt: 'desc' };
1771
1620
  if (sort === 'biggest-discount')
1772
- return { subscriberDiscountPercentage: 'desc', rate: 'desc', shoppingCount: 'desc' };
1621
+ return { subscriberDiscountPercentage: 'desc' };
1773
1622
  };
1774
1623
  this.buildLimitQuery = (options) => {
1775
1624
  const limit = options?.perPage || 20;
@@ -1781,15 +1630,6 @@ class CatalogService {
1781
1630
  this.hasProfile = (options) => 'profile' in options;
1782
1631
  this.hasTerm = (options) => 'term' in options;
1783
1632
  this.hasCategory = (options) => 'category' in options;
1784
- this.buildIndexBrands = (options) => {
1785
- if (this.hasCategory(options))
1786
- return `category-${options.category.id}`;
1787
- if (this.hasTerm(options))
1788
- return `term-${options.term}`;
1789
- if (this.hasProfile(options))
1790
- return `profile-${options.profile.join(',')}`;
1791
- return '';
1792
- };
1793
1633
  }
1794
1634
  async fetchProducts(options) {
1795
1635
  const limits = this.buildLimitQuery(options);
@@ -1799,42 +1639,29 @@ class CatalogService {
1799
1639
  throw new InvalidArgumentError(`It couldn't filled tags when profile is given`);
1800
1640
  if (this.hasTerm(options) && options.filters?.customOptions)
1801
1641
  throw new InvalidArgumentError(`It couldn't filled customOptions when term is given`);
1802
- return await this.findCatalog(options, limits).then(async ({ data, count: total, maximum, minimal, distinct }) => {
1803
- await this.setBrandsList(options, distinct?.brand);
1804
- return {
1805
- products: { data: data.map((product) => RoundProductPricesHelper.roundProductPrices(product)), total },
1806
- pages: Math.ceil(total / limits.limit),
1807
- prices: {
1808
- price: { min: +minimal?.price?.price?.toFixed(2), max: +maximum?.price?.price?.toFixed(2) },
1809
- subscriberPrice: {
1810
- min: +minimal?.price?.subscriberPrice?.toFixed(2),
1811
- max: +maximum?.price?.subscriberPrice?.toFixed(2),
1812
- },
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),
1813
1650
  },
1814
- brands: this.brandsList[this.buildIndexBrands(options)],
1815
- };
1816
- });
1817
- }
1818
- async addCustomerToStockNotification(shop, productId, name, email) {
1819
- return this.productStockNotificationRepository.addCustomerEmail(shop, productId, name, email);
1651
+ },
1652
+ brands: distinct?.brand,
1653
+ }));
1820
1654
  }
1821
1655
  async findCatalog(options, limits) {
1822
1656
  if (this.hasTerm(options) && options.sort === 'most-relevant') {
1823
- const productsIds = await this.findCatalogIdsBySearch(options.term);
1824
- return this.findCatalogAndSortByMostRevelantByTerm(productsIds, options, limits);
1657
+ const productsIds = await this.findCatalogIdsByElasticSearch(options.term);
1658
+ return this.findCatalogAndSortByMostRevelant(productsIds, options, limits);
1825
1659
  }
1826
1660
  if (this.hasCategory(options) && options.sort === 'most-relevant') {
1827
- const mostRelevant = options.category.isWishlist ? [] : options.category.getMostRelevantByShop(this.shop);
1828
- const productsIds = await this.productRepository
1829
- .findCatalog({
1830
- fields: ['id'],
1831
- filters: {
1832
- ...(await this.buildMainFilter(options)),
1833
- ...this.buildFilterQuery(options?.filters || {}),
1834
- },
1835
- })
1836
- .then((products) => products.data.map((product) => product.id));
1837
- 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);
1838
1665
  }
1839
1666
  const repoParams = {
1840
1667
  filters: {
@@ -1846,9 +1673,7 @@ class CatalogService {
1846
1673
  options: {
1847
1674
  minimal: ['price'],
1848
1675
  maximum: ['price'],
1849
- ...(!this.brandsList[this.buildIndexBrands(options)] && isEmpty(options.filters?.brands)
1850
- ? { distinct: ['brand'] }
1851
- : {}),
1676
+ ...(!this.hasCategory(options) ? { distinct: ['brand'] } : {}),
1852
1677
  },
1853
1678
  };
1854
1679
  if (['biggest-price', 'lowest-price', 'biggest-discount', 'best-rating'].includes(options.sort))
@@ -1861,72 +1686,27 @@ class CatalogService {
1861
1686
  if (profile)
1862
1687
  return { tags: { operator: Where.LIKE, value: profile } };
1863
1688
  if (term)
1864
- return this.productSearch
1865
- .search(term, 999, this.shop == Shops.GLAMSHOP ? 'female' : 'male')
1866
- .then((data) => ({ id: { operator: Where.IN, value: data.map((_source) => _source.id) } }));
1689
+ return this.productIndex
1690
+ .search(term, 999, this.shop)
1691
+ .then((data) => ({ id: { operator: Where.IN, value: data.hits.map(({ _source }) => _source.id) } }));
1867
1692
  }
1868
- async findCatalogAndSortByMostRevelant(mostRelevants, productIds, options, limits) {
1869
- const brandsList = this.brandsList[this.buildIndexBrands(options)];
1870
- const mostRelevantProductsIds = [...new Set(mostRelevants.concat(productIds))];
1693
+ async findCatalogAndSortByMostRevelant(productIds, options, limits) {
1871
1694
  const totalResult = await this.productRepository.findCatalog({
1872
- filters: {
1873
- id: { operator: Where.IN, value: mostRelevantProductsIds },
1874
- ...this.buildFilterQuery(options?.filters || {}),
1875
- },
1876
- orderBy: this.buildSortQuery('best-sellers'),
1877
- options: {
1878
- minimal: ['price'],
1879
- maximum: ['price'],
1880
- ...(!brandsList && isEmpty(options.filters?.brands) ? { distinct: ['brand'] } : {}),
1881
- },
1882
- }, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female');
1883
- const mostRelevantWithouyStock = totalResult.data.filter((product) => mostRelevants.includes(product.id) && product.stock.quantity <= 0);
1884
- const firstProducts = totalResult.data
1885
- .filter((product) => mostRelevants.includes(product.id) && product.stock.quantity > 0)
1886
- .sort((a, b) => mostRelevants.indexOf(a.id) - mostRelevants.indexOf(b.id));
1887
- const lastProducts = totalResult.data
1888
- .filter((product) => !mostRelevants.includes(product.id))
1889
- .concat(mostRelevantWithouyStock);
1890
- const categoryMostRelevants = firstProducts.concat(lastProducts);
1891
- const resultFinal = categoryMostRelevants.slice(limits.offset, limits.offset + limits.limit);
1892
- await this.setBrandsList(options, totalResult.distinct?.brand);
1893
- return {
1894
- data: resultFinal,
1895
- count: totalResult.count,
1896
- maximum: totalResult.maximum,
1897
- minimal: totalResult.minimal,
1898
- distinct: {
1899
- ...totalResult.distinct,
1900
- brand: this.brandsList[this.buildIndexBrands(options)],
1901
- },
1902
- };
1903
- }
1904
- async findCatalogAndSortByMostRevelantByTerm(productIds, options, limits) {
1905
- const brandsList = this.brandsList[this.buildIndexBrands(options)];
1906
- const totalResult = await this.productRepository.findCatalog({
1907
- fields: ['id', 'stock', 'gender'],
1695
+ fields: ['id', 'stock'],
1908
1696
  filters: {
1909
1697
  id: { operator: Where.IN, value: productIds },
1910
- published: { operator: Where.EQUALS, value: true },
1911
1698
  ...this.buildFilterQuery(options?.filters || {}),
1912
1699
  },
1913
1700
  options: {
1914
1701
  minimal: ['price'],
1915
1702
  maximum: ['price'],
1916
- ...(!brandsList && isEmpty(options.filters?.brands) ? { distinct: ['brand'] } : {}),
1703
+ distinct: ['brand'],
1917
1704
  },
1918
1705
  }, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female');
1919
- const defaultGender = options?.filters?.gender
1920
- ? options?.filters?.gender.at(0)
1921
- : this.shop === Shops.GLAMSHOP
1922
- ? 'female'
1923
- : 'male';
1924
1706
  const stockData = totalResult.data.filter((product) => product.stock.quantity > 0);
1925
1707
  const stockOut = totalResult.data.filter((product) => product.stock.quantity <= 0);
1926
- const productIdsStockGender = productIds.filter((product) => stockData.some((result) => result.id === product && (result.gender?.includes(defaultGender) || result.gender?.includes('unisex'))));
1927
- const productIdsStockNotGender = productIds.filter((product) => stockData.some((result) => result.id === product && !result.gender?.includes(defaultGender) && !result.gender?.includes('unisex')));
1928
- const productIdsStock = productIdsStockGender.concat(productIdsStockNotGender);
1929
- 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));
1930
1710
  const limitedProductId = productIdsStock
1931
1711
  .concat(productIdsStockOut)
1932
1712
  .slice(limits.offset, limits.offset + limits.limit);
@@ -1936,55 +1716,27 @@ class CatalogService {
1936
1716
  id: { operator: Where.IN, value: orderedId },
1937
1717
  },
1938
1718
  });
1939
- await this.setBrandsList(options, totalResult.distinct?.brand);
1940
1719
  return {
1941
1720
  data: limitedProductId.map((id) => productResult.data.find((product) => product.id === id)).filter(Boolean),
1942
1721
  count: totalResult.count,
1943
1722
  maximum: totalResult.maximum,
1944
1723
  minimal: totalResult.minimal,
1945
- distinct: {
1946
- ...totalResult.distinct,
1947
- brand: this.brandsList[this.buildIndexBrands(options)],
1948
- },
1724
+ distinct: totalResult.distinct,
1949
1725
  };
1950
1726
  }
1951
- async findCatalogIdsBySearch(term, preview = false) {
1727
+ async findCatalogIdsByElasticSearch(term) {
1952
1728
  if (this.productsByTerm[term])
1953
1729
  return this.productsByTerm[term];
1954
- return (this.productsByTerm[term] = await this.productSearch
1955
- .search(term, 999, this.shop == Shops.GLAMSHOP ? 'female' : 'male')
1956
- .then((products) => [...new Set(products.map((product) => product.id))]));
1957
- }
1958
- async fetchBrandsOnly(options, productIds = []) {
1959
- return this.productRepository
1960
- .findCatalog({
1961
- fields: ['id'],
1962
- filters: {
1963
- ...(!isEmpty(productIds) ? { id: { operator: Where.IN, value: productIds } } : {}),
1964
- published: { operator: Where.EQUALS, value: true },
1965
- ...this.buildFilterQuery(options?.filters || {}),
1966
- },
1967
- options: {
1968
- distinct: ['brand'],
1969
- },
1970
- }, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female')
1971
- .then((result) => {
1972
- return result.distinct.brand;
1973
- });
1974
- }
1975
- async setBrandsList(options, brands) {
1976
- const filterBrands = options.filters?.brands;
1977
- if (isEmpty(brands))
1978
- delete options.filters?.brands;
1979
- this.brandsList[this.buildIndexBrands(options)] =
1980
- this.brandsList[this.buildIndexBrands(options)] || brands || (await this.fetchBrandsOnly(options));
1981
- this.brandsList[this.buildIndexBrands(options)] = this.brandsList[this.buildIndexBrands(options)].filter(Boolean);
1982
- options.filters = {
1983
- ...options.filters,
1984
- brands: filterBrands,
1985
- };
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
+ }));
1986
1738
  }
1987
- 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 }); }
1988
1740
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CatalogService }); }
1989
1741
  }
1990
1742
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CatalogService, decorators: [{
@@ -1992,9 +1744,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
1992
1744
  }], ctorParameters: () => [{ type: undefined, decorators: [{
1993
1745
  type: Inject,
1994
1746
  args: ['ProductRepository']
1995
- }] }, { type: undefined, decorators: [{
1996
- type: Inject,
1997
- args: ['ProductStockNotificationRepository']
1998
1747
  }] }, { type: undefined, decorators: [{
1999
1748
  type: Inject,
2000
1749
  args: ['CategoryRepository']
@@ -2004,10 +1753,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2004
1753
  }] }, { type: i1$2.Shops, decorators: [{
2005
1754
  type: Inject,
2006
1755
  args: [DEFAULT_SHOP]
2007
- }] }, { type: undefined, decorators: [{
2008
- type: Inject,
2009
- args: ['ProductSearch']
2010
- }] }] });
1756
+ }] }, { type: i1$2.ProductsIndex }] });
2011
1757
 
2012
1758
  class CategoryService {
2013
1759
  constructor(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop) {
@@ -2017,15 +1763,15 @@ class CategoryService {
2017
1763
  this.categoryStructureAdapter = categoryStructureAdapter;
2018
1764
  this.shop = shop;
2019
1765
  }
2020
- async fetchBrands(category, options) {
1766
+ async fetchBrands(category, mainGender) {
2021
1767
  const brands = await this.productRepository
2022
1768
  .findCatalog({
2023
1769
  filters: await this.categoryStructureAdapter.buildProductFilterByCategory(category),
2024
1770
  fields: ['brand'],
2025
- }, options?.mainGender ? options?.mainGender : this.shop === Shops.MENSMARKET ? 'male' : 'female')
1771
+ }, mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female')
2026
1772
  .then(({ data }) => Object.keys(data.map((product) => product.brand).reduce((brands, brand) => ({ ...brands, [brand]: true }), {})));
2027
1773
  return this.categoryRepository
2028
- .find({ filters: { brandCategory: true, shop: options?.shop || this.shop }, orderBy: { name: 'asc' } })
1774
+ .find({ filters: { brandCategory: true, shop: this.shop }, orderBy: { name: 'asc' } })
2029
1775
  .then(({ data }) => data.filter((category) => brands.includes(category.conditions.brand)));
2030
1776
  }
2031
1777
  async fetchFilterOptions(category) {
@@ -2074,14 +1820,11 @@ __decorate([
2074
1820
  ], CategoryWithTree.prototype, "children", void 0);
2075
1821
 
2076
1822
  class WishlistService {
2077
- constructor(wishlistRepository, shop, productRepository, categoryFilterRepository, categoryRepository, productStockNotificationRepository, productSearch, logRepository) {
1823
+ constructor(wishlistRepository, shop, productRepository, categoryFilterRepository, categoryRepository, productIndex) {
2078
1824
  this.wishlistRepository = wishlistRepository;
2079
1825
  this.shop = shop;
2080
- this.productRepository = productRepository;
2081
- this.productSearch = productSearch;
2082
- this.logRepository = logRepository;
2083
1826
  const categoryStructureAdapter = new NewCategoryStructureAdapter(wishlistRepository);
2084
- this.catalogService = new CatalogService(productRepository, productStockNotificationRepository, categoryRepository, categoryStructureAdapter, shop, productSearch);
1827
+ this.catalogService = new CatalogService(productRepository, categoryRepository, categoryStructureAdapter, shop, productIndex);
2085
1828
  this.categoryService = new CategoryService(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop);
2086
1829
  }
2087
1830
  getCatalogService() {
@@ -2090,76 +1833,46 @@ class WishlistService {
2090
1833
  getCategoryService() {
2091
1834
  return this.categoryService;
2092
1835
  }
2093
- async create({ personId, title, description, published, userFullName, userPhoto, theme, bannerUrl, personType, personIsSubscriber, }) {
1836
+ async create({ personId, title, description, userFullName, userPhoto, theme, bannerUrl, }) {
2094
1837
  const data = {
2095
1838
  slug: '',
2096
1839
  name: title,
2097
1840
  description,
2098
- metadatas: [
2099
- {
2100
- shop: this.shop,
2101
- title: `${userFullName} - ${title}`,
2102
- description: `${userFullName} - ${description}`,
2103
- },
2104
- ],
1841
+ metadata: {
1842
+ title: `${userFullName} - ${title}`,
1843
+ description: `${userFullName} - ${description}`,
1844
+ },
2105
1845
  shop: this.shop,
2106
1846
  shops: [this.shop],
2107
1847
  personId,
2108
1848
  personName: userFullName,
2109
1849
  personPhoto: userPhoto,
2110
1850
  brandCategory: false,
2111
- published,
1851
+ published: true,
2112
1852
  theme,
2113
1853
  bannerUrl,
2114
- personType: personType ?? PersonTypes.NONE,
2115
- personIsSubscriber: personIsSubscriber ?? false,
2116
1854
  };
2117
- const hasWishlist = await this.wishlistRepository
2118
- .find({
2119
- filters: {
2120
- personId,
2121
- },
2122
- options: {
2123
- enableCount: false,
2124
- },
2125
- orderBy: {
2126
- id: 'asc',
2127
- },
2128
- })
2129
- .then((res) => res.data);
2130
- await this.createWishlistLog(WishlistLogType.CREATE, data);
2131
- if (hasWishlist.length)
2132
- return hasWishlist.at(0);
2133
1855
  const newWishlist = await this.wishlistRepository.create(data);
2134
1856
  await this.wishlistRepository.update({ id: newWishlist.id, slug: newWishlist.id });
2135
1857
  return Wishlist.toInstance({ ...newWishlist.toPlain(), slug: newWishlist.id });
2136
1858
  }
2137
- async update({ id, title, description, published, userFullName, userPhoto, theme, bannerUrl, personType, personIsSubscriber, }) {
1859
+ update({ id, title, description, userFullName, userPhoto, theme, bannerUrl, }) {
2138
1860
  const data = {
2139
1861
  id,
2140
1862
  name: title,
2141
1863
  description,
2142
- published,
2143
- metadatas: [
2144
- {
2145
- shop: this.shop,
2146
- title: `${userFullName} - ${title}`,
2147
- description: `${userFullName} - ${description}`,
2148
- },
2149
- ],
1864
+ metadata: {
1865
+ title: `${userFullName} - ${title}`,
1866
+ description: `${userFullName} - ${description}`,
1867
+ },
2150
1868
  personName: userFullName,
2151
1869
  personPhoto: userPhoto,
2152
1870
  theme,
2153
1871
  bannerUrl,
2154
- personType: personType ?? PersonTypes.NONE,
2155
- personIsSubscriber: personIsSubscriber ?? false,
2156
1872
  };
2157
- await this.createWishlistLog(WishlistLogType.UPDATE, data);
2158
1873
  return this.wishlistRepository.update(data);
2159
1874
  }
2160
- async delete(wishlistId) {
2161
- const wishlist = await this.findById(wishlistId);
2162
- await this.createWishlistLog(WishlistLogType.DELETE, wishlist);
1875
+ delete(wishlistId) {
2163
1876
  return this.wishlistRepository.delete({ id: wishlistId });
2164
1877
  }
2165
1878
  getWishlistBySlug(slug) {
@@ -2174,9 +1887,6 @@ class WishlistService {
2174
1887
  async addProduct(wishlistId, productId) {
2175
1888
  const wishlist = await this.wishlistRepository.get({ id: wishlistId });
2176
1889
  const hasProduct = wishlist.products.some((p) => p == productId);
2177
- const wishlistData = await this.findById(wishlistId);
2178
- const productData = await this.findProductById(productId);
2179
- await this.createWishlistLog(WishlistLogType.ADD_PRODUCT, wishlistData, productData);
2180
1890
  if (!hasProduct) {
2181
1891
  wishlist.products = [...wishlist.products, productId];
2182
1892
  return this.wishlistRepository.update({ id: wishlistId, products: wishlist.products });
@@ -2188,90 +1898,13 @@ class WishlistService {
2188
1898
  const productIndex = wishlist.products.findIndex((p) => p == productId);
2189
1899
  if (productIndex != -1) {
2190
1900
  wishlist.products.splice(productIndex, 1);
2191
- const wishlistData = await this.findById(wishlistId);
2192
- const productData = await this.findProductById(productId);
2193
- await this.createWishlistLog(WishlistLogType.REMOVE_PRODUCT, wishlistData, productData);
2194
1901
  if (!wishlist.products.length)
2195
1902
  return this.wishlistRepository.update({ id: wishlistId, products: { action: 'remove' } });
2196
1903
  return this.wishlistRepository.update({ id: wishlistId, products: wishlist.products });
2197
1904
  }
2198
1905
  return wishlist;
2199
1906
  }
2200
- async findById(id) {
2201
- return this.wishlistRepository
2202
- .find({
2203
- fields: ['id', 'name', 'description', 'personId', 'personIsSubscriber', 'personType', 'personName'],
2204
- filters: {
2205
- id,
2206
- },
2207
- })
2208
- .then((res) => res.data.at(0));
2209
- }
2210
- async findProductById(id) {
2211
- return this.productRepository
2212
- .find({
2213
- fields: ['id', 'sku', 'EAN', 'name', 'brand'],
2214
- filters: {
2215
- id,
2216
- },
2217
- })
2218
- .then((res) => res.data.at(0));
2219
- }
2220
- async createWishlistLog(type, wishlist, product) {
2221
- switch (type) {
2222
- case WishlistLogType.CREATE:
2223
- case WishlistLogType.UPDATE:
2224
- case WishlistLogType.DELETE:
2225
- await this.logRepository.create({
2226
- collection: 'wishlist',
2227
- date: new Date(),
2228
- operation: WishlistLogType.CREATE ? 'CREATE' : WishlistLogType.UPDATE ? 'UPDATE' : 'DELETE',
2229
- documentId: wishlist.id,
2230
- document: {
2231
- id: wishlist.id,
2232
- shop: this.shop,
2233
- name: wishlist.name,
2234
- description: wishlist.description,
2235
- published: wishlist.published,
2236
- type: type,
2237
- personType: wishlist.personType,
2238
- personId: wishlist.personId,
2239
- personName: wishlist.personName,
2240
- personIsSubscriber: wishlist.personIsSubscriber,
2241
- },
2242
- });
2243
- break;
2244
- case WishlistLogType.ADD_PRODUCT:
2245
- case WishlistLogType.REMOVE_PRODUCT:
2246
- await this.logRepository.create({
2247
- collection: 'wishlist',
2248
- date: new Date(),
2249
- operation: 'UPDATE',
2250
- documentId: wishlist.id,
2251
- document: {
2252
- id: wishlist.id,
2253
- shop: this.shop,
2254
- name: wishlist.name,
2255
- description: wishlist.description,
2256
- published: wishlist.published,
2257
- type: type,
2258
- personType: wishlist.personType,
2259
- personId: wishlist.personId,
2260
- personName: wishlist.personName,
2261
- personIsSubscriber: wishlist.personIsSubscriber,
2262
- productId: product.id,
2263
- productEAN: product.EAN,
2264
- productSKU: product.sku,
2265
- productName: product.name,
2266
- productBrand: product.brand,
2267
- },
2268
- });
2269
- break;
2270
- default:
2271
- break;
2272
- }
2273
- }
2274
- 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 }); }
2275
1908
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: WishlistService }); }
2276
1909
  }
2277
1910
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: WishlistService, decorators: [{
@@ -2291,30 +1924,31 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2291
1924
  }] }, { type: undefined, decorators: [{
2292
1925
  type: Inject,
2293
1926
  args: ['CategoryRepository']
2294
- }] }, { type: undefined, decorators: [{
2295
- type: Inject,
2296
- args: ['ProductStockNotificationRepository']
2297
- }] }, { type: undefined, decorators: [{
2298
- type: Inject,
2299
- args: ['ProductSearch']
2300
- }] }, { type: undefined, decorators: [{
2301
- type: Inject,
2302
- args: ['LogRepository']
2303
- }] }] });
1927
+ }] }, { type: i1$2.ProductsIndex }] });
2304
1928
 
2305
1929
  class CheckoutSubscriptionService {
2306
- constructor(checkoutSubscriptionRepository, dataPersistence, couponService) {
1930
+ constructor(checkoutSubscriptionRepository, subscriptionRepository, couponService) {
2307
1931
  this.checkoutSubscriptionRepository = checkoutSubscriptionRepository;
2308
- this.dataPersistence = dataPersistence;
1932
+ this.subscriptionRepository = subscriptionRepository;
2309
1933
  this.couponService = couponService;
2310
1934
  }
2311
1935
  getCheckoutSubscription(checkoutData) {
2312
- return this.dataPersistence
2313
- .get('checkoutSubscriptionId')
2314
- .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;
2315
1948
  }
2316
1949
  clearCheckoutSubscriptionFromSession() {
2317
- return this.dataPersistence.remove('checkoutSubscriptionId');
1950
+ cookie.remove('checkoutSubscriptionId');
1951
+ return of();
2318
1952
  }
2319
1953
  checkCoupon(nickname, userEmail) {
2320
1954
  return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService
@@ -2324,15 +1958,7 @@ class CheckoutSubscriptionService {
2324
1958
  calcDiscountSubscription(coupon) {
2325
1959
  return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService.calcDiscountSubscription(coupon, checkout).pipe()));
2326
1960
  }
2327
- async createCheckoutSubscription(checkoutData) {
2328
- const checkout = await this.checkoutSubscriptionRepository.create({
2329
- createdAt: new Date(),
2330
- ...CheckoutSubscription.toInstance(pick(checkoutData, ['user', 'shop'])).toPlain(),
2331
- });
2332
- await this.dataPersistence.set('checkoutSubscriptionId', checkout.id).toPromise();
2333
- return checkout;
2334
- }
2335
- 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 }); }
2336
1962
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutSubscriptionService }); }
2337
1963
  }
2338
1964
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutSubscriptionService, decorators: [{
@@ -2342,7 +1968,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2342
1968
  args: ['CheckoutSubscriptionRepository']
2343
1969
  }] }, { type: undefined, decorators: [{
2344
1970
  type: Inject,
2345
- args: [PERSISTENCE_PROVIDER]
1971
+ args: ['SubscriptionRepository']
2346
1972
  }] }, { type: CouponService }] });
2347
1973
 
2348
1974
  class UtilHelper {
@@ -2427,10 +2053,10 @@ class HomeShopService {
2427
2053
  return this.getHomeConfiguration().pipe(map((home) => home.minValueForFreeShipping));
2428
2054
  }
2429
2055
  getDiscoverProducts(gender) {
2430
- 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)))));
2431
2057
  }
2432
2058
  getFeaturedProducts(gender) {
2433
- 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)))));
2434
2060
  }
2435
2061
  getVerticalProducts(gender) {
2436
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({
@@ -2600,12 +2226,10 @@ class AngularConnectModule {
2600
2226
  ? OldCategoryStructureAdapter
2601
2227
  : NewCategoryStructureAdapter,
2602
2228
  },
2603
- { provide: PERSISTENCE_PROVIDER, useClass: options?.persistenceProvider || CookieDataPersistence },
2604
2229
  ...(isNil(defaultShop) ? [] : [{ provide: DEFAULT_SHOP, useValue: defaultShop }]),
2605
2230
  ...(isNil(options?.firebase) ? [] : [{ provide: FIREBASE_OPTIONS, useValue: options?.firebase }]),
2606
2231
  ...(isNil(options?.firebase) ? [] : [{ provide: FIREBASE_APP_NAME, useValue: nameOrConfig }]),
2607
2232
  ...(isNil(options?.elasticSearch) ? [] : [{ provide: ES_CONFIG, useValue: options.elasticSearch }]),
2608
- ...(isNil(options?.vertexConfig) ? [] : [{ provide: VERTEX_CONFIG, useValue: options.vertexConfig }]),
2609
2233
  ...(isNil(options?.hasura) ? [] : [{ provide: HASURA_OPTIONS, useValue: options.hasura }]),
2610
2234
  ...(isNil(options?.backendUrl) ? [] : [{ provide: BACKEND_URL, useValue: options.backendUrl }]),
2611
2235
  ...(isNil(options?.storageBaseUrl) ? [] : [{ provide: STORAGE_BASE_URL, useValue: options.storageBaseUrl }]),
@@ -2613,8 +2237,7 @@ class AngularConnectModule {
2613
2237
  };
2614
2238
  }
2615
2239
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularConnectModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
2616
- static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularConnectModule, imports: [i1$4.FirebaseAppModule, i2.StorageModule, AngularElasticSeachModule,
2617
- AngularVertexSeachModule,
2240
+ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularConnectModule, imports: [i1$4.FirebaseAppModule, AngularElasticSeachModule,
2618
2241
  AngularFirebaseAuthModule,
2619
2242
  AngularFirestoreModule,
2620
2243
  AngularHasuraGraphQLModule] }); }
@@ -2637,17 +2260,6 @@ class AngularConnectModule {
2637
2260
  },
2638
2261
  deps: ['UserRepository', 'FileUploaderService'],
2639
2262
  },
2640
- {
2641
- provide: 'FileUploaderService',
2642
- useFactory: (storage, baseUrl) => {
2643
- return new FirebaseFileUploaderService(storage, baseUrl);
2644
- },
2645
- deps: [Storage, STORAGE_BASE_URL],
2646
- },
2647
- {
2648
- provide: 'ProductSearch',
2649
- useExisting: ProductsVertexSearch,
2650
- },
2651
2263
  ], imports: [provideFirebaseApp((injector) => {
2652
2264
  const appName = injector.get(FIREBASE_APP_NAME) || '[DEFAULT]';
2653
2265
  try {
@@ -2657,9 +2269,7 @@ class AngularConnectModule {
2657
2269
  return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2658
2270
  }
2659
2271
  }),
2660
- provideStorage((injector) => getStorage(injector.get(FirebaseApp))),
2661
2272
  AngularElasticSeachModule,
2662
- AngularVertexSeachModule,
2663
2273
  AngularFirebaseAuthModule,
2664
2274
  AngularFirestoreModule,
2665
2275
  AngularHasuraGraphQLModule] }); }
@@ -2677,9 +2287,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2677
2287
  return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2678
2288
  }
2679
2289
  }),
2680
- provideStorage((injector) => getStorage(injector.get(FirebaseApp))),
2681
2290
  AngularElasticSeachModule,
2682
- AngularVertexSeachModule,
2683
2291
  AngularFirebaseAuthModule,
2684
2292
  AngularFirestoreModule,
2685
2293
  AngularHasuraGraphQLModule,
@@ -2703,17 +2311,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2703
2311
  },
2704
2312
  deps: ['UserRepository', 'FileUploaderService'],
2705
2313
  },
2706
- {
2707
- provide: 'FileUploaderService',
2708
- useFactory: (storage, baseUrl) => {
2709
- return new FirebaseFileUploaderService(storage, baseUrl);
2710
- },
2711
- deps: [Storage, STORAGE_BASE_URL],
2712
- },
2713
- {
2714
- provide: 'ProductSearch',
2715
- useExisting: ProductsVertexSearch,
2716
- },
2717
2314
  ],
2718
2315
  }]
2719
2316
  }] });
@@ -2722,5 +2319,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2722
2319
  * Generated bundle index. Do not edit.
2723
2320
  */
2724
2321
 
2725
- 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 };
2726
2323
  //# sourceMappingURL=infrab4a-connect-angular.mjs.map