@infrab4a/connect-angular 5.0.0-beta.97 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/angular-connect.module.d.ts +8 -14
  2. package/angular-firestore.module.d.ts +2 -1
  3. package/angular-hasura-graphql.module.d.ts +6 -4
  4. package/consts/firebase-const.d.ts +0 -1
  5. package/consts/index.d.ts +0 -1
  6. package/esm2020/angular-connect.module.mjs +115 -0
  7. package/esm2020/angular-elastic-search.module.mjs +34 -0
  8. package/esm2020/angular-firebase-auth.module.mjs +115 -0
  9. package/esm2020/angular-firestore.module.mjs +504 -0
  10. package/esm2020/angular-hasura-graphql.module.mjs +265 -0
  11. package/{esm2022 → esm2020}/consts/firebase-const.mjs +1 -2
  12. package/{esm2022 → esm2020}/consts/index.mjs +1 -2
  13. package/{esm2022 → esm2020}/persistence/cookie-data-persistence.mjs +4 -4
  14. package/{esm2022 → esm2020}/services/auth.service.mjs +6 -6
  15. package/esm2020/services/cart.service.mjs +281 -0
  16. package/{esm2022 → esm2020}/services/catalog/adapters/new-category-structure.adapter.mjs +6 -6
  17. package/{esm2022 → esm2020}/services/catalog/adapters/old-category-structure.adapter.mjs +6 -6
  18. package/esm2020/services/catalog/catalog.service.mjs +194 -0
  19. package/esm2020/services/catalog/category.service.mjs +51 -0
  20. package/{esm2022 → esm2020}/services/catalog/models/category-with-tree.model.mjs +1 -1
  21. package/esm2020/services/catalog/wishlist.service.mjs +115 -0
  22. package/{esm2022 → esm2020}/services/checkout-subscription.service.mjs +6 -6
  23. package/esm2020/services/checkout.service.mjs +68 -0
  24. package/esm2020/services/coupon.service.mjs +235 -0
  25. package/{esm2022 → esm2020}/services/home-shop.service.mjs +9 -9
  26. package/{esm2022 → esm2020}/services/index.mjs +2 -1
  27. package/{esm2022 → esm2020}/services/order.service.mjs +6 -6
  28. package/esm2020/services/shipping.service.mjs +96 -0
  29. package/esm2020/services/types/shipping-methods.type.mjs +2 -0
  30. package/fesm2015/infrab4a-connect-angular.mjs +2417 -0
  31. package/fesm2015/infrab4a-connect-angular.mjs.map +1 -0
  32. package/{fesm2022 → fesm2020}/infrab4a-connect-angular.mjs +1304 -1555
  33. package/fesm2020/infrab4a-connect-angular.mjs.map +1 -0
  34. package/package.json +15 -9
  35. package/services/cart.service.d.ts +19 -8
  36. package/services/catalog/catalog.service.d.ts +5 -15
  37. package/services/catalog/category.service.d.ts +3 -7
  38. package/services/catalog/wishlist.service.d.ts +4 -16
  39. package/services/checkout.service.d.ts +6 -16
  40. package/services/coupon.service.d.ts +2 -0
  41. package/services/index.d.ts +1 -0
  42. package/services/shipping.service.d.ts +19 -0
  43. package/services/types/shipping-methods.type.d.ts +12 -0
  44. package/angular-vertex-search.module.d.ts +0 -9
  45. package/consts/vertex-config.const.d.ts +0 -1
  46. package/esm2022/angular-connect.module.mjs +0 -187
  47. package/esm2022/angular-elastic-search.module.mjs +0 -34
  48. package/esm2022/angular-firebase-auth.module.mjs +0 -141
  49. package/esm2022/angular-firestore.module.mjs +0 -541
  50. package/esm2022/angular-hasura-graphql.module.mjs +0 -333
  51. package/esm2022/angular-vertex-search.module.mjs +0 -34
  52. package/esm2022/consts/vertex-config.const.mjs +0 -2
  53. package/esm2022/services/cart.service.mjs +0 -86
  54. package/esm2022/services/catalog/catalog.service.mjs +0 -325
  55. package/esm2022/services/catalog/category.service.mjs +0 -51
  56. package/esm2022/services/catalog/wishlist.service.mjs +0 -235
  57. package/esm2022/services/checkout.service.mjs +0 -122
  58. package/esm2022/services/coupon.service.mjs +0 -228
  59. package/fesm2022/infrab4a-connect-angular.mjs.map +0 -1
  60. /package/{esm2022 → esm2020}/consts/backend-url.const.mjs +0 -0
  61. /package/{esm2022 → esm2020}/consts/category-structure.mjs +0 -0
  62. /package/{esm2022 → esm2020}/consts/default-shop.const.mjs +0 -0
  63. /package/{esm2022 → esm2020}/consts/es-config.const.mjs +0 -0
  64. /package/{esm2022 → esm2020}/consts/hasura-options.const.mjs +0 -0
  65. /package/{esm2022 → esm2020}/consts/persistence.const.mjs +0 -0
  66. /package/{esm2022 → esm2020}/consts/storage-base-url.const.mjs +0 -0
  67. /package/{esm2022 → esm2020}/helpers/index.mjs +0 -0
  68. /package/{esm2022 → esm2020}/helpers/mobile-operation-system-checker.helper.mjs +0 -0
  69. /package/{esm2022 → esm2020}/index.mjs +0 -0
  70. /package/{esm2022 → esm2020}/infrab4a-connect-angular.mjs +0 -0
  71. /package/{esm2022 → esm2020}/persistence/data-persistence.mjs +0 -0
  72. /package/{esm2022 → esm2020}/persistence/index.mjs +0 -0
  73. /package/{esm2022 → esm2020}/services/catalog/adapters/category-structure.adapter.mjs +0 -0
  74. /package/{esm2022 → esm2020}/services/catalog/adapters/index.mjs +0 -0
  75. /package/{esm2022 → esm2020}/services/catalog/enums/index.mjs +0 -0
  76. /package/{esm2022 → esm2020}/services/catalog/enums/product-sorts.enum.mjs +0 -0
  77. /package/{esm2022 → esm2020}/services/catalog/index.mjs +0 -0
  78. /package/{esm2022 → esm2020}/services/catalog/models/index.mjs +0 -0
  79. /package/{esm2022 → esm2020}/services/catalog/types/index.mjs +0 -0
  80. /package/{esm2022 → esm2020}/services/catalog/types/product-sort.type.mjs +0 -0
  81. /package/{esm2022 → esm2020}/services/helpers/index.mjs +0 -0
  82. /package/{esm2022 → esm2020}/services/helpers/util.helper.mjs +0 -0
  83. /package/{esm2022 → esm2020}/services/types/index.mjs +0 -0
  84. /package/{esm2022 → esm2020}/services/types/required-checkout-data.type.mjs +0 -0
  85. /package/{esm2022 → esm2020}/services/types/required-checkout-subscription-data.type.mjs +0 -0
  86. /package/{esm2022 → esm2020}/types/firebase-app-config.type.mjs +0 -0
  87. /package/{esm2022 → esm2020}/types/index.mjs +0 -0
@@ -2,23 +2,21 @@ 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/app-check';
6
- import { provideAppCheck, initializeAppCheck } from '@angular/fire/app-check';
7
- import * as i3 from '@angular/fire/storage';
8
- import { Storage, provideStorage, getStorage } from '@angular/fire/storage';
9
- import * as i1$3 from '@infrab4a/connect';
10
- import { ProductsIndex, AxiosAdapter, Authentication, AuthenticationFirebaseAuthService, Register, RegisterFirebaseAuthService, SignOut, RecoveryPassword, ConnectFirestoreService, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, CampaignHashtagFirestoreRepository, CampaignDashboardFirestoreRepository, SubscriptionEditionFirestoreRepository, GroupFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, ShopSettingsFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, SubscriptionMaterializationFirestoreRepository, SubscriptionSummaryFirestoreRepository, ProductVariantFirestoreRepository, OrderBlockedFirestoreRepository, LogFirestoreRepository, SequenceFirestoreRepository, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository, ProductReviewHasuraGraphQLRepository, VariantHasuraGraphQLRepository, ProductStockNotificationHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryProductHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, ProductErrorsHasuraGraphQLRepository, ProductsVertexSearch, VertexAxiosAdapter, isNil, NotFoundError, Checkout, pick, LineItem, Where, set, InvalidArgumentError, RoundProductPricesHelper, isEmpty, Shops, Category, PersonTypes, WishlistLogType, Wishlist, CheckoutTypes, CouponTypes, Exclusivities, OrderStatus, CheckoutSubscription, Product, RequiredArgumentError, add, Order, UpdateUserImage, FirebaseFileUploaderService } from '@infrab4a/connect';
5
+ import * as i1$2 from '@infrab4a/connect';
6
+ 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, 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';
11
7
  import * as i1 from '@angular/fire/auth';
12
- import { Auth, provideAuth, initializeAuth, indexedDBLocalPersistence, browserLocalPersistence, browserSessionPersistence, getAuth, getIdToken, authState } from '@angular/fire/auth';
8
+ import { Auth, provideAuth, getAuth, getIdToken, authState } from '@angular/fire/auth';
13
9
  import { isPlatformBrowser, isPlatformServer } from '@angular/common';
14
10
  import * as i1$1 from '@angular/fire/firestore';
15
11
  import { Firestore, provideFirestore, 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';
16
14
  import cookie from 'js-cookie';
17
- import { of, from, combineLatest, throwError, Subject, forkJoin } from 'rxjs';
15
+ import { of, from, combineLatest, throwError, Subject, iif, forkJoin } from 'rxjs';
18
16
  import { map, mergeMap, catchError, concatMap, tap } from 'rxjs/operators';
19
- import * as i1$2 from '@angular/common/http';
20
17
  import { __decorate, __metadata } from 'tslib';
21
18
  import { Type } from 'class-transformer';
19
+ import * as i1$3 from '@angular/common/http';
22
20
 
23
21
  const ES_CONFIG = 'ES_CONFIG';
24
22
 
@@ -29,17 +27,17 @@ class AngularElasticSeachModule {
29
27
  providers: [{ provide: ES_CONFIG, useValue: options }],
30
28
  };
31
29
  }
32
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularElasticSeachModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
33
- static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularElasticSeachModule }); }
34
- static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularElasticSeachModule, providers: [
35
- {
36
- provide: ProductsIndex,
37
- useFactory: (configuration) => new ProductsIndex(new AxiosAdapter(configuration)),
38
- deps: [ES_CONFIG],
39
- },
40
- ] }); }
41
30
  }
42
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularElasticSeachModule, decorators: [{
31
+ AngularElasticSeachModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
32
+ AngularElasticSeachModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule });
33
+ AngularElasticSeachModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, providers: [
34
+ {
35
+ provide: ProductsIndex,
36
+ useFactory: (configuration) => new ProductsIndex(new AxiosAdapter(configuration)),
37
+ deps: [ES_CONFIG],
38
+ },
39
+ ] });
40
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, decorators: [{
43
41
  type: NgModule,
44
42
  args: [{
45
43
  providers: [
@@ -60,14 +58,11 @@ const DEFAULT_SHOP = 'DEFAULT_SHOP';
60
58
 
61
59
  const FIREBASE_APP_NAME = new InjectionToken('firebaseAppName');
62
60
  const FIREBASE_OPTIONS = new InjectionToken('firebaseOptions');
63
- const APP_CHECK_PROVIDER = new InjectionToken('appCheckProvider');
64
61
 
65
62
  const HASURA_OPTIONS = 'HASURA_OPTIONS';
66
63
 
67
64
  const PERSISTENCE_PROVIDER = 'PERSISTENCE_PROVIDER';
68
65
 
69
- const VERTEX_CONFIG = 'VERTEX_CONFIG';
70
-
71
66
  class AngularFirebaseAuthModule {
72
67
  static initializeApp(options, nameOrConfig) {
73
68
  return {
@@ -78,83 +73,57 @@ class AngularFirebaseAuthModule {
78
73
  ],
79
74
  };
80
75
  }
81
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularFirebaseAuthModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
82
- static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularFirebaseAuthModule, imports: [i1.AuthModule] }); }
83
- static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularFirebaseAuthModule, providers: [
84
- {
85
- provide: 'Authentication',
86
- useFactory: (authenticationService, userRepository) => {
87
- return new Authentication(authenticationService, userRepository);
88
- },
89
- deps: ['AuthenticationService', 'UserRepository'],
90
- },
91
- {
92
- provide: 'AuthenticationService',
93
- useFactory: (angularFireAuth) => {
94
- return new AuthenticationFirebaseAuthService(angularFireAuth);
95
- },
96
- deps: [Auth],
97
- },
98
- {
99
- provide: 'Register',
100
- useFactory: (registerService, userRepository) => {
101
- return new Register(registerService, userRepository);
102
- },
103
- deps: ['RegisterService', 'UserRepository'],
104
- },
105
- {
106
- provide: 'RegisterService',
107
- useFactory: (angularFireAuth) => {
108
- return new RegisterFirebaseAuthService(angularFireAuth);
109
- },
110
- deps: [Auth],
111
- },
112
- {
113
- provide: 'SignOut',
114
- useFactory: (authenticationService) => {
115
- return new SignOut(authenticationService);
116
- },
117
- deps: ['AuthenticationService'],
118
- },
119
- {
120
- provide: 'RecoveryPassword',
121
- useFactory: (authenticationService) => {
122
- return new RecoveryPassword(authenticationService);
123
- },
124
- deps: ['AuthenticationService'],
125
- },
126
- ], imports: [provideAuth((injector) => {
127
- const app = injector.get(FirebaseApp);
128
- try {
129
- return initializeAuth(app, {
130
- persistence: [indexedDBLocalPersistence, browserLocalPersistence, browserSessionPersistence],
131
- });
132
- }
133
- catch (error) {
134
- if (error instanceof Error)
135
- console.error('Error initializing auth', error.message);
136
- return getAuth(app);
137
- }
138
- })] }); }
139
76
  }
140
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularFirebaseAuthModule, decorators: [{
77
+ AngularFirebaseAuthModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
78
+ AngularFirebaseAuthModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, imports: [i1.AuthModule] });
79
+ AngularFirebaseAuthModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, providers: [
80
+ {
81
+ provide: 'Authentication',
82
+ useFactory: (authenticationService, userRepository) => {
83
+ return new Authentication(authenticationService, userRepository);
84
+ },
85
+ deps: ['AuthenticationService', 'UserRepository'],
86
+ },
87
+ {
88
+ provide: 'AuthenticationService',
89
+ useFactory: (angularFireAuth) => {
90
+ return new AuthenticationFirebaseAuthService(angularFireAuth);
91
+ },
92
+ deps: [Auth],
93
+ },
94
+ {
95
+ provide: 'Register',
96
+ useFactory: (registerService, userRepository) => {
97
+ return new Register(registerService, userRepository);
98
+ },
99
+ deps: ['RegisterService', 'UserRepository'],
100
+ },
101
+ {
102
+ provide: 'RegisterService',
103
+ useFactory: (angularFireAuth) => {
104
+ return new RegisterFirebaseAuthService(angularFireAuth);
105
+ },
106
+ deps: [Auth],
107
+ },
108
+ {
109
+ provide: 'SignOut',
110
+ useFactory: (authenticationService) => {
111
+ return new SignOut(authenticationService);
112
+ },
113
+ deps: ['AuthenticationService'],
114
+ },
115
+ {
116
+ provide: 'RecoveryPassword',
117
+ useFactory: (authenticationService) => {
118
+ return new RecoveryPassword(authenticationService);
119
+ },
120
+ deps: ['AuthenticationService'],
121
+ },
122
+ ], imports: [provideAuth((injector) => getAuth(injector.get(FirebaseApp)))] });
123
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, decorators: [{
141
124
  type: NgModule,
142
125
  args: [{
143
- imports: [
144
- provideAuth((injector) => {
145
- const app = injector.get(FirebaseApp);
146
- try {
147
- return initializeAuth(app, {
148
- persistence: [indexedDBLocalPersistence, browserLocalPersistence, browserSessionPersistence],
149
- });
150
- }
151
- catch (error) {
152
- if (error instanceof Error)
153
- console.error('Error initializing auth', error.message);
154
- return getAuth(app);
155
- }
156
- }),
157
- ],
126
+ imports: [provideAuth((injector) => getAuth(injector.get(FirebaseApp)))],
158
127
  providers: [
159
128
  {
160
129
  provide: 'Authentication',
@@ -202,6 +171,8 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
202
171
  }]
203
172
  }] });
204
173
 
174
+ const STORAGE_BASE_URL = 'STORAGE_BASE_URL';
175
+
205
176
  class MobileOperationSystemCheckerHelper {
206
177
  static isAppleDevice() {
207
178
  return (['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator?.platform) ||
@@ -220,264 +191,244 @@ class AngularFirestoreModule {
220
191
  ],
221
192
  };
222
193
  }
223
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularFirestoreModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
224
- static { thismod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularFirestoreModule, imports: [AngularElasticSeachModule, i1$1.FirestoreModule] }); }
225
- static { thisinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularFirestoreModule, providers: [
226
- {
227
- provide: 'FirestoreOptions',
228
- useFactory: (firestore, platformId) => ({
229
- firestore: new ConnectFirestoreService(firestore),
230
- interceptors: {
231
- request: (request) => {
232
- if (isPlatformBrowser(platformId))
233
- return request;
234
- const interval = setInterval(() => { }, 100);
235
- request.interval = interval;
194
+ }
195
+ AngularFirestoreModulefac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
196
+ AngularFirestoreModulemod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, imports: [AngularElasticSeachModule, i1$1.FirestoreModule, i2.StorageModule] });
197
+ AngularFirestoreModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, providers: [
198
+ {
199
+ provide: 'FirestoreOptions',
200
+ useFactory: (firestore, platformId) => ({
201
+ firestore: new ConnectFirestoreService(firestore),
202
+ interceptors: {
203
+ request: (request) => {
204
+ if (isPlatformBrowser(platformId))
236
205
  return request;
237
- },
238
- response: (response, request) => {
239
- if (isPlatformBrowser(platformId))
240
- return response;
241
- clearInterval(request.interval);
206
+ const interval = setInterval(() => { }, 100);
207
+ request.interval = interval;
208
+ return request;
209
+ },
210
+ response: (response, request) => {
211
+ if (isPlatformBrowser(platformId))
242
212
  return response;
243
- },
213
+ clearInterval(request.interval);
214
+ return response;
244
215
  },
245
- }),
246
- deps: [Firestore, PLATFORM_ID],
247
- },
248
- {
249
- provide: 'BeautyProfileRepository',
250
- useFactory: (config, userRepository) => {
251
- return new UserBeautyProfileFirestoreRepository(config, userRepository);
252
- },
253
- deps: ['FirestoreOptions', 'UserRepository'],
254
- },
255
- {
256
- provide: 'Buy2WinRepository',
257
- useFactory: (options) => {
258
- return new Buy2WinFirestoreRepository(options);
259
- },
260
- deps: ['FirestoreOptions'],
261
- },
262
- {
263
- provide: CategoryFirestoreRepository,
264
- useFactory: (options) => {
265
- return new CategoryFirestoreRepository(options);
266
- },
267
- deps: ['FirestoreOptions'],
268
- },
269
- {
270
- provide: 'CheckoutRepository',
271
- useFactory: (options) => {
272
- return new CheckoutFirestoreRepository(options);
273
- },
274
- deps: ['FirestoreOptions'],
275
- },
276
- {
277
- provide: 'CheckoutSubscriptionRepository',
278
- useFactory: (options) => {
279
- return new CheckoutSubscriptionFirestoreRepository(options);
280
- },
281
- deps: ['FirestoreOptions'],
282
- },
283
- {
284
- provide: 'CouponRepository',
285
- useFactory: (options) => {
286
- return new CouponFirestoreRepository(options);
287
- },
288
- deps: ['FirestoreOptions'],
289
- },
290
- {
291
- provide: 'CampaignHashtagRepository',
292
- useFactory: (options) => {
293
- return new CampaignHashtagFirestoreRepository(options);
294
- },
295
- deps: ['FirestoreOptions'],
296
- },
297
- {
298
- provide: 'CampaignDashboardRepository',
299
- useFactory: (options) => {
300
- return new CampaignDashboardFirestoreRepository(options);
301
- },
302
- deps: ['FirestoreOptions'],
303
- },
304
- {
305
- provide: 'EditionRepository',
306
- useFactory: (options, subscriptionRepository) => {
307
- return new SubscriptionEditionFirestoreRepository(options, subscriptionRepository);
308
- },
309
- deps: ['FirestoreOptions', 'SubscriptionRepository'],
310
- },
311
- {
312
- provide: 'GroupRepository',
313
- useFactory: (options) => {
314
- return new GroupFirestoreRepository(options);
315
- },
316
- deps: ['FirestoreOptions'],
317
- },
318
- {
319
- provide: 'HomeRepository',
320
- useFactory: (options) => {
321
- return new HomeFirestoreRepository(options);
322
- },
323
- deps: ['FirestoreOptions'],
324
- },
325
- {
326
- provide: 'LeadRepository',
327
- useFactory: (options) => {
328
- return new LeadFirestoreRepository(options);
329
- },
330
- deps: ['FirestoreOptions'],
331
- },
332
- {
333
- provide: 'LegacyOrderRepository',
334
- useFactory: (options) => {
335
- return new LegacyOrderFirestoreRepository(options);
336
- },
337
- deps: ['FirestoreOptions'],
338
- },
339
- {
340
- provide: 'ShopMenuRepository',
341
- useFactory: (options) => {
342
- return new ShopMenuFirestoreRepository(options);
343
- },
344
- deps: ['FirestoreOptions'],
345
- },
346
- {
347
- provide: 'OrderRepository',
348
- useFactory: (options) => {
349
- return new OrderFirestoreRepository(options);
350
- },
351
- deps: ['FirestoreOptions'],
352
- },
353
- {
354
- provide: 'PaymentRepository',
355
- useFactory: (options) => {
356
- return new PaymentFirestoreRepository(options);
357
- },
358
- deps: ['FirestoreOptions'],
359
- },
360
- {
361
- provide: ProductFirestoreRepository,
362
- useFactory: (options) => {
363
- return new ProductFirestoreRepository(options);
364
- },
365
- deps: ['FirestoreOptions'],
366
- },
367
- {
368
- provide: 'ShopSettingsRepository',
369
- useFactory: (options) => {
370
- return new ShopSettingsFirestoreRepository(options);
371
- },
372
- deps: ['FirestoreOptions'],
373
- },
374
- {
375
- provide: 'SubscriptionPaymentRepository',
376
- useFactory: (options, subscriptionRepository) => {
377
- return new SubscriptionPaymentFirestoreRepository(options, subscriptionRepository);
378
- },
379
- deps: ['FirestoreOptions', 'SubscriptionRepository'],
380
- },
381
- {
382
- provide: 'SubscriptionPlanRepository',
383
- useFactory: (options) => {
384
- return new SubscriptionPlanFirestoreRepository(options);
385
- },
386
- deps: ['FirestoreOptions'],
387
- },
388
- {
389
- provide: 'SubscriptionProductRepository',
390
- useFactory: (options) => {
391
- return new SubscriptionProductFirestoreRepository(options);
392
- },
393
- deps: ['FirestoreOptions'],
394
- },
395
- {
396
- provide: 'SubscriptionRepository',
397
- useFactory: (options) => {
398
- return new SubscriptionFirestoreRepository(options);
399
- },
400
- deps: ['FirestoreOptions'],
401
- },
402
- {
403
- provide: 'UserRepository',
404
- useFactory: (options) => {
405
- return new UserFirestoreRepository(options);
406
- },
407
- deps: ['FirestoreOptions'],
408
- },
409
- {
410
- provide: 'UserAddressRepository',
411
- useFactory: (options, userRepository) => {
412
- return new UserAddressFirestoreRepository(options, userRepository);
413
- },
414
- deps: ['FirestoreOptions', 'UserRepository'],
415
- },
416
- {
417
- provide: 'UserPaymentMethodRepository',
418
- useFactory: (options, userRepository) => {
419
- return new UserPaymentMethodFirestoreRepository(options, userRepository);
420
- },
421
- deps: ['FirestoreOptions', 'UserRepository'],
422
- },
423
- {
424
- provide: 'SubscriptionMaterializationRepository',
425
- useFactory: (options) => {
426
- return new SubscriptionMaterializationFirestoreRepository(options);
427
- },
428
- deps: ['FirestoreOptions'],
429
- },
430
- {
431
- provide: 'SubscriptionSummaryRepository',
432
- useFactory: (options) => {
433
- return new SubscriptionSummaryFirestoreRepository(options);
434
- },
435
- deps: ['FirestoreOptions'],
436
- },
437
- {
438
- provide: ProductVariantFirestoreRepository,
439
- useFactory: (options, productRepository) => {
440
- return new ProductVariantFirestoreRepository(options, productRepository);
441
- },
442
- deps: ['FirestoreOptions', ProductFirestoreRepository],
443
- },
444
- {
445
- provide: 'OrderBlockedRepository',
446
- useFactory: (options) => {
447
- return new OrderBlockedFirestoreRepository(options);
448
- },
449
- deps: ['FirestoreOptions'],
450
- },
451
- {
452
- provide: 'LogRepository',
453
- useFactory: (options) => {
454
- return new LogFirestoreRepository(options);
455
- },
456
- deps: ['FirestoreOptions'],
457
- },
458
- {
459
- provide: 'SequenceRepository',
460
- useFactory: (options) => {
461
- return new SequenceFirestoreRepository(options);
462
216
  },
463
- deps: ['FirestoreOptions'],
464
- },
465
- ], imports: [AngularElasticSeachModule,
466
- provideFirestore((injector) => {
467
- const platformId = injector.get(PLATFORM_ID);
468
- if (isPlatformServer(platformId) || !MobileOperationSystemCheckerHelper.isAppleDevice())
469
- return initializeFirestore(injector.get(FirebaseApp), {
470
- ignoreUndefinedProperties: true,
471
- });
472
- const firestore = initializeFirestore(injector.get(FirebaseApp), {
473
- experimentalForceLongPolling: true,
217
+ }),
218
+ deps: [Firestore, PLATFORM_ID],
219
+ },
220
+ {
221
+ provide: 'BeautyProfileRepository',
222
+ useFactory: (config, userRepository) => {
223
+ return new UserBeautyProfileFirestoreRepository(config, userRepository);
224
+ },
225
+ deps: ['FirestoreOptions', 'UserRepository'],
226
+ },
227
+ {
228
+ provide: 'Buy2WinRepository',
229
+ useFactory: (options) => {
230
+ return new Buy2WinFirestoreRepository(options);
231
+ },
232
+ deps: ['FirestoreOptions'],
233
+ },
234
+ {
235
+ provide: CategoryFirestoreRepository,
236
+ useFactory: (options) => {
237
+ return new CategoryFirestoreRepository(options);
238
+ },
239
+ deps: ['FirestoreOptions'],
240
+ },
241
+ {
242
+ provide: 'CheckoutRepository',
243
+ useFactory: (options) => {
244
+ return new CheckoutFirestoreRepository(options);
245
+ },
246
+ deps: ['FirestoreOptions'],
247
+ },
248
+ {
249
+ provide: 'CheckoutSubscriptionRepository',
250
+ useFactory: (options) => {
251
+ return new CheckoutSubscriptionFirestoreRepository(options);
252
+ },
253
+ deps: ['FirestoreOptions'],
254
+ },
255
+ {
256
+ provide: 'CouponRepository',
257
+ useFactory: (options) => {
258
+ return new CouponFirestoreRepository(options);
259
+ },
260
+ deps: ['FirestoreOptions'],
261
+ },
262
+ {
263
+ provide: 'CampaignHashtagRepository',
264
+ useFactory: (options) => {
265
+ return new CampaignHashtagFirestoreRepository(options);
266
+ },
267
+ deps: ['FirestoreOptions'],
268
+ },
269
+ {
270
+ provide: 'CampaignDashboardRepository',
271
+ useFactory: (options) => {
272
+ return new CampaignDashboardFirestoreRepository(options);
273
+ },
274
+ deps: ['FirestoreOptions'],
275
+ },
276
+ {
277
+ provide: 'EditionRepository',
278
+ useFactory: (options, subscriptionRepository) => {
279
+ return new SubscriptionEditionFirestoreRepository(options, subscriptionRepository);
280
+ },
281
+ deps: ['FirestoreOptions', 'SubscriptionRepository'],
282
+ },
283
+ {
284
+ provide: 'HomeRepository',
285
+ useFactory: (options) => {
286
+ return new HomeFirestoreRepository(options);
287
+ },
288
+ deps: ['FirestoreOptions'],
289
+ },
290
+ {
291
+ provide: 'LeadRepository',
292
+ useFactory: (options) => {
293
+ return new LeadFirestoreRepository(options);
294
+ },
295
+ deps: ['FirestoreOptions'],
296
+ },
297
+ {
298
+ provide: 'LegacyOrderRepository',
299
+ useFactory: (options) => {
300
+ return new LegacyOrderFirestoreRepository(options);
301
+ },
302
+ deps: ['FirestoreOptions'],
303
+ },
304
+ {
305
+ provide: 'ShopMenuRepository',
306
+ useFactory: (options) => {
307
+ return new ShopMenuFirestoreRepository(options);
308
+ },
309
+ deps: ['FirestoreOptions'],
310
+ },
311
+ {
312
+ provide: 'OrderRepository',
313
+ useFactory: (options) => {
314
+ return new OrderFirestoreRepository(options);
315
+ },
316
+ deps: ['FirestoreOptions'],
317
+ },
318
+ {
319
+ provide: 'PaymentRepository',
320
+ useFactory: (options) => {
321
+ return new PaymentFirestoreRepository(options);
322
+ },
323
+ deps: ['FirestoreOptions'],
324
+ },
325
+ {
326
+ provide: ProductFirestoreRepository,
327
+ useFactory: (options) => {
328
+ return new ProductFirestoreRepository(options);
329
+ },
330
+ deps: ['FirestoreOptions'],
331
+ },
332
+ {
333
+ provide: 'ShopSettingsRepository',
334
+ useFactory: (options) => {
335
+ return new ShopSettingsFirestoreRepository(options);
336
+ },
337
+ deps: ['FirestoreOptions'],
338
+ },
339
+ {
340
+ provide: 'SubscriptionPaymentRepository',
341
+ useFactory: (options, subscriptionRepository) => {
342
+ return new SubscriptionPaymentFirestoreRepository(options, subscriptionRepository);
343
+ },
344
+ deps: ['FirestoreOptions', 'SubscriptionRepository'],
345
+ },
346
+ {
347
+ provide: 'SubscriptionPlanRepository',
348
+ useFactory: (options) => {
349
+ return new SubscriptionPlanFirestoreRepository(options);
350
+ },
351
+ deps: ['FirestoreOptions'],
352
+ },
353
+ {
354
+ provide: 'SubscriptionProductRepository',
355
+ useFactory: (options) => {
356
+ return new SubscriptionProductFirestoreRepository(options);
357
+ },
358
+ deps: ['FirestoreOptions'],
359
+ },
360
+ {
361
+ provide: 'SubscriptionRepository',
362
+ useFactory: (options) => {
363
+ return new SubscriptionFirestoreRepository(options);
364
+ },
365
+ deps: ['FirestoreOptions'],
366
+ },
367
+ {
368
+ provide: 'UserRepository',
369
+ useFactory: (options) => {
370
+ return new UserFirestoreRepository(options);
371
+ },
372
+ deps: ['FirestoreOptions'],
373
+ },
374
+ {
375
+ provide: 'UserAddressRepository',
376
+ useFactory: (options, userRepository) => {
377
+ return new UserAddressFirestoreRepository(options, userRepository);
378
+ },
379
+ deps: ['FirestoreOptions', 'UserRepository'],
380
+ },
381
+ {
382
+ provide: 'UserPaymentMethodRepository',
383
+ useFactory: (options, userRepository) => {
384
+ return new UserPaymentMethodFirestoreRepository(options, userRepository);
385
+ },
386
+ deps: ['FirestoreOptions', 'UserRepository'],
387
+ },
388
+ {
389
+ provide: 'SubscriptionMaterializationRepository',
390
+ useFactory: (options) => {
391
+ return new SubscriptionMaterializationFirestoreRepository(options);
392
+ },
393
+ deps: ['FirestoreOptions'],
394
+ },
395
+ {
396
+ provide: 'SubscriptionSummaryRepository',
397
+ useFactory: (options) => {
398
+ return new SubscriptionSummaryFirestoreRepository(options);
399
+ },
400
+ deps: ['FirestoreOptions'],
401
+ },
402
+ {
403
+ provide: ProductVariantFirestoreRepository,
404
+ useFactory: (options, productRepository) => {
405
+ return new ProductVariantFirestoreRepository(options, productRepository);
406
+ },
407
+ deps: ['FirestoreOptions', ProductFirestoreRepository],
408
+ },
409
+ {
410
+ provide: 'FileUploaderService',
411
+ useFactory: (storage, baseUrl) => {
412
+ return new FirebaseFileUploaderService(storage, baseUrl);
413
+ },
414
+ deps: [Storage, STORAGE_BASE_URL],
415
+ },
416
+ ], imports: [AngularElasticSeachModule,
417
+ provideFirestore((injector) => {
418
+ const platformId = injector.get(PLATFORM_ID);
419
+ if (isPlatformServer(platformId) || !MobileOperationSystemCheckerHelper.isAppleDevice())
420
+ return initializeFirestore(injector.get(FirebaseApp), {
474
421
  ignoreUndefinedProperties: true,
475
- localCache: memoryLocalCache(),
476
422
  });
477
- return firestore;
478
- })] }); }
479
- }
480
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularFirestoreModule, decorators: [{
423
+ const firestore = initializeFirestore(injector.get(FirebaseApp), {
424
+ experimentalForceLongPolling: true,
425
+ ignoreUndefinedProperties: true,
426
+ localCache: memoryLocalCache(),
427
+ });
428
+ return firestore;
429
+ }),
430
+ provideStorage(() => getStorage())] });
431
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, decorators: [{
481
432
  type: NgModule,
482
433
  args: [{
483
434
  imports: [
@@ -495,6 +446,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
495
446
  });
496
447
  return firestore;
497
448
  }),
449
+ provideStorage(() => getStorage()),
498
450
  ],
499
451
  providers: [
500
452
  {
@@ -582,13 +534,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
582
534
  },
583
535
  deps: ['FirestoreOptions', 'SubscriptionRepository'],
584
536
  },
585
- {
586
- provide: 'GroupRepository',
587
- useFactory: (options) => {
588
- return new GroupFirestoreRepository(options);
589
- },
590
- deps: ['FirestoreOptions'],
591
- },
592
537
  {
593
538
  provide: 'HomeRepository',
594
539
  useFactory: (options) => {
@@ -716,25 +661,11 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
716
661
  deps: ['FirestoreOptions', ProductFirestoreRepository],
717
662
  },
718
663
  {
719
- provide: 'OrderBlockedRepository',
720
- useFactory: (options) => {
721
- return new OrderBlockedFirestoreRepository(options);
722
- },
723
- deps: ['FirestoreOptions'],
724
- },
725
- {
726
- provide: 'LogRepository',
727
- useFactory: (options) => {
728
- return new LogFirestoreRepository(options);
729
- },
730
- deps: ['FirestoreOptions'],
731
- },
732
- {
733
- provide: 'SequenceRepository',
734
- useFactory: (options) => {
735
- return new SequenceFirestoreRepository(options);
664
+ provide: 'FileUploaderService',
665
+ useFactory: (storage, baseUrl) => {
666
+ return new FirebaseFileUploaderService(storage, baseUrl);
736
667
  },
737
- deps: ['FirestoreOptions'],
668
+ deps: [Storage, STORAGE_BASE_URL],
738
669
  },
739
670
  ],
740
671
  }]
@@ -747,166 +678,132 @@ class AngularHasuraGraphQLModule {
747
678
  providers: [{ provide: HASURA_OPTIONS, useValue: options }],
748
679
  };
749
680
  }
750
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularHasuraGraphQLModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
751
- static { thismod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularHasuraGraphQLModule }); }
752
- static { thisinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularHasuraGraphQLModule, providers: [
753
- {
754
- provide: 'HasuraConfig',
755
- useFactory: (options, platformId) => ({
756
- endpoint: options.endpoint,
757
- authOptions: options.credentials,
758
- cache: options.cache,
759
- interceptors: {
760
- request: (request) => {
761
- if (isPlatformBrowser(platformId))
762
- return request;
763
- const interval = setInterval(() => { }, 100);
764
- request.interval = interval;
681
+ }
682
+ AngularHasuraGraphQLModulefac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
683
+ AngularHasuraGraphQLModulemod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule });
684
+ AngularHasuraGraphQLModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, providers: [
685
+ {
686
+ provide: 'HasuraConfig',
687
+ useFactory: (options, platformId) => ({
688
+ endpoint: options.endpoint,
689
+ authOptions: options.credentials,
690
+ interceptors: {
691
+ request: (request) => {
692
+ if (isPlatformBrowser(platformId))
765
693
  return request;
766
- },
767
- response: (response, request) => {
768
- if (isPlatformBrowser(platformId))
769
- return response;
770
- clearInterval(request.interval);
694
+ const interval = setInterval(() => { }, 100);
695
+ request.interval = interval;
696
+ return request;
697
+ },
698
+ response: (response, request) => {
699
+ if (isPlatformBrowser(platformId))
771
700
  return response;
772
- },
701
+ clearInterval(request.interval);
702
+ return response;
773
703
  },
774
- }),
775
- deps: [HASURA_OPTIONS, PLATFORM_ID],
776
- },
777
- {
778
- provide: 'CategoryRepository',
779
- useExisting: CategoryHasuraGraphQLRepository,
780
- },
781
- {
782
- provide: CategoryHasuraGraphQLRepository,
783
- useFactory: (options, productRepository, categoryFilterRepository) => {
784
- return new CategoryHasuraGraphQLRepository(options, productRepository, categoryFilterRepository);
785
704
  },
786
- deps: ['HasuraConfig', ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
787
- },
788
- {
789
- provide: 'ProductRepository',
790
- useExisting: ProductHasuraGraphQLRepository,
791
- },
792
- {
793
- provide: ProductHasuraGraphQLRepository,
794
- useFactory: (hasuraConfig) => {
795
- return new ProductHasuraGraphQLRepository(hasuraConfig);
796
- },
797
- deps: ['HasuraConfig'],
798
- },
799
- {
800
- provide: 'ProductReviewRepository',
801
- useExisting: ProductReviewHasuraGraphQLRepository,
802
- },
803
- {
804
- provide: ProductReviewHasuraGraphQLRepository,
805
- useFactory: (hasuraConfig) => {
806
- return new ProductReviewHasuraGraphQLRepository(hasuraConfig);
807
- },
808
- deps: ['HasuraConfig'],
809
- },
810
- {
811
- provide: 'VariantRepository',
812
- useExisting: VariantHasuraGraphQLRepository,
813
- },
814
- {
815
- provide: VariantHasuraGraphQLRepository,
816
- useFactory: (hasuraConfig) => {
817
- return new VariantHasuraGraphQLRepository(hasuraConfig);
818
- },
819
- deps: ['HasuraConfig'],
820
- },
821
- {
822
- provide: 'ProductStockNotificationRepository',
823
- useExisting: ProductStockNotificationHasuraGraphQLRepository,
824
- },
825
- {
826
- provide: ProductStockNotificationHasuraGraphQLRepository,
827
- useFactory: (hasuraConfig) => {
828
- return new ProductStockNotificationHasuraGraphQLRepository(hasuraConfig);
829
- },
830
- deps: ['HasuraConfig'],
831
- },
832
- {
833
- provide: 'CategoryFilterRepository',
834
- useExisting: CategoryFilterHasuraGraphQLRepository,
835
- },
836
- {
837
- provide: CategoryFilterHasuraGraphQLRepository,
838
- useFactory: (options) => {
839
- return new CategoryFilterHasuraGraphQLRepository(options);
840
- },
841
- deps: ['HasuraConfig'],
842
- },
843
- {
844
- provide: 'FilterOptionRepository',
845
- useExisting: FilterOptionHasuraGraphQLRepository,
846
- },
847
- {
848
- provide: FilterOptionHasuraGraphQLRepository,
849
- useFactory: (options) => {
850
- return new FilterOptionHasuraGraphQLRepository(options);
851
- },
852
- deps: ['HasuraConfig'],
853
- },
854
- {
855
- provide: 'FilterRepository',
856
- useExisting: FilterHasuraGraphQLRepository,
857
- },
858
- {
859
- provide: FilterHasuraGraphQLRepository,
860
- useFactory: (options, filterOptionRepository, categoryFilterRepository) => {
861
- return new FilterHasuraGraphQLRepository(options, filterOptionRepository, categoryFilterRepository);
862
- },
863
- deps: ['HasuraConfig', FilterOptionHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
864
- },
865
- {
866
- provide: CategoryCollectionChildrenHasuraGraphQLRepository,
867
- useFactory: (options) => new CategoryCollectionChildrenHasuraGraphQLRepository(options),
868
- deps: ['HasuraConfig'],
869
- },
870
- {
871
- provide: 'CategoryCollectionChildrenRepository',
872
- useExisting: CategoryCollectionChildrenHasuraGraphQLRepository,
873
- },
874
- {
875
- provide: CategoryProductHasuraGraphQLRepository,
876
- useFactory: (options) => {
877
- return new CategoryProductHasuraGraphQLRepository(options);
878
- },
879
- deps: ['HasuraConfig'],
880
- },
881
- {
882
- provide: 'CategoryProductRepository',
883
- useExisting: CategoryProductHasuraGraphQLRepository,
884
- },
885
- {
886
- provide: WishlistHasuraGraphQLRepository,
887
- useFactory: (options, categoryProductRepository) => {
888
- return new WishlistHasuraGraphQLRepository(options, categoryProductRepository);
889
- },
890
- deps: ['HasuraConfig', CategoryProductHasuraGraphQLRepository],
891
- },
892
- {
893
- provide: 'WishlistRepository',
894
- useExisting: WishlistHasuraGraphQLRepository,
895
- },
896
- {
897
- provide: ProductErrorsHasuraGraphQLRepository,
898
- useFactory: (options, productRepository) => {
899
- return new ProductErrorsHasuraGraphQLRepository(options, productRepository);
900
- },
901
- deps: ['HasuraConfig', ProductHasuraGraphQLRepository],
902
- },
903
- {
904
- provide: 'ProductErrorsRepository',
905
- useExisting: ProductErrorsHasuraGraphQLRepository,
906
- },
907
- ] }); }
908
- }
909
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularHasuraGraphQLModule, decorators: [{
705
+ }),
706
+ deps: [HASURA_OPTIONS, PLATFORM_ID],
707
+ },
708
+ {
709
+ provide: 'CategoryRepository',
710
+ useExisting: CategoryHasuraGraphQLRepository,
711
+ },
712
+ {
713
+ provide: CategoryHasuraGraphQLRepository,
714
+ useFactory: (options, productRepository, categoryFilterRepository) => {
715
+ return new CategoryHasuraGraphQLRepository(options, productRepository, categoryFilterRepository);
716
+ },
717
+ deps: ['HasuraConfig', ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
718
+ },
719
+ {
720
+ provide: 'ProductRepository',
721
+ useExisting: ProductHasuraGraphQLRepository,
722
+ },
723
+ {
724
+ provide: ProductHasuraGraphQLRepository,
725
+ useFactory: (hasuraConfig) => {
726
+ return new ProductHasuraGraphQLRepository(hasuraConfig);
727
+ },
728
+ deps: ['HasuraConfig'],
729
+ },
730
+ {
731
+ provide: 'ProductReviewsRepository',
732
+ useExisting: ProductReviewsHasuraGraphQLRepository,
733
+ },
734
+ {
735
+ provide: ProductReviewsHasuraGraphQLRepository,
736
+ useFactory: (hasuraConfig) => {
737
+ return new ProductReviewsHasuraGraphQLRepository(hasuraConfig);
738
+ },
739
+ deps: ['HasuraConfig'],
740
+ },
741
+ {
742
+ provide: 'VariantRepository',
743
+ useExisting: VariantHasuraGraphQLRepository,
744
+ },
745
+ {
746
+ provide: VariantHasuraGraphQLRepository,
747
+ useFactory: (hasuraConfig) => {
748
+ return new VariantHasuraGraphQLRepository(hasuraConfig);
749
+ },
750
+ deps: ['HasuraConfig'],
751
+ },
752
+ {
753
+ provide: 'CategoryFilterRepository',
754
+ useExisting: CategoryFilterHasuraGraphQLRepository,
755
+ },
756
+ {
757
+ provide: CategoryFilterHasuraGraphQLRepository,
758
+ useFactory: (options) => {
759
+ return new CategoryFilterHasuraGraphQLRepository(options);
760
+ },
761
+ deps: ['HasuraConfig'],
762
+ },
763
+ {
764
+ provide: 'FilterOptionRepository',
765
+ useExisting: FilterOptionHasuraGraphQLRepository,
766
+ },
767
+ {
768
+ provide: FilterOptionHasuraGraphQLRepository,
769
+ useFactory: (options) => {
770
+ return new FilterOptionHasuraGraphQLRepository(options);
771
+ },
772
+ deps: ['HasuraConfig'],
773
+ },
774
+ {
775
+ provide: 'FilterRepository',
776
+ useExisting: FilterHasuraGraphQLRepository,
777
+ },
778
+ {
779
+ provide: FilterHasuraGraphQLRepository,
780
+ useFactory: (options, filterOptionRepository, categoryFilterRepository) => {
781
+ return new FilterHasuraGraphQLRepository(options, filterOptionRepository, categoryFilterRepository);
782
+ },
783
+ deps: ['HasuraConfig', FilterOptionHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
784
+ },
785
+ {
786
+ provide: CategoryCollectionChildrenHasuraGraphQLRepository,
787
+ useFactory: (options) => new CategoryCollectionChildrenHasuraGraphQLRepository(options),
788
+ deps: ['HasuraConfig'],
789
+ },
790
+ {
791
+ provide: 'CategoryCollectionChildrenRepository',
792
+ useExisting: CategoryCollectionChildrenHasuraGraphQLRepository,
793
+ },
794
+ {
795
+ provide: WishlistHasuraGraphQLRepository,
796
+ useFactory: (options, categoryFilterRepository) => {
797
+ return new WishlistHasuraGraphQLRepository(options, categoryFilterRepository);
798
+ },
799
+ deps: ['HasuraConfig', CategoryFilterHasuraGraphQLRepository],
800
+ },
801
+ {
802
+ provide: 'WishlistRepository',
803
+ useExisting: WishlistHasuraGraphQLRepository,
804
+ },
805
+ ] });
806
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, decorators: [{
910
807
  type: NgModule,
911
808
  args: [{
912
809
  providers: [
@@ -915,7 +812,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
915
812
  useFactory: (options, platformId) => ({
916
813
  endpoint: options.endpoint,
917
814
  authOptions: options.credentials,
918
- cache: options.cache,
919
815
  interceptors: {
920
816
  request: (request) => {
921
817
  if (isPlatformBrowser(platformId))
@@ -957,13 +853,13 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
957
853
  deps: ['HasuraConfig'],
958
854
  },
959
855
  {
960
- provide: 'ProductReviewRepository',
961
- useExisting: ProductReviewHasuraGraphQLRepository,
856
+ provide: 'ProductReviewsRepository',
857
+ useExisting: ProductReviewsHasuraGraphQLRepository,
962
858
  },
963
859
  {
964
- provide: ProductReviewHasuraGraphQLRepository,
860
+ provide: ProductReviewsHasuraGraphQLRepository,
965
861
  useFactory: (hasuraConfig) => {
966
- return new ProductReviewHasuraGraphQLRepository(hasuraConfig);
862
+ return new ProductReviewsHasuraGraphQLRepository(hasuraConfig);
967
863
  },
968
864
  deps: ['HasuraConfig'],
969
865
  },
@@ -978,17 +874,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
978
874
  },
979
875
  deps: ['HasuraConfig'],
980
876
  },
981
- {
982
- provide: 'ProductStockNotificationRepository',
983
- useExisting: ProductStockNotificationHasuraGraphQLRepository,
984
- },
985
- {
986
- provide: ProductStockNotificationHasuraGraphQLRepository,
987
- useFactory: (hasuraConfig) => {
988
- return new ProductStockNotificationHasuraGraphQLRepository(hasuraConfig);
989
- },
990
- deps: ['HasuraConfig'],
991
- },
992
877
  {
993
878
  provide: 'CategoryFilterRepository',
994
879
  useExisting: CategoryFilterHasuraGraphQLRepository,
@@ -1031,75 +916,21 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
1031
916
  provide: 'CategoryCollectionChildrenRepository',
1032
917
  useExisting: CategoryCollectionChildrenHasuraGraphQLRepository,
1033
918
  },
1034
- {
1035
- provide: CategoryProductHasuraGraphQLRepository,
1036
- useFactory: (options) => {
1037
- return new CategoryProductHasuraGraphQLRepository(options);
1038
- },
1039
- deps: ['HasuraConfig'],
1040
- },
1041
- {
1042
- provide: 'CategoryProductRepository',
1043
- useExisting: CategoryProductHasuraGraphQLRepository,
1044
- },
1045
919
  {
1046
920
  provide: WishlistHasuraGraphQLRepository,
1047
- useFactory: (options, categoryProductRepository) => {
1048
- return new WishlistHasuraGraphQLRepository(options, categoryProductRepository);
921
+ useFactory: (options, categoryFilterRepository) => {
922
+ return new WishlistHasuraGraphQLRepository(options, categoryFilterRepository);
1049
923
  },
1050
- deps: ['HasuraConfig', CategoryProductHasuraGraphQLRepository],
924
+ deps: ['HasuraConfig', CategoryFilterHasuraGraphQLRepository],
1051
925
  },
1052
926
  {
1053
927
  provide: 'WishlistRepository',
1054
928
  useExisting: WishlistHasuraGraphQLRepository,
1055
929
  },
1056
- {
1057
- provide: ProductErrorsHasuraGraphQLRepository,
1058
- useFactory: (options, productRepository) => {
1059
- return new ProductErrorsHasuraGraphQLRepository(options, productRepository);
1060
- },
1061
- deps: ['HasuraConfig', ProductHasuraGraphQLRepository],
1062
- },
1063
- {
1064
- provide: 'ProductErrorsRepository',
1065
- useExisting: ProductErrorsHasuraGraphQLRepository,
1066
- },
1067
- ],
1068
- }]
1069
- }] });
1070
-
1071
- class AngularVertexSeachModule {
1072
- static initializeApp(options) {
1073
- return {
1074
- ngModule: AngularVertexSeachModule,
1075
- providers: [{ provide: VERTEX_CONFIG, useValue: options }],
1076
- };
1077
- }
1078
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
1079
- static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule }); }
1080
- static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule, providers: [
1081
- {
1082
- provide: ProductsVertexSearch,
1083
- useFactory: (configuration) => new ProductsVertexSearch(new VertexAxiosAdapter(configuration)),
1084
- deps: [VERTEX_CONFIG],
1085
- },
1086
- ] }); }
1087
- }
1088
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularVertexSeachModule, decorators: [{
1089
- type: NgModule,
1090
- args: [{
1091
- providers: [
1092
- {
1093
- provide: ProductsVertexSearch,
1094
- useFactory: (configuration) => new ProductsVertexSearch(new VertexAxiosAdapter(configuration)),
1095
- deps: [VERTEX_CONFIG],
1096
- },
1097
930
  ],
1098
931
  }]
1099
932
  }] });
1100
933
 
1101
- const STORAGE_BASE_URL = 'STORAGE_BASE_URL';
1102
-
1103
934
  class CookieDataPersistence {
1104
935
  get(key) {
1105
936
  return of(cookie.get(key));
@@ -1110,10 +941,10 @@ class CookieDataPersistence {
1110
941
  set(key, value) {
1111
942
  return from(cookie.set(key, value)).pipe(map(() => { }));
1112
943
  }
1113
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CookieDataPersistence, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1114
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CookieDataPersistence }); }
1115
944
  }
1116
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CookieDataPersistence, decorators: [{
945
+ CookieDataPersistence.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CookieDataPersistence, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
946
+ CookieDataPersistence.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CookieDataPersistence });
947
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CookieDataPersistence, decorators: [{
1117
948
  type: Injectable
1118
949
  }] });
1119
950
 
@@ -1138,138 +969,326 @@ class AuthService {
1138
969
  getFireUser() {
1139
970
  return authState(this.angularFireAuth).pipe(catchError(() => of(null)));
1140
971
  }
1141
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AuthService, deps: [{ token: i1.Auth }, { token: 'UserRepository' }], target: i0.ɵɵFactoryTarget.Injectable }); }
1142
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AuthService }); }
1143
972
  }
1144
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AuthService, decorators: [{
973
+ AuthService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AuthService, deps: [{ token: i1.Auth }, { token: 'UserRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
974
+ AuthService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AuthService });
975
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AuthService, decorators: [{
1145
976
  type: Injectable
1146
- }], ctorParameters: () => [{ type: i1.Auth }, { type: undefined, decorators: [{
977
+ }], ctorParameters: function () { return [{ type: i1.Auth }, { type: undefined, decorators: [{
1147
978
  type: Inject,
1148
979
  args: ['UserRepository']
1149
- }] }] });
980
+ }] }]; } });
1150
981
 
1151
- class CheckoutService {
1152
- constructor(checkoutRepository, userRepository, defaultShop, dataPersistence, firebaseOptions, http) {
1153
- this.checkoutRepository = checkoutRepository;
1154
- this.userRepository = userRepository;
982
+ class CouponService {
983
+ constructor(couponRepository, defaultShop, orderRepository, categoryRepository) {
984
+ this.couponRepository = couponRepository;
1155
985
  this.defaultShop = defaultShop;
1156
- this.dataPersistence = dataPersistence;
1157
- this.firebaseOptions = firebaseOptions;
1158
- this.http = http;
1159
- this.checkoutUrl = null;
1160
- this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`;
1161
- }
1162
- getCheckout(checkoutData) {
1163
- return this.dataPersistence
1164
- .get('checkoutId')
1165
- .pipe(concatMap((id) => (!isNil(id) ? this.checkoutRepository.get({ id }) : this.createCheckout(checkoutData))));
1166
- }
1167
- getUserByCheckout(checkoutId) {
1168
- 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'))));
1169
- }
1170
- updateCheckoutLineItems(checkout) {
1171
- return from(this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, lineItems: checkout.lineItems })));
1172
- }
1173
- updateCheckoutUser(checkout) {
1174
- return from(this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, user: checkout.user })));
1175
- }
1176
- clearCheckoutFromSession() {
1177
- return this.dataPersistence.remove('checkoutId');
1178
- }
1179
- resetCheckoutValues() {
1180
- return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutResetValues`, {
1181
- checkoutId: checkout.id,
1182
- })), concatMap(() => this.getCheckout()));
1183
- }
1184
- applyCouponDiscount(nickname, checkoutType) {
1185
- return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutApplyDiscount`, {
1186
- checkoutId: checkout.id,
1187
- coupon: nickname,
1188
- checkoutType,
1189
- })), concatMap(() => this.getCheckout()), map((checkout) => checkout.coupon));
1190
- }
1191
- removeCouponDiscount() {
1192
- return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutRemoveDiscount`, {
1193
- checkoutId: checkout.id,
1194
- })), concatMap(() => this.getCheckout()));
1195
- }
1196
- validateStockProducts() {
1197
- return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutValidateProductStock`, {
1198
- checkoutId: checkout.id,
1199
- })));
1200
- }
1201
- selectShippingAddress(address) {
1202
- return this.getCheckout().pipe(concatMap((checkout) => {
1203
- return this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, shippingAddress: address, billingAddress: address }));
1204
- }));
1205
- }
1206
- getAvailableShippingForProduct(productShipping) {
1207
- return this.http.post(`${this.checkoutUrl}/checkoutGetAvailableShipping`, {
1208
- checkoutId: null,
1209
- productShipping,
1210
- });
1211
- }
1212
- getAvailableShippingForCheckout() {
1213
- return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutGetAvailableShipping`, {
1214
- checkoutId: checkout.id,
1215
- productShipping: null,
1216
- })));
986
+ this.orderRepository = orderRepository;
987
+ this.categoryRepository = categoryRepository;
988
+ this.emailIsFromCollaborator = (userEmail) => !!userEmail?.match(/@b4a.com.br/g);
1217
989
  }
1218
- selectShipping(option) {
1219
- return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutSelectShipping`, {
1220
- checkoutId: checkout.id,
1221
- shippingOption: option,
1222
- })), concatMap(() => this.getCheckout()));
1223
- }
1224
- createOrder(checkoutPayload, paymentProvider, applicationVersion) {
1225
- return this.http.post(`${this.checkoutUrl}/checkout`, {
1226
- data: {
1227
- ...checkoutPayload,
1228
- applicationVersion,
1229
- paymentProvider,
990
+ checkCoupon(nickname, checkoutType, checkout, plan) {
991
+ return from(this.couponRepository
992
+ .find({
993
+ filters: {
994
+ nickname: { operator: Where.EQUALS, value: nickname },
995
+ active: { operator: Where.EQUALS, value: true },
1230
996
  },
1231
- });
1232
- }
1233
- async createCheckout(checkoutData) {
1234
- const checkout = await this.checkoutRepository.create({
1235
- createdAt: new Date(),
1236
- ...Checkout.toInstance(pick(checkoutData, ['user', 'shop'])).toPlain(),
1237
- shop: checkoutData?.shop || this.defaultShop,
1238
- });
1239
- await this.dataPersistence.set('checkoutId', checkout.id).toPromise();
1240
- return checkout;
997
+ })
998
+ .then((result) => result.data[0])).pipe(concatMap((coupon) => this.couponValidation(coupon, checkoutType)), concatMap((couponValid) => this.couponRulesValidation(couponValid, checkoutType, checkout, plan)), map((couponValidated) => couponValidated));
1241
999
  }
1242
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutService, deps: [{ token: 'CheckoutRepository' }, { token: 'UserRepository' }, { token: DEFAULT_SHOP }, { token: PERSISTENCE_PROVIDER }, { token: FIREBASE_OPTIONS }, { token: i1$2.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable }); }
1243
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutService }); }
1244
- }
1245
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutService, decorators: [{
1246
- type: Injectable
1247
- }], ctorParameters: () => [{ type: undefined, decorators: [{
1000
+ async couponValidation(coupon, checkoutType) {
1001
+ if (!coupon)
1002
+ throw 'Cupom inválido.';
1003
+ if (coupon?.beginAt && coupon?.beginAt.getTime() > new Date().getTime())
1004
+ throw 'Cupom inválido.';
1005
+ if (coupon?.expiresIn && coupon?.expiresIn.getTime() < new Date().getTime())
1006
+ throw 'Cupom expirado.';
1007
+ const isInShop = coupon.shopAvailability === Shops.ALL || coupon.shopAvailability === this.defaultShop;
1008
+ if (!isInShop)
1009
+ throw 'Cupom inválido para loja.';
1010
+ const isCheckoutType = coupon.checkoutType === CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
1011
+ if (!isCheckoutType)
1012
+ throw 'Cupom inválido. Erro de checkout.';
1013
+ return coupon;
1014
+ }
1015
+ async couponRulesValidation(coupon, checkoutType, checkout, plan) {
1016
+ if (checkoutType == CheckoutTypes.SUBSCRIPTION) {
1017
+ if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
1018
+ throw 'Cupom inválido para sua assinatura.';
1019
+ return coupon;
1020
+ }
1021
+ const validUser = this.coupomUserValidation(coupon, checkout?.user);
1022
+ if (!validUser)
1023
+ throw 'Usuário não elegível.';
1024
+ const couponUseLimits = this.getCouponUseLimits(coupon, checkoutType, checkout.user);
1025
+ if (couponUseLimits.firstOrder) {
1026
+ const ordersUser = await this.getOrdersFromUser(checkout.user.email.toLocaleLowerCase());
1027
+ if (couponUseLimits.firstOrder && ordersUser.length >= 1)
1028
+ throw 'Limite de uso atingido';
1029
+ }
1030
+ if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
1031
+ const orders = await this.getOrdersWithCoupon(coupon);
1032
+ if (!couponUseLimits.unlimited && couponUseLimits.total && orders.length >= couponUseLimits.total)
1033
+ throw 'Limite de uso atingido.';
1034
+ if (couponUseLimits.limitedPerUser) {
1035
+ const ordersWithUser = this.countOrdersWithUser(orders, checkout.user.email);
1036
+ if (ordersWithUser > 0)
1037
+ throw 'Limite de uso por usuário atingido.';
1038
+ }
1039
+ }
1040
+ const hasProductCategories = await this.hasProductCategories(coupon, checkout);
1041
+ if (!hasProductCategories)
1042
+ throw 'Seu carrinho não possui produtos elegíveis para desconto.';
1043
+ const hasMinSubTotal = await this.hasMinSubTotal(coupon, checkout);
1044
+ if (!hasMinSubTotal)
1045
+ throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido`;
1046
+ return coupon;
1047
+ }
1048
+ calcDiscountSubscription(coupon, checkout) {
1049
+ let discount = 0;
1050
+ if (coupon.discount.subscription.type == CouponTypes.ABSOLUTE)
1051
+ discount = coupon.discount.subscription.value;
1052
+ else
1053
+ discount = checkout.subscriptionPlan.recurrencePrice * (coupon.discount.subscription.value / 100);
1054
+ return of(discount);
1055
+ }
1056
+ async calcDiscountShopping(coupon, checkout) {
1057
+ let discount = 0;
1058
+ if (checkout.user.isSubscriber && coupon.discount.subscriber.value) {
1059
+ discount = await this.calcDiscountByType(coupon.discount.subscriber.type, coupon.discount.subscriber.value, coupon.productsCategories, checkout);
1060
+ }
1061
+ else {
1062
+ discount = await this.calcDiscountByType(coupon.discount.non_subscriber.type, coupon.discount.non_subscriber.value, coupon.productsCategories, checkout);
1063
+ }
1064
+ return discount;
1065
+ }
1066
+ async calcDiscountByType(type, value, categories, checkout) {
1067
+ let discount = 0;
1068
+ let lineItensDiscount = await this.getLineItensEligebleForDiscount(categories, checkout);
1069
+ const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user, checkout.shop);
1070
+ if (type == CouponTypes.ABSOLUTE) {
1071
+ discount = value > subTotal ? subTotal : value;
1072
+ }
1073
+ else {
1074
+ discount = subTotal * (value / 100);
1075
+ }
1076
+ return discount;
1077
+ }
1078
+ async hasMinSubTotal(coupon, checkout) {
1079
+ if (!coupon.minSubTotalValue)
1080
+ return true;
1081
+ let lineItensDiscount = await this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
1082
+ const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user, checkout.shop);
1083
+ if (coupon.minSubTotalValue <= subTotal)
1084
+ return true;
1085
+ return false;
1086
+ }
1087
+ async hasProductCategories(coupon, checkout) {
1088
+ if (!coupon.productsCategories || !coupon.productsCategories.length) {
1089
+ return true;
1090
+ }
1091
+ const couponCategories = await this.getCouponCategoriesId(coupon.productsCategories);
1092
+ const hasCategories = checkout.lineItems?.filter((i) => {
1093
+ if (!i.categories || !i.categories?.length)
1094
+ return true;
1095
+ return i.categories.some((c) => couponCategories.some((cat) => cat == c));
1096
+ });
1097
+ return hasCategories.length ? true : false;
1098
+ }
1099
+ coupomUserValidation(coupon, user) {
1100
+ if (!user || coupon.exclusivityType.includes(Exclusivities.ALL_USERS))
1101
+ return true;
1102
+ let userTypes = [];
1103
+ if (coupon.exclusivityType.includes(Exclusivities.COLLABORATORS) &&
1104
+ this.emailIsFromCollaborator(user.email.toLocaleLowerCase()))
1105
+ userTypes.push(Exclusivities.COLLABORATORS);
1106
+ if (coupon.exclusivityType.includes(Exclusivities.SPECIFIC_USER) &&
1107
+ coupon.userExclusiveEmail.includes(user.email.toLocaleLowerCase()))
1108
+ userTypes.push(Exclusivities.SPECIFIC_USER);
1109
+ if (coupon.exclusivityType.includes(Exclusivities.ACTIVE_SUBSCRIBER) &&
1110
+ user.isSubscriber &&
1111
+ user.subscriptionPlan != '')
1112
+ userTypes.push(Exclusivities.ACTIVE_SUBSCRIBER);
1113
+ if (user.isSubscriber &&
1114
+ user.subscriptionPlan == '' &&
1115
+ coupon.exclusivityType.includes(Exclusivities.INACTIVE_SUBSCRIBER))
1116
+ userTypes.push(Exclusivities.INACTIVE_SUBSCRIBER);
1117
+ if (coupon.exclusivityType.includes(Exclusivities.NON_SUBSCRIBER) && !user.isSubscriber)
1118
+ userTypes.push(Exclusivities.NON_SUBSCRIBER);
1119
+ return coupon.exclusivityType.some((r) => userTypes.includes(r));
1120
+ }
1121
+ async getCouponCategoriesId(productsCategories) {
1122
+ const couponCategories = [];
1123
+ for (let index = 0; index < productsCategories.length; index++) {
1124
+ const category = await this.categoryRepository.get({
1125
+ id: productsCategories[index],
1126
+ });
1127
+ if (category) {
1128
+ const children = await this.categoryRepository.getChildren(parseInt(productsCategories[index]));
1129
+ couponCategories.push(category.id, ...children.map((c) => c.id.toString()));
1130
+ }
1131
+ }
1132
+ return [...new Set(couponCategories)];
1133
+ }
1134
+ async getLineItensEligebleForDiscount(productsCategories, checkout) {
1135
+ let lineItensDiscount = [];
1136
+ const couponCategories = await this.getCouponCategoriesId(productsCategories);
1137
+ if (productsCategories && productsCategories.length) {
1138
+ lineItensDiscount = checkout.lineItems?.filter((i) => {
1139
+ if (i.categories?.length) {
1140
+ return i.categories.some((c) => couponCategories.some((cat) => cat == c));
1141
+ }
1142
+ return true;
1143
+ });
1144
+ }
1145
+ else {
1146
+ lineItensDiscount = checkout.lineItems;
1147
+ }
1148
+ return lineItensDiscount;
1149
+ }
1150
+ calcCheckoutSubtotal(lineItens, user, shop) {
1151
+ return (lineItens?.reduce((acc, curr) => user?.isSubscriber && curr.price.subscriberPrice
1152
+ ? acc + curr.price?.subscriberPrice * curr.quantity
1153
+ : acc + curr.pricePaid * curr.quantity, 0) || 0);
1154
+ }
1155
+ async getOrdersWithCoupon(coupon) {
1156
+ return await this.orderRepository
1157
+ .find({
1158
+ filters: {
1159
+ coupon: { id: coupon.id },
1160
+ payment: { status: 'paid' },
1161
+ },
1162
+ })
1163
+ .then((result) => result.data);
1164
+ }
1165
+ async getOrdersFromUser(email) {
1166
+ return await this.orderRepository
1167
+ .find({
1168
+ filters: {
1169
+ user: { email: { operator: Where.EQUALS, value: email } },
1170
+ payment: { status: 'paid' },
1171
+ },
1172
+ })
1173
+ .then((result) => result.data);
1174
+ }
1175
+ countOrdersWithUser(orders, email) {
1176
+ return orders.filter((o) => o.user.email == email).length;
1177
+ }
1178
+ getCouponUseLimits(coupon, checkoutType, user) {
1179
+ let couponUseLimits;
1180
+ if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
1181
+ couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
1182
+ }
1183
+ else {
1184
+ couponUseLimits = coupon.useLimits.subscription;
1185
+ }
1186
+ return couponUseLimits;
1187
+ }
1188
+ }
1189
+ CouponService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, deps: [{ token: 'CouponRepository' }, { token: DEFAULT_SHOP }, { token: 'OrderRepository' }, { token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1190
+ CouponService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, providedIn: 'root' });
1191
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, decorators: [{
1192
+ type: Injectable,
1193
+ args: [{
1194
+ providedIn: 'root',
1195
+ }]
1196
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1197
+ type: Inject,
1198
+ args: ['CouponRepository']
1199
+ }] }, { type: i1$2.Shops, decorators: [{
1200
+ type: Inject,
1201
+ args: [DEFAULT_SHOP]
1202
+ }] }, { type: undefined, decorators: [{
1203
+ type: Inject,
1204
+ args: ['OrderRepository']
1205
+ }] }, { type: undefined, decorators: [{
1206
+ type: Inject,
1207
+ args: ['CategoryRepository']
1208
+ }] }]; } });
1209
+
1210
+ class CheckoutService {
1211
+ constructor(couponService, checkoutRepository, userRepository, defaultShop, dataPersistence) {
1212
+ this.couponService = couponService;
1213
+ this.checkoutRepository = checkoutRepository;
1214
+ this.userRepository = userRepository;
1215
+ this.defaultShop = defaultShop;
1216
+ this.dataPersistence = dataPersistence;
1217
+ }
1218
+ getCheckout(checkoutData) {
1219
+ return this.dataPersistence
1220
+ .get('checkoutId')
1221
+ .pipe(concatMap((id) => (!isNil(id) ? this.checkoutRepository.get({ id }) : this.createCheckout(checkoutData))));
1222
+ }
1223
+ getUserByCheckout(checkoutId) {
1224
+ 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'))));
1225
+ }
1226
+ updateCheckoutLineItems(checkout) {
1227
+ return from(this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, lineItems: checkout.lineItems })));
1228
+ }
1229
+ updateCheckoutUser(checkout) {
1230
+ return from(this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, user: checkout.user })));
1231
+ }
1232
+ clearCheckoutFromSession() {
1233
+ return this.dataPersistence.remove('checkoutId');
1234
+ }
1235
+ calcDiscount(coupon) {
1236
+ return this.getCheckout().pipe(concatMap(async (checkout) => await this.couponService.calcDiscountShopping(coupon, checkout)));
1237
+ }
1238
+ checkCoupon(nickname, checkoutType) {
1239
+ return this.getCheckout().pipe(concatMap((checkout) => this.couponService.checkCoupon(nickname, CheckoutTypes.ECOMMERCE, checkout, null).pipe()));
1240
+ }
1241
+ async createCheckout(checkoutData) {
1242
+ const checkout = await this.checkoutRepository.create({
1243
+ createdAt: new Date(),
1244
+ ...Checkout.toInstance(pick(checkoutData, ['user', 'shop'])).toPlain(),
1245
+ shop: checkoutData?.shop || this.defaultShop,
1246
+ });
1247
+ await this.dataPersistence.set('checkoutId', checkout.id).toPromise();
1248
+ return checkout;
1249
+ }
1250
+ }
1251
+ CheckoutService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService, deps: [{ token: CouponService }, { token: 'CheckoutRepository' }, { token: 'UserRepository' }, { token: DEFAULT_SHOP }, { token: PERSISTENCE_PROVIDER }], target: i0.ɵɵFactoryTarget.Injectable });
1252
+ CheckoutService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService });
1253
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService, decorators: [{
1254
+ type: Injectable
1255
+ }], ctorParameters: function () { return [{ type: CouponService }, { type: undefined, decorators: [{
1248
1256
  type: Inject,
1249
1257
  args: ['CheckoutRepository']
1250
1258
  }] }, { type: undefined, decorators: [{
1251
1259
  type: Inject,
1252
1260
  args: ['UserRepository']
1253
- }] }, { type: i1$3.Shops, decorators: [{
1261
+ }] }, { type: i1$2.Shops, decorators: [{
1254
1262
  type: Inject,
1255
1263
  args: [DEFAULT_SHOP]
1256
1264
  }] }, { type: undefined, decorators: [{
1257
1265
  type: Inject,
1258
1266
  args: [PERSISTENCE_PROVIDER]
1259
- }] }, { type: undefined, decorators: [{
1260
- type: Inject,
1261
- args: [FIREBASE_OPTIONS]
1262
- }] }, { type: i1$2.HttpClient }] });
1267
+ }] }]; } });
1263
1268
 
1264
1269
  class CartService {
1265
- constructor(authService, checkoutService, defaultShop, firebaseOptions, http) {
1270
+ constructor(authService, checkoutService, defaultShop, productRepository, categoryRepository, variantRepository, buy2WinRepository) {
1266
1271
  this.authService = authService;
1267
1272
  this.checkoutService = checkoutService;
1268
1273
  this.defaultShop = defaultShop;
1269
- this.firebaseOptions = firebaseOptions;
1270
- this.http = http;
1274
+ this.productRepository = productRepository;
1275
+ this.categoryRepository = categoryRepository;
1276
+ this.variantRepository = variantRepository;
1277
+ this.buy2WinRepository = buy2WinRepository;
1271
1278
  this.cartSubject = new Subject();
1272
- this.checkoutUrl = null;
1279
+ this.updateLineItemInCart = (lineItem, quantity, checkout) => (isNil(checkout) ? this.checkoutService.getCheckout() : of(checkout)).pipe(concatMap((checkoutLoaded) => {
1280
+ const items = [];
1281
+ const index = checkoutLoaded.lineItems?.map((checkoutItem) => checkoutItem.id).indexOf(lineItem.id);
1282
+ if (index > -1) {
1283
+ checkoutLoaded.lineItems[index].quantity += quantity;
1284
+ checkoutLoaded.lineItems[index].pricePaid = lineItem.pricePaid;
1285
+ }
1286
+ else
1287
+ checkoutLoaded.lineItems = items.concat(checkoutLoaded.lineItems ? checkoutLoaded.lineItems.concat([lineItem]) : [lineItem]);
1288
+ return this.checkoutService
1289
+ .updateCheckoutLineItems(checkoutLoaded)
1290
+ .pipe(map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)));
1291
+ }));
1273
1292
  this.generateCartObject = (items) => items?.reduce((cart, item) => ({
1274
1293
  ...cart,
1275
1294
  [item.id]: LineItem.toInstance({
@@ -1277,41 +1296,95 @@ class CartService {
1277
1296
  quantity: (cart[item.id]?.quantity || 0) + (item.quantity ? item.quantity : 1),
1278
1297
  }),
1279
1298
  }), {}) || {};
1280
- this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`;
1299
+ this.buildLineItem = async ({ checkout, item, quantity, }) => {
1300
+ const product = await this.getProductData(item.id);
1301
+ item.quantity = item?.quantity || checkout?.lineItems?.find((lineItem) => lineItem.id === item.id)?.quantity || 0;
1302
+ if (this.checkMaxStock(item, quantity || 0))
1303
+ throw new Error('Desculpe! Temos apenas ' + item.stock?.quantity + ' em estoque.');
1304
+ const image = item.image || item.images?.shift();
1305
+ const { id, name, EAN, slug, stock, price, weight, sku, type } = item;
1306
+ const isGift = item.isGift || null;
1307
+ const pricePaid = this.getProductPrice({
1308
+ product: item,
1309
+ shop: checkout.shop || this.defaultShop,
1310
+ isSubscriber: checkout.user?.isSubscriber,
1311
+ });
1312
+ RoundProductPricesHelper.roundProductPrices(item);
1313
+ return {
1314
+ checkout,
1315
+ lineItem: LineItem.toInstance({
1316
+ id,
1317
+ name: name ?? product.name,
1318
+ EAN: EAN ?? product.EAN,
1319
+ brand: product.brand,
1320
+ slug: slug ?? product.slug,
1321
+ sku: sku ?? product.sku,
1322
+ stock,
1323
+ price: this.roundPrice(price),
1324
+ image,
1325
+ weight: weight ?? product.weight,
1326
+ quantity: (item.quantity || 0) + (quantity || 0),
1327
+ pricePaid,
1328
+ categories: product.categories ?? [],
1329
+ isGift: isGift ?? null,
1330
+ costPrice: product.costPrice ?? 0,
1331
+ type,
1332
+ }),
1333
+ };
1334
+ };
1335
+ this.getProductPrice = ({ product, isSubscriber, }) => {
1336
+ const info = product.price;
1337
+ if (product.isGift)
1338
+ return 0;
1339
+ return isSubscriber && info.subscriberPrice > 0
1340
+ ? Number(info.subscriberPrice.toFixed(2))
1341
+ : Number(info.price.toFixed(2));
1342
+ };
1343
+ this.checkMaxStock = (item, quantity) => {
1344
+ const maxStock = item.stock?.quantity || 0;
1345
+ const currentItemAmount = item.quantity || 0;
1346
+ return currentItemAmount + quantity > maxStock;
1347
+ };
1281
1348
  }
1282
1349
  addItem(item, quantity = 1) {
1283
- return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutAddItemToCart`, {
1284
- checkoutId: checkout.id,
1285
- productId: item.id,
1286
- quantity,
1287
- })), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1350
+ return from(this.checkoutService.getCheckout()).pipe(concatMap(async (checkout) => await this.buildLineItem({ checkout, item, quantity: quantity || 1 })), mergeMap(({ checkout, lineItem }) => this.updateLineItemInCart(lineItem, quantity || 1, checkout)), tap((cart) => this.cartSubject.next(cart)));
1288
1351
  }
1289
1352
  decreaseItem(item) {
1290
- return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutDecreaseProductFromCart`, {
1291
- checkoutId: checkout.id,
1292
- productId: item.id,
1293
- quantity: 1,
1294
- })), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1295
- }
1296
- removeItem(item) {
1297
- return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutRemoveProductFromCart`, {
1298
- checkoutId: checkout.id,
1299
- productId: item.id,
1300
- })), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1301
- }
1302
- updateUserCart(user) {
1303
- return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user }))), concatMap((checkout) => {
1304
- return this.http.post(`${this.checkoutUrl}/checkoutUpdateUserCart`, {
1305
- checkoutId: checkout.id,
1306
- });
1307
- }), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => {
1308
- return this.generateCartObject(updatedCheckout.lineItems);
1309
- }), tap((cart) => this.cartSubject.next(cart)));
1353
+ return this.checkoutService.getCheckout().pipe(map((checkout) => {
1354
+ const checkoutItem = checkout.lineItems?.find((lineItem) => lineItem.id === item.id);
1355
+ if (!isNil(checkoutItem))
1356
+ checkoutItem.quantity -= checkoutItem.quantity > 1 ? 1 : 0;
1357
+ return checkout;
1358
+ }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1310
1359
  }
1311
1360
  getCart(checkout) {
1312
1361
  this.buildCartFromCheckout(checkout).subscribe((cart) => this.cartSubject.next(cart));
1313
1362
  return this.cartSubject;
1314
1363
  }
1364
+ /**
1365
+ * @deprecated The method should not be used
1366
+ */
1367
+ getVariantPriceDiscount(item) {
1368
+ return this.authService.getUser().pipe(concatMap((user) => iif(() => user.isSubscriber && !!item.price.subscriberPrice, of(item.price.subscriberPrice), of(item.price.price))), catchError(() => of(item.price.price)));
1369
+ }
1370
+ removeItem(item) {
1371
+ return this.checkoutService.getCheckout().pipe(map((checkout) => {
1372
+ const index = checkout.lineItems.findIndex((lineItem) => lineItem.id === item.id);
1373
+ if (index >= 0)
1374
+ checkout.lineItems.splice(index, 1);
1375
+ return checkout;
1376
+ }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1377
+ }
1378
+ updateUserCart(user) {
1379
+ return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user }))), concatMap(async (checkout) => await this.checkoutService
1380
+ .updateCheckoutLineItems(Checkout.toInstance({
1381
+ ...checkout.toPlain(),
1382
+ lineItems: checkout.lineItems?.length
1383
+ ? await Promise.all(checkout.lineItems?.map(async (item) => (await this.buildLineItem({ checkout, item })).lineItem))
1384
+ : [],
1385
+ }))
1386
+ .toPromise()), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1387
+ }
1315
1388
  clearCart() {
1316
1389
  return this.checkoutService.getCheckout().pipe(map((checkout) => {
1317
1390
  this.checkoutService.clearCheckoutFromSession();
@@ -1321,18 +1394,147 @@ class CartService {
1321
1394
  buildCartFromCheckout(checkoutData) {
1322
1395
  return this.checkoutService.getCheckout(checkoutData).pipe(map((checkout) => checkout.lineItems), concatMap((lineItems) => of(this.generateCartObject(lineItems))));
1323
1396
  }
1324
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CartService, deps: [{ token: AuthService }, { token: CheckoutService }, { token: DEFAULT_SHOP }, { token: FIREBASE_OPTIONS }, { token: i1$2.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable }); }
1325
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CartService }); }
1397
+ roundPrice(productPrice) {
1398
+ const { price, fullPrice, subscriberPrice } = productPrice;
1399
+ return {
1400
+ ...productPrice,
1401
+ price: Number(price.toFixed(2)),
1402
+ fullPrice: Number(fullPrice.toFixed(2)),
1403
+ ...(subscriberPrice && { subscriberPrice: Number(subscriberPrice.toFixed(2)) }),
1404
+ };
1405
+ }
1406
+ async getProductData(productId) {
1407
+ let product;
1408
+ let variant;
1409
+ try {
1410
+ product = await this.productRepository.get({ id: productId });
1411
+ }
1412
+ catch (error) {
1413
+ if (!(error instanceof NotFoundError))
1414
+ throw error;
1415
+ const { data: variants } = await this.variantRepository.find({ filters: { id: productId } });
1416
+ variant = variants.shift();
1417
+ if (!variant)
1418
+ throw error;
1419
+ product = await this.productRepository.get({ id: variant.productId });
1420
+ }
1421
+ return {
1422
+ ...product.toPlain(),
1423
+ ...(variant && { ...variant.toPlain() }),
1424
+ };
1425
+ }
1426
+ getGifts() {
1427
+ return this.checkoutService.getCheckout().pipe(mergeMap(async (checkout) => {
1428
+ const notGiftItems = checkout.lineItems ? checkout.lineItems.filter((item) => !item.isGift) : [];
1429
+ if (!notGiftItems.length)
1430
+ return { ...checkout, lineItems: [] };
1431
+ const cartTotal = notGiftItems.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1432
+ const campaigns = await this.buy2WinRepository
1433
+ .find({
1434
+ filters: {
1435
+ active: { operator: Where.EQUALS, value: true },
1436
+ shop: { operator: Where.EQUALS, value: this.defaultShop },
1437
+ },
1438
+ })
1439
+ .then((data) => data.data);
1440
+ if (!campaigns.length)
1441
+ return { ...checkout, lineItems: notGiftItems };
1442
+ const elegibleCampaigns = [];
1443
+ for (const campaign of campaigns) {
1444
+ const today = new Date().getTime();
1445
+ if (!(campaign.startDate.getTime() <= today) && !(campaign.endDate.getTime() >= today))
1446
+ continue;
1447
+ if (campaign.activeCategory) {
1448
+ const categoriesCampaing = campaign.categories.map((c) => c.id.toString());
1449
+ const categoriesCampaingFullTree = [];
1450
+ for (const id of categoriesCampaing) {
1451
+ const children = await this.categoryRepository.getChildren(parseInt(id));
1452
+ categoriesCampaingFullTree.push(id, ...children.map((c) => c.id.toString()));
1453
+ }
1454
+ const categoriesCampaingTree = [...new Set(categoriesCampaingFullTree)];
1455
+ const filterProductsCategories = checkout.lineItems.filter((l) => {
1456
+ if (!l.categories || !l.categories?.length)
1457
+ return true;
1458
+ return l.categories.some((c) => categoriesCampaingTree.some((cat) => cat == c));
1459
+ });
1460
+ if (filterProductsCategories.length) {
1461
+ const cartTotalCategories = filterProductsCategories.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1462
+ if (cartTotalCategories >= campaign.cartValueMin)
1463
+ elegibleCampaigns.push(campaign);
1464
+ }
1465
+ }
1466
+ else {
1467
+ if (campaign.cartValue && campaign.cartValue > 0) {
1468
+ if (campaign.cartValue <= cartTotal)
1469
+ elegibleCampaigns.push(campaign);
1470
+ }
1471
+ }
1472
+ }
1473
+ if (!elegibleCampaigns.length)
1474
+ return { ...checkout, lineItems: notGiftItems };
1475
+ const campaingnProducts = [];
1476
+ for (const campaign of elegibleCampaigns) {
1477
+ let elegibleProducts = [];
1478
+ for (const product of campaign.products) {
1479
+ const { data: productData } = await this.productRepository.find({ filters: { sku: product } });
1480
+ if (!productData.length)
1481
+ continue;
1482
+ const gift = productData.shift();
1483
+ if (gift.stock.quantity < 1)
1484
+ continue;
1485
+ elegibleProducts.push(gift);
1486
+ }
1487
+ campaingnProducts.push(elegibleProducts);
1488
+ }
1489
+ if (!campaingnProducts.length)
1490
+ return { ...checkout, lineItems: notGiftItems };
1491
+ const gifts = this.giftToLineItems([].concat(...campaingnProducts));
1492
+ return { ...checkout, lineItems: notGiftItems.concat(gifts) };
1493
+ }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1494
+ }
1495
+ giftToLineItems(items) {
1496
+ return items.map((item) => {
1497
+ const { brand, categories, id, name, price, sku, slug, stock, weight, EAN } = item;
1498
+ const image = item?.miniatures?.length ? item.miniatures[0] : item.images[0];
1499
+ return LineItem.toInstance({
1500
+ brand,
1501
+ categories,
1502
+ id: id.toString(),
1503
+ name,
1504
+ price,
1505
+ sku,
1506
+ slug,
1507
+ stock,
1508
+ weight,
1509
+ EAN,
1510
+ image,
1511
+ pricePaid: 0,
1512
+ quantity: 1,
1513
+ isGift: true,
1514
+ });
1515
+ });
1516
+ }
1326
1517
  }
1327
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CartService, decorators: [{
1518
+ CartService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService, deps: [{ token: AuthService }, { token: CheckoutService }, { token: DEFAULT_SHOP }, { token: 'ProductRepository' }, { token: 'CategoryRepository' }, { token: 'VariantRepository' }, { token: 'Buy2WinRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1519
+ CartService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService });
1520
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService, decorators: [{
1328
1521
  type: Injectable
1329
- }], ctorParameters: () => [{ type: AuthService }, { type: CheckoutService }, { type: i1$3.Shops, decorators: [{
1522
+ }], ctorParameters: function () { return [{ type: AuthService }, { type: CheckoutService }, { type: i1$2.Shops, decorators: [{
1330
1523
  type: Inject,
1331
1524
  args: [DEFAULT_SHOP]
1332
1525
  }] }, { type: undefined, decorators: [{
1333
1526
  type: Inject,
1334
- args: [FIREBASE_OPTIONS]
1335
- }] }, { type: i1$2.HttpClient }] });
1527
+ args: ['ProductRepository']
1528
+ }] }, { type: undefined, decorators: [{
1529
+ type: Inject,
1530
+ args: ['CategoryRepository']
1531
+ }] }, { type: undefined, decorators: [{
1532
+ type: Inject,
1533
+ args: ['VariantRepository']
1534
+ }] }, { type: i1$2.Buy2WinFirestoreRepository, decorators: [{
1535
+ type: Inject,
1536
+ args: ['Buy2WinRepository']
1537
+ }] }]; } });
1336
1538
 
1337
1539
  class NewCategoryStructureAdapter {
1338
1540
  constructor(categoryRepository) {
@@ -1364,15 +1566,15 @@ class NewCategoryStructureAdapter {
1364
1566
  category.brandCategory;
1365
1567
  return collectionCategory ? this.categoryRepository.get({ id: category.id }) : category;
1366
1568
  }
1367
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: NewCategoryStructureAdapter, deps: [{ token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable }); }
1368
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: NewCategoryStructureAdapter }); }
1369
1569
  }
1370
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: NewCategoryStructureAdapter, decorators: [{
1570
+ NewCategoryStructureAdapter.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: NewCategoryStructureAdapter, deps: [{ token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1571
+ NewCategoryStructureAdapter.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: NewCategoryStructureAdapter });
1572
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: NewCategoryStructureAdapter, decorators: [{
1371
1573
  type: Injectable
1372
- }], ctorParameters: () => [{ type: undefined, decorators: [{
1574
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1373
1575
  type: Inject,
1374
1576
  args: ['CategoryRepository']
1375
- }] }] });
1577
+ }] }]; } });
1376
1578
 
1377
1579
  class OldCategoryStructureAdapter {
1378
1580
  constructor(categoryRepository) {
@@ -1384,53 +1586,24 @@ class OldCategoryStructureAdapter {
1384
1586
  : await this.categoryRepository.get({ id: category.id }).then((categoryFound) => categoryFound.products);
1385
1587
  return { id: { operator: Where.IN, value: productsIds } };
1386
1588
  }
1387
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: OldCategoryStructureAdapter, deps: [{ token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable }); }
1388
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: OldCategoryStructureAdapter }); }
1389
1589
  }
1390
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: OldCategoryStructureAdapter, decorators: [{
1590
+ OldCategoryStructureAdapter.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OldCategoryStructureAdapter, deps: [{ token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1591
+ OldCategoryStructureAdapter.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OldCategoryStructureAdapter });
1592
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OldCategoryStructureAdapter, decorators: [{
1391
1593
  type: Injectable
1392
- }], ctorParameters: () => [{ type: undefined, decorators: [{
1594
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1393
1595
  type: Inject,
1394
1596
  args: ['CategoryRepository']
1395
- }] }] });
1597
+ }] }]; } });
1396
1598
 
1397
1599
  class CatalogService {
1398
- constructor(productRepository, productStockNotificationRepository, categoryRepository, categoryStructureAdapter, shop, productSearch) {
1600
+ constructor(productRepository, categoryRepository, categoryStructureAdapter, shop, productIndex) {
1399
1601
  this.productRepository = productRepository;
1400
- this.productStockNotificationRepository = productStockNotificationRepository;
1401
1602
  this.categoryRepository = categoryRepository;
1402
1603
  this.categoryStructureAdapter = categoryStructureAdapter;
1403
1604
  this.shop = shop;
1404
- this.productSearch = productSearch;
1605
+ this.productIndex = productIndex;
1405
1606
  this.productsByTerm = {};
1406
- this.brandsList = {};
1407
- this.fields = [
1408
- 'id',
1409
- 'name',
1410
- 'slug',
1411
- 'images',
1412
- 'miniatures',
1413
- 'price',
1414
- 'stock',
1415
- 'published',
1416
- 'CEST',
1417
- 'EAN',
1418
- 'NCM',
1419
- 'brand',
1420
- 'costPrice',
1421
- 'hasVariants',
1422
- 'isKit',
1423
- 'sku',
1424
- 'rate',
1425
- 'tags',
1426
- 'type',
1427
- 'shoppingCount',
1428
- 'gender',
1429
- 'createdAt',
1430
- 'label',
1431
- 'outlet',
1432
- 'group',
1433
- ];
1434
1607
  this.buildFilterQuery = ({ clubDiscount, brands, prices, gender, tags, rate, customOptions, }) => {
1435
1608
  const filters = {};
1436
1609
  if (clubDiscount?.length)
@@ -1441,7 +1614,7 @@ class CatalogService {
1441
1614
  filters.gender = { operator: Where.IN, value: gender };
1442
1615
  if (prices?.min || prices?.max)
1443
1616
  set(filters, prices.subscriberPrice ? 'price.subscriberPrice' : 'price.price', [
1444
- ...(prices.min ? [{ operator: Where.GTE, value: Math.floor(prices.min) }] : []),
1617
+ ...(prices.min ? [{ operator: Where.GTE, value: Math.round(prices.min) }] : []),
1445
1618
  ...(prices.max ? [{ operator: Where.LTE, value: Math.ceil(prices.max) }] : []),
1446
1619
  ]);
1447
1620
  if (rate)
@@ -1483,17 +1656,8 @@ class CatalogService {
1483
1656
  this.hasProfile = (options) => 'profile' in options;
1484
1657
  this.hasTerm = (options) => 'term' in options;
1485
1658
  this.hasCategory = (options) => 'category' in options;
1486
- this.buildIndexBrands = (options) => {
1487
- if (this.hasCategory(options))
1488
- return `category-${options.category.id}`;
1489
- if (this.hasTerm(options))
1490
- return `term-${options.term}`;
1491
- if (this.hasProfile(options))
1492
- return `profile-${options.profile.join(',')}`;
1493
- return '';
1494
- };
1495
1659
  }
1496
- async fetchProducts(options, optionsCache) {
1660
+ async fetchProducts(options) {
1497
1661
  const limits = this.buildLimitQuery(options);
1498
1662
  if (this.hasProfile(options) && options.filters?.customOptions)
1499
1663
  throw new InvalidArgumentError(`It couldn't filled customOptions when profile is given`);
@@ -1501,45 +1665,35 @@ class CatalogService {
1501
1665
  throw new InvalidArgumentError(`It couldn't filled tags when profile is given`);
1502
1666
  if (this.hasTerm(options) && options.filters?.customOptions)
1503
1667
  throw new InvalidArgumentError(`It couldn't filled customOptions when term is given`);
1504
- return await this.findCatalog(options, limits, optionsCache).then(async ({ data, count: total, maximum, minimal, distinct }) => {
1505
- await this.setBrandsList(options, distinct?.brand);
1506
- return {
1507
- products: { data: data.map((product) => RoundProductPricesHelper.roundProductPrices(product)), total },
1508
- pages: Math.ceil(total / limits.limit),
1509
- prices: {
1510
- price: { min: +minimal?.price?.price?.toFixed(2), max: +maximum?.price?.price?.toFixed(2) },
1511
- subscriberPrice: {
1512
- min: +minimal?.price?.subscriberPrice?.toFixed(2),
1513
- max: +maximum?.price?.subscriberPrice?.toFixed(2),
1514
- },
1668
+ return await this.findCatalog(options, limits).then(({ data, count: total, maximum, minimal, distinct }) => ({
1669
+ products: { data: data.map((product) => RoundProductPricesHelper.roundProductPrices(product)), total },
1670
+ pages: Math.ceil(total / limits.limit),
1671
+ prices: {
1672
+ price: { min: +minimal?.price?.price?.toFixed(2), max: +maximum?.price?.price?.toFixed(2) },
1673
+ subscriberPrice: {
1674
+ min: +minimal?.price?.subscriberPrice?.toFixed(2),
1675
+ max: +maximum?.price?.subscriberPrice?.toFixed(2),
1515
1676
  },
1516
- brands: this.brandsList[this.buildIndexBrands(options)],
1517
- };
1518
- });
1519
- }
1520
- async addCustomerToStockNotification(shop, productId, name, email) {
1521
- return this.productStockNotificationRepository.addCustomerEmail(shop, productId, name, email);
1677
+ },
1678
+ brands: distinct?.brand,
1679
+ }));
1522
1680
  }
1523
- async findCatalog(options, limits, optionsCache) {
1681
+ async findCatalog(options, limits) {
1524
1682
  if (this.hasTerm(options) && options.sort === 'most-relevant') {
1525
- const productsIds = await this.findCatalogIdsBySearch(options.term);
1526
- return this.findCatalogAndSortByMostRevelantByTerm(productsIds, options, limits);
1683
+ const productsIds = await this.findCatalogIdsByElasticSearch(options.term);
1684
+ return this.findCatalogAndSortByMostRevelant(productsIds, options, limits);
1527
1685
  }
1528
1686
  if (this.hasCategory(options) && options.sort === 'most-relevant') {
1529
- const mostRelevant = options.category.isWishlist ? [] : options.category.getMostRelevantByShop(this.shop);
1530
1687
  const productsIds = await this.productRepository
1531
- .findCatalog({
1532
- fields: ['id'],
1688
+ .find({
1533
1689
  filters: {
1534
1690
  ...(await this.buildMainFilter(options)),
1535
- ...this.buildFilterQuery(options?.filters || {}),
1536
1691
  },
1537
- }, undefined, optionsCache)
1692
+ })
1538
1693
  .then((products) => products.data.map((product) => product.id));
1539
- return this.findCatalogAndSortByMostRevelant(mostRelevant, productsIds, options, limits, optionsCache);
1694
+ return this.findCatalogAndSortByMostRevelant(productsIds, options, limits);
1540
1695
  }
1541
1696
  const repoParams = {
1542
- fields: this.fields,
1543
1697
  filters: {
1544
1698
  ...(await this.buildMainFilter(options)),
1545
1699
  ...this.buildFilterQuery(options?.filters || {}),
@@ -1549,14 +1703,12 @@ class CatalogService {
1549
1703
  options: {
1550
1704
  minimal: ['price'],
1551
1705
  maximum: ['price'],
1552
- ...(!this.brandsList[this.buildIndexBrands(options)] && isEmpty(options.filters?.brands)
1553
- ? { distinct: ['brand'] }
1554
- : {}),
1706
+ ...(!this.hasCategory(options) ? { distinct: ['brand'] } : {}),
1555
1707
  },
1556
1708
  };
1557
1709
  if (['biggest-price', 'lowest-price', 'biggest-discount', 'best-rating'].includes(options.sort))
1558
- return this.productRepository.findCatalog(repoParams, undefined, optionsCache);
1559
- return this.productRepository.findCatalog(repoParams, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female', optionsCache);
1710
+ return this.productRepository.findCatalog(repoParams);
1711
+ return this.productRepository.findCatalog(repoParams, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female');
1560
1712
  }
1561
1713
  async buildMainFilter({ category, profile, term, }) {
1562
1714
  if (category)
@@ -1564,73 +1716,27 @@ class CatalogService {
1564
1716
  if (profile)
1565
1717
  return { tags: { operator: Where.LIKE, value: profile } };
1566
1718
  if (term)
1567
- return this.productSearch
1568
- .search(term, 999, this.shop == Shops.GLAMSHOP ? 'female' : 'male')
1569
- .then((data) => ({ id: { operator: Where.IN, value: data.map((_source) => _source.id) } }));
1570
- }
1571
- async findCatalogAndSortByMostRevelant(mostRelevants, productIds, options, limits, optionsCache) {
1572
- const brandsList = this.brandsList[this.buildIndexBrands(options)];
1573
- const mostRelevantProductsIds = [...new Set(mostRelevants.concat(productIds))];
1574
- const totalResult = await this.productRepository.findCatalog({
1575
- fields: this.fields,
1576
- filters: {
1577
- id: { operator: Where.IN, value: mostRelevantProductsIds },
1578
- ...this.buildFilterQuery(options?.filters || {}),
1579
- },
1580
- orderBy: this.buildSortQuery('best-sellers'),
1581
- options: {
1582
- minimal: ['price'],
1583
- maximum: ['price'],
1584
- ...(!brandsList && isEmpty(options.filters?.brands) ? { distinct: ['brand'] } : {}),
1585
- },
1586
- }, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female', optionsCache);
1587
- const mostRelevantWithouyStock = totalResult.data.filter((product) => mostRelevants.includes(product.id) && product.stock.quantity <= 0);
1588
- const firstProducts = totalResult.data
1589
- .filter((product) => mostRelevants.includes(product.id) && product.stock.quantity > 0)
1590
- .sort((a, b) => mostRelevants.indexOf(a.id) - mostRelevants.indexOf(b.id));
1591
- const lastProducts = totalResult.data
1592
- .filter((product) => !mostRelevants.includes(product.id))
1593
- .concat(mostRelevantWithouyStock);
1594
- const categoryMostRelevants = firstProducts.concat(lastProducts);
1595
- const resultFinal = categoryMostRelevants.slice(limits.offset, limits.offset + limits.limit);
1596
- await this.setBrandsList(options, totalResult.distinct?.brand);
1597
- return {
1598
- data: resultFinal,
1599
- count: totalResult.count,
1600
- maximum: totalResult.maximum,
1601
- minimal: totalResult.minimal,
1602
- distinct: {
1603
- ...totalResult.distinct,
1604
- brand: this.brandsList[this.buildIndexBrands(options)],
1605
- },
1606
- };
1719
+ return this.productIndex
1720
+ .search(term, 999, this.shop)
1721
+ .then((data) => ({ id: { operator: Where.IN, value: data.hits.map(({ _source }) => _source.id) } }));
1607
1722
  }
1608
- async findCatalogAndSortByMostRevelantByTerm(productIds, options, limits) {
1609
- const brandsList = this.brandsList[this.buildIndexBrands(options)];
1723
+ async findCatalogAndSortByMostRevelant(productIds, options, limits) {
1610
1724
  const totalResult = await this.productRepository.findCatalog({
1611
- fields: ['id', 'stock', 'gender'],
1725
+ fields: ['id', 'stock'],
1612
1726
  filters: {
1613
1727
  id: { operator: Where.IN, value: productIds },
1614
- published: { operator: Where.EQUALS, value: true },
1615
1728
  ...this.buildFilterQuery(options?.filters || {}),
1616
1729
  },
1617
1730
  options: {
1618
1731
  minimal: ['price'],
1619
1732
  maximum: ['price'],
1620
- ...(!brandsList && isEmpty(options.filters?.brands) ? { distinct: ['brand'] } : {}),
1733
+ distinct: ['brand'],
1621
1734
  },
1622
1735
  }, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female');
1623
- const defaultGender = options?.filters?.gender
1624
- ? options?.filters?.gender.at(0)
1625
- : this.shop === Shops.GLAMSHOP
1626
- ? 'female'
1627
- : 'male';
1628
1736
  const stockData = totalResult.data.filter((product) => product.stock.quantity > 0);
1629
1737
  const stockOut = totalResult.data.filter((product) => product.stock.quantity <= 0);
1630
- const productIdsStockGender = productIds.filter((product) => stockData.some((result) => result.id === product && (result.gender?.includes(defaultGender) || result.gender?.includes('unisex'))));
1631
- const productIdsStockNotGender = productIds.filter((product) => stockData.some((result) => result.id === product && !result.gender?.includes(defaultGender) && !result.gender?.includes('unisex')));
1632
- const productIdsStock = productIdsStockGender.concat(productIdsStockNotGender);
1633
- const productIdsStockOut = productIds.filter((product) => stockOut.some((result) => result.id === product));
1738
+ const productIdsStock = productIds.filter((product) => stockData.some((result) => result.id == product));
1739
+ const productIdsStockOut = productIds.filter((product) => stockOut.some((result) => result.id == product));
1634
1740
  const limitedProductId = productIdsStock
1635
1741
  .concat(productIdsStockOut)
1636
1742
  .slice(limits.offset, limits.offset + limits.limit);
@@ -1639,592 +1745,216 @@ class CatalogService {
1639
1745
  filters: {
1640
1746
  id: { operator: Where.IN, value: orderedId },
1641
1747
  },
1642
- fields: this.fields,
1643
1748
  });
1644
- await this.setBrandsList(options, totalResult.distinct?.brand);
1645
1749
  return {
1646
1750
  data: limitedProductId.map((id) => productResult.data.find((product) => product.id === id)).filter(Boolean),
1647
1751
  count: totalResult.count,
1648
1752
  maximum: totalResult.maximum,
1649
1753
  minimal: totalResult.minimal,
1650
- distinct: {
1651
- ...totalResult.distinct,
1652
- brand: this.brandsList[this.buildIndexBrands(options)],
1653
- },
1754
+ distinct: totalResult.distinct,
1654
1755
  };
1655
1756
  }
1656
- async findCatalogIdsBySearch(term, preview = false) {
1757
+ async findCatalogIdsByElasticSearch(term) {
1657
1758
  if (this.productsByTerm[term])
1658
1759
  return this.productsByTerm[term];
1659
- return (this.productsByTerm[term] = await this.productSearch
1660
- .search(term, 999, this.shop == Shops.GLAMSHOP ? 'female' : 'male')
1661
- .then((products) => [...new Set(products.map((product) => product.id))]));
1662
- }
1663
- async fetchBrandsOnly(options, productIds = []) {
1664
- return this.productRepository
1665
- .findCatalog({
1666
- fields: ['id'],
1667
- filters: {
1668
- ...(!isEmpty(productIds) ? { id: { operator: Where.IN, value: productIds } } : {}),
1669
- published: { operator: Where.EQUALS, value: true },
1670
- ...this.buildFilterQuery(options?.filters || {}),
1671
- },
1672
- options: {
1673
- distinct: ['brand'],
1674
- },
1675
- }, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female')
1676
- .then((result) => {
1677
- return result.distinct.brand;
1678
- });
1679
- }
1680
- async setBrandsList(options, brands) {
1681
- const filterBrands = options.filters?.brands;
1682
- if (isEmpty(brands))
1683
- delete options.filters?.brands;
1684
- this.brandsList[this.buildIndexBrands(options)] =
1685
- this.brandsList[this.buildIndexBrands(options)] || brands || (await this.fetchBrandsOnly(options));
1686
- this.brandsList[this.buildIndexBrands(options)] = this.brandsList[this.buildIndexBrands(options)].filter(Boolean);
1687
- options.filters = {
1688
- ...options.filters,
1689
- brands: filterBrands,
1690
- };
1691
- }
1692
- 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 }); }
1693
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CatalogService }); }
1694
- }
1695
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CatalogService, decorators: [{
1696
- type: Injectable
1697
- }], ctorParameters: () => [{ type: undefined, decorators: [{
1698
- type: Inject,
1699
- args: ['ProductRepository']
1700
- }] }, { type: undefined, decorators: [{
1701
- type: Inject,
1702
- args: ['ProductStockNotificationRepository']
1703
- }] }, { type: undefined, decorators: [{
1704
- type: Inject,
1705
- args: ['CategoryRepository']
1706
- }] }, { type: undefined, decorators: [{
1707
- type: Inject,
1708
- args: [CATEGORY_STRUCTURE]
1709
- }] }, { type: i1$3.Shops, decorators: [{
1710
- type: Inject,
1711
- args: [DEFAULT_SHOP]
1712
- }] }, { type: undefined, decorators: [{
1713
- type: Inject,
1714
- args: ['ProductSearch']
1715
- }] }] });
1716
-
1717
- class CategoryService {
1718
- constructor(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop) {
1719
- this.productRepository = productRepository;
1720
- this.categoryRepository = categoryRepository;
1721
- this.categoryFilterRepository = categoryFilterRepository;
1722
- this.categoryStructureAdapter = categoryStructureAdapter;
1723
- this.shop = shop;
1724
- }
1725
- async fetchBrands(category, options, optionsCache) {
1726
- const brands = await this.productRepository
1727
- .findCatalog({
1728
- filters: await this.categoryStructureAdapter.buildProductFilterByCategory(category),
1729
- fields: ['brand'],
1730
- }, options?.mainGender ? options?.mainGender : this.shop === Shops.MENSMARKET ? 'male' : 'female', optionsCache)
1731
- .then(({ data }) => Object.keys(data.map((product) => product.brand).reduce((brands, brand) => ({ ...brands, [brand]: true }), {})));
1732
- return this.categoryRepository
1733
- .find({ filters: { brandCategory: true, shop: options?.shop || this.shop }, orderBy: { name: 'asc' } }, optionsCache)
1734
- .then(({ data }) => data.filter((category) => brands.includes(category.conditions.brand)));
1735
- }
1736
- async fetchFilterOptions(category, optionsCache) {
1737
- return await this.categoryFilterRepository
1738
- .find({ filters: { categoryId: +category.id } }, optionsCache)
1739
- .then(({ data }) => data.map((categoryFilter) => categoryFilter.filter));
1740
- }
1741
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CategoryService, deps: [{ token: 'ProductRepository' }, { token: 'CategoryRepository' }, { token: 'CategoryFilterRepository' }, { token: CATEGORY_STRUCTURE }, { token: DEFAULT_SHOP }], target: i0.ɵɵFactoryTarget.Injectable }); }
1742
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CategoryService }); }
1743
- }
1744
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CategoryService, decorators: [{
1745
- type: Injectable
1746
- }], ctorParameters: () => [{ type: undefined, decorators: [{
1747
- type: Inject,
1748
- args: ['ProductRepository']
1749
- }] }, { type: undefined, decorators: [{
1750
- type: Inject,
1751
- args: ['CategoryRepository']
1752
- }] }, { type: undefined, decorators: [{
1753
- type: Inject,
1754
- args: ['CategoryFilterRepository']
1755
- }] }, { type: undefined, decorators: [{
1756
- type: Inject,
1757
- args: [CATEGORY_STRUCTURE]
1758
- }] }, { type: i1$3.Shops, decorators: [{
1759
- type: Inject,
1760
- args: [DEFAULT_SHOP]
1761
- }] }] });
1762
-
1763
- var ProductSorts;
1764
- (function (ProductSorts) {
1765
- ProductSorts["MOST_RELEVANT"] = "most-relevant";
1766
- ProductSorts["BEST_SELLER"] = "best-sellers";
1767
- ProductSorts["BIGGEST_PRICE"] = "biggest-price";
1768
- ProductSorts["LOWEST_PRICE"] = "lowest-price";
1769
- ProductSorts["BIGGEST_DISCOUNT"] = "biggest-discount";
1770
- ProductSorts["BEST_RATING"] = "best-rating";
1771
- ProductSorts["NEWS"] = "news";
1772
- })(ProductSorts || (ProductSorts = {}));
1773
-
1774
- class CategoryWithTree extends Category {
1775
- }
1776
- __decorate([
1777
- Type(() => CategoryWithTree),
1778
- __metadata("design:type", Array)
1779
- ], CategoryWithTree.prototype, "children", void 0);
1780
-
1781
- class WishlistService {
1782
- constructor(wishlistRepository, shop, productRepository, categoryFilterRepository, categoryRepository, productStockNotificationRepository, productSearch, logRepository) {
1783
- this.wishlistRepository = wishlistRepository;
1784
- this.shop = shop;
1785
- this.productRepository = productRepository;
1786
- this.productSearch = productSearch;
1787
- this.logRepository = logRepository;
1788
- const categoryStructureAdapter = new NewCategoryStructureAdapter(wishlistRepository);
1789
- this.catalogService = new CatalogService(productRepository, productStockNotificationRepository, categoryRepository, categoryStructureAdapter, shop, productSearch);
1790
- this.categoryService = new CategoryService(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop);
1791
- }
1792
- getCatalogService() {
1793
- return this.catalogService;
1794
- }
1795
- getCategoryService() {
1796
- return this.categoryService;
1797
- }
1798
- async create({ personId, title, description, published, userFullName, userPhoto, theme, bannerUrl, personType, personIsSubscriber, }) {
1799
- const data = {
1800
- slug: '',
1801
- name: title,
1802
- description,
1803
- metadatas: [
1804
- {
1805
- shop: this.shop,
1806
- title: `${userFullName} - ${title}`,
1807
- description: `${userFullName} - ${description}`,
1808
- },
1809
- ],
1810
- shop: this.shop,
1811
- shops: [this.shop],
1812
- personId,
1813
- personName: userFullName,
1814
- personPhoto: userPhoto,
1815
- brandCategory: false,
1816
- published,
1817
- theme,
1818
- bannerUrl,
1819
- personType: personType ?? PersonTypes.NONE,
1820
- personIsSubscriber: personIsSubscriber ?? false,
1821
- };
1822
- const hasWishlist = await this.wishlistRepository
1823
- .find({
1824
- filters: {
1825
- personId,
1826
- },
1827
- options: {
1828
- enableCount: false,
1829
- },
1830
- orderBy: {
1831
- id: 'asc',
1832
- },
1833
- })
1834
- .then((res) => res.data);
1835
- await this.createWishlistLog(WishlistLogType.CREATE, data);
1836
- if (hasWishlist.length)
1837
- return hasWishlist.at(0);
1838
- const newWishlist = await this.wishlistRepository.create(data);
1839
- await this.wishlistRepository.update({ id: newWishlist.id, slug: newWishlist.id });
1840
- return Wishlist.toInstance({ ...newWishlist.toPlain(), slug: newWishlist.id });
1841
- }
1842
- async update({ id, title, description, published, userFullName, userPhoto, theme, bannerUrl, personType, personIsSubscriber, }) {
1843
- const data = {
1844
- id,
1845
- name: title,
1846
- description,
1847
- published,
1848
- metadatas: [
1849
- {
1850
- shop: this.shop,
1851
- title: `${userFullName} - ${title}`,
1852
- description: `${userFullName} - ${description}`,
1853
- },
1854
- ],
1855
- personName: userFullName,
1856
- personPhoto: userPhoto,
1857
- theme,
1858
- bannerUrl,
1859
- personType: personType ?? PersonTypes.NONE,
1860
- personIsSubscriber: personIsSubscriber ?? false,
1861
- };
1862
- await this.createWishlistLog(WishlistLogType.UPDATE, data);
1863
- return this.wishlistRepository.update(data);
1864
- }
1865
- async delete(wishlistId) {
1866
- const wishlist = await this.findById(wishlistId);
1867
- await this.createWishlistLog(WishlistLogType.DELETE, wishlist);
1868
- return this.wishlistRepository.delete({ id: wishlistId });
1869
- }
1870
- getWishlistBySlug(slug) {
1871
- const [id] = slug.split('-');
1872
- if (+id)
1873
- return this.wishlistRepository.get({ id });
1874
- return this.wishlistRepository.getWishlistBySlug(slug);
1875
- }
1876
- getWishlistsByPerson(personId) {
1877
- return this.wishlistRepository.getWishlistByPerson(personId);
1878
- }
1879
- async addProduct(wishlistId, productId) {
1880
- const wishlist = await this.wishlistRepository.get({ id: wishlistId });
1881
- const hasProduct = wishlist.products.some((p) => p == productId);
1882
- const wishlistData = await this.findById(wishlistId);
1883
- const productData = await this.findProductById(productId);
1884
- await this.createWishlistLog(WishlistLogType.ADD_PRODUCT, wishlistData, productData);
1885
- if (!hasProduct) {
1886
- wishlist.products = [...wishlist.products, productId];
1887
- await this.wishlistRepository.addProduct(wishlistId, productId);
1888
- }
1889
- return wishlist;
1890
- }
1891
- async removeProduct(wishlistId, productId) {
1892
- const wishlist = await this.wishlistRepository.get({ id: wishlistId });
1893
- const productIndex = wishlist.products.findIndex((p) => p == productId);
1894
- if (productIndex != -1) {
1895
- wishlist.products.splice(productIndex, 1);
1896
- const wishlistData = await this.findById(wishlistId);
1897
- const productData = await this.findProductById(productId);
1898
- await this.createWishlistLog(WishlistLogType.REMOVE_PRODUCT, wishlistData, productData);
1899
- await this.wishlistRepository.removeProduct(wishlistId, productId);
1900
- }
1901
- return wishlist;
1902
- }
1903
- async findById(id) {
1904
- return this.wishlistRepository
1905
- .find({
1906
- fields: ['id', 'name', 'description', 'personId', 'personIsSubscriber', 'personType', 'personName'],
1907
- filters: {
1908
- id,
1909
- },
1910
- })
1911
- .then((res) => res.data.at(0));
1912
- }
1913
- async findProductById(id) {
1914
- return this.productRepository
1915
- .find({
1916
- fields: ['id', 'sku', 'EAN', 'name', 'brand'],
1917
- filters: {
1918
- id,
1919
- },
1920
- })
1921
- .then((res) => res.data.at(0));
1922
- }
1923
- async createWishlistLog(type, wishlist, product) {
1924
- switch (type) {
1925
- case WishlistLogType.CREATE:
1926
- case WishlistLogType.UPDATE:
1927
- case WishlistLogType.DELETE:
1928
- await this.logRepository.create({
1929
- collection: 'wishlist',
1930
- date: new Date(),
1931
- operation: WishlistLogType.CREATE ? 'CREATE' : WishlistLogType.UPDATE ? 'UPDATE' : 'DELETE',
1932
- documentId: wishlist.id,
1933
- document: {
1934
- id: wishlist.id,
1935
- shop: this.shop,
1936
- name: wishlist.name,
1937
- description: wishlist.description,
1938
- published: wishlist.published,
1939
- type: type,
1940
- personType: wishlist.personType,
1941
- personId: wishlist.personId,
1942
- personName: wishlist.personName,
1943
- personIsSubscriber: wishlist.personIsSubscriber,
1944
- },
1945
- });
1946
- break;
1947
- case WishlistLogType.ADD_PRODUCT:
1948
- case WishlistLogType.REMOVE_PRODUCT:
1949
- await this.logRepository.create({
1950
- collection: 'wishlist',
1951
- date: new Date(),
1952
- operation: 'UPDATE',
1953
- documentId: wishlist.id,
1954
- document: {
1955
- id: wishlist.id,
1956
- shop: this.shop,
1957
- name: wishlist.name,
1958
- description: wishlist.description,
1959
- published: wishlist.published,
1960
- type: type,
1961
- personType: wishlist.personType,
1962
- personId: wishlist.personId,
1963
- personName: wishlist.personName,
1964
- personIsSubscriber: wishlist.personIsSubscriber,
1965
- productId: product.id,
1966
- productEAN: product.EAN,
1967
- productSKU: product.sku,
1968
- productName: product.name,
1969
- productBrand: product.brand,
1970
- },
1971
- });
1972
- break;
1973
- default:
1974
- break;
1975
- }
1760
+ return (this.productsByTerm[term] = await this.productIndex
1761
+ .search(term, 999, this.shop)
1762
+ .then(({ hits: products }) => {
1763
+ const withStock = products.filter(({ _source }) => _source.stock.quantity > 0);
1764
+ const withOutStock = products.filter(({ _source }) => _source.stock.quantity <= 0);
1765
+ const sorted = [...withStock, ...withOutStock];
1766
+ return [...new Set(sorted.map(({ _source }) => _source.id))];
1767
+ }));
1976
1768
  }
1977
- 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 }); }
1978
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: WishlistService }); }
1979
1769
  }
1980
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: WishlistService, decorators: [{
1770
+ CatalogService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService, deps: [{ token: 'ProductRepository' }, { token: 'CategoryRepository' }, { token: CATEGORY_STRUCTURE }, { token: DEFAULT_SHOP }, { token: i1$2.ProductsIndex }], target: i0.ɵɵFactoryTarget.Injectable });
1771
+ CatalogService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService });
1772
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService, decorators: [{
1981
1773
  type: Injectable
1982
- }], ctorParameters: () => [{ type: undefined, decorators: [{
1983
- type: Inject,
1984
- args: ['WishlistRepository']
1985
- }] }, { type: i1$3.Shops, decorators: [{
1986
- type: Inject,
1987
- args: [DEFAULT_SHOP]
1988
- }] }, { type: undefined, decorators: [{
1774
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1989
1775
  type: Inject,
1990
1776
  args: ['ProductRepository']
1991
- }] }, { type: undefined, decorators: [{
1992
- type: Inject,
1993
- args: ['CategoryFilterRepository']
1994
1777
  }] }, { type: undefined, decorators: [{
1995
1778
  type: Inject,
1996
1779
  args: ['CategoryRepository']
1997
- }] }, { type: undefined, decorators: [{
1998
- type: Inject,
1999
- args: ['ProductStockNotificationRepository']
2000
- }] }, { type: undefined, decorators: [{
2001
- type: Inject,
2002
- args: ['ProductSearch']
2003
- }] }, { type: undefined, decorators: [{
2004
- type: Inject,
2005
- args: ['LogRepository']
2006
- }] }] });
2007
-
2008
- class CouponService {
2009
- constructor(couponRepository, defaultShop, orderRepository, categoryRepository) {
2010
- this.couponRepository = couponRepository;
2011
- this.defaultShop = defaultShop;
2012
- this.orderRepository = orderRepository;
2013
- this.categoryRepository = categoryRepository;
2014
- this.emailIsFromCollaborator = (userEmail) => !!userEmail?.match(/@b4a.com.br/g);
2015
- }
2016
- checkCoupon(nickname, checkoutType, checkout, plan) {
2017
- return from(this.couponRepository
2018
- .find({
2019
- filters: {
2020
- nickname: { operator: Where.EQUALS, value: nickname },
2021
- active: { operator: Where.EQUALS, value: true },
2022
- },
2023
- })
2024
- .then((result) => result.data[0])).pipe(concatMap((coupon) => this.couponValidation(coupon, checkoutType)), concatMap((couponValid) => this.couponRulesValidation(couponValid, checkoutType, checkout, plan)), map((couponValidated) => couponValidated));
2025
- }
2026
- async couponValidation(coupon, checkoutType) {
2027
- if (!coupon)
2028
- throw 'Cupom inválido.';
2029
- if (coupon?.beginAt && coupon?.beginAt.getTime() > new Date().getTime())
2030
- throw 'Cupom inválido.';
2031
- if (coupon?.expiresIn && (coupon?.expiresIn).getTime() < new Date().getTime())
2032
- throw 'Cupom expirado.';
2033
- const isInShop = coupon.shopAvailability === Shops.ALL || coupon.shopAvailability === this.defaultShop;
2034
- if (!isInShop)
2035
- throw 'Cupom inválido para loja.';
2036
- const isCheckoutType = coupon.checkoutType === CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
2037
- if (!isCheckoutType)
2038
- throw 'Cupom inválido. Erro de checkout.';
2039
- return coupon;
2040
- }
2041
- async couponRulesValidation(coupon, checkoutType, checkout, plan) {
2042
- if (checkoutType == CheckoutTypes.SUBSCRIPTION) {
2043
- if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
2044
- throw 'Cupom inválido para sua assinatura.';
2045
- return coupon;
2046
- }
2047
- const validUser = this.coupomUserValidation(coupon, checkout?.user);
2048
- if (!validUser)
2049
- throw 'Usuário não elegível.';
2050
- const couponUseLimits = this.getCouponUseLimits(coupon, checkoutType, checkout.user);
2051
- if (couponUseLimits.firstOrder) {
2052
- const ordersUser = await this.getOrdersFromUser(checkout.user.email.toLocaleLowerCase());
2053
- if (couponUseLimits.firstOrder && ordersUser.length >= 1)
2054
- throw 'Limite de uso atingido';
2055
- }
2056
- if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
2057
- const ordersCoupon = await this.getOrdersWithCoupon(coupon);
2058
- if (!couponUseLimits.unlimited && couponUseLimits.total && ordersCoupon.length >= couponUseLimits.total)
2059
- throw 'Limite de uso atingido.';
2060
- if (couponUseLimits.limitedPerUser) {
2061
- const ordersWithUser = this.countOrdersWithUser(ordersCoupon, checkout.user.email);
2062
- if (ordersWithUser > 0)
2063
- throw 'Limite de uso por usuário atingido.';
2064
- }
2065
- }
2066
- const hasProductCategories = await this.hasProductCategories(coupon, checkout);
2067
- if (!hasProductCategories)
2068
- throw 'Seu carrinho não possui produtos elegíveis para desconto.';
2069
- const hasMinSubTotal = await this.hasMinSubTotal(coupon, checkout);
2070
- if (!hasMinSubTotal) {
2071
- if (coupon.productsCategories?.length) {
2072
- 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.`;
2073
- }
2074
- throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido.`;
2075
- }
2076
- return coupon;
2077
- }
2078
- calcDiscountSubscription(coupon, checkout) {
2079
- let discount = 0;
2080
- if (coupon.discount.subscription.type == CouponTypes.ABSOLUTE)
2081
- discount = coupon.discount.subscription.value;
2082
- else
2083
- discount = checkout.subscriptionPlan.recurrencePrice * (coupon.discount.subscription.value / 100);
2084
- return of(discount);
2085
- }
2086
- async hasMinSubTotal(coupon, checkout) {
2087
- if (!coupon.minSubTotalValue)
2088
- return true;
2089
- const lineItensDiscount = await this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
2090
- const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user);
2091
- if (coupon.minSubTotalValue <= subTotal)
2092
- return true;
2093
- return false;
1780
+ }] }, { type: undefined, decorators: [{
1781
+ type: Inject,
1782
+ args: [CATEGORY_STRUCTURE]
1783
+ }] }, { type: i1$2.Shops, decorators: [{
1784
+ type: Inject,
1785
+ args: [DEFAULT_SHOP]
1786
+ }] }, { type: i1$2.ProductsIndex }]; } });
1787
+
1788
+ class CategoryService {
1789
+ constructor(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop) {
1790
+ this.productRepository = productRepository;
1791
+ this.categoryRepository = categoryRepository;
1792
+ this.categoryFilterRepository = categoryFilterRepository;
1793
+ this.categoryStructureAdapter = categoryStructureAdapter;
1794
+ this.shop = shop;
2094
1795
  }
2095
- async hasProductCategories(coupon, checkout) {
2096
- if (!coupon.productsCategories || !coupon.productsCategories?.length) {
2097
- return true;
2098
- }
2099
- const couponCategories = await this.getCouponCategoriesId(coupon.productsCategories);
2100
- const hasCategories = checkout.lineItems?.filter((item) => {
2101
- if (item.isGift)
2102
- return false;
2103
- if (!item.categories || !item.categories?.length)
2104
- return true;
2105
- return item.categories.some((c) => couponCategories.some((cat) => cat == c));
2106
- });
2107
- return hasCategories.length ? true : false;
1796
+ async fetchBrands(category, options) {
1797
+ const brands = await this.productRepository
1798
+ .findCatalog({
1799
+ filters: await this.categoryStructureAdapter.buildProductFilterByCategory(category),
1800
+ fields: ['brand'],
1801
+ }, options?.mainGender ? options?.mainGender : this.shop === Shops.MENSMARKET ? 'male' : 'female')
1802
+ .then(({ data }) => Object.keys(data.map((product) => product.brand).reduce((brands, brand) => ({ ...brands, [brand]: true }), {})));
1803
+ return this.categoryRepository
1804
+ .find({ filters: { brandCategory: true, shop: options?.shop || this.shop }, orderBy: { name: 'asc' } })
1805
+ .then(({ data }) => data.filter((category) => brands.includes(category.conditions.brand)));
2108
1806
  }
2109
- coupomUserValidation(coupon, user) {
2110
- if (!user || coupon.exclusivityType.includes(Exclusivities.ALL_USERS))
2111
- return true;
2112
- let userTypes = [];
2113
- if (coupon.exclusivityType.includes(Exclusivities.COLLABORATORS) &&
2114
- this.emailIsFromCollaborator(user.email.toLocaleLowerCase()))
2115
- userTypes.push(Exclusivities.COLLABORATORS);
2116
- if (coupon.exclusivityType.includes(Exclusivities.SPECIFIC_USER) &&
2117
- coupon.userExclusiveEmail.includes(user.email.toLocaleLowerCase()))
2118
- userTypes.push(Exclusivities.SPECIFIC_USER);
2119
- if (coupon.exclusivityType.includes(Exclusivities.ACTIVE_SUBSCRIBER) &&
2120
- user.isSubscriber &&
2121
- user.subscriptionPlan != '')
2122
- userTypes.push(Exclusivities.ACTIVE_SUBSCRIBER);
2123
- if (user.isSubscriber &&
2124
- user.subscriptionPlan == '' &&
2125
- coupon.exclusivityType.includes(Exclusivities.INACTIVE_SUBSCRIBER))
2126
- userTypes.push(Exclusivities.INACTIVE_SUBSCRIBER);
2127
- if (coupon.exclusivityType.includes(Exclusivities.NON_SUBSCRIBER) && !user.isSubscriber)
2128
- userTypes.push(Exclusivities.NON_SUBSCRIBER);
2129
- return coupon.exclusivityType.some((r) => userTypes.includes(r));
1807
+ async fetchFilterOptions(category) {
1808
+ return await this.categoryFilterRepository
1809
+ .find({ filters: { categoryId: +category.id } })
1810
+ .then(({ data }) => data.map((categoryFilter) => categoryFilter.filter));
2130
1811
  }
2131
- async getCouponCategoriesId(productsCategories) {
2132
- const couponCategories = [];
2133
- for (let index = 0; index < productsCategories.length; index++) {
2134
- const category = await this.categoryRepository.get({
2135
- id: productsCategories[index],
2136
- });
2137
- if (category) {
2138
- const children = await this.categoryRepository.getChildren(parseInt(productsCategories[index]));
2139
- couponCategories.push(category.id, ...children.map((c) => c.id.toString()));
2140
- }
2141
- }
2142
- return [...new Set(couponCategories)];
1812
+ }
1813
+ CategoryService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CategoryService, deps: [{ token: 'ProductRepository' }, { token: 'CategoryRepository' }, { token: 'CategoryFilterRepository' }, { token: CATEGORY_STRUCTURE }, { token: DEFAULT_SHOP }], target: i0.ɵɵFactoryTarget.Injectable });
1814
+ CategoryService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CategoryService });
1815
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CategoryService, decorators: [{
1816
+ type: Injectable
1817
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1818
+ type: Inject,
1819
+ args: ['ProductRepository']
1820
+ }] }, { type: undefined, decorators: [{
1821
+ type: Inject,
1822
+ args: ['CategoryRepository']
1823
+ }] }, { type: undefined, decorators: [{
1824
+ type: Inject,
1825
+ args: ['CategoryFilterRepository']
1826
+ }] }, { type: undefined, decorators: [{
1827
+ type: Inject,
1828
+ args: [CATEGORY_STRUCTURE]
1829
+ }] }, { type: i1$2.Shops, decorators: [{
1830
+ type: Inject,
1831
+ args: [DEFAULT_SHOP]
1832
+ }] }]; } });
1833
+
1834
+ var ProductSorts;
1835
+ (function (ProductSorts) {
1836
+ ProductSorts["MOST_RELEVANT"] = "most-relevant";
1837
+ ProductSorts["BEST_SELLER"] = "best-sellers";
1838
+ ProductSorts["BIGGEST_PRICE"] = "biggest-price";
1839
+ ProductSorts["LOWEST_PRICE"] = "lowest-price";
1840
+ ProductSorts["BIGGEST_DISCOUNT"] = "biggest-discount";
1841
+ ProductSorts["BEST_RATING"] = "best-rating";
1842
+ ProductSorts["NEWS"] = "news";
1843
+ })(ProductSorts || (ProductSorts = {}));
1844
+
1845
+ class CategoryWithTree extends Category {
1846
+ }
1847
+ __decorate([
1848
+ Type(() => CategoryWithTree),
1849
+ __metadata("design:type", Array)
1850
+ ], CategoryWithTree.prototype, "children", void 0);
1851
+
1852
+ class WishlistService {
1853
+ constructor(wishlistRepository, shop, productRepository, categoryFilterRepository, categoryRepository, productIndex) {
1854
+ this.wishlistRepository = wishlistRepository;
1855
+ this.shop = shop;
1856
+ const categoryStructureAdapter = new NewCategoryStructureAdapter(wishlistRepository);
1857
+ this.catalogService = new CatalogService(productRepository, categoryRepository, categoryStructureAdapter, shop, productIndex);
1858
+ this.categoryService = new CategoryService(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop);
2143
1859
  }
2144
- async getLineItensEligebleForDiscount(productsCategories, checkout) {
2145
- let lineItensDiscount = [];
2146
- const couponCategories = await this.getCouponCategoriesId(productsCategories);
2147
- if (productsCategories && productsCategories.length) {
2148
- lineItensDiscount = checkout.lineItems?.filter((item) => {
2149
- if (item.isGift)
2150
- return false;
2151
- if (item.categories?.length) {
2152
- return item.categories.some((c) => couponCategories.some((cat) => cat == c));
2153
- }
2154
- return true;
2155
- });
2156
- }
2157
- else {
2158
- lineItensDiscount = checkout.lineItems.filter((item) => !item.isGift);
2159
- }
2160
- return lineItensDiscount;
1860
+ getCatalogService() {
1861
+ return this.catalogService;
2161
1862
  }
2162
- calcCheckoutSubtotal(lineItens, user) {
2163
- return (lineItens
2164
- ?.filter((item) => !item.isGift)
2165
- .reduce((acc, curr) => user?.isSubscriber && curr.price.subscriberPrice
2166
- ? acc + curr.price?.subscriberPrice * curr.quantity
2167
- : acc + curr.pricePaid * curr.quantity, 0) || 0);
1863
+ getCategoryService() {
1864
+ return this.categoryService;
2168
1865
  }
2169
- async getOrdersWithCoupon(coupon) {
2170
- return await this.orderRepository
2171
- .find({
2172
- filters: {
2173
- coupon: { id: coupon.id },
2174
- status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1866
+ async create({ personId, title, description, userFullName, userPhoto, theme, bannerUrl, }) {
1867
+ const data = {
1868
+ slug: '',
1869
+ name: title,
1870
+ description,
1871
+ metadata: {
1872
+ title: `${userFullName} - ${title}`,
1873
+ description: `${userFullName} - ${description}`,
2175
1874
  },
2176
- })
2177
- .then((result) => result.data);
1875
+ shop: this.shop,
1876
+ shops: [this.shop],
1877
+ personId,
1878
+ personName: userFullName,
1879
+ personPhoto: userPhoto,
1880
+ brandCategory: false,
1881
+ published: true,
1882
+ theme,
1883
+ bannerUrl,
1884
+ };
1885
+ const newWishlist = await this.wishlistRepository.create(data);
1886
+ await this.wishlistRepository.update({ id: newWishlist.id, slug: newWishlist.id });
1887
+ return Wishlist.toInstance({ ...newWishlist.toPlain(), slug: newWishlist.id });
2178
1888
  }
2179
- async getOrdersFromUser(email) {
2180
- return await this.orderRepository
2181
- .find({
2182
- filters: {
2183
- user: { email: { operator: Where.EQUALS, value: email } },
2184
- status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1889
+ update({ id, title, description, userFullName, userPhoto, theme, bannerUrl, }) {
1890
+ const data = {
1891
+ id,
1892
+ name: title,
1893
+ description,
1894
+ metadata: {
1895
+ title: `${userFullName} - ${title}`,
1896
+ description: `${userFullName} - ${description}`,
2185
1897
  },
2186
- })
2187
- .then((result) => result.data);
1898
+ personName: userFullName,
1899
+ personPhoto: userPhoto,
1900
+ theme,
1901
+ bannerUrl,
1902
+ };
1903
+ return this.wishlistRepository.update(data);
2188
1904
  }
2189
- countOrdersWithUser(orders, email) {
2190
- return orders.filter((o) => o.user.email == email).length;
1905
+ delete(wishlistId) {
1906
+ return this.wishlistRepository.delete({ id: wishlistId });
2191
1907
  }
2192
- getCouponUseLimits(coupon, checkoutType, user) {
2193
- let couponUseLimits;
2194
- if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
2195
- if (coupon.exclusivityType.length === 1 &&
2196
- (coupon.exclusivityType.at(0) === Exclusivities.SPECIFIC_USER ||
2197
- coupon.exclusivityType.at(0) === Exclusivities.COLLABORATORS))
2198
- couponUseLimits = coupon.useLimits.non_subscriber;
2199
- else
2200
- couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
1908
+ getWishlistBySlug(slug) {
1909
+ const [id] = slug.split('-');
1910
+ if (+id)
1911
+ return this.wishlistRepository.get({ id });
1912
+ return this.wishlistRepository.getWishlistBySlug(slug);
1913
+ }
1914
+ getWishlistsByPerson(personId) {
1915
+ return this.wishlistRepository.getWishlistByPerson(personId);
1916
+ }
1917
+ async addProduct(wishlistId, productId) {
1918
+ const wishlist = await this.wishlistRepository.get({ id: wishlistId });
1919
+ const hasProduct = wishlist.products.some((p) => p == productId);
1920
+ if (!hasProduct) {
1921
+ wishlist.products = [...wishlist.products, productId];
1922
+ return this.wishlistRepository.update({ id: wishlistId, products: wishlist.products });
2201
1923
  }
2202
- else {
2203
- couponUseLimits = coupon.useLimits.subscription;
1924
+ return wishlist;
1925
+ }
1926
+ async removeProduct(wishlistId, productId) {
1927
+ const wishlist = await this.wishlistRepository.get({ id: wishlistId });
1928
+ const productIndex = wishlist.products.findIndex((p) => p == productId);
1929
+ if (productIndex != -1) {
1930
+ wishlist.products.splice(productIndex, 1);
1931
+ if (!wishlist.products.length)
1932
+ return this.wishlistRepository.update({ id: wishlistId, products: { action: 'remove' } });
1933
+ return this.wishlistRepository.update({ id: wishlistId, products: wishlist.products });
2204
1934
  }
2205
- return couponUseLimits;
1935
+ return wishlist;
2206
1936
  }
2207
- 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 }); }
2208
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CouponService, providedIn: 'root' }); }
2209
1937
  }
2210
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CouponService, decorators: [{
2211
- type: Injectable,
2212
- args: [{
2213
- providedIn: 'root',
2214
- }]
2215
- }], ctorParameters: () => [{ type: undefined, decorators: [{
1938
+ WishlistService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService, deps: [{ token: 'WishlistRepository' }, { token: DEFAULT_SHOP }, { token: 'ProductRepository' }, { token: 'CategoryFilterRepository' }, { token: 'CategoryRepository' }, { token: i1$2.ProductsIndex }], target: i0.ɵɵFactoryTarget.Injectable });
1939
+ WishlistService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService });
1940
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService, decorators: [{
1941
+ type: Injectable
1942
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
2216
1943
  type: Inject,
2217
- args: ['CouponRepository']
2218
- }] }, { type: i1$3.Shops, decorators: [{
1944
+ args: ['WishlistRepository']
1945
+ }] }, { type: i1$2.Shops, decorators: [{
2219
1946
  type: Inject,
2220
1947
  args: [DEFAULT_SHOP]
2221
1948
  }] }, { type: undefined, decorators: [{
2222
1949
  type: Inject,
2223
- args: ['OrderRepository']
1950
+ args: ['ProductRepository']
1951
+ }] }, { type: undefined, decorators: [{
1952
+ type: Inject,
1953
+ args: ['CategoryFilterRepository']
2224
1954
  }] }, { type: undefined, decorators: [{
2225
1955
  type: Inject,
2226
1956
  args: ['CategoryRepository']
2227
- }] }] });
1957
+ }] }, { type: i1$2.ProductsIndex }]; } });
2228
1958
 
2229
1959
  class CheckoutSubscriptionService {
2230
1960
  constructor(checkoutSubscriptionRepository, dataPersistence, couponService) {
@@ -2256,18 +1986,18 @@ class CheckoutSubscriptionService {
2256
1986
  await this.dataPersistence.set('checkoutSubscriptionId', checkout.id).toPromise();
2257
1987
  return checkout;
2258
1988
  }
2259
- 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 }); }
2260
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutSubscriptionService }); }
2261
1989
  }
2262
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: CheckoutSubscriptionService, decorators: [{
1990
+ CheckoutSubscriptionService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutSubscriptionService, deps: [{ token: 'CheckoutSubscriptionRepository' }, { token: PERSISTENCE_PROVIDER }, { token: CouponService }], target: i0.ɵɵFactoryTarget.Injectable });
1991
+ CheckoutSubscriptionService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutSubscriptionService });
1992
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutSubscriptionService, decorators: [{
2263
1993
  type: Injectable
2264
- }], ctorParameters: () => [{ type: undefined, decorators: [{
1994
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
2265
1995
  type: Inject,
2266
1996
  args: ['CheckoutSubscriptionRepository']
2267
1997
  }] }, { type: undefined, decorators: [{
2268
1998
  type: Inject,
2269
1999
  args: [PERSISTENCE_PROVIDER]
2270
- }] }, { type: CouponService }] });
2000
+ }] }, { type: CouponService }]; } });
2271
2001
 
2272
2002
  class UtilHelper {
2273
2003
  static createSlug(name) {
@@ -2351,10 +2081,10 @@ class HomeShopService {
2351
2081
  return this.getHomeConfiguration().pipe(map((home) => home.minValueForFreeShipping));
2352
2082
  }
2353
2083
  getDiscoverProducts(gender) {
2354
- return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.discoverCategories, this.defaultShop)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
2084
+ return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.discoverCategories, undefined, gender)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
2355
2085
  }
2356
2086
  getFeaturedProducts(gender) {
2357
- return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.featuredCategories, this.defaultShop)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
2087
+ return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.featuredCategories, undefined, gender)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
2358
2088
  }
2359
2089
  getVerticalProducts(gender) {
2360
2090
  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({
@@ -2386,12 +2116,12 @@ class HomeShopService {
2386
2116
  get gender() {
2387
2117
  return this.homeId === 'mens_market' ? 'masculino' : undefined;
2388
2118
  }
2389
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: HomeShopService, deps: [{ token: 'CategoryRepository' }, { token: 'HomeRepository' }, { token: 'ProductRepository' }, { token: DEFAULT_SHOP }], target: i0.ɵɵFactoryTarget.Injectable }); }
2390
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: HomeShopService }); }
2391
2119
  }
2392
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: HomeShopService, decorators: [{
2120
+ HomeShopService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService, deps: [{ token: 'CategoryRepository' }, { token: 'HomeRepository' }, { token: 'ProductRepository' }, { token: DEFAULT_SHOP }], target: i0.ɵɵFactoryTarget.Injectable });
2121
+ HomeShopService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService });
2122
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService, decorators: [{
2393
2123
  type: Injectable
2394
- }], ctorParameters: () => [{ type: undefined, decorators: [{
2124
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
2395
2125
  type: Inject,
2396
2126
  args: ['CategoryRepository']
2397
2127
  }] }, { type: undefined, decorators: [{
@@ -2400,10 +2130,10 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2400
2130
  }] }, { type: undefined, decorators: [{
2401
2131
  type: Inject,
2402
2132
  args: ['ProductRepository']
2403
- }] }, { type: i1$3.Shops, decorators: [{
2133
+ }] }, { type: i1$2.Shops, decorators: [{
2404
2134
  type: Inject,
2405
2135
  args: [DEFAULT_SHOP]
2406
- }] }] });
2136
+ }] }]; } });
2407
2137
 
2408
2138
  class OrderService {
2409
2139
  constructor(angularFirestore, orderRepository) {
@@ -2417,23 +2147,107 @@ class OrderService {
2417
2147
  .subscribe((doc) => this.orderSubject.next(doc));
2418
2148
  return this.orderSubject;
2419
2149
  }
2420
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: OrderService, deps: [{ token: i1$1.Firestore }, { token: 'OrderRepository' }], target: i0.ɵɵFactoryTarget.Injectable }); }
2421
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: OrderService }); }
2422
2150
  }
2423
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: OrderService, decorators: [{
2151
+ OrderService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService, deps: [{ token: i1$1.Firestore }, { token: 'OrderRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
2152
+ OrderService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService });
2153
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService, decorators: [{
2424
2154
  type: Injectable
2425
- }], ctorParameters: () => [{ type: i1$1.Firestore }, { type: i1$3.OrderFirestoreRepository, decorators: [{
2155
+ }], ctorParameters: function () { return [{ type: i1$1.Firestore }, { type: i1$2.OrderFirestoreRepository, decorators: [{
2426
2156
  type: Inject,
2427
2157
  args: ['OrderRepository']
2428
- }] }] });
2158
+ }] }]; } });
2159
+
2160
+ class ShippingService {
2161
+ constructor(http, apiUrl, homeService) {
2162
+ this.http = http;
2163
+ this.apiUrl = apiUrl;
2164
+ this.homeService = homeService;
2165
+ }
2166
+ getShippingMethods(shop, zip, weightGrams, totalPrice, personId, subscriptionPlan) {
2167
+ return combineLatest([
2168
+ this.homeService.getHomeData(),
2169
+ this.http.get(`${this.apiUrl}open/checkshippingcompany?personId=${personId}&postalCode=${zip}&weightGrams=${weightGrams}`),
2170
+ ]).pipe(map(([datas, shippingMethodsResponse]) => {
2171
+ let shippingMethods = shippingMethodsResponse.result;
2172
+ if (!shippingMethods.length)
2173
+ return [];
2174
+ shippingMethods = shippingMethods.map((shippingMethod) => {
2175
+ if (shippingMethod.ShippingCompanyName == 'Same Day EG')
2176
+ shippingMethod.ShippingCompanyName = 'Same Day';
2177
+ return shippingMethod;
2178
+ });
2179
+ const datasSameDayNotAvaliable = datas.sameDayNotAvaliable;
2180
+ if (this.isHolidays(datasSameDayNotAvaliable)) {
2181
+ shippingMethods = shippingMethods.filter((method) => method.serviceName !== 'Same Day');
2182
+ }
2183
+ if (totalPrice >= 200) {
2184
+ shippingMethods = shippingMethods.map((s) => {
2185
+ if (s.serviceName !== 'Same Day')
2186
+ return { ...s, totalPrice: 0 };
2187
+ else
2188
+ return s;
2189
+ });
2190
+ }
2191
+ if (shop == Shops.GLAMSHOP)
2192
+ return shippingMethods;
2193
+ if (this.isFreeShippingBySubscription(shop, subscriptionPlan)) {
2194
+ shippingMethods = shippingMethods.map((s) => {
2195
+ if (s.serviceName == 'Same Day')
2196
+ return { ...s, totalPrice: s.totalPrice / 2 };
2197
+ else
2198
+ return { ...s, totalPrice: 0 };
2199
+ });
2200
+ }
2201
+ if (this.isHalfShippingBySubscription(shop, subscriptionPlan)) {
2202
+ shippingMethods = shippingMethods.map((s) => {
2203
+ return { ...s, totalPrice: s.totalPrice / 2 };
2204
+ });
2205
+ }
2206
+ return shippingMethods;
2207
+ }));
2208
+ }
2209
+ isFreeShippingBySubscription(shop, subscriptionPlan) {
2210
+ if (!subscriptionPlan)
2211
+ return false;
2212
+ if (shop == Shops.MENSMARKET && subscriptionPlan == 'SELECT')
2213
+ return true;
2214
+ return false;
2215
+ }
2216
+ isHalfShippingBySubscription(shop, subscriptionPlan) {
2217
+ if (!subscriptionPlan)
2218
+ return false;
2219
+ if (shop == Shops.MENSMARKET && subscriptionPlan == 'PRIME') {
2220
+ return true;
2221
+ }
2222
+ return false;
2223
+ }
2224
+ isHolidays(datas) {
2225
+ const today = new Date();
2226
+ for (const key in datas) {
2227
+ let start = new Date(`${today.getFullYear()}-${datas[key].beginDate}`);
2228
+ let end = new Date(`${today.getFullYear()}-${datas[key].endDate}`);
2229
+ if (start > end)
2230
+ end = new Date(`${today.getFullYear() + 1}-${datas[key].endDate}`);
2231
+ if (today >= start && today <= end)
2232
+ return true;
2233
+ }
2234
+ return false;
2235
+ }
2236
+ }
2237
+ ShippingService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService, deps: [{ token: i1$3.HttpClient }, { token: BACKEND_URL }, { token: HomeShopService }], target: i0.ɵɵFactoryTarget.Injectable });
2238
+ ShippingService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService });
2239
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService, decorators: [{
2240
+ type: Injectable
2241
+ }], ctorParameters: function () { return [{ type: i1$3.HttpClient }, { type: undefined, decorators: [{
2242
+ type: Inject,
2243
+ args: [BACKEND_URL]
2244
+ }] }, { type: HomeShopService }]; } });
2429
2245
 
2430
2246
  class AngularConnectModule {
2431
2247
  static initializeApp(defaultShop, options, nameOrConfig) {
2432
2248
  return {
2433
2249
  ngModule: AngularConnectModule,
2434
2250
  providers: [
2435
- { provide: FIREBASE_APP_NAME, useValue: nameOrConfig },
2436
- { provide: APP_CHECK_PROVIDER, useValue: options.appCheckProvider },
2437
2251
  {
2438
2252
  provide: CATEGORY_STRUCTURE,
2439
2253
  useClass: isNil(options?.oldCategoryStructure) || options?.oldCategoryStructure
@@ -2443,121 +2257,66 @@ class AngularConnectModule {
2443
2257
  { provide: PERSISTENCE_PROVIDER, useClass: options?.persistenceProvider || CookieDataPersistence },
2444
2258
  ...(isNil(defaultShop) ? [] : [{ provide: DEFAULT_SHOP, useValue: defaultShop }]),
2445
2259
  ...(isNil(options?.firebase) ? [] : [{ provide: FIREBASE_OPTIONS, useValue: options?.firebase }]),
2260
+ ...(isNil(options?.firebase) ? [] : [{ provide: FIREBASE_APP_NAME, useValue: nameOrConfig }]),
2446
2261
  ...(isNil(options?.elasticSearch) ? [] : [{ provide: ES_CONFIG, useValue: options.elasticSearch }]),
2447
- ...(isNil(options?.vertexConfig) ? [] : [{ provide: VERTEX_CONFIG, useValue: options.vertexConfig }]),
2448
2262
  ...(isNil(options?.hasura) ? [] : [{ provide: HASURA_OPTIONS, useValue: options.hasura }]),
2449
2263
  ...(isNil(options?.backendUrl) ? [] : [{ provide: BACKEND_URL, useValue: options.backendUrl }]),
2450
2264
  ...(isNil(options?.storageBaseUrl) ? [] : [{ provide: STORAGE_BASE_URL, useValue: options.storageBaseUrl }]),
2451
2265
  ],
2452
2266
  };
2453
2267
  }
2454
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularConnectModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
2455
- static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.0.3", ngImport: i0, type: AngularConnectModule, imports: [i1$4.FirebaseAppModule, i2.AppCheckModule, i3.StorageModule, AngularElasticSeachModule,
2456
- AngularVertexSeachModule,
2457
- AngularFirebaseAuthModule,
2458
- AngularFirestoreModule,
2459
- AngularHasuraGraphQLModule] }); }
2460
- static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularConnectModule, providers: [
2461
- AuthService,
2462
- CartService,
2463
- CatalogService,
2464
- CategoryService,
2465
- CheckoutService,
2466
- CheckoutSubscriptionService,
2467
- CouponService,
2468
- HomeShopService,
2469
- OrderService,
2470
- WishlistService,
2471
- {
2472
- provide: UpdateUserImage,
2473
- useFactory: (userRepository, fileUploader) => {
2474
- return new UpdateUserImage(userRepository, fileUploader);
2475
- },
2476
- deps: ['UserRepository', 'FileUploaderService'],
2477
- },
2478
- {
2479
- provide: 'FileUploaderService',
2480
- useFactory: (storage, baseUrl) => {
2481
- return new FirebaseFileUploaderService(storage, baseUrl);
2482
- },
2483
- deps: [Storage, STORAGE_BASE_URL],
2484
- },
2485
- {
2486
- provide: 'ProductSearch',
2487
- useExisting: ProductsVertexSearch,
2488
- },
2489
- ], imports: [provideFirebaseApp((injector) => {
2490
- const appName = injector.get(FIREBASE_APP_NAME);
2491
- try {
2492
- const app = appName ? getApp(appName) : getApp();
2493
- return app;
2494
- }
2495
- catch (error) {
2496
- console.warn('Firebase app not found, initializing new app');
2497
- if (error instanceof Error)
2498
- console.error(error.message);
2499
- return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2500
- }
2501
- }),
2502
- provideAppCheck((injector) => {
2503
- const app = injector.get(FirebaseApp);
2504
- try {
2505
- const provider = injector.get(APP_CHECK_PROVIDER);
2506
- if (provider)
2507
- return initializeAppCheck(app, {
2508
- provider,
2509
- isTokenAutoRefreshEnabled: true,
2510
- });
2511
- }
2512
- catch (error) {
2513
- if (error instanceof Error)
2514
- console.error(error.message);
2515
- return;
2516
- }
2517
- }),
2518
- provideStorage((injector) => getStorage(injector.get(FirebaseApp))),
2519
- AngularElasticSeachModule,
2520
- AngularVertexSeachModule,
2521
- AngularFirebaseAuthModule,
2522
- AngularFirestoreModule,
2523
- AngularHasuraGraphQLModule] }); }
2524
2268
  }
2525
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImport: i0, type: AngularConnectModule, decorators: [{
2269
+ AngularConnectModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2270
+ AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, imports: [i1$4.FirebaseAppModule, AngularElasticSeachModule,
2271
+ AngularFirebaseAuthModule,
2272
+ AngularFirestoreModule,
2273
+ AngularHasuraGraphQLModule] });
2274
+ AngularConnectModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, providers: [
2275
+ AuthService,
2276
+ CartService,
2277
+ CatalogService,
2278
+ CategoryService,
2279
+ CheckoutService,
2280
+ CheckoutSubscriptionService,
2281
+ CouponService,
2282
+ HomeShopService,
2283
+ OrderService,
2284
+ ShippingService,
2285
+ WishlistService,
2286
+ {
2287
+ provide: UpdateUserImage,
2288
+ useFactory: (userRepository, fileUploader) => {
2289
+ return new UpdateUserImage(userRepository, fileUploader);
2290
+ },
2291
+ deps: ['UserRepository', 'FileUploaderService'],
2292
+ },
2293
+ ], imports: [provideFirebaseApp((injector) => {
2294
+ const appName = injector.get(FIREBASE_APP_NAME) || '[DEFAULT]';
2295
+ try {
2296
+ return getApp(appName);
2297
+ }
2298
+ catch (error) {
2299
+ return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2300
+ }
2301
+ }),
2302
+ AngularElasticSeachModule,
2303
+ AngularFirebaseAuthModule,
2304
+ AngularFirestoreModule,
2305
+ AngularHasuraGraphQLModule] });
2306
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, decorators: [{
2526
2307
  type: NgModule,
2527
2308
  args: [{
2528
2309
  imports: [
2529
2310
  provideFirebaseApp((injector) => {
2530
- const appName = injector.get(FIREBASE_APP_NAME);
2311
+ const appName = injector.get(FIREBASE_APP_NAME) || '[DEFAULT]';
2531
2312
  try {
2532
- const app = appName ? getApp(appName) : getApp();
2533
- return app;
2313
+ return getApp(appName);
2534
2314
  }
2535
2315
  catch (error) {
2536
- console.warn('Firebase app not found, initializing new app');
2537
- if (error instanceof Error)
2538
- console.error(error.message);
2539
2316
  return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2540
2317
  }
2541
2318
  }),
2542
- provideAppCheck((injector) => {
2543
- const app = injector.get(FirebaseApp);
2544
- try {
2545
- const provider = injector.get(APP_CHECK_PROVIDER);
2546
- if (provider)
2547
- return initializeAppCheck(app, {
2548
- provider,
2549
- isTokenAutoRefreshEnabled: true,
2550
- });
2551
- }
2552
- catch (error) {
2553
- if (error instanceof Error)
2554
- console.error(error.message);
2555
- return;
2556
- }
2557
- }),
2558
- provideStorage((injector) => getStorage(injector.get(FirebaseApp))),
2559
2319
  AngularElasticSeachModule,
2560
- AngularVertexSeachModule,
2561
2320
  AngularFirebaseAuthModule,
2562
2321
  AngularFirestoreModule,
2563
2322
  AngularHasuraGraphQLModule,
@@ -2572,6 +2331,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2572
2331
  CouponService,
2573
2332
  HomeShopService,
2574
2333
  OrderService,
2334
+ ShippingService,
2575
2335
  WishlistService,
2576
2336
  {
2577
2337
  provide: UpdateUserImage,
@@ -2580,17 +2340,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2580
2340
  },
2581
2341
  deps: ['UserRepository', 'FileUploaderService'],
2582
2342
  },
2583
- {
2584
- provide: 'FileUploaderService',
2585
- useFactory: (storage, baseUrl) => {
2586
- return new FirebaseFileUploaderService(storage, baseUrl);
2587
- },
2588
- deps: [Storage, STORAGE_BASE_URL],
2589
- },
2590
- {
2591
- provide: 'ProductSearch',
2592
- useExisting: ProductsVertexSearch,
2593
- },
2594
2343
  ],
2595
2344
  }]
2596
2345
  }] });
@@ -2599,5 +2348,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.3", ngImpor
2599
2348
  * Generated bundle index. Do not edit.
2600
2349
  */
2601
2350
 
2602
- export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CookieDataPersistence, CouponService, HomeShopService, NewCategoryStructureAdapter, OldCategoryStructureAdapter, OrderService, ProductSorts, UtilHelper, WishlistService };
2351
+ export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CookieDataPersistence, CouponService, HomeShopService, NewCategoryStructureAdapter, OldCategoryStructureAdapter, OrderService, ProductSorts, ShippingService, UtilHelper, WishlistService };
2603
2352
  //# sourceMappingURL=infrab4a-connect-angular.mjs.map