@infrab4a/connect-angular 4.0.0-beta.60 → 4.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/angular-connect.module.d.ts +4 -7
  2. package/angular-firestore.module.d.ts +1 -2
  3. package/consts/index.d.ts +0 -2
  4. package/esm2020/angular-connect.module.mjs +6 -23
  5. package/esm2020/angular-elastic-search.module.mjs +7 -3
  6. package/esm2020/angular-firestore.module.mjs +139 -240
  7. package/esm2020/angular-hasura-graphql.module.mjs +10 -116
  8. package/esm2020/consts/index.mjs +1 -3
  9. package/esm2020/index.mjs +3 -3
  10. package/esm2020/services/auth.service.mjs +3 -3
  11. package/esm2020/services/cart.service.mjs +23 -161
  12. package/esm2020/services/checkout-subscription.service.mjs +3 -5
  13. package/esm2020/services/checkout.service.mjs +5 -3
  14. package/esm2020/services/coupon.service.mjs +140 -132
  15. package/esm2020/services/errors/group-invalid-coupon.error.mjs +8 -0
  16. package/esm2020/services/errors/index.mjs +3 -0
  17. package/esm2020/services/errors/invalid-coupon.error.mjs +7 -0
  18. package/esm2020/services/index.mjs +3 -6
  19. package/fesm2015/infrab4a-connect-angular.mjs +1017 -1827
  20. package/fesm2015/infrab4a-connect-angular.mjs.map +1 -1
  21. package/fesm2020/infrab4a-connect-angular.mjs +1002 -1789
  22. package/fesm2020/infrab4a-connect-angular.mjs.map +1 -1
  23. package/index.d.ts +2 -2
  24. package/package.json +3 -2
  25. package/services/cart.service.d.ts +2 -9
  26. package/services/coupon.service.d.ts +10 -13
  27. package/services/errors/group-invalid-coupon.error.d.ts +6 -0
  28. package/services/errors/index.d.ts +2 -0
  29. package/services/errors/invalid-coupon.error.d.ts +4 -0
  30. package/services/index.d.ts +2 -5
  31. package/consts/backend-url.const.d.ts +0 -1
  32. package/consts/category-structure.d.ts +0 -1
  33. package/esm2020/consts/backend-url.const.mjs +0 -2
  34. package/esm2020/consts/category-structure.mjs +0 -2
  35. package/esm2020/helpers/index.mjs +0 -2
  36. package/esm2020/helpers/mobile-operation-system-checker.helper.mjs +0 -7
  37. package/esm2020/services/catalog/adapters/category-structure.adapter.mjs +0 -2
  38. package/esm2020/services/catalog/adapters/index.mjs +0 -4
  39. package/esm2020/services/catalog/adapters/new-category-structure.adapter.mjs +0 -42
  40. package/esm2020/services/catalog/adapters/old-category-structure.adapter.mjs +0 -23
  41. package/esm2020/services/catalog/catalog.service.mjs +0 -122
  42. package/esm2020/services/catalog/category.service.mjs +0 -51
  43. package/esm2020/services/catalog/enums/index.mjs +0 -2
  44. package/esm2020/services/catalog/enums/product-sorts.enum.mjs +0 -11
  45. package/esm2020/services/catalog/index.mjs +0 -7
  46. package/esm2020/services/catalog/models/category-with-tree.model.mjs +0 -10
  47. package/esm2020/services/catalog/models/index.mjs +0 -2
  48. package/esm2020/services/catalog/types/index.mjs +0 -2
  49. package/esm2020/services/catalog/types/product-sort.type.mjs +0 -2
  50. package/esm2020/services/catalog/wishlist.service.mjs +0 -105
  51. package/esm2020/services/helpers/index.mjs +0 -2
  52. package/esm2020/services/helpers/util.helper.mjs +0 -18
  53. package/esm2020/services/shipping.service.mjs +0 -96
  54. package/esm2020/services/types/shipping-methods.type.mjs +0 -2
  55. package/helpers/index.d.ts +0 -1
  56. package/helpers/mobile-operation-system-checker.helper.d.ts +0 -3
  57. package/services/catalog/adapters/category-structure.adapter.d.ts +0 -4
  58. package/services/catalog/adapters/index.d.ts +0 -3
  59. package/services/catalog/adapters/new-category-structure.adapter.d.ts +0 -14
  60. package/services/catalog/adapters/old-category-structure.adapter.d.ts +0 -10
  61. package/services/catalog/catalog.service.d.ts +0 -80
  62. package/services/catalog/category.service.d.ts +0 -15
  63. package/services/catalog/enums/index.d.ts +0 -1
  64. package/services/catalog/enums/product-sorts.enum.d.ts +0 -9
  65. package/services/catalog/index.d.ts +0 -6
  66. package/services/catalog/models/category-with-tree.model.d.ts +0 -4
  67. package/services/catalog/models/index.d.ts +0 -1
  68. package/services/catalog/types/index.d.ts +0 -1
  69. package/services/catalog/types/product-sort.type.d.ts +0 -2
  70. package/services/catalog/wishlist.service.d.ts +0 -22
  71. package/services/helpers/index.d.ts +0 -1
  72. package/services/helpers/util.helper.d.ts +0 -3
  73. package/services/shipping.service.d.ts +0 -19
  74. package/services/types/shipping-methods.type.d.ts +0 -12
@@ -1,1006 +1,205 @@
1
1
  import * as i0 from '@angular/core';
2
- import { NgModule, InjectionToken, PLATFORM_ID, Injectable, Inject } from '@angular/core';
3
- import * as i1$3 from '@infrab4a/connect';
4
- import { ProductsIndex, AxiosAdapter, Authentication, AuthenticationFirebaseAuthService, Register, RegisterFirebaseAuthService, SignOut, RecoveryPassword, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, CampaignHashtagFirestoreRepository, CampaignDashboardFirestoreRepository, SubscriptionEditionFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, ShopSettingsFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, ProductVariantFirestoreRepository, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository, VariantHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, Where, Shops, CheckoutTypes, CouponTypes, Exclusivities, isNil, NotFoundError, Checkout, pick, LineItem, RoundProductPricesHelper, set, InvalidArgumentError, Category, CheckoutSubscription, Product, RequiredArgumentError, add, Order } from '@infrab4a/connect';
5
- import * as i1 from '@angular/fire/app';
6
- import { provideFirebaseApp, initializeApp, FirebaseApp } from '@angular/fire/app';
7
- import * as i1$1 from '@angular/fire/auth';
8
- import { Auth, provideAuth, getAuth, getIdToken, authState } from '@angular/fire/auth';
9
- import { isPlatformBrowser } from '@angular/common';
10
- import * as i1$2 from '@angular/fire/firestore';
11
- import { Firestore, provideFirestore, getFirestore, initializeFirestore, enableIndexedDbPersistence, docSnapshots, doc } from '@angular/fire/firestore';
12
- import { initializeApp as initializeApp$1 } from 'firebase/app';
13
- import { combineLatest, from, of, throwError, Subject, iif, forkJoin } from 'rxjs';
2
+ import { Injectable, Inject, InjectionToken, NgModule, PLATFORM_ID } from '@angular/core';
3
+ import * as i1 from '@angular/fire/auth';
4
+ import { getIdToken, authState, Auth, provideAuth, getAuth } from '@angular/fire/auth';
5
+ import { combineLatest, of, from, throwError, Subject, iif, forkJoin } from 'rxjs';
14
6
  import { map, mergeMap, catchError, concatMap, tap } from 'rxjs/operators';
7
+ import * as i2 from '@infrab4a/connect';
8
+ import { Where, Shops, CheckoutTypes, CouponTypes, Exclusivities, Status, isNil, NotFoundError, Checkout, pick, LineItem, CheckoutSubscription, Order, Category, Product, RequiredArgumentError, add, Authentication, AuthenticationFirebaseAuthService, Register, RegisterFirebaseAuthService, SignOut, RecoveryPassword, ProductsIndex, AxiosAdapter, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, SubscriptionEditionFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, ProductVariantFirestoreRepository, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, VariantHasuraGraphQLRepository } from '@infrab4a/connect';
15
9
  import cookie from 'js-cookie';
16
- import { __decorate, __metadata } from 'tslib';
17
- import { Type } from 'class-transformer';
18
- import * as i1$4 from '@angular/common/http';
19
-
20
- const ES_CONFIG = 'ES_CONFIG';
10
+ import { CustomError } from 'ts-custom-error';
11
+ import * as i1$1 from '@angular/fire/firestore';
12
+ import { docSnapshots, doc, Firestore, provideFirestore, getFirestore } from '@angular/fire/firestore';
13
+ import * as i1$2 from '@angular/fire/app';
14
+ import { provideFirebaseApp, initializeApp } from '@angular/fire/app';
15
+ import { isPlatformBrowser } from '@angular/common';
21
16
 
22
- class AngularElasticSeachModule {
23
- static initializeApp(options) {
24
- return {
25
- ngModule: AngularElasticSeachModule,
26
- providers: [{ provide: ES_CONFIG, useValue: options }],
27
- };
17
+ class AuthService {
18
+ constructor(angularFireAuth, userRepository) {
19
+ this.angularFireAuth = angularFireAuth;
20
+ this.userRepository = userRepository;
21
+ }
22
+ getAuthstate() {
23
+ const observables = [this.getFireUser(), this.getUser()];
24
+ return combineLatest(observables).pipe(map(([fireUser, user]) => ({
25
+ user,
26
+ isAnonymous: fireUser?.isAnonymous,
27
+ })));
28
+ }
29
+ getUser() {
30
+ return this.getFireUser().pipe(map((user) => user?.uid), mergeMap((id) => (id ? this.userRepository.get({ id }) : of(null))), catchError(() => of(null)));
31
+ }
32
+ getTokenId() {
33
+ return from(getIdToken(this.angularFireAuth.currentUser));
34
+ }
35
+ getFireUser() {
36
+ return authState(this.angularFireAuth).pipe(catchError(() => of(null)));
28
37
  }
29
38
  }
30
- AngularElasticSeachModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
31
- AngularElasticSeachModulemod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule });
32
- AngularElasticSeachModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, providers: [
33
- {
34
- provide: ProductsIndex,
35
- useFactory: (configuration) => new ProductsIndex(new AxiosAdapter(configuration)),
36
- deps: [ES_CONFIG],
37
- },
38
- ] });
39
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, decorators: [{
40
- type: NgModule,
41
- args: [{
42
- providers: [
43
- {
44
- provide: ProductsIndex,
45
- useFactory: (configuration) => new ProductsIndex(new AxiosAdapter(configuration)),
46
- deps: [ES_CONFIG],
47
- },
48
- ],
49
- }]
50
- }] });
51
-
52
- const BACKEND_URL = 'BACKEND_URL';
53
-
54
- const CATEGORY_STRUCTURE = 'CATEGORY_STRUCTURE';
39
+ 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 });
40
+ AuthServiceprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AuthService });
41
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AuthService, decorators: [{
42
+ type: Injectable
43
+ }], ctorParameters: function () { return [{ type: i1.Auth }, { type: undefined, decorators: [{
44
+ type: Inject,
45
+ args: ['UserRepository']
46
+ }] }]; } });
55
47
 
56
48
  const DEFAULT_SHOP = 'DEFAULT_SHOP';
57
49
 
50
+ const ES_CONFIG = 'ES_CONFIG';
51
+
58
52
  const FIREBASE_APP_NAME = new InjectionToken('firebaseAppName');
59
53
  const FIREBASE_OPTIONS = new InjectionToken('firebaseOptions');
60
54
 
61
55
  const HASURA_OPTIONS = 'HASURA_OPTIONS';
62
56
 
63
- class AngularFirebaseAuthModule {
64
- static initializeApp(options, nameOrConfig) {
65
- return {
66
- ngModule: AngularFirebaseAuthModule,
67
- providers: [
68
- { provide: FIREBASE_OPTIONS, useValue: options },
69
- { provide: FIREBASE_APP_NAME, useValue: nameOrConfig },
70
- ],
71
- };
57
+ class InvalidCouponError extends CustomError {
58
+ constructor(message) {
59
+ super(message);
72
60
  }
73
61
  }
74
- AngularFirebaseAuthModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
75
- AngularFirebaseAuthModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, imports: [i1.FirebaseAppModule, i1$1.AuthModule] });
76
- AngularFirebaseAuthModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, providers: [
77
- {
78
- provide: 'Authentication',
79
- useFactory: (authenticationService, userRepository) => {
80
- return new Authentication(authenticationService, userRepository);
81
- },
82
- deps: ['AuthenticationService', 'UserRepository'],
83
- },
84
- {
85
- provide: 'AuthenticationService',
86
- useFactory: (angularFireAuth) => {
87
- return new AuthenticationFirebaseAuthService(angularFireAuth);
88
- },
89
- deps: [Auth],
90
- },
91
- {
92
- provide: 'Register',
93
- useFactory: (registerService, userRepository) => {
94
- return new Register(registerService, userRepository);
95
- },
96
- deps: ['RegisterService', 'UserRepository'],
97
- },
98
- {
99
- provide: 'RegisterService',
100
- useFactory: (angularFireAuth) => {
101
- return new RegisterFirebaseAuthService(angularFireAuth);
102
- },
103
- deps: [Auth],
104
- },
105
- {
106
- provide: 'SignOut',
107
- useFactory: (authenticationService) => {
108
- return new SignOut(authenticationService);
109
- },
110
- deps: ['AuthenticationService'],
111
- },
112
- {
113
- provide: 'RecoveryPassword',
114
- useFactory: (authenticationService) => {
115
- return new RecoveryPassword(authenticationService);
116
- },
117
- deps: ['AuthenticationService'],
118
- },
119
- ], imports: [provideFirebaseApp((injector) => {
120
- const appName = injector.get(FIREBASE_APP_NAME);
121
- return appName
122
- ? initializeApp(injector.get(FIREBASE_OPTIONS), appName)
123
- : initializeApp(injector.get(FIREBASE_OPTIONS));
124
- }),
125
- provideAuth(() => getAuth())] });
126
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, decorators: [{
127
- type: NgModule,
128
- args: [{
129
- imports: [
130
- provideFirebaseApp((injector) => {
131
- const appName = injector.get(FIREBASE_APP_NAME);
132
- return appName
133
- ? initializeApp(injector.get(FIREBASE_OPTIONS), appName)
134
- : initializeApp(injector.get(FIREBASE_OPTIONS));
135
- }),
136
- provideAuth(() => getAuth()),
137
- ],
138
- providers: [
139
- {
140
- provide: 'Authentication',
141
- useFactory: (authenticationService, userRepository) => {
142
- return new Authentication(authenticationService, userRepository);
143
- },
144
- deps: ['AuthenticationService', 'UserRepository'],
145
- },
146
- {
147
- provide: 'AuthenticationService',
148
- useFactory: (angularFireAuth) => {
149
- return new AuthenticationFirebaseAuthService(angularFireAuth);
150
- },
151
- deps: [Auth],
152
- },
153
- {
154
- provide: 'Register',
155
- useFactory: (registerService, userRepository) => {
156
- return new Register(registerService, userRepository);
157
- },
158
- deps: ['RegisterService', 'UserRepository'],
159
- },
160
- {
161
- provide: 'RegisterService',
162
- useFactory: (angularFireAuth) => {
163
- return new RegisterFirebaseAuthService(angularFireAuth);
164
- },
165
- deps: [Auth],
166
- },
167
- {
168
- provide: 'SignOut',
169
- useFactory: (authenticationService) => {
170
- return new SignOut(authenticationService);
171
- },
172
- deps: ['AuthenticationService'],
173
- },
174
- {
175
- provide: 'RecoveryPassword',
176
- useFactory: (authenticationService) => {
177
- return new RecoveryPassword(authenticationService);
178
- },
179
- deps: ['AuthenticationService'],
180
- },
181
- ],
182
- }]
183
- }] });
184
62
 
185
- class MobileOperationSystemCheckerHelper {
186
- static isAppleDevice() {
187
- return (['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator?.platform) ||
188
- (navigator?.userAgent?.includes?.('Mac') && 'ontouchend' in (document || {})));
63
+ class GroupInvalidCouponError extends CustomError {
64
+ constructor(errors) {
65
+ super('Many coupon errors throw');
66
+ this.errors = errors;
189
67
  }
190
68
  }
191
69
 
192
- class AngularFirestoreModule {
193
- static initializeApp(options, nameOrConfig) {
194
- return {
195
- ngModule: AngularFirestoreModule,
196
- providers: [
197
- { provide: FIREBASE_OPTIONS, useValue: options.firebase },
198
- { provide: FIREBASE_APP_NAME, useValue: nameOrConfig },
199
- { provide: ES_CONFIG, useValue: options.elasticSearch },
200
- ],
201
- };
70
+ class CouponService {
71
+ constructor(couponRepository, defaultShop, orderRepository, subscriptionRepository, categoryRepository) {
72
+ this.couponRepository = couponRepository;
73
+ this.defaultShop = defaultShop;
74
+ this.orderRepository = orderRepository;
75
+ this.subscriptionRepository = subscriptionRepository;
76
+ this.categoryRepository = categoryRepository;
77
+ this.emailIsFromCollaborator = (userEmail) => !!userEmail?.match(/@b4a.com.br/g);
202
78
  }
203
- }
204
- AngularFirestoreModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
205
- AngularFirestoreModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, imports: [AngularElasticSeachModule, i1.FirebaseAppModule, i1$2.FirestoreModule] });
206
- AngularFirestoreModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, providers: [
207
- {
208
- provide: 'FirestoreOptions',
209
- useFactory: (firestore, platformId) => ({
210
- firestore,
211
- interceptors: {
212
- request: (request) => {
213
- if (isPlatformBrowser(platformId))
214
- return request;
215
- const interval = setInterval(() => { }, 100);
216
- request.interval = interval;
217
- return request;
218
- },
219
- response: (response, request) => {
220
- if (isPlatformBrowser(platformId))
221
- return response;
222
- clearInterval(request.interval);
223
- return response;
224
- },
225
- },
226
- }),
227
- deps: [Firestore, PLATFORM_ID],
228
- },
229
- {
230
- provide: 'BeautyProfileRepository',
231
- useFactory: (config, userRepository) => {
232
- return new UserBeautyProfileFirestoreRepository(config, userRepository);
233
- },
234
- deps: ['FirestoreOptions', 'UserRepository'],
235
- },
236
- {
237
- provide: 'Buy2WinRepository',
238
- useFactory: (options) => {
239
- return new Buy2WinFirestoreRepository(options);
240
- },
241
- deps: ['FirestoreOptions'],
242
- },
243
- {
244
- provide: CategoryFirestoreRepository,
245
- useFactory: (options) => {
246
- return new CategoryFirestoreRepository(options);
247
- },
248
- deps: ['FirestoreOptions'],
249
- },
250
- {
251
- provide: 'CheckoutRepository',
252
- useFactory: (options) => {
253
- return new CheckoutFirestoreRepository(options);
254
- },
255
- deps: ['FirestoreOptions'],
256
- },
257
- {
258
- provide: 'CheckoutSubscriptionRepository',
259
- useFactory: (options) => {
260
- return new CheckoutSubscriptionFirestoreRepository(options);
261
- },
262
- deps: ['FirestoreOptions'],
263
- },
264
- {
265
- provide: 'CouponRepository',
266
- useFactory: (options) => {
267
- return new CouponFirestoreRepository(options);
79
+ checkCoupon(nickname, userEmail, checkoutType, plan, checkout, isSubscription) {
80
+ return from(this.couponRepository.find({
81
+ filters: {
82
+ nickname: { operator: Where.EQUALS, value: nickname },
83
+ active: { operator: Where.EQUALS, value: true },
268
84
  },
269
- deps: ['FirestoreOptions'],
270
- },
271
- {
272
- provide: 'CampaignHashtagRepository',
273
- useFactory: (options) => {
274
- return new CampaignHashtagFirestoreRepository(options);
85
+ })).pipe(concatMap((coupons) => this.checkCouponRules(coupons, checkoutType, plan, checkout, isSubscription)), concatMap((coupon) => this.checkCouponUseAndLimit(coupon, userEmail, checkout)), map((coupon) => this.isValidCoupon(coupon, userEmail)), map((coupon) => coupon));
86
+ }
87
+ checkCouponRules(coupons, checkoutType, plan, checkout, isSubscription) {
88
+ // Caso não ache nenhum cupom, retorna erro
89
+ if (coupons.count < 1) {
90
+ return throwError('Cupom inválido.');
91
+ }
92
+ // Get Primeiro Cupom (o find do repository retorna um array)
93
+ const coupon = coupons.data.shift();
94
+ // Verifica se o cupom é aplicavel na loja
95
+ const isInShop = coupon.shopAvailability === Shops.ALL || coupon.shopAvailability === this.defaultShop;
96
+ // Cupon não aplicavel a loja retorna erro
97
+ if (!isInShop)
98
+ return throwError('Cupom inválido para loja.');
99
+ // Verifica se o coupon é aplicado no checkout que está sendo realizado
100
+ const isCheckoutType = coupon.checkoutType === CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
101
+ // Cupon não aplicavel ao checkout retorna erro
102
+ if (!isCheckoutType)
103
+ return throwError('Cupom inválido. Erro de checkout.');
104
+ // Verifica se o cupom é ou pode ser aplicado para subscription
105
+ if (checkoutType === CheckoutTypes.ALL || checkoutType === CheckoutTypes.SUBSCRIPTION) {
106
+ // Se o cupom tiver um plano associado, verifica se é o mesmo plano do checkout da assinatura
107
+ if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
108
+ return throwError('Cupom inválido para sua assinatura.');
109
+ }
110
+ if (isSubscription)
111
+ return of(coupon);
112
+ // Verifica se possui o valor minimo de compra para utilização do cupom
113
+ const hasMinSubTotal = this.hasMinSubTotal(coupon, checkout);
114
+ // Se não tem valor mínimo atingido, retorna erro
115
+ if (!hasMinSubTotal)
116
+ return throwError('Valor mínimo não atingido');
117
+ return of(coupon);
118
+ }
119
+ isValidCoupon(coupon, userEmail) {
120
+ // Verifica a data de inicio de validade do cupom
121
+ if (coupon?.beginAt > new Date())
122
+ throw new InvalidCouponError('Cupom ainda não liberado.');
123
+ // Verifica a data de validade do cupom
124
+ if (coupon?.expiresIn < new Date())
125
+ throw new InvalidCouponError('Cupom expirado.');
126
+ return coupon;
127
+ }
128
+ async checkCouponUseAndLimit(coupon, userEmail, checkout) {
129
+ const orders = await this.orderRepository.find({
130
+ filters: {
131
+ coupon: { id: coupon.id },
132
+ payment: { status: 'paid' },
275
133
  },
276
- deps: ['FirestoreOptions'],
277
- },
278
- {
279
- provide: 'CampaignDashboardRepository',
280
- useFactory: (options) => {
281
- return new CampaignDashboardFirestoreRepository(options);
282
- },
283
- deps: ['FirestoreOptions'],
284
- },
285
- {
286
- provide: 'EditionRepository',
287
- useFactory: (options, subscriptionRepository) => {
288
- return new SubscriptionEditionFirestoreRepository(options, subscriptionRepository);
289
- },
290
- deps: ['FirestoreOptions', 'SubscriptionRepository'],
291
- },
292
- {
293
- provide: 'HomeRepository',
294
- useFactory: (options) => {
295
- return new HomeFirestoreRepository(options);
296
- },
297
- deps: ['FirestoreOptions'],
298
- },
299
- {
300
- provide: 'LeadRepository',
301
- useFactory: (options) => {
302
- return new LeadFirestoreRepository(options);
303
- },
304
- deps: ['FirestoreOptions'],
305
- },
306
- {
307
- provide: 'LegacyOrderRepository',
308
- useFactory: (options) => {
309
- return new LegacyOrderFirestoreRepository(options);
310
- },
311
- deps: ['FirestoreOptions'],
312
- },
313
- {
314
- provide: 'ShopMenuRepository',
315
- useFactory: (options) => {
316
- return new ShopMenuFirestoreRepository(options);
317
- },
318
- deps: ['FirestoreOptions'],
319
- },
320
- {
321
- provide: 'OrderRepository',
322
- useFactory: (options) => {
323
- return new OrderFirestoreRepository(options);
324
- },
325
- deps: ['FirestoreOptions'],
326
- },
327
- {
328
- provide: 'PaymentRepository',
329
- useFactory: (options) => {
330
- return new PaymentFirestoreRepository(options);
331
- },
332
- deps: ['FirestoreOptions'],
333
- },
334
- {
335
- provide: ProductFirestoreRepository,
336
- useFactory: (options) => {
337
- return new ProductFirestoreRepository(options);
338
- },
339
- deps: ['FirestoreOptions'],
340
- },
341
- {
342
- provide: 'ShopSettingsRepository',
343
- useFactory: (options) => {
344
- return new ShopSettingsFirestoreRepository(options);
345
- },
346
- deps: ['FirestoreOptions'],
347
- },
348
- {
349
- provide: 'SubscriptionPaymentRepository',
350
- useFactory: (options, subscriptionRepository) => {
351
- return new SubscriptionPaymentFirestoreRepository(options, subscriptionRepository);
352
- },
353
- deps: ['FirestoreOptions', 'SubscriptionRepository'],
354
- },
355
- {
356
- provide: 'SubscriptionPlanRepository',
357
- useFactory: (options) => {
358
- return new SubscriptionPlanFirestoreRepository(options);
359
- },
360
- deps: ['FirestoreOptions'],
361
- },
362
- {
363
- provide: 'SubscriptionProductRepository',
364
- useFactory: (options) => {
365
- return new SubscriptionProductFirestoreRepository(options);
366
- },
367
- deps: ['FirestoreOptions'],
368
- },
369
- {
370
- provide: 'SubscriptionRepository',
371
- useFactory: (options) => {
372
- return new SubscriptionFirestoreRepository(options);
373
- },
374
- deps: ['FirestoreOptions'],
375
- },
376
- {
377
- provide: 'UserRepository',
378
- useFactory: (options) => {
379
- return new UserFirestoreRepository(options);
380
- },
381
- deps: ['FirestoreOptions'],
382
- },
383
- {
384
- provide: 'UserAddressRepository',
385
- useFactory: (options, userRepository) => {
386
- return new UserAddressFirestoreRepository(options, userRepository);
387
- },
388
- deps: ['FirestoreOptions', 'UserRepository'],
389
- },
390
- {
391
- provide: 'UserPaymentMethodRepository',
392
- useFactory: (options, userRepository) => {
393
- return new UserPaymentMethodFirestoreRepository(options, userRepository);
394
- },
395
- deps: ['FirestoreOptions', 'UserRepository'],
396
- },
397
- {
398
- provide: ProductVariantFirestoreRepository,
399
- useFactory: (options, productRepository) => {
400
- return new ProductVariantFirestoreRepository(options, productRepository);
401
- },
402
- deps: ['FirestoreOptions', ProductFirestoreRepository],
403
- },
404
- ], imports: [AngularElasticSeachModule,
405
- provideFirebaseApp((injector) => {
406
- const appName = injector.get(FIREBASE_APP_NAME);
407
- return appName
408
- ? initializeApp$1(injector.get(FIREBASE_OPTIONS), appName)
409
- : initializeApp$1(injector.get(FIREBASE_OPTIONS));
410
- }),
411
- provideFirestore((injector) => {
412
- if (!MobileOperationSystemCheckerHelper.isAppleDevice())
413
- return getFirestore();
414
- const firestore = initializeFirestore(injector.get(FirebaseApp), { experimentalForceLongPolling: true });
415
- enableIndexedDbPersistence(firestore).catch(console.error);
416
- return firestore;
417
- })] });
418
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, decorators: [{
419
- type: NgModule,
420
- args: [{
421
- imports: [
422
- AngularElasticSeachModule,
423
- provideFirebaseApp((injector) => {
424
- const appName = injector.get(FIREBASE_APP_NAME);
425
- return appName
426
- ? initializeApp$1(injector.get(FIREBASE_OPTIONS), appName)
427
- : initializeApp$1(injector.get(FIREBASE_OPTIONS));
428
- }),
429
- provideFirestore((injector) => {
430
- if (!MobileOperationSystemCheckerHelper.isAppleDevice())
431
- return getFirestore();
432
- const firestore = initializeFirestore(injector.get(FirebaseApp), { experimentalForceLongPolling: true });
433
- enableIndexedDbPersistence(firestore).catch(console.error);
434
- return firestore;
435
- }),
436
- ],
437
- providers: [
438
- {
439
- provide: 'FirestoreOptions',
440
- useFactory: (firestore, platformId) => ({
441
- firestore,
442
- interceptors: {
443
- request: (request) => {
444
- if (isPlatformBrowser(platformId))
445
- return request;
446
- const interval = setInterval(() => { }, 100);
447
- request.interval = interval;
448
- return request;
449
- },
450
- response: (response, request) => {
451
- if (isPlatformBrowser(platformId))
452
- return response;
453
- clearInterval(request.interval);
454
- return response;
455
- },
456
- },
457
- }),
458
- deps: [Firestore, PLATFORM_ID],
459
- },
460
- {
461
- provide: 'BeautyProfileRepository',
462
- useFactory: (config, userRepository) => {
463
- return new UserBeautyProfileFirestoreRepository(config, userRepository);
464
- },
465
- deps: ['FirestoreOptions', 'UserRepository'],
466
- },
467
- {
468
- provide: 'Buy2WinRepository',
469
- useFactory: (options) => {
470
- return new Buy2WinFirestoreRepository(options);
471
- },
472
- deps: ['FirestoreOptions'],
473
- },
474
- {
475
- provide: CategoryFirestoreRepository,
476
- useFactory: (options) => {
477
- return new CategoryFirestoreRepository(options);
478
- },
479
- deps: ['FirestoreOptions'],
480
- },
481
- {
482
- provide: 'CheckoutRepository',
483
- useFactory: (options) => {
484
- return new CheckoutFirestoreRepository(options);
485
- },
486
- deps: ['FirestoreOptions'],
487
- },
488
- {
489
- provide: 'CheckoutSubscriptionRepository',
490
- useFactory: (options) => {
491
- return new CheckoutSubscriptionFirestoreRepository(options);
492
- },
493
- deps: ['FirestoreOptions'],
494
- },
495
- {
496
- provide: 'CouponRepository',
497
- useFactory: (options) => {
498
- return new CouponFirestoreRepository(options);
499
- },
500
- deps: ['FirestoreOptions'],
501
- },
502
- {
503
- provide: 'CampaignHashtagRepository',
504
- useFactory: (options) => {
505
- return new CampaignHashtagFirestoreRepository(options);
506
- },
507
- deps: ['FirestoreOptions'],
508
- },
509
- {
510
- provide: 'CampaignDashboardRepository',
511
- useFactory: (options) => {
512
- return new CampaignDashboardFirestoreRepository(options);
513
- },
514
- deps: ['FirestoreOptions'],
515
- },
516
- {
517
- provide: 'EditionRepository',
518
- useFactory: (options, subscriptionRepository) => {
519
- return new SubscriptionEditionFirestoreRepository(options, subscriptionRepository);
520
- },
521
- deps: ['FirestoreOptions', 'SubscriptionRepository'],
522
- },
523
- {
524
- provide: 'HomeRepository',
525
- useFactory: (options) => {
526
- return new HomeFirestoreRepository(options);
527
- },
528
- deps: ['FirestoreOptions'],
529
- },
530
- {
531
- provide: 'LeadRepository',
532
- useFactory: (options) => {
533
- return new LeadFirestoreRepository(options);
534
- },
535
- deps: ['FirestoreOptions'],
536
- },
537
- {
538
- provide: 'LegacyOrderRepository',
539
- useFactory: (options) => {
540
- return new LegacyOrderFirestoreRepository(options);
541
- },
542
- deps: ['FirestoreOptions'],
543
- },
544
- {
545
- provide: 'ShopMenuRepository',
546
- useFactory: (options) => {
547
- return new ShopMenuFirestoreRepository(options);
548
- },
549
- deps: ['FirestoreOptions'],
550
- },
551
- {
552
- provide: 'OrderRepository',
553
- useFactory: (options) => {
554
- return new OrderFirestoreRepository(options);
555
- },
556
- deps: ['FirestoreOptions'],
557
- },
558
- {
559
- provide: 'PaymentRepository',
560
- useFactory: (options) => {
561
- return new PaymentFirestoreRepository(options);
562
- },
563
- deps: ['FirestoreOptions'],
564
- },
565
- {
566
- provide: ProductFirestoreRepository,
567
- useFactory: (options) => {
568
- return new ProductFirestoreRepository(options);
569
- },
570
- deps: ['FirestoreOptions'],
571
- },
572
- {
573
- provide: 'ShopSettingsRepository',
574
- useFactory: (options) => {
575
- return new ShopSettingsFirestoreRepository(options);
576
- },
577
- deps: ['FirestoreOptions'],
578
- },
579
- {
580
- provide: 'SubscriptionPaymentRepository',
581
- useFactory: (options, subscriptionRepository) => {
582
- return new SubscriptionPaymentFirestoreRepository(options, subscriptionRepository);
583
- },
584
- deps: ['FirestoreOptions', 'SubscriptionRepository'],
585
- },
586
- {
587
- provide: 'SubscriptionPlanRepository',
588
- useFactory: (options) => {
589
- return new SubscriptionPlanFirestoreRepository(options);
590
- },
591
- deps: ['FirestoreOptions'],
592
- },
593
- {
594
- provide: 'SubscriptionProductRepository',
595
- useFactory: (options) => {
596
- return new SubscriptionProductFirestoreRepository(options);
597
- },
598
- deps: ['FirestoreOptions'],
599
- },
600
- {
601
- provide: 'SubscriptionRepository',
602
- useFactory: (options) => {
603
- return new SubscriptionFirestoreRepository(options);
604
- },
605
- deps: ['FirestoreOptions'],
606
- },
607
- {
608
- provide: 'UserRepository',
609
- useFactory: (options) => {
610
- return new UserFirestoreRepository(options);
611
- },
612
- deps: ['FirestoreOptions'],
613
- },
614
- {
615
- provide: 'UserAddressRepository',
616
- useFactory: (options, userRepository) => {
617
- return new UserAddressFirestoreRepository(options, userRepository);
618
- },
619
- deps: ['FirestoreOptions', 'UserRepository'],
620
- },
621
- {
622
- provide: 'UserPaymentMethodRepository',
623
- useFactory: (options, userRepository) => {
624
- return new UserPaymentMethodFirestoreRepository(options, userRepository);
625
- },
626
- deps: ['FirestoreOptions', 'UserRepository'],
627
- },
628
- {
629
- provide: ProductVariantFirestoreRepository,
630
- useFactory: (options, productRepository) => {
631
- return new ProductVariantFirestoreRepository(options, productRepository);
632
- },
633
- deps: ['FirestoreOptions', ProductFirestoreRepository],
634
- },
635
- ],
636
- }]
637
- }] });
638
-
639
- class AngularHasuraGraphQLModule {
640
- static initializeApp(options) {
641
- return {
642
- ngModule: AngularHasuraGraphQLModule,
643
- providers: [{ provide: HASURA_OPTIONS, useValue: options }],
644
- };
645
- }
646
- }
647
- AngularHasuraGraphQLModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
648
- AngularHasuraGraphQLModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule });
649
- AngularHasuraGraphQLModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, providers: [
650
- {
651
- provide: 'HasuraConfig',
652
- useFactory: (options, platformId) => ({
653
- endpoint: options.endpoint,
654
- authOptions: options.credentials,
655
- interceptors: {
656
- request: (request) => {
657
- if (isPlatformBrowser(platformId))
658
- return request;
659
- const interval = setInterval(() => { }, 100);
660
- request.interval = interval;
661
- return request;
662
- },
663
- response: (response, request) => {
664
- if (isPlatformBrowser(platformId))
665
- return response;
666
- clearInterval(request.interval);
667
- return response;
668
- },
669
- },
670
- }),
671
- deps: [HASURA_OPTIONS, PLATFORM_ID],
672
- },
673
- {
674
- provide: 'CategoryRepository',
675
- useExisting: CategoryHasuraGraphQLRepository,
676
- },
677
- {
678
- provide: CategoryHasuraGraphQLRepository,
679
- useFactory: (options, productRepository, categoryFilterRepository) => {
680
- return new CategoryHasuraGraphQLRepository(options, productRepository, categoryFilterRepository);
681
- },
682
- deps: ['HasuraConfig', ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
683
- },
684
- {
685
- provide: 'ProductRepository',
686
- useExisting: ProductHasuraGraphQLRepository,
687
- },
688
- {
689
- provide: ProductHasuraGraphQLRepository,
690
- useFactory: (hasuraConfig) => {
691
- return new ProductHasuraGraphQLRepository(hasuraConfig);
692
- },
693
- deps: ['HasuraConfig'],
694
- },
695
- {
696
- provide: 'VariantRepository',
697
- useExisting: VariantHasuraGraphQLRepository,
698
- },
699
- {
700
- provide: VariantHasuraGraphQLRepository,
701
- useFactory: (hasuraConfig) => {
702
- return new VariantHasuraGraphQLRepository(hasuraConfig);
703
- },
704
- deps: ['HasuraConfig'],
705
- },
706
- {
707
- provide: 'CategoryFilterRepository',
708
- useExisting: CategoryFilterHasuraGraphQLRepository,
709
- },
710
- {
711
- provide: CategoryFilterHasuraGraphQLRepository,
712
- useFactory: (options) => {
713
- return new CategoryFilterHasuraGraphQLRepository(options);
714
- },
715
- deps: ['HasuraConfig'],
716
- },
717
- {
718
- provide: 'FilterOptionRepository',
719
- useExisting: FilterOptionHasuraGraphQLRepository,
720
- },
721
- {
722
- provide: FilterOptionHasuraGraphQLRepository,
723
- useFactory: (options) => {
724
- return new FilterOptionHasuraGraphQLRepository(options);
725
- },
726
- deps: ['HasuraConfig'],
727
- },
728
- {
729
- provide: 'FilterRepository',
730
- useExisting: FilterHasuraGraphQLRepository,
731
- },
732
- {
733
- provide: FilterHasuraGraphQLRepository,
734
- useFactory: (options, filterOptionRepository, categoryFilterRepository) => {
735
- return new FilterHasuraGraphQLRepository(options, filterOptionRepository, categoryFilterRepository);
736
- },
737
- deps: ['HasuraConfig', FilterOptionHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
738
- },
739
- {
740
- provide: CategoryCollectionChildrenHasuraGraphQLRepository,
741
- useFactory: (options) => new CategoryCollectionChildrenHasuraGraphQLRepository(options),
742
- deps: ['HasuraConfig'],
743
- },
744
- {
745
- provide: 'CategoryCollectionChildrenRepository',
746
- useExisting: CategoryCollectionChildrenHasuraGraphQLRepository,
747
- },
748
- {
749
- provide: WishlistHasuraGraphQLRepository,
750
- useFactory: (options, categoryFilterRepository) => {
751
- return new WishlistHasuraGraphQLRepository(options, categoryFilterRepository);
752
- },
753
- deps: ['HasuraConfig', CategoryFilterHasuraGraphQLRepository],
754
- },
755
- {
756
- provide: 'WishlistRepository',
757
- useExisting: WishlistHasuraGraphQLRepository,
758
- },
759
- ] });
760
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, decorators: [{
761
- type: NgModule,
762
- args: [{
763
- providers: [
764
- {
765
- provide: 'HasuraConfig',
766
- useFactory: (options, platformId) => ({
767
- endpoint: options.endpoint,
768
- authOptions: options.credentials,
769
- interceptors: {
770
- request: (request) => {
771
- if (isPlatformBrowser(platformId))
772
- return request;
773
- const interval = setInterval(() => { }, 100);
774
- request.interval = interval;
775
- return request;
776
- },
777
- response: (response, request) => {
778
- if (isPlatformBrowser(platformId))
779
- return response;
780
- clearInterval(request.interval);
781
- return response;
782
- },
783
- },
784
- }),
785
- deps: [HASURA_OPTIONS, PLATFORM_ID],
786
- },
787
- {
788
- provide: 'CategoryRepository',
789
- useExisting: CategoryHasuraGraphQLRepository,
790
- },
791
- {
792
- provide: CategoryHasuraGraphQLRepository,
793
- useFactory: (options, productRepository, categoryFilterRepository) => {
794
- return new CategoryHasuraGraphQLRepository(options, productRepository, categoryFilterRepository);
795
- },
796
- deps: ['HasuraConfig', ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
797
- },
798
- {
799
- provide: 'ProductRepository',
800
- useExisting: ProductHasuraGraphQLRepository,
801
- },
802
- {
803
- provide: ProductHasuraGraphQLRepository,
804
- useFactory: (hasuraConfig) => {
805
- return new ProductHasuraGraphQLRepository(hasuraConfig);
806
- },
807
- deps: ['HasuraConfig'],
808
- },
809
- {
810
- provide: 'VariantRepository',
811
- useExisting: VariantHasuraGraphQLRepository,
812
- },
813
- {
814
- provide: VariantHasuraGraphQLRepository,
815
- useFactory: (hasuraConfig) => {
816
- return new VariantHasuraGraphQLRepository(hasuraConfig);
817
- },
818
- deps: ['HasuraConfig'],
819
- },
820
- {
821
- provide: 'CategoryFilterRepository',
822
- useExisting: CategoryFilterHasuraGraphQLRepository,
823
- },
824
- {
825
- provide: CategoryFilterHasuraGraphQLRepository,
826
- useFactory: (options) => {
827
- return new CategoryFilterHasuraGraphQLRepository(options);
828
- },
829
- deps: ['HasuraConfig'],
830
- },
831
- {
832
- provide: 'FilterOptionRepository',
833
- useExisting: FilterOptionHasuraGraphQLRepository,
834
- },
835
- {
836
- provide: FilterOptionHasuraGraphQLRepository,
837
- useFactory: (options) => {
838
- return new FilterOptionHasuraGraphQLRepository(options);
839
- },
840
- deps: ['HasuraConfig'],
841
- },
842
- {
843
- provide: 'FilterRepository',
844
- useExisting: FilterHasuraGraphQLRepository,
845
- },
846
- {
847
- provide: FilterHasuraGraphQLRepository,
848
- useFactory: (options, filterOptionRepository, categoryFilterRepository) => {
849
- return new FilterHasuraGraphQLRepository(options, filterOptionRepository, categoryFilterRepository);
850
- },
851
- deps: ['HasuraConfig', FilterOptionHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
852
- },
853
- {
854
- provide: CategoryCollectionChildrenHasuraGraphQLRepository,
855
- useFactory: (options) => new CategoryCollectionChildrenHasuraGraphQLRepository(options),
856
- deps: ['HasuraConfig'],
857
- },
858
- {
859
- provide: 'CategoryCollectionChildrenRepository',
860
- useExisting: CategoryCollectionChildrenHasuraGraphQLRepository,
861
- },
862
- {
863
- provide: WishlistHasuraGraphQLRepository,
864
- useFactory: (options, categoryFilterRepository) => {
865
- return new WishlistHasuraGraphQLRepository(options, categoryFilterRepository);
866
- },
867
- deps: ['HasuraConfig', CategoryFilterHasuraGraphQLRepository],
868
- },
869
- {
870
- provide: 'WishlistRepository',
871
- useExisting: WishlistHasuraGraphQLRepository,
872
- },
873
- ],
874
- }]
875
- }] });
876
-
877
- class AuthService {
878
- constructor(angularFireAuth, userRepository) {
879
- this.angularFireAuth = angularFireAuth;
880
- this.userRepository = userRepository;
881
- }
882
- getAuthstate() {
883
- const observables = [this.getFireUser(), this.getUser()];
884
- return combineLatest(observables).pipe(map(([fireUser, user]) => ({
885
- user,
886
- isAnonymous: fireUser?.isAnonymous,
887
- })));
888
- }
889
- getUser() {
890
- return this.getFireUser().pipe(map((user) => user?.uid), mergeMap((id) => (id ? from(this.userRepository.get({ id })).pipe(catchError(() => of(null))) : of(null))));
891
- }
892
- getTokenId() {
893
- return from(getIdToken(this.angularFireAuth.currentUser));
894
- }
895
- getFireUser() {
896
- return authState(this.angularFireAuth).pipe(catchError(() => of(null)));
897
- }
898
- }
899
- AuthService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AuthService, deps: [{ token: i1$1.Auth }, { token: 'UserRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
900
- AuthService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AuthService });
901
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AuthService, decorators: [{
902
- type: Injectable
903
- }], ctorParameters: function () { return [{ type: i1$1.Auth }, { type: undefined, decorators: [{
904
- type: Inject,
905
- args: ['UserRepository']
906
- }] }]; } });
907
-
908
- class CouponService {
909
- constructor(couponRepository, defaultShop, orderRepository, categoryRepository) {
910
- this.couponRepository = couponRepository;
911
- this.defaultShop = defaultShop;
912
- this.orderRepository = orderRepository;
913
- this.categoryRepository = categoryRepository;
914
- this.emailIsFromCollaborator = (userEmail) => !!userEmail?.match(/@b4a.com.br/g);
915
- }
916
- checkCoupon(nickname, checkoutType, checkout, plan) {
917
- return from(this.couponRepository
918
- .find({
919
- filters: {
920
- nickname: { operator: Where.EQUALS, value: nickname },
921
- active: { operator: Where.EQUALS, value: true },
922
- },
923
- })
924
- .then((result) => result.data[0])).pipe(concatMap((coupon) => this.couponValidation(coupon, checkoutType)), concatMap((couponValid) => this.couponRulesValidation(couponValid, checkoutType, checkout, plan)), map((couponValidated) => couponValidated));
925
- }
926
- async couponValidation(coupon, checkoutType) {
927
- if (!coupon)
928
- throw 'Cupom inválido.';
929
- if (coupon?.beginAt && coupon?.beginAt.getTime() > new Date().getTime())
930
- throw 'Cupom inválido.';
931
- if (coupon?.expiresIn && coupon?.expiresIn.getTime() < new Date().getTime())
932
- throw 'Cupom expirado.';
933
- const isInShop = coupon.shopAvailability === Shops.ALL || coupon.shopAvailability === this.defaultShop;
934
- if (!isInShop)
935
- throw 'Cupom inválido para loja.';
936
- const isCheckoutType = coupon.checkoutType === CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
937
- if (!isCheckoutType)
938
- throw 'Cupom inválido. Erro de checkout.';
939
- return coupon;
940
- }
941
- async couponRulesValidation(coupon, checkoutType, checkout, plan) {
942
- if (checkoutType == CheckoutTypes.SUBSCRIPTION) {
943
- if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
944
- throw 'Cupom inválido para sua assinatura.';
945
- return coupon;
946
- }
947
- const validUser = this.coupomUserValidation(coupon, checkout?.user);
134
+ });
135
+ // orders que usuario ja fez com o cupom
136
+ const ordersUserCoupon = orders.data.filter((o) => o.user.email == userEmail);
137
+ // Verifica o limite de uso de cupom por usuario
138
+ if (coupon.useLimitPerUser && ordersUserCoupon.length)
139
+ throw new InvalidCouponError('Limite de uso por usuário atingido.');
140
+ // Verifica o limite de uso geral por usuario
141
+ if (coupon.useLimit && orders.data.length >= coupon.useLimit)
142
+ throw new InvalidCouponError('Limite de uso atingido.');
143
+ const validUser = await this.userValidationAndSubscriptionStatus(coupon, userEmail);
948
144
  if (!validUser)
949
- throw 'Usuário não elegível.';
950
- const couponUseLimits = this.getCouponUseLimits(coupon, checkoutType, checkout.user);
951
- if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
952
- const orders = await this.getOrdersWithCoupon(coupon);
953
- if (!couponUseLimits.unlimited && couponUseLimits.total && orders.length >= couponUseLimits.total)
954
- throw 'Limite de uso atingido.';
955
- if (couponUseLimits.limitedPerUser) {
956
- const ordersWithUser = this.countOrdersWithUser(orders, checkout.user.email);
957
- if (ordersWithUser > 0)
958
- throw 'Limite de uso por usuário atingido.';
959
- }
960
- }
145
+ throw new InvalidCouponError('Usuário não elegível.');
961
146
  const hasProductCategories = await this.hasProductCategories(coupon, checkout);
962
147
  if (!hasProductCategories)
963
148
  throw 'Seu carrinho não possui produtos elegíveis para desconto.';
964
- const hasMinSubTotal = await this.hasMinSubTotal(coupon, checkout);
965
- if (!hasMinSubTotal)
966
- throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido`;
967
149
  return coupon;
968
150
  }
969
151
  calcDiscountSubscription(coupon, checkout) {
152
+ //
970
153
  let discount = 0;
971
- if (coupon.discount.subscription.type == CouponTypes.ABSOLUTE)
972
- discount = coupon.discount.subscription.value;
973
- else
974
- discount = checkout.subscriptionPlan.recurrencePrice * (coupon.discount.subscription.value / 100);
154
+ if (coupon.type === CouponTypes.ABSOLUTE)
155
+ discount = coupon.discount;
156
+ else if (coupon.type === CouponTypes.PERCENTAGE)
157
+ discount = checkout.subscriptionPlan.recurrencePrice * (coupon.discount / 100);
975
158
  return of(discount);
976
159
  }
977
160
  async calcDiscountShopping(coupon, checkout) {
978
161
  let discount = 0;
979
- if (checkout.user.isSubscriber && coupon.discount.subscriber.value) {
980
- discount = await this.calcDiscountByType(coupon.discount.subscriber.type, coupon.discount.subscriber.value, coupon.productsCategories, checkout);
981
- }
982
- else {
983
- discount = await this.calcDiscountByType(coupon.discount.non_subscriber.type, coupon.discount.non_subscriber.value, coupon.productsCategories, checkout);
162
+ switch (coupon.type) {
163
+ case CouponTypes.ABSOLUTE: {
164
+ discount = coupon.discount;
165
+ break;
166
+ }
167
+ case CouponTypes.PERCENTAGE: {
168
+ discount = await this.calcShoppingPercentageDiscount(coupon, checkout);
169
+ break;
170
+ }
984
171
  }
985
172
  return discount;
986
173
  }
987
- async calcDiscountByType(type, value, categories, checkout) {
174
+ async calcShoppingPercentageDiscount(coupon, checkout) {
988
175
  let discount = 0;
989
- let lineItensDiscount = await this.getLineItensEligebleForDiscount(categories, checkout);
990
- const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user, checkout.shop);
991
- if (type == CouponTypes.ABSOLUTE) {
992
- discount = value > subTotal ? subTotal : value;
176
+ const shop = checkout.shop;
177
+ let lineItensDiscount = [];
178
+ const couponCategories = await this.getCouponCategoriesId(coupon);
179
+ if (coupon.productsCategories && coupon.productsCategories.length) {
180
+ lineItensDiscount = checkout.lineItems?.filter((i) => {
181
+ if (i.categories?.length) {
182
+ return i.categories.some((c) => couponCategories.some((cat) => cat.id == c || cat.firestoreId == c));
183
+ }
184
+ return true;
185
+ });
993
186
  }
994
187
  else {
995
- discount = subTotal * (value / 100);
188
+ lineItensDiscount = checkout.lineItems;
996
189
  }
190
+ const subTotal = lineItensDiscount.reduce((acc, curr) => checkout.user?.isSubscriber && curr.price?.subscriberPrice
191
+ ? acc + curr.price?.subscriberPrice * curr.quantity
192
+ : acc + curr.pricePaid * curr.quantity, 0) || 0;
193
+ discount = subTotal * (coupon.discount / 100);
997
194
  return discount;
998
195
  }
999
- async hasMinSubTotal(coupon, checkout) {
196
+ hasMinSubTotal(coupon, checkout) {
1000
197
  if (!coupon.minSubTotalValue)
1001
198
  return true;
1002
- let lineItensDiscount = await this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
1003
- const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user, checkout.shop);
199
+ const shop = checkout.shop;
200
+ let subTotal = checkout.lineItems?.reduce((acc, curr) => checkout.user?.isSubscriber && curr.price?.subscriberPrice
201
+ ? acc + curr.price?.subscriberPrice * curr.quantity
202
+ : acc + curr.pricePaid * curr.quantity, 0) || 0;
1004
203
  if (coupon.minSubTotalValue <= subTotal)
1005
204
  return true;
1006
205
  return false;
@@ -1009,93 +208,60 @@ class CouponService {
1009
208
  if (!coupon.productsCategories || !coupon.productsCategories.length) {
1010
209
  return true;
1011
210
  }
1012
- const couponCategories = await this.getCouponCategoriesId(coupon.productsCategories);
211
+ const couponCategories = await this.getCouponCategoriesId(coupon);
1013
212
  const hasCategories = checkout.lineItems?.filter((i) => {
1014
213
  if (!i.categories || !i.categories?.length)
1015
214
  return true;
1016
- return i.categories.some((c) => couponCategories.some((cat) => cat == c));
215
+ return i.categories.some((c) => couponCategories.some((cat) => cat.id == c || cat.firestoreId == c));
1017
216
  });
1018
217
  return hasCategories.length ? true : false;
1019
218
  }
1020
- coupomUserValidation(coupon, user) {
1021
- if (!user || coupon.exclusivityType.includes(Exclusivities.ALL_USERS))
1022
- return true;
1023
- let userTypes = [];
1024
- if (coupon.exclusivityType.includes(Exclusivities.COLLABORATORS) && this.emailIsFromCollaborator(user.email))
1025
- userTypes.push(Exclusivities.COLLABORATORS);
1026
- if (coupon.exclusivityType.includes(Exclusivities.SPECIFIC_USER) && coupon.userExclusiveEmail.includes(user.email))
1027
- userTypes.push(Exclusivities.SPECIFIC_USER);
1028
- if (coupon.exclusivityType.includes(Exclusivities.ACTIVE_SUBSCRIBER) &&
1029
- user.isSubscriber &&
1030
- user.subscriptionPlan != '')
1031
- userTypes.push(Exclusivities.ACTIVE_SUBSCRIBER);
1032
- if (user.isSubscriber &&
1033
- user.subscriptionPlan == '' &&
1034
- coupon.exclusivityType.includes(Exclusivities.INACTIVE_SUBSCRIBER))
1035
- userTypes.push(Exclusivities.INACTIVE_SUBSCRIBER);
1036
- if (coupon.exclusivityType.includes(Exclusivities.NON_SUBSCRIBER) && !user.isSubscriber)
1037
- userTypes.push(Exclusivities.NON_SUBSCRIBER);
1038
- return coupon.exclusivityType.some((r) => userTypes.includes(r));
1039
- }
1040
- async getCouponCategoriesId(productsCategories) {
1041
- const couponCategories = [];
1042
- for (let index = 0; index < productsCategories.length; index++) {
1043
- const category = await this.categoryRepository.get({
1044
- id: productsCategories[index],
1045
- });
1046
- if (category) {
1047
- const children = await this.categoryRepository.getChildren(parseInt(productsCategories[index]));
1048
- couponCategories.push(category.id, ...children.map((c) => c.id.toString()));
219
+ async userValidationAndSubscriptionStatus(coupon, userEmail) {
220
+ // Verifica se o email do usuário é coorporativo
221
+ if (!this.emailIsFromCollaborator(userEmail) && coupon.exclusivityType === Exclusivities.COLLABORATORS)
222
+ throw new InvalidCouponError('Você não é colaborador.');
223
+ // Verifica se o email do usuário é associado ao cupom de uso por usuario
224
+ if (coupon.exclusivityType === Exclusivities.SPECIFIC_USER && coupon.userExclusiveEmail !== userEmail)
225
+ throw new InvalidCouponError('Cupom não é válido para este usuário.');
226
+ const couponRuleSubscription = coupon.exclusivityType === Exclusivities.ACTIVE_SUBSCRIBER ||
227
+ coupon.exclusivityType === Exclusivities.INACTIVE_SUBSCRIBER ||
228
+ coupon.exclusivityType === Exclusivities.NON_SUBSCRIBER;
229
+ if (couponRuleSubscription && userEmail) {
230
+ const sub = await this.subscriptionRepository
231
+ .find({
232
+ filters: {
233
+ user: {
234
+ email: { operator: Where.EQUALS, value: userEmail },
235
+ },
236
+ },
237
+ })
238
+ .then((sub) => sub.data);
239
+ const activeSubs = sub?.filter((s) => s.status === Status.ACTIVE);
240
+ switch (coupon.exclusivityType) {
241
+ case Exclusivities.ACTIVE_SUBSCRIBER:
242
+ return activeSubs.length > 0;
243
+ case Exclusivities.INACTIVE_SUBSCRIBER:
244
+ return activeSubs.length === 0;
245
+ case Exclusivities.NON_SUBSCRIBER:
246
+ return sub.length === 0;
247
+ default:
248
+ return false;
1049
249
  }
1050
250
  }
1051
- return [...new Set(couponCategories)];
251
+ return true;
1052
252
  }
1053
- async getLineItensEligebleForDiscount(productsCategories, checkout) {
1054
- let lineItensDiscount = [];
1055
- const couponCategories = await this.getCouponCategoriesId(productsCategories);
1056
- if (productsCategories && productsCategories.length) {
1057
- lineItensDiscount = checkout.lineItems?.filter((i) => {
1058
- if (i.categories?.length) {
1059
- return i.categories.some((c) => couponCategories.some((cat) => cat == c));
1060
- }
1061
- return true;
253
+ async getCouponCategoriesId(coupon) {
254
+ let couponCategories = [];
255
+ for (let index = 0; index < coupon.productsCategories.length; index++) {
256
+ let c = await this.categoryRepository.get({
257
+ id: coupon.productsCategories[index],
1062
258
  });
259
+ couponCategories.push({ id: c.id, firestoreId: c.firestoreId });
1063
260
  }
1064
- else {
1065
- lineItensDiscount = checkout.lineItems;
1066
- }
1067
- return lineItensDiscount;
1068
- }
1069
- calcCheckoutSubtotal(lineItens, user, shop) {
1070
- return (lineItens?.reduce((acc, curr) => user?.isSubscriber && curr.price.subscriberPrice
1071
- ? acc + curr.price?.subscriberPrice * curr.quantity
1072
- : acc + curr.pricePaid * curr.quantity, 0) || 0);
1073
- }
1074
- async getOrdersWithCoupon(coupon) {
1075
- return await this.orderRepository
1076
- .find({
1077
- filters: {
1078
- coupon: { id: coupon.id },
1079
- payment: { status: 'paid' },
1080
- },
1081
- })
1082
- .then((result) => result.data);
1083
- }
1084
- countOrdersWithUser(orders, email) {
1085
- return orders.filter((o) => o.user.email == email).length;
1086
- }
1087
- getCouponUseLimits(coupon, checkoutType, user) {
1088
- let couponUseLimits;
1089
- if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
1090
- couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
1091
- }
1092
- else {
1093
- couponUseLimits = coupon.useLimits.subscription;
1094
- }
1095
- return couponUseLimits;
261
+ return couponCategories;
1096
262
  }
1097
263
  }
1098
- 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 });
264
+ 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: 'SubscriptionRepository' }, { token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1099
265
  CouponService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, providedIn: 'root' });
1100
266
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, decorators: [{
1101
267
  type: Injectable,
@@ -1105,12 +271,15 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
1105
271
  }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1106
272
  type: Inject,
1107
273
  args: ['CouponRepository']
1108
- }] }, { type: i1$3.Shops, decorators: [{
274
+ }] }, { type: i2.Shops, decorators: [{
1109
275
  type: Inject,
1110
276
  args: [DEFAULT_SHOP]
1111
277
  }] }, { type: undefined, decorators: [{
1112
278
  type: Inject,
1113
279
  args: ['OrderRepository']
280
+ }] }, { type: undefined, decorators: [{
281
+ type: Inject,
282
+ args: ['SubscriptionRepository']
1114
283
  }] }, { type: undefined, decorators: [{
1115
284
  type: Inject,
1116
285
  args: ['CategoryRepository']
@@ -1147,7 +316,9 @@ class CheckoutService {
1147
316
  return this.getCheckout().pipe(concatMap(async (checkout) => await this.couponService.calcDiscountShopping(coupon, checkout)));
1148
317
  }
1149
318
  checkCoupon(nickname, checkoutType) {
1150
- return this.getCheckout().pipe(concatMap((checkout) => this.couponService.checkCoupon(nickname, CheckoutTypes.ECOMMERCE, checkout, null).pipe()));
319
+ return this.getCheckout().pipe(concatMap((checkout) => this.couponService
320
+ .checkCoupon(nickname, checkout.user?.email, CheckoutTypes.ECOMMERCE, checkout.user.subscriptionPlan, checkout, false)
321
+ .pipe()));
1151
322
  }
1152
323
  async createCheckout(checkoutData) {
1153
324
  const checkout = await this.checkoutRepository.create({
@@ -1172,24 +343,21 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
1172
343
  }] }, { type: undefined, decorators: [{
1173
344
  type: Inject,
1174
345
  args: ['UserRepository']
1175
- }] }, { type: i1$3.Shops, decorators: [{
346
+ }] }, { type: i2.Shops, decorators: [{
1176
347
  type: Inject,
1177
348
  args: [DEFAULT_SHOP]
1178
349
  }] }]; } });
1179
350
 
1180
351
  class CartService {
1181
- constructor(authService, checkoutService, defaultShop, productRepository, categoryRepository, variantRepository, buy2WinRepository) {
352
+ constructor(authService, checkoutService, defaultShop, productRepository) {
1182
353
  this.authService = authService;
1183
354
  this.checkoutService = checkoutService;
1184
355
  this.defaultShop = defaultShop;
1185
356
  this.productRepository = productRepository;
1186
- this.categoryRepository = categoryRepository;
1187
- this.variantRepository = variantRepository;
1188
- this.buy2WinRepository = buy2WinRepository;
1189
357
  this.cartSubject = new Subject();
1190
358
  this.updateLineItemInCart = (lineItem, quantity, checkout) => (isNil(checkout) ? this.checkoutService.getCheckout() : of(checkout)).pipe(concatMap((checkoutLoaded) => {
1191
359
  const items = [];
1192
- const index = checkoutLoaded.lineItems?.map((checkoutItem) => checkoutItem.id).indexOf(lineItem.id);
360
+ const index = checkoutLoaded.lineItems?.map((checkoutItem) => checkoutItem.sku).indexOf(lineItem.sku);
1193
361
  if (index > -1) {
1194
362
  checkoutLoaded.lineItems[index].quantity += quantity;
1195
363
  checkoutLoaded.lineItems[index].pricePaid = lineItem.pricePaid;
@@ -1200,27 +368,27 @@ class CartService {
1200
368
  .updateCheckoutLineItems(checkoutLoaded)
1201
369
  .pipe(map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)));
1202
370
  }));
1203
- this.generateCartObject = (items) => items?.reduce((cart, item) => ({
1204
- ...cart,
1205
- [item.id]: LineItem.toInstance({
1206
- ...(cart[item.id] || item),
1207
- quantity: (cart[item.id]?.quantity || 0) + (item.quantity ? item.quantity : 1),
1208
- }),
1209
- }), {}) || {};
371
+ this.generateCartObject = (items) => {
372
+ const cart = {};
373
+ items?.forEach((item) => (cart[item.sku] = LineItem.toInstance({
374
+ ...(cart[item.sku] || item),
375
+ quantity: (cart[item.sku]?.quantity || 0) + (item.quantity ? item.quantity : 1),
376
+ })));
377
+ return cart;
378
+ };
1210
379
  this.buildLineItem = async ({ checkout, item, quantity, }) => {
1211
- const product = await this.getProductData(item.id);
1212
- item.quantity = item?.quantity || checkout?.lineItems?.find((lineItem) => lineItem.id === item.id)?.quantity || 0;
380
+ const product = await this.productRepository.get({ id: item.id });
381
+ item.quantity = item?.quantity || checkout?.lineItems?.find((lineItem) => lineItem.sku === item.sku)?.quantity || 0;
1213
382
  if (this.checkMaxStock(item, quantity || 0))
1214
383
  throw new Error('Desculpe! Temos apenas ' + item.stock?.quantity + ' em estoque.');
1215
384
  const image = item.image || item.images?.shift();
1216
- const { id, name, EAN, slug, stock, price, weight, sku, type } = item;
385
+ const { id, name, EAN, brand, slug, stock, price, weight, categories, sku, type } = item;
1217
386
  const isGift = item.isGift || null;
1218
387
  const pricePaid = this.getProductPrice({
1219
388
  product: item,
1220
389
  shop: checkout.shop || this.defaultShop,
1221
390
  isSubscriber: checkout.user?.isSubscriber,
1222
391
  });
1223
- RoundProductPricesHelper.roundProductPrices(item);
1224
392
  return {
1225
393
  checkout,
1226
394
  lineItem: LineItem.toInstance({
@@ -1231,7 +399,7 @@ class CartService {
1231
399
  slug: slug ?? product.slug,
1232
400
  sku: sku ?? product.sku,
1233
401
  stock,
1234
- price: this.roundPrice(price),
402
+ price,
1235
403
  image,
1236
404
  weight: weight ?? product.weight,
1237
405
  quantity: (item.quantity || 0) + (quantity || 0),
@@ -1247,9 +415,7 @@ class CartService {
1247
415
  const info = product.price;
1248
416
  if (product.isGift)
1249
417
  return 0;
1250
- return isSubscriber && info.subscriberPrice > 0
1251
- ? Number(info.subscriberPrice.toFixed(2))
1252
- : Number(info.price.toFixed(2));
418
+ return isSubscriber && info.subscriberPrice > 0 ? info.subscriberPrice : info.price;
1253
419
  };
1254
420
  this.checkMaxStock = (item, quantity) => {
1255
421
  const maxStock = item.stock?.quantity || 0;
@@ -1262,7 +428,7 @@ class CartService {
1262
428
  }
1263
429
  decreaseItem(item) {
1264
430
  return this.checkoutService.getCheckout().pipe(map((checkout) => {
1265
- const checkoutItem = checkout.lineItems?.find((lineItem) => lineItem.id === item.id);
431
+ const checkoutItem = checkout.lineItems?.find((lineItem) => lineItem.sku === item.sku);
1266
432
  if (!isNil(checkoutItem))
1267
433
  checkoutItem.quantity -= checkoutItem.quantity > 1 ? 1 : 0;
1268
434
  return checkout;
@@ -1280,526 +446,39 @@ class CartService {
1280
446
  }
1281
447
  removeItem(item) {
1282
448
  return this.checkoutService.getCheckout().pipe(map((checkout) => {
1283
- const index = checkout.lineItems.findIndex((lineItem) => lineItem.id === item.id);
449
+ const index = checkout.lineItems.findIndex((lineItem) => lineItem.sku === item.sku);
1284
450
  if (index >= 0)
1285
451
  checkout.lineItems.splice(index, 1);
1286
- return checkout;
1287
- }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1288
- }
1289
- updateUserCart(user) {
1290
- return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user }))), concatMap(async (checkout) => this.checkoutService
1291
- .updateCheckoutLineItems(Checkout.toInstance({
1292
- ...checkout.toPlain(),
1293
- lineItems: checkout.lineItems?.length
1294
- ? await Promise.all(checkout.lineItems?.map(async (item) => (await this.buildLineItem({ checkout, item })).lineItem))
1295
- : [],
1296
- }))
1297
- .toPromise()), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1298
- }
1299
- clearCart() {
1300
- return this.checkoutService.getCheckout().pipe(map((checkout) => {
1301
- this.checkoutService.clearCheckoutFromSession();
1302
- return checkout;
1303
- }), concatMap((oldCheckout) => this.buildCartFromCheckout(oldCheckout)), tap((cart) => this.cartSubject.next(cart)));
1304
- }
1305
- buildCartFromCheckout(checkoutData) {
1306
- return this.checkoutService.getCheckout(checkoutData).pipe(map((checkout) => checkout.lineItems), concatMap((lineItems) => of(this.generateCartObject(lineItems))));
1307
- }
1308
- roundPrice(productPrice) {
1309
- const { price, fullPrice, subscriberPrice } = productPrice;
1310
- return {
1311
- ...productPrice,
1312
- price: Number(price.toFixed(2)),
1313
- fullPrice: Number(fullPrice.toFixed(2)),
1314
- ...(subscriberPrice && { subscriberPrice: Number(subscriberPrice.toFixed(2)) }),
1315
- };
1316
- }
1317
- async getProductData(productId) {
1318
- let product;
1319
- let variant;
1320
- try {
1321
- product = await this.productRepository.get({ id: productId });
1322
- }
1323
- catch (error) {
1324
- if (!(error instanceof NotFoundError))
1325
- throw error;
1326
- const { data: variants } = await this.variantRepository.find({ filters: { id: productId } });
1327
- variant = variants.shift();
1328
- if (!variant)
1329
- throw error;
1330
- product = await this.productRepository.get({ id: variant.productId });
1331
- }
1332
- return {
1333
- ...product.toPlain(),
1334
- ...(variant && { ...variant.toPlain() }),
1335
- };
1336
- }
1337
- getGifts() {
1338
- return this.checkoutService.getCheckout().pipe(mergeMap(async (checkout) => {
1339
- const notGiftItems = checkout.lineItems ? checkout.lineItems.filter((item) => !item.isGift) : [];
1340
- if (!notGiftItems.length)
1341
- return { ...checkout, lineItems: [] };
1342
- const cartTotal = notGiftItems.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1343
- const campaigns = await this.buy2WinRepository
1344
- .find({
1345
- filters: {
1346
- active: { operator: Where.EQUALS, value: true },
1347
- shop: { operator: Where.EQUALS, value: this.defaultShop },
1348
- },
1349
- })
1350
- .then((data) => data.data);
1351
- if (!campaigns.length)
1352
- return { ...checkout, lineItems: notGiftItems };
1353
- const elegibleCampaigns = [];
1354
- for (const campaign of campaigns) {
1355
- const today = new Date().getDate();
1356
- if (!(campaign.startDate.getDate() <= today) && !(campaign.endDate.getDate() >= today))
1357
- continue;
1358
- if (campaign.activeCategory) {
1359
- const categoriesCampaing = campaign.categories.map((c) => c.id.toString());
1360
- const categoriesCampaingFullTree = [];
1361
- for (const id of categoriesCampaing) {
1362
- const children = await this.categoryRepository.getChildren(parseInt(id));
1363
- categoriesCampaingFullTree.push(id, ...children.map((c) => c.id.toString()));
1364
- }
1365
- const categoriesCampaingTree = [...new Set(categoriesCampaingFullTree)];
1366
- const filterProductsCategories = checkout.lineItems.filter((l) => {
1367
- if (!l.categories || !l.categories?.length)
1368
- return true;
1369
- return l.categories.some((c) => categoriesCampaingTree.some((cat) => cat == c));
1370
- });
1371
- if (filterProductsCategories.length) {
1372
- const cartTotalCategories = filterProductsCategories.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1373
- if (cartTotalCategories >= campaign.cartValueMin)
1374
- elegibleCampaigns.push(campaign);
1375
- }
1376
- }
1377
- else {
1378
- if (campaign.cartValue && campaign.cartValue > 0) {
1379
- if (campaign.cartValue <= cartTotal)
1380
- elegibleCampaigns.push(campaign);
1381
- }
1382
- }
1383
- }
1384
- if (!elegibleCampaigns.length)
1385
- return { ...checkout, lineItems: notGiftItems };
1386
- const campaingnProducts = [];
1387
- for (const campaign of elegibleCampaigns) {
1388
- let elegibleProducts = [];
1389
- for (const product of campaign.products) {
1390
- const { data: productData } = await this.productRepository.find({ filters: { sku: product } });
1391
- if (!productData.length)
1392
- continue;
1393
- const gift = productData.shift();
1394
- if (gift.stock.quantity < 1)
1395
- continue;
1396
- elegibleProducts.push(gift);
1397
- }
1398
- campaingnProducts.push(elegibleProducts);
1399
- }
1400
- if (!campaingnProducts.length)
1401
- return { ...checkout, lineItems: notGiftItems };
1402
- const gifts = this.giftToLineItems([].concat(...campaingnProducts));
1403
- return { ...checkout, lineItems: notGiftItems.concat(gifts) };
1404
- }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1405
- }
1406
- giftToLineItems(items) {
1407
- return items.map((item) => {
1408
- const { brand, categories, id, name, price, sku, slug, stock, weight, EAN } = item;
1409
- const image = item?.miniatures?.length ? item.miniatures[0] : item.images[0];
1410
- return LineItem.toInstance({
1411
- brand,
1412
- categories,
1413
- id: id.toString(),
1414
- name,
1415
- price,
1416
- sku,
1417
- slug,
1418
- stock,
1419
- weight,
1420
- EAN,
1421
- image,
1422
- pricePaid: 0,
1423
- quantity: 1,
1424
- isGift: true,
1425
- });
1426
- });
1427
- }
1428
- }
1429
- 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 });
1430
- CartService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService });
1431
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService, decorators: [{
1432
- type: Injectable
1433
- }], ctorParameters: function () { return [{ type: AuthService }, { type: CheckoutService }, { type: i1$3.Shops, decorators: [{
1434
- type: Inject,
1435
- args: [DEFAULT_SHOP]
1436
- }] }, { type: undefined, decorators: [{
1437
- type: Inject,
1438
- args: ['ProductRepository']
1439
- }] }, { type: undefined, decorators: [{
1440
- type: Inject,
1441
- args: ['CategoryRepository']
1442
- }] }, { type: undefined, decorators: [{
1443
- type: Inject,
1444
- args: ['VariantRepository']
1445
- }] }, { type: i1$3.Buy2WinFirestoreRepository, decorators: [{
1446
- type: Inject,
1447
- args: ['Buy2WinRepository']
1448
- }] }]; } });
1449
-
1450
- class CatalogService {
1451
- constructor(productRepository, categoryStructureAdapter, shop, productIndex) {
1452
- this.productRepository = productRepository;
1453
- this.categoryStructureAdapter = categoryStructureAdapter;
1454
- this.shop = shop;
1455
- this.productIndex = productIndex;
1456
- this.buildFilterQuery = ({ clubDiscount, brands, prices, gender, tags, rate, customOptions, }) => {
1457
- const filters = {};
1458
- if (clubDiscount?.length)
1459
- set(filters, 'price.subscriberDiscountPercentage', { operator: Where.IN, value: clubDiscount });
1460
- if (brands?.length)
1461
- filters.brand = { operator: Where.IN, value: brands };
1462
- if (gender?.length)
1463
- filters.gender = { operator: Where.IN, value: gender };
1464
- if (prices?.min || prices?.max)
1465
- set(filters, prices.subscriberPrice ? 'price.subscriberPrice' : 'price.price', [
1466
- ...(prices.min ? [{ operator: Where.GTE, value: Math.round(prices.min) }] : []),
1467
- ...(prices.max ? [{ operator: Where.LTE, value: Math.ceil(prices.max) }] : []),
1468
- ]);
1469
- if (rate)
1470
- filters.rate = { operator: Where.GTE, value: rate };
1471
- if (tags?.length)
1472
- filters.tags = { operator: Where.LIKE, value: tags };
1473
- if (customOptions?.length)
1474
- filters.filters = { operator: Where.LIKE, value: customOptions };
1475
- return filters;
1476
- };
1477
- this.buildSortQuery = (sort) => {
1478
- if (!sort || sort === 'most-relevant')
1479
- return {};
1480
- if (sort === 'best-sellers')
1481
- return { shoppingCount: 'desc' };
1482
- if (sort === 'biggest-price')
1483
- return { subscriberPrice: 'desc' };
1484
- if (sort === 'lowest-price')
1485
- return { subscriberPrice: 'asc' };
1486
- if (sort === 'best-rating')
1487
- return { rate: 'desc' };
1488
- if (sort === 'news')
1489
- return { createdAt: 'desc' };
1490
- };
1491
- this.buildLimitQuery = (options) => {
1492
- const limit = options?.perPage || 20;
1493
- return {
1494
- limit,
1495
- offset: ((options?.page || 1) - 1) * limit,
1496
- };
1497
- };
1498
- this.hasProfile = (options) => 'profile' in options;
1499
- this.hasTerm = (options) => 'term' in options;
1500
- this.hasCategory = (options) => 'category' in options;
1501
- }
1502
- async fetchProducts(options) {
1503
- const limits = this.buildLimitQuery(options);
1504
- if (this.hasProfile(options) && options.filters?.customOptions)
1505
- throw new InvalidArgumentError(`It couldn't filled customOptions when profile is given`);
1506
- if (this.hasProfile(options) && options.filters?.tags)
1507
- throw new InvalidArgumentError(`It couldn't filled tags when profile is given`);
1508
- if (this.hasTerm(options) && options.filters?.customOptions)
1509
- throw new InvalidArgumentError(`It couldn't filled customOptions when term is given`);
1510
- return await this.findCatalog(options, limits).then(({ data, count: total, maximum, minimal, distinct }) => ({
1511
- products: { data: data.map((product) => RoundProductPricesHelper.roundProductPrices(product)), total },
1512
- pages: Math.ceil(total / limits.limit),
1513
- prices: {
1514
- price: { min: +minimal?.price?.price?.toFixed(2), max: +maximum?.price?.price?.toFixed(2) },
1515
- subscriberPrice: {
1516
- min: +minimal?.price?.subscriberPrice?.toFixed(2),
1517
- max: +maximum?.price?.subscriberPrice?.toFixed(2),
1518
- },
1519
- },
1520
- brands: distinct?.brand,
1521
- }));
1522
- }
1523
- async findCatalog(options, limits) {
1524
- const repoParams = {
1525
- filters: {
1526
- ...(await this.buildMainFilter(options)),
1527
- ...this.buildFilterQuery(options?.filters || {}),
1528
- },
1529
- ...(options?.sort ? { orderBy: this.buildSortQuery(options?.sort) } : {}),
1530
- limits,
1531
- options: {
1532
- minimal: ['price'],
1533
- maximum: ['price'],
1534
- ...(!this.hasCategory(options) ? { distinct: ['brand'] } : {}),
1535
- },
1536
- };
1537
- if (['biggest-price', 'lowest-price', 'biggest-discount', 'best-rating'].includes(options.sort))
1538
- return this.productRepository.findCatalog(repoParams);
1539
- return this.productRepository.findCatalog(repoParams, options?.mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female');
1540
- }
1541
- async buildMainFilter({ category, profile, term, }) {
1542
- if (category)
1543
- return this.categoryStructureAdapter.buildProductFilterByCategory(category);
1544
- if (profile)
1545
- return { tags: { operator: Where.LIKE, value: profile } };
1546
- if (term)
1547
- return this.productIndex
1548
- .search(term, 9999, this.shop)
1549
- .then((data) => ({ id: { operator: Where.IN, value: data.hits.map(({ _source }) => _source.id) } }));
1550
- }
1551
- }
1552
- CatalogService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService, deps: [{ token: 'ProductRepository' }, { token: CATEGORY_STRUCTURE }, { token: DEFAULT_SHOP }, { token: i1$3.ProductsIndex }], target: i0.ɵɵFactoryTarget.Injectable });
1553
- CatalogService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService });
1554
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService, decorators: [{
1555
- type: Injectable
1556
- }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1557
- type: Inject,
1558
- args: ['ProductRepository']
1559
- }] }, { type: undefined, decorators: [{
1560
- type: Inject,
1561
- args: [CATEGORY_STRUCTURE]
1562
- }] }, { type: i1$3.Shops, decorators: [{
1563
- type: Inject,
1564
- args: [DEFAULT_SHOP]
1565
- }] }, { type: i1$3.ProductsIndex }]; } });
1566
-
1567
- class CategoryService {
1568
- constructor(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop) {
1569
- this.productRepository = productRepository;
1570
- this.categoryRepository = categoryRepository;
1571
- this.categoryFilterRepository = categoryFilterRepository;
1572
- this.categoryStructureAdapter = categoryStructureAdapter;
1573
- this.shop = shop;
1574
- }
1575
- async fetchBrands(category, mainGender) {
1576
- const brands = await this.productRepository
1577
- .findCatalog({
1578
- filters: await this.categoryStructureAdapter.buildProductFilterByCategory(category),
1579
- fields: ['brand'],
1580
- }, mainGender || this.shop === Shops.MENSMARKET ? 'male' : 'female')
1581
- .then(({ data }) => Object.keys(data.map((product) => product.brand).reduce((brands, brand) => ({ ...brands, [brand]: true }), {})));
1582
- return this.categoryRepository
1583
- .find({ filters: { brandCategory: true }, orderBy: { name: 'asc' } })
1584
- .then(({ data }) => data.filter((category) => brands.includes(category.conditions.brand)));
1585
- }
1586
- async fetchFilterOptions(category, filters) {
1587
- return await this.categoryFilterRepository
1588
- .find({ filters: { categoryId: +category.id } })
1589
- .then(({ data }) => data.map((categoryFilter) => categoryFilter.filter));
1590
- }
1591
- }
1592
- 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 });
1593
- CategoryService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CategoryService });
1594
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CategoryService, decorators: [{
1595
- type: Injectable
1596
- }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1597
- type: Inject,
1598
- args: ['ProductRepository']
1599
- }] }, { type: undefined, decorators: [{
1600
- type: Inject,
1601
- args: ['CategoryRepository']
1602
- }] }, { type: undefined, decorators: [{
1603
- type: Inject,
1604
- args: ['CategoryFilterRepository']
1605
- }] }, { type: undefined, decorators: [{
1606
- type: Inject,
1607
- args: [CATEGORY_STRUCTURE]
1608
- }] }, { type: i1$3.Shops, decorators: [{
1609
- type: Inject,
1610
- args: [DEFAULT_SHOP]
1611
- }] }]; } });
1612
-
1613
- var ProductSorts;
1614
- (function (ProductSorts) {
1615
- ProductSorts["MOST_RELEVANT"] = "most-relevant";
1616
- ProductSorts["BEST_SELLER"] = "best-sellers";
1617
- ProductSorts["BIGGEST_PRICE"] = "biggest-price";
1618
- ProductSorts["LOWEST_PRICE"] = "lowest-price";
1619
- ProductSorts["BIGGEST_DISCOUNT"] = "biggest-discount";
1620
- ProductSorts["BEST_RATING"] = "best-rating";
1621
- ProductSorts["NEWS"] = "news";
1622
- })(ProductSorts || (ProductSorts = {}));
1623
-
1624
- class CategoryWithTree extends Category {
1625
- }
1626
- __decorate([
1627
- Type(() => CategoryWithTree),
1628
- __metadata("design:type", Array)
1629
- ], CategoryWithTree.prototype, "children", void 0);
1630
-
1631
- class UtilHelper {
1632
- static createSlug(name) {
1633
- return name
1634
- .toLowerCase()
1635
- .replace(/\s+/g, '-') // Replace spaces with -
1636
- .replace(/[ãàáäâ]/g, 'a') // Replace spaces with -
1637
- .replace(/[ẽèéëê]/g, 'e') // Replace spaces with -
1638
- .replace(/[ìíïî]/g, 'i') // Replace spaces with -
1639
- .replace(/[õòóöô]/g, 'o') // Replace spaces with -
1640
- .replace(/[ùúüû]/g, 'u') // Replace spaces with -
1641
- .replace(/[ñ]/g, 'n') // Replace spaces with -
1642
- .replace(/[ç]/g, 'c') // Replace spaces with -
1643
- .replace(/[&]/g, 'and') // Replace spaces with -
1644
- .replace(/[^\w\-]+/g, '') // Remove all non-word chars
1645
- .replace(/\-\-+/g, '-'); // Replace multiple - with single -
1646
- }
1647
- }
1648
-
1649
- class NewCategoryStructureAdapter {
1650
- constructor(categoryRepository, categoryCollectionChildrenRepository) {
1651
- this.categoryRepository = categoryRepository;
1652
- this.categoryCollectionChildrenRepository = categoryCollectionChildrenRepository;
1653
- }
1654
- async buildProductFilterByCategory(category) {
1655
- const categoriesIds = (await this.isCollection(category))
1656
- ? await this.getAllCategoriesIdFromCollection(category)
1657
- : [...(await this.getAllCategoriesIdFromCategory(category)), category.id.toString()];
1658
- return { category: { id: { operator: Where.IN, value: categoriesIds } } };
1659
- }
1660
- async getAllCategoriesIdFromCategory(category) {
1661
- return this.categoryRepository
1662
- .getChildren(+category.id)
1663
- .then((categories) => categories.map((category) => category.id.toString()));
1664
- }
1665
- async getAllCategoriesIdFromCollection(category) {
1666
- return this.categoryCollectionChildrenRepository
1667
- .find({ filters: { collectionId: +category.id } })
1668
- .then(({ data }) => data.map((categoryCollection) => categoryCollection.categoryId.toString()));
1669
- }
1670
- async isCollection(category) {
1671
- return !isNil(category.isCollection)
1672
- ? category.isCollection
1673
- : this.categoryRepository.get({ id: category.id }).then((category) => category.isCollection);
1674
- }
1675
- }
1676
- NewCategoryStructureAdapter.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: NewCategoryStructureAdapter, deps: [{ token: 'CategoryRepository' }, { token: 'CategoryCollectionChildrenRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1677
- NewCategoryStructureAdapter.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: NewCategoryStructureAdapter });
1678
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: NewCategoryStructureAdapter, decorators: [{
1679
- type: Injectable
1680
- }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1681
- type: Inject,
1682
- args: ['CategoryRepository']
1683
- }] }, { type: undefined, decorators: [{
1684
- type: Inject,
1685
- args: ['CategoryCollectionChildrenRepository']
1686
- }] }]; } });
1687
-
1688
- class OldCategoryStructureAdapter {
1689
- constructor(categoryRepository) {
1690
- this.categoryRepository = categoryRepository;
1691
- }
1692
- async buildProductFilterByCategory(category) {
1693
- const productsIds = category.products?.length
1694
- ? category.products
1695
- : await this.categoryRepository.get({ id: category.id }).then((categoryFound) => categoryFound.products);
1696
- return { id: { operator: Where.IN, value: productsIds } };
1697
- }
1698
- }
1699
- OldCategoryStructureAdapter.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OldCategoryStructureAdapter, deps: [{ token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1700
- OldCategoryStructureAdapter.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OldCategoryStructureAdapter });
1701
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OldCategoryStructureAdapter, decorators: [{
1702
- type: Injectable
1703
- }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1704
- type: Inject,
1705
- args: ['CategoryRepository']
1706
- }] }]; } });
1707
-
1708
- class WishlistService {
1709
- constructor(wishlistRepository, shop, productRepository, categoryFilterRepository, categoryCollectionChildrenRepository, productIndex) {
1710
- this.wishlistRepository = wishlistRepository;
1711
- this.shop = shop;
1712
- const categoryStructureAdapter = new NewCategoryStructureAdapter(wishlistRepository, categoryCollectionChildrenRepository);
1713
- this.catalogService = new CatalogService(productRepository, categoryStructureAdapter, shop, productIndex);
1714
- this.categoryService = new CategoryService(productRepository, wishlistRepository, categoryFilterRepository, categoryStructureAdapter, shop);
1715
- }
1716
- getCatalogService() {
1717
- return this.catalogService;
1718
- }
1719
- getCategoryService() {
1720
- return this.categoryService;
1721
- }
1722
- async create(personId, title, description, userFullName) {
1723
- const data = {
1724
- slug: UtilHelper.createSlug(`favoritos ${userFullName} ${title}`),
1725
- name: title,
1726
- description,
1727
- metadata: {
1728
- title: `${userFullName} - ${title}`,
1729
- description: `${userFullName} - ${description}`,
1730
- },
1731
- shop: this.shop,
1732
- shops: [this.shop],
1733
- personId,
1734
- brandCategory: false,
1735
- published: true,
1736
- };
1737
- const newWishlist = await this.wishlistRepository.create(data);
1738
- return this.wishlistRepository.update({ id: newWishlist.id, slug: `${newWishlist.id}-${newWishlist.slug}` });
1739
- }
1740
- update(id, title, description, userFullName) {
1741
- const data = {
1742
- id,
1743
- slug: UtilHelper.createSlug(`${id}-favoritos ${userFullName} ${title}`),
1744
- name: title,
1745
- description,
1746
- metadata: {
1747
- title: `${userFullName} - ${title}`,
1748
- description: `${userFullName} - ${description}`,
1749
- },
1750
- };
1751
- return this.wishlistRepository.update(data);
1752
- }
1753
- delete(wishlistId) {
1754
- return this.wishlistRepository.delete({ id: wishlistId });
1755
- }
1756
- getWishlistBySlug(slug) {
1757
- return this.wishlistRepository.getWishlistBySlug(slug);
452
+ return checkout;
453
+ }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1758
454
  }
1759
- getWishlistsByPerson(personId) {
1760
- return this.wishlistRepository.getWishlistByPerson(personId);
455
+ updateUserCart(user) {
456
+ return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user }))), concatMap(async (checkout) => this.checkoutService.updateCheckoutLineItems(Checkout.toInstance({
457
+ ...checkout.toPlain(),
458
+ lineItems: checkout.lineItems?.length ? await Promise.all(checkout.lineItems?.map(async (item) => (await this.buildLineItem({ checkout, item })).lineItem)) : [],
459
+ })).toPromise()), map(checkout => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1761
460
  }
1762
- async addProduct(wishlistId, productId) {
1763
- const wishlist = await this.wishlistRepository.get({ id: wishlistId });
1764
- const hasProduct = wishlist.products.some((p) => p == productId);
1765
- if (!hasProduct) {
1766
- wishlist.products = [...wishlist.products, productId];
1767
- return this.wishlistRepository.update({ id: wishlistId, products: wishlist.products });
1768
- }
1769
- return wishlist;
461
+ clearCart() {
462
+ return this.checkoutService.getCheckout().pipe(map((checkout) => {
463
+ this.checkoutService.clearCheckoutFromSession();
464
+ return checkout;
465
+ }), concatMap((oldCheckout) => this.buildCartFromCheckout(oldCheckout)), tap((cart) => this.cartSubject.next(cart)));
1770
466
  }
1771
- async removeProduct(wishlistId, productId) {
1772
- const wishlist = await this.wishlistRepository.get({ id: wishlistId });
1773
- const productIndex = wishlist.products.findIndex((p) => p == productId);
1774
- if (productIndex != -1) {
1775
- wishlist.products.splice(productIndex, 1);
1776
- if (!wishlist.products.length)
1777
- return this.wishlistRepository.update({ id: wishlistId, products: { action: 'remove' } });
1778
- return this.wishlistRepository.update({ id: wishlistId, products: wishlist.products });
1779
- }
1780
- return wishlist;
467
+ buildCartFromCheckout(checkoutData) {
468
+ return this.checkoutService.getCheckout(checkoutData).pipe(map((checkout) => checkout.lineItems), concatMap((lineItems) => of(this.generateCartObject(lineItems))));
1781
469
  }
1782
470
  }
1783
- 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: 'CategoryCollectionChildrenRepository' }, { token: i1$3.ProductsIndex }], target: i0.ɵɵFactoryTarget.Injectable });
1784
- WishlistService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService });
1785
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService, decorators: [{
471
+ 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' }], target: i0.ɵɵFactoryTarget.Injectable });
472
+ CartService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService });
473
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService, decorators: [{
1786
474
  type: Injectable
1787
- }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1788
- type: Inject,
1789
- args: ['WishlistRepository']
1790
- }] }, { type: i1$3.Shops, decorators: [{
475
+ }], ctorParameters: function () { return [{ type: AuthService }, { type: CheckoutService }, { type: i2.Shops, decorators: [{
1791
476
  type: Inject,
1792
477
  args: [DEFAULT_SHOP]
1793
478
  }] }, { type: undefined, decorators: [{
1794
479
  type: Inject,
1795
480
  args: ['ProductRepository']
1796
- }] }, { type: undefined, decorators: [{
1797
- type: Inject,
1798
- args: ['CategoryFilterRepository']
1799
- }] }, { type: undefined, decorators: [{
1800
- type: Inject,
1801
- args: ['CategoryCollectionChildrenRepository']
1802
- }] }, { type: i1$3.ProductsIndex }]; } });
481
+ }] }]; } });
1803
482
 
1804
483
  class CheckoutSubscriptionService {
1805
484
  constructor(checkoutSubscriptionRepository, subscriptionRepository, couponService) {
@@ -1826,9 +505,7 @@ class CheckoutSubscriptionService {
1826
505
  return of();
1827
506
  }
1828
507
  checkCoupon(nickname, userEmail) {
1829
- return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService
1830
- .checkCoupon(nickname, CheckoutTypes.SUBSCRIPTION, checkout, checkout.subscriptionPlan.name)
1831
- .pipe()));
508
+ return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService.checkCoupon(nickname, userEmail, CheckoutTypes.SUBSCRIPTION, checkout.subscriptionPlan.name, null, true).pipe()));
1832
509
  }
1833
510
  calcDiscountSubscription(coupon) {
1834
511
  return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService.calcDiscountSubscription(coupon, checkout).pipe()));
@@ -1846,273 +523,809 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
1846
523
  args: ['SubscriptionRepository']
1847
524
  }] }, { type: CouponService }]; } });
1848
525
 
1849
- class HomeShopService {
1850
- constructor(categoryRepository, homeRepository, productRepository, defaultShop) {
1851
- this.categoryRepository = categoryRepository;
1852
- this.homeRepository = homeRepository;
1853
- this.productRepository = productRepository;
1854
- this.defaultShop = defaultShop;
1855
- this.buildCategoryGroupWithRequiredData = (group) => ({
1856
- category: Category.toInstance(pick(group?.category?.toPlain() || {}, ['id', 'name', 'slug', 'conditions'])),
1857
- products: group?.products?.map((product) => Product.toInstance(pick(product?.toPlain() || {}, [
1858
- 'id',
1859
- 'price',
1860
- 'reviews',
1861
- 'hasVariants',
1862
- 'slug',
1863
- 'sku',
1864
- 'stock',
1865
- 'costPrice',
1866
- 'images',
1867
- 'miniatures',
1868
- 'name',
1869
- 'weight',
1870
- 'rate',
1871
- 'type',
1872
- ]))) || [],
1873
- });
1874
- }
1875
- get homeId() {
1876
- if (this.defaultShop === Shops.GLAMSHOP)
1877
- return 'glamshop';
1878
- if (this.defaultShop === Shops.MENSMARKET)
1879
- return 'mens_market';
1880
- return null;
1881
- }
1882
- getHomeData() {
1883
- return this.getHomeConfiguration().pipe(map((home) => (home?.data?.expiresAt > new Date() ? home : null)), concatMap((home) => home
1884
- ? of(home)
1885
- : forkJoin([this.getDiscoverProducts(), this.getFeaturedProducts(), this.getVerticalProducts()]).pipe(map(([discoverProducts, featuredProducts, verticalProducts]) => ({
1886
- discoverProducts,
1887
- featuredProducts,
1888
- verticalProducts,
1889
- })), concatMap((data) => this.saveHomeData(data)))));
1890
- }
1891
- getBanners(type) {
1892
- return this.getHomeConfiguration().pipe(map((home) => {
1893
- if (type === 'brand')
1894
- return home.brandsCarousel;
1895
- if (type === 'buyToWin')
1896
- return [home.buyToWinBanner];
1897
- if (type === 'block')
1898
- return home.blockBanners;
1899
- if (type === 'blog')
1900
- return [home.blogBanner];
1901
- return [];
1902
- }));
1903
- }
1904
- getMinValueForFreeShipping() {
1905
- return this.getHomeConfiguration().pipe(map((home) => home.minValueForFreeShipping));
1906
- }
1907
- getDiscoverProducts() {
1908
- return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.discoverCategories)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
1909
- }
1910
- getFeaturedProducts() {
1911
- return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.featuredCategories)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
1912
- }
1913
- getVerticalProducts() {
1914
- 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({
1915
- filters: { categories: { operator: Where.IN, value: [category.id] } },
1916
- limits: { limit: 12 },
1917
- })).pipe(map((products) => ({ category, products })))), map(({ category, products }) => ({ category, products: products.data })), map(this.buildCategoryGroupWithRequiredData))))));
1918
- }
1919
- getHomeConfiguration() {
1920
- return of(this.homeConfiguration).pipe(concatMap((home) => home
1921
- ? of(home)
1922
- : !this.homeId
1923
- ? throwError(new RequiredArgumentError(['homeId']))
1924
- : from(this.homeRepository.get({ id: this.homeId })).pipe(tap((homeLoaded) => (this.homeConfiguration = homeLoaded)))));
1925
- }
1926
- saveHomeData(homeData) {
1927
- const data = {
1928
- createdAt: new Date(),
1929
- expiresAt: add(new Date(), { hours: 1 }),
1930
- data: homeData,
526
+ class OrderService {
527
+ constructor(angularFirestore, orderRepository) {
528
+ this.angularFirestore = angularFirestore;
529
+ this.orderRepository = orderRepository;
530
+ this.orderSubject = new Subject();
531
+ }
532
+ getOrder(id) {
533
+ docSnapshots(doc(this.angularFirestore, `${this.orderRepository.collectionName}/${id}`))
534
+ .pipe(map((doc) => Order.toInstance(doc.data())))
535
+ .subscribe((doc) => this.orderSubject.next(doc));
536
+ return this.orderSubject;
537
+ }
538
+ }
539
+ 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 });
540
+ OrderService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService });
541
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService, decorators: [{
542
+ type: Injectable
543
+ }], ctorParameters: function () { return [{ type: i1$1.Firestore }, { type: i2.OrderFirestoreRepository, decorators: [{
544
+ type: Inject,
545
+ args: ['OrderRepository']
546
+ }] }]; } });
547
+
548
+ class HomeShopService {
549
+ constructor(categoryRepository, homeRepository, productRepository, defaultShop) {
550
+ this.categoryRepository = categoryRepository;
551
+ this.homeRepository = homeRepository;
552
+ this.productRepository = productRepository;
553
+ this.defaultShop = defaultShop;
554
+ this.buildCategoryGroupWithRequiredData = (group) => ({
555
+ category: Category.toInstance(pick(group?.category?.toPlain() || {}, ['id', 'name', 'slug', 'conditions'])),
556
+ products: group?.products?.map((product) => Product.toInstance(pick(product?.toPlain() || {}, [
557
+ 'id',
558
+ 'price',
559
+ 'reviews',
560
+ 'hasVariants',
561
+ 'slug',
562
+ 'sku',
563
+ 'stock',
564
+ 'costPrice',
565
+ 'images',
566
+ 'miniatures',
567
+ 'name',
568
+ 'weight',
569
+ 'rate',
570
+ 'type',
571
+ ]))) || [],
572
+ });
573
+ }
574
+ get homeId() {
575
+ if (this.defaultShop === Shops.GLAMSHOP)
576
+ return 'glamshop';
577
+ if (this.defaultShop === Shops.MENSMARKET)
578
+ return 'mens_market';
579
+ return null;
580
+ }
581
+ getHomeData() {
582
+ return this.getHomeConfiguration().pipe(map((home) => (home?.data?.expiresAt > new Date() ? home : null)), concatMap((home) => home
583
+ ? of(home)
584
+ : forkJoin([this.getDiscoverProducts(), this.getFeaturedProducts(), this.getVerticalProducts()]).pipe(map(([discoverProducts, featuredProducts, verticalProducts]) => ({
585
+ discoverProducts,
586
+ featuredProducts,
587
+ verticalProducts,
588
+ })), concatMap((data) => this.saveHomeData(data)))));
589
+ }
590
+ getBanners(type) {
591
+ return this.getHomeConfiguration().pipe(map((home) => {
592
+ if (type === 'brand')
593
+ return home.brandsCarousel;
594
+ if (type === 'buyToWin')
595
+ return [home.buyToWinBanner];
596
+ if (type === 'block')
597
+ return home.blockBanners;
598
+ if (type === 'blog')
599
+ return [home.blogBanner];
600
+ return [];
601
+ }));
602
+ }
603
+ getMinValueForFreeShipping() {
604
+ return this.getHomeConfiguration().pipe(map((home) => home.minValueForFreeShipping));
605
+ }
606
+ getDiscoverProducts() {
607
+ return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.discoverCategories)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
608
+ }
609
+ getFeaturedProducts() {
610
+ return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.featuredCategories)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
611
+ }
612
+ getVerticalProducts() {
613
+ 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({
614
+ filters: { categories: { operator: Where.IN, value: [category.id] } },
615
+ limits: { limit: 12 },
616
+ })).pipe(map((products) => ({ category, products })))), map(({ category, products }) => ({ category, products: products.data })), map(this.buildCategoryGroupWithRequiredData))))));
617
+ }
618
+ getHomeConfiguration() {
619
+ return of(this.homeConfiguration).pipe(concatMap((home) => home
620
+ ? of(home)
621
+ : !this.homeId
622
+ ? throwError(new RequiredArgumentError(['homeId']))
623
+ : from(this.homeRepository.get({ id: this.homeId })).pipe(tap((homeLoaded) => (this.homeConfiguration = homeLoaded)))));
624
+ }
625
+ saveHomeData(homeData) {
626
+ const data = {
627
+ createdAt: new Date(),
628
+ expiresAt: add(new Date(), { hours: 1 }),
629
+ data: homeData,
630
+ };
631
+ return from(this.homeRepository.update({
632
+ id: this.homeId,
633
+ data,
634
+ })).pipe(tap(() => (this.homeConfiguration.data = data)), map(() => this.homeConfiguration));
635
+ }
636
+ }
637
+ 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 });
638
+ HomeShopService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService });
639
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService, decorators: [{
640
+ type: Injectable
641
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
642
+ type: Inject,
643
+ args: ['CategoryRepository']
644
+ }] }, { type: undefined, decorators: [{
645
+ type: Inject,
646
+ args: ['HomeRepository']
647
+ }] }, { type: undefined, decorators: [{
648
+ type: Inject,
649
+ args: ['ProductRepository']
650
+ }] }, { type: i2.Shops, decorators: [{
651
+ type: Inject,
652
+ args: [DEFAULT_SHOP]
653
+ }] }]; } });
654
+
655
+ class AngularFirebaseAuthModule {
656
+ static initializeApp(options, nameOrConfig) {
657
+ return {
658
+ ngModule: AngularFirebaseAuthModule,
659
+ providers: [
660
+ { provide: FIREBASE_OPTIONS, useValue: options },
661
+ { provide: FIREBASE_APP_NAME, useValue: nameOrConfig },
662
+ ],
663
+ };
664
+ }
665
+ }
666
+ AngularFirebaseAuthModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
667
+ AngularFirebaseAuthModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, imports: [i1$2.FirebaseAppModule, i1.AuthModule] });
668
+ AngularFirebaseAuthModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, providers: [
669
+ {
670
+ provide: 'Authentication',
671
+ useFactory: (authenticationService, userRepository) => {
672
+ return new Authentication(authenticationService, userRepository);
673
+ },
674
+ deps: ['AuthenticationService', 'UserRepository'],
675
+ },
676
+ {
677
+ provide: 'AuthenticationService',
678
+ useFactory: (angularFireAuth) => {
679
+ return new AuthenticationFirebaseAuthService(angularFireAuth);
680
+ },
681
+ deps: [Auth],
682
+ },
683
+ {
684
+ provide: 'Register',
685
+ useFactory: (registerService, userRepository) => {
686
+ return new Register(registerService, userRepository);
687
+ },
688
+ deps: ['RegisterService', 'UserRepository'],
689
+ },
690
+ {
691
+ provide: 'RegisterService',
692
+ useFactory: (angularFireAuth) => {
693
+ return new RegisterFirebaseAuthService(angularFireAuth);
694
+ },
695
+ deps: [Auth],
696
+ },
697
+ {
698
+ provide: 'SignOut',
699
+ useFactory: (authenticationService) => {
700
+ return new SignOut(authenticationService);
701
+ },
702
+ deps: ['AuthenticationService'],
703
+ },
704
+ {
705
+ provide: 'RecoveryPassword',
706
+ useFactory: (authenticationService) => {
707
+ return new RecoveryPassword(authenticationService);
708
+ },
709
+ deps: ['AuthenticationService'],
710
+ },
711
+ ], imports: [provideFirebaseApp((injector) => {
712
+ const appName = injector.get(FIREBASE_APP_NAME);
713
+ return appName
714
+ ? initializeApp(injector.get(FIREBASE_OPTIONS), appName)
715
+ : initializeApp(injector.get(FIREBASE_OPTIONS));
716
+ }),
717
+ provideAuth(() => getAuth())] });
718
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, decorators: [{
719
+ type: NgModule,
720
+ args: [{
721
+ imports: [
722
+ provideFirebaseApp((injector) => {
723
+ const appName = injector.get(FIREBASE_APP_NAME);
724
+ return appName
725
+ ? initializeApp(injector.get(FIREBASE_OPTIONS), appName)
726
+ : initializeApp(injector.get(FIREBASE_OPTIONS));
727
+ }),
728
+ provideAuth(() => getAuth()),
729
+ ],
730
+ providers: [
731
+ {
732
+ provide: 'Authentication',
733
+ useFactory: (authenticationService, userRepository) => {
734
+ return new Authentication(authenticationService, userRepository);
735
+ },
736
+ deps: ['AuthenticationService', 'UserRepository'],
737
+ },
738
+ {
739
+ provide: 'AuthenticationService',
740
+ useFactory: (angularFireAuth) => {
741
+ return new AuthenticationFirebaseAuthService(angularFireAuth);
742
+ },
743
+ deps: [Auth],
744
+ },
745
+ {
746
+ provide: 'Register',
747
+ useFactory: (registerService, userRepository) => {
748
+ return new Register(registerService, userRepository);
749
+ },
750
+ deps: ['RegisterService', 'UserRepository'],
751
+ },
752
+ {
753
+ provide: 'RegisterService',
754
+ useFactory: (angularFireAuth) => {
755
+ return new RegisterFirebaseAuthService(angularFireAuth);
756
+ },
757
+ deps: [Auth],
758
+ },
759
+ {
760
+ provide: 'SignOut',
761
+ useFactory: (authenticationService) => {
762
+ return new SignOut(authenticationService);
763
+ },
764
+ deps: ['AuthenticationService'],
765
+ },
766
+ {
767
+ provide: 'RecoveryPassword',
768
+ useFactory: (authenticationService) => {
769
+ return new RecoveryPassword(authenticationService);
770
+ },
771
+ deps: ['AuthenticationService'],
772
+ },
773
+ ],
774
+ }]
775
+ }] });
776
+
777
+ class AngularElasticSeachModule {
778
+ static initializeApp(options) {
779
+ return {
780
+ ngModule: AngularElasticSeachModule,
781
+ providers: [{ provide: ES_CONFIG, useValue: options }],
1931
782
  };
1932
- return from(this.homeRepository.update({
1933
- id: this.homeId,
1934
- data,
1935
- })).pipe(tap(() => (this.homeConfiguration.data = data)), map(() => this.homeConfiguration));
1936
783
  }
1937
784
  }
1938
- 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 });
1939
- HomeShopServiceprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService });
1940
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService, decorators: [{
1941
- type: Injectable
1942
- }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1943
- type: Inject,
1944
- args: ['CategoryRepository']
1945
- }] }, { type: undefined, decorators: [{
1946
- type: Inject,
1947
- args: ['HomeRepository']
1948
- }] }, { type: undefined, decorators: [{
1949
- type: Inject,
1950
- args: ['ProductRepository']
1951
- }] }, { type: i1$3.Shops, decorators: [{
1952
- type: Inject,
1953
- args: [DEFAULT_SHOP]
1954
- }] }]; } });
785
+ AngularElasticSeachModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
786
+ AngularElasticSeachModulemod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule });
787
+ AngularElasticSeachModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, providers: [
788
+ {
789
+ provide: ProductsIndex,
790
+ useFactory: (configuration) => {
791
+ return new ProductsIndex(new AxiosAdapter(configuration));
792
+ },
793
+ deps: [ES_CONFIG],
794
+ },
795
+ ] });
796
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, decorators: [{
797
+ type: NgModule,
798
+ args: [{
799
+ providers: [
800
+ {
801
+ provide: ProductsIndex,
802
+ useFactory: (configuration) => {
803
+ return new ProductsIndex(new AxiosAdapter(configuration));
804
+ },
805
+ deps: [ES_CONFIG],
806
+ },
807
+ ],
808
+ }]
809
+ }] });
1955
810
 
1956
- class OrderService {
1957
- constructor(angularFirestore, orderRepository) {
1958
- this.angularFirestore = angularFirestore;
1959
- this.orderRepository = orderRepository;
1960
- this.orderSubject = new Subject();
1961
- }
1962
- getOrder(id) {
1963
- docSnapshots(doc(this.angularFirestore, `${this.orderRepository.collectionName}/${id}`))
1964
- .pipe(map((doc) => Order.toInstance(doc.data())))
1965
- .subscribe((doc) => this.orderSubject.next(doc));
1966
- return this.orderSubject;
811
+ class AngularFirestoreModule {
812
+ static initializeApp(options, nameOrConfig) {
813
+ return {
814
+ ngModule: AngularFirestoreModule,
815
+ providers: [
816
+ { provide: FIREBASE_OPTIONS, useValue: options.firebase },
817
+ { provide: FIREBASE_APP_NAME, useValue: nameOrConfig },
818
+ { provide: ES_CONFIG, useValue: options.elasticSearch },
819
+ ],
820
+ };
1967
821
  }
1968
822
  }
1969
- OrderService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService, deps: [{ token: i1$2.Firestore }, { token: 'OrderRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1970
- OrderServiceprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService });
1971
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService, decorators: [{
1972
- type: Injectable
1973
- }], ctorParameters: function () { return [{ type: i1$2.Firestore }, { type: i1$3.OrderFirestoreRepository, decorators: [{
1974
- type: Inject,
1975
- args: ['OrderRepository']
1976
- }] }]; } });
823
+ AngularFirestoreModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
824
+ AngularFirestoreModulemod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, imports: [AngularElasticSeachModule, i1$2.FirebaseAppModule, i1$1.FirestoreModule] });
825
+ AngularFirestoreModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, providers: [
826
+ {
827
+ provide: 'BeautyProfileRepository',
828
+ useFactory: (firestore, userRepository) => {
829
+ return new UserBeautyProfileFirestoreRepository(firestore, userRepository);
830
+ },
831
+ deps: [Firestore, 'UserRepository'],
832
+ },
833
+ {
834
+ provide: 'Buy2WinRepository',
835
+ useFactory: (firestore) => {
836
+ return new Buy2WinFirestoreRepository(firestore);
837
+ },
838
+ deps: [Firestore],
839
+ },
840
+ {
841
+ provide: CategoryFirestoreRepository,
842
+ useFactory: (firestore) => {
843
+ return new CategoryFirestoreRepository(firestore);
844
+ },
845
+ deps: [Firestore],
846
+ },
847
+ {
848
+ provide: 'CheckoutRepository',
849
+ useFactory: (firestore) => {
850
+ return new CheckoutFirestoreRepository(firestore);
851
+ },
852
+ deps: [Firestore],
853
+ },
854
+ {
855
+ provide: 'CheckoutSubscriptionRepository',
856
+ useFactory: (firestore) => {
857
+ return new CheckoutSubscriptionFirestoreRepository(firestore);
858
+ },
859
+ deps: [Firestore],
860
+ },
861
+ {
862
+ provide: 'CouponRepository',
863
+ useFactory: (firestore) => {
864
+ return new CouponFirestoreRepository(firestore);
865
+ },
866
+ deps: [Firestore],
867
+ },
868
+ {
869
+ provide: 'EditionRepository',
870
+ useFactory: (firestore, subscriptionRepository) => {
871
+ return new SubscriptionEditionFirestoreRepository(firestore, subscriptionRepository);
872
+ },
873
+ deps: [Firestore, 'SubscriptionRepository'],
874
+ },
875
+ {
876
+ provide: 'HomeRepository',
877
+ useFactory: (firestore) => {
878
+ return new HomeFirestoreRepository(firestore);
879
+ },
880
+ deps: [Firestore],
881
+ },
882
+ {
883
+ provide: 'LeadRepository',
884
+ useFactory: (firestore) => {
885
+ return new LeadFirestoreRepository(firestore);
886
+ },
887
+ deps: [Firestore],
888
+ },
889
+ {
890
+ provide: 'LegacyOrderRepository',
891
+ useFactory: (firestore) => {
892
+ return new LegacyOrderFirestoreRepository(firestore);
893
+ },
894
+ deps: [Firestore],
895
+ },
896
+ {
897
+ provide: 'ShopMenuRepository',
898
+ useFactory: (firestore) => {
899
+ return new ShopMenuFirestoreRepository(firestore);
900
+ },
901
+ deps: [Firestore],
902
+ },
903
+ {
904
+ provide: 'OrderRepository',
905
+ useFactory: (firestore) => {
906
+ return new OrderFirestoreRepository(firestore);
907
+ },
908
+ deps: [Firestore],
909
+ },
910
+ {
911
+ provide: 'PaymentRepository',
912
+ useFactory: (firestore) => {
913
+ return new PaymentFirestoreRepository(firestore);
914
+ },
915
+ deps: [Firestore],
916
+ },
917
+ {
918
+ provide: ProductFirestoreRepository,
919
+ useFactory: (firestore) => {
920
+ return new ProductFirestoreRepository(firestore);
921
+ },
922
+ deps: [Firestore],
923
+ },
924
+ {
925
+ provide: 'SubscriptionPaymentRepository',
926
+ useFactory: (firestore, subscriptionRepository) => {
927
+ return new SubscriptionPaymentFirestoreRepository(firestore, subscriptionRepository);
928
+ },
929
+ deps: [Firestore, 'SubscriptionRepository'],
930
+ },
931
+ {
932
+ provide: 'SubscriptionPlanRepository',
933
+ useFactory: (firestore) => {
934
+ return new SubscriptionPlanFirestoreRepository(firestore);
935
+ },
936
+ deps: [Firestore],
937
+ },
938
+ {
939
+ provide: 'SubscriptionProductRepository',
940
+ useFactory: (firestore) => {
941
+ return new SubscriptionProductFirestoreRepository(firestore);
942
+ },
943
+ deps: [Firestore],
944
+ },
945
+ {
946
+ provide: 'SubscriptionRepository',
947
+ useFactory: (firestore) => {
948
+ return new SubscriptionFirestoreRepository(firestore);
949
+ },
950
+ deps: [Firestore],
951
+ },
952
+ {
953
+ provide: 'UserRepository',
954
+ useFactory: (firestore) => {
955
+ return new UserFirestoreRepository(firestore);
956
+ },
957
+ deps: [Firestore],
958
+ },
959
+ {
960
+ provide: 'UserAddressRepository',
961
+ useFactory: (firestore, userRepository) => {
962
+ return new UserAddressFirestoreRepository(firestore, userRepository);
963
+ },
964
+ deps: [Firestore, 'UserRepository'],
965
+ },
966
+ {
967
+ provide: 'UserPaymentMethodRepository',
968
+ useFactory: (firestore, userRepository) => {
969
+ return new UserPaymentMethodFirestoreRepository(firestore, userRepository);
970
+ },
971
+ deps: [Firestore, 'UserRepository'],
972
+ },
973
+ {
974
+ provide: ProductVariantFirestoreRepository,
975
+ useFactory: (firestore, productRepository) => {
976
+ return new ProductVariantFirestoreRepository(firestore, productRepository);
977
+ },
978
+ deps: [Firestore, ProductFirestoreRepository],
979
+ },
980
+ ], imports: [AngularElasticSeachModule,
981
+ provideFirebaseApp((injector) => {
982
+ const appName = injector.get(FIREBASE_APP_NAME);
983
+ return appName
984
+ ? initializeApp(injector.get(FIREBASE_OPTIONS), appName)
985
+ : initializeApp(injector.get(FIREBASE_OPTIONS));
986
+ }),
987
+ provideFirestore(() => getFirestore())] });
988
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, decorators: [{
989
+ type: NgModule,
990
+ args: [{
991
+ imports: [
992
+ AngularElasticSeachModule,
993
+ provideFirebaseApp((injector) => {
994
+ const appName = injector.get(FIREBASE_APP_NAME);
995
+ return appName
996
+ ? initializeApp(injector.get(FIREBASE_OPTIONS), appName)
997
+ : initializeApp(injector.get(FIREBASE_OPTIONS));
998
+ }),
999
+ provideFirestore(() => getFirestore()),
1000
+ ],
1001
+ providers: [
1002
+ {
1003
+ provide: 'BeautyProfileRepository',
1004
+ useFactory: (firestore, userRepository) => {
1005
+ return new UserBeautyProfileFirestoreRepository(firestore, userRepository);
1006
+ },
1007
+ deps: [Firestore, 'UserRepository'],
1008
+ },
1009
+ {
1010
+ provide: 'Buy2WinRepository',
1011
+ useFactory: (firestore) => {
1012
+ return new Buy2WinFirestoreRepository(firestore);
1013
+ },
1014
+ deps: [Firestore],
1015
+ },
1016
+ {
1017
+ provide: CategoryFirestoreRepository,
1018
+ useFactory: (firestore) => {
1019
+ return new CategoryFirestoreRepository(firestore);
1020
+ },
1021
+ deps: [Firestore],
1022
+ },
1023
+ {
1024
+ provide: 'CheckoutRepository',
1025
+ useFactory: (firestore) => {
1026
+ return new CheckoutFirestoreRepository(firestore);
1027
+ },
1028
+ deps: [Firestore],
1029
+ },
1030
+ {
1031
+ provide: 'CheckoutSubscriptionRepository',
1032
+ useFactory: (firestore) => {
1033
+ return new CheckoutSubscriptionFirestoreRepository(firestore);
1034
+ },
1035
+ deps: [Firestore],
1036
+ },
1037
+ {
1038
+ provide: 'CouponRepository',
1039
+ useFactory: (firestore) => {
1040
+ return new CouponFirestoreRepository(firestore);
1041
+ },
1042
+ deps: [Firestore],
1043
+ },
1044
+ {
1045
+ provide: 'EditionRepository',
1046
+ useFactory: (firestore, subscriptionRepository) => {
1047
+ return new SubscriptionEditionFirestoreRepository(firestore, subscriptionRepository);
1048
+ },
1049
+ deps: [Firestore, 'SubscriptionRepository'],
1050
+ },
1051
+ {
1052
+ provide: 'HomeRepository',
1053
+ useFactory: (firestore) => {
1054
+ return new HomeFirestoreRepository(firestore);
1055
+ },
1056
+ deps: [Firestore],
1057
+ },
1058
+ {
1059
+ provide: 'LeadRepository',
1060
+ useFactory: (firestore) => {
1061
+ return new LeadFirestoreRepository(firestore);
1062
+ },
1063
+ deps: [Firestore],
1064
+ },
1065
+ {
1066
+ provide: 'LegacyOrderRepository',
1067
+ useFactory: (firestore) => {
1068
+ return new LegacyOrderFirestoreRepository(firestore);
1069
+ },
1070
+ deps: [Firestore],
1071
+ },
1072
+ {
1073
+ provide: 'ShopMenuRepository',
1074
+ useFactory: (firestore) => {
1075
+ return new ShopMenuFirestoreRepository(firestore);
1076
+ },
1077
+ deps: [Firestore],
1078
+ },
1079
+ {
1080
+ provide: 'OrderRepository',
1081
+ useFactory: (firestore) => {
1082
+ return new OrderFirestoreRepository(firestore);
1083
+ },
1084
+ deps: [Firestore],
1085
+ },
1086
+ {
1087
+ provide: 'PaymentRepository',
1088
+ useFactory: (firestore) => {
1089
+ return new PaymentFirestoreRepository(firestore);
1090
+ },
1091
+ deps: [Firestore],
1092
+ },
1093
+ {
1094
+ provide: ProductFirestoreRepository,
1095
+ useFactory: (firestore) => {
1096
+ return new ProductFirestoreRepository(firestore);
1097
+ },
1098
+ deps: [Firestore],
1099
+ },
1100
+ {
1101
+ provide: 'SubscriptionPaymentRepository',
1102
+ useFactory: (firestore, subscriptionRepository) => {
1103
+ return new SubscriptionPaymentFirestoreRepository(firestore, subscriptionRepository);
1104
+ },
1105
+ deps: [Firestore, 'SubscriptionRepository'],
1106
+ },
1107
+ {
1108
+ provide: 'SubscriptionPlanRepository',
1109
+ useFactory: (firestore) => {
1110
+ return new SubscriptionPlanFirestoreRepository(firestore);
1111
+ },
1112
+ deps: [Firestore],
1113
+ },
1114
+ {
1115
+ provide: 'SubscriptionProductRepository',
1116
+ useFactory: (firestore) => {
1117
+ return new SubscriptionProductFirestoreRepository(firestore);
1118
+ },
1119
+ deps: [Firestore],
1120
+ },
1121
+ {
1122
+ provide: 'SubscriptionRepository',
1123
+ useFactory: (firestore) => {
1124
+ return new SubscriptionFirestoreRepository(firestore);
1125
+ },
1126
+ deps: [Firestore],
1127
+ },
1128
+ {
1129
+ provide: 'UserRepository',
1130
+ useFactory: (firestore) => {
1131
+ return new UserFirestoreRepository(firestore);
1132
+ },
1133
+ deps: [Firestore],
1134
+ },
1135
+ {
1136
+ provide: 'UserAddressRepository',
1137
+ useFactory: (firestore, userRepository) => {
1138
+ return new UserAddressFirestoreRepository(firestore, userRepository);
1139
+ },
1140
+ deps: [Firestore, 'UserRepository'],
1141
+ },
1142
+ {
1143
+ provide: 'UserPaymentMethodRepository',
1144
+ useFactory: (firestore, userRepository) => {
1145
+ return new UserPaymentMethodFirestoreRepository(firestore, userRepository);
1146
+ },
1147
+ deps: [Firestore, 'UserRepository'],
1148
+ },
1149
+ {
1150
+ provide: ProductVariantFirestoreRepository,
1151
+ useFactory: (firestore, productRepository) => {
1152
+ return new ProductVariantFirestoreRepository(firestore, productRepository);
1153
+ },
1154
+ deps: [Firestore, ProductFirestoreRepository],
1155
+ },
1156
+ ],
1157
+ }]
1158
+ }] });
1977
1159
 
1978
- class ShippingService {
1979
- constructor(http, apiUrl, homeService) {
1980
- this.http = http;
1981
- this.apiUrl = apiUrl;
1982
- this.homeService = homeService;
1983
- }
1984
- getShippingMethods(shop, zip, weightGrams, totalPrice, personId, subscriptionPlan) {
1985
- return combineLatest([
1986
- this.homeService.getHomeData(),
1987
- this.http.get(`${this.apiUrl}open/checkshippingcompany?personId=${personId}&postalCode=${zip}&weightGrams=${weightGrams}`),
1988
- ]).pipe(map(([datas, shippingMethodsResponse]) => {
1989
- let shippingMethods = shippingMethodsResponse.result;
1990
- if (!shippingMethods.length)
1991
- return [];
1992
- shippingMethods = shippingMethods.map((shippingMethod) => {
1993
- if (shippingMethod.ShippingCompanyName == 'Same Day EG')
1994
- shippingMethod.ShippingCompanyName = 'Same Day';
1995
- return shippingMethod;
1996
- });
1997
- const datasSameDayNotAvaliable = datas.sameDayNotAvaliable;
1998
- if (this.isHolidays(datasSameDayNotAvaliable)) {
1999
- shippingMethods = shippingMethods.filter((method) => method.serviceName !== 'Same Day');
2000
- }
2001
- if (totalPrice >= 200) {
2002
- shippingMethods = shippingMethods.map((s) => {
2003
- if (s.serviceName !== 'Same Day')
2004
- return { ...s, totalPrice: 0 };
2005
- else
2006
- return s;
2007
- });
2008
- }
2009
- if (shop == Shops.GLAMSHOP)
2010
- return shippingMethods;
2011
- if (this.isFreeShippingBySubscription(shop, subscriptionPlan)) {
2012
- shippingMethods = shippingMethods.map((s) => {
2013
- if (s.serviceName == 'Same Day')
2014
- return { ...s, totalPrice: s.totalPrice / 2 };
2015
- else
2016
- return { ...s, totalPrice: 0 };
2017
- });
2018
- }
2019
- if (this.isHalfShippingBySubscription(shop, subscriptionPlan)) {
2020
- shippingMethods = shippingMethods.map((s) => {
2021
- return { ...s, totalPrice: s.totalPrice / 2 };
2022
- });
2023
- }
2024
- return shippingMethods;
2025
- }));
2026
- }
2027
- isFreeShippingBySubscription(shop, subscriptionPlan) {
2028
- if (!subscriptionPlan)
2029
- return false;
2030
- if (shop == Shops.MENSMARKET && subscriptionPlan == 'SELECT')
2031
- return true;
2032
- return false;
2033
- }
2034
- isHalfShippingBySubscription(shop, subscriptionPlan) {
2035
- if (!subscriptionPlan)
2036
- return false;
2037
- if (shop == Shops.MENSMARKET && subscriptionPlan == 'PRIME') {
2038
- return true;
2039
- }
2040
- return false;
2041
- }
2042
- isHolidays(datas) {
2043
- const today = new Date();
2044
- for (const key in datas) {
2045
- let start = new Date(`${today.getFullYear()}-${datas[key].beginDate}`);
2046
- let end = new Date(`${today.getFullYear()}-${datas[key].endDate}`);
2047
- if (start > end)
2048
- end = new Date(`${today.getFullYear() + 1}-${datas[key].endDate}`);
2049
- if (today >= start && today <= end)
2050
- return true;
2051
- }
2052
- return false;
1160
+ class AngularHasuraGraphQLModule {
1161
+ static initializeApp(options) {
1162
+ return {
1163
+ ngModule: AngularHasuraGraphQLModule,
1164
+ providers: [{ provide: HASURA_OPTIONS, useValue: options }],
1165
+ };
2053
1166
  }
2054
1167
  }
2055
- ShippingService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService, deps: [{ token: i1$4.HttpClient }, { token: BACKEND_URL }, { token: HomeShopService }], target: i0.ɵɵFactoryTarget.Injectable });
2056
- ShippingServiceprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService });
2057
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService, decorators: [{
2058
- type: Injectable
2059
- }], ctorParameters: function () { return [{ type: i1$4.HttpClient }, { type: undefined, decorators: [{
2060
- type: Inject,
2061
- args: [BACKEND_URL]
2062
- }] }, { type: HomeShopService }]; } });
1168
+ AngularHasuraGraphQLModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
1169
+ AngularHasuraGraphQLModulemod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule });
1170
+ AngularHasuraGraphQLModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, providers: [
1171
+ {
1172
+ provide: 'HasuraConfig',
1173
+ useFactory: (options, platformId) => ({
1174
+ endpoint: options.endpoint,
1175
+ authOptions: options.credentials,
1176
+ interceptors: {
1177
+ request: (request) => {
1178
+ if (isPlatformBrowser(platformId))
1179
+ return request;
1180
+ const interval = setInterval(null, 100);
1181
+ request.interval = interval;
1182
+ return request;
1183
+ },
1184
+ response: (response, request) => {
1185
+ if (isPlatformBrowser(platformId))
1186
+ return response;
1187
+ clearInterval(request.interval);
1188
+ return response;
1189
+ },
1190
+ },
1191
+ }),
1192
+ deps: [HASURA_OPTIONS, PLATFORM_ID],
1193
+ },
1194
+ {
1195
+ provide: 'CategoryRepository',
1196
+ useExisting: CategoryHasuraGraphQLRepository,
1197
+ },
1198
+ {
1199
+ provide: CategoryHasuraGraphQLRepository,
1200
+ useFactory: (hasuraConfig, productRepository) => {
1201
+ return new CategoryHasuraGraphQLRepository(hasuraConfig, productRepository);
1202
+ },
1203
+ deps: ['HasuraConfig', ProductHasuraGraphQLRepository],
1204
+ },
1205
+ {
1206
+ provide: 'ProductRepository',
1207
+ useExisting: ProductHasuraGraphQLRepository,
1208
+ },
1209
+ {
1210
+ provide: ProductHasuraGraphQLRepository,
1211
+ useFactory: (hasuraConfig) => {
1212
+ return new ProductHasuraGraphQLRepository(hasuraConfig);
1213
+ },
1214
+ deps: ['HasuraConfig'],
1215
+ },
1216
+ {
1217
+ provide: 'VariantRepository',
1218
+ useExisting: VariantHasuraGraphQLRepository,
1219
+ },
1220
+ {
1221
+ provide: VariantHasuraGraphQLRepository,
1222
+ useFactory: (hasuraConfig) => {
1223
+ return new VariantHasuraGraphQLRepository(hasuraConfig);
1224
+ },
1225
+ deps: ['HasuraConfig'],
1226
+ },
1227
+ ] });
1228
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, decorators: [{
1229
+ type: NgModule,
1230
+ args: [{
1231
+ providers: [
1232
+ {
1233
+ provide: 'HasuraConfig',
1234
+ useFactory: (options, platformId) => ({
1235
+ endpoint: options.endpoint,
1236
+ authOptions: options.credentials,
1237
+ interceptors: {
1238
+ request: (request) => {
1239
+ if (isPlatformBrowser(platformId))
1240
+ return request;
1241
+ const interval = setInterval(null, 100);
1242
+ request.interval = interval;
1243
+ return request;
1244
+ },
1245
+ response: (response, request) => {
1246
+ if (isPlatformBrowser(platformId))
1247
+ return response;
1248
+ clearInterval(request.interval);
1249
+ return response;
1250
+ },
1251
+ },
1252
+ }),
1253
+ deps: [HASURA_OPTIONS, PLATFORM_ID],
1254
+ },
1255
+ {
1256
+ provide: 'CategoryRepository',
1257
+ useExisting: CategoryHasuraGraphQLRepository,
1258
+ },
1259
+ {
1260
+ provide: CategoryHasuraGraphQLRepository,
1261
+ useFactory: (hasuraConfig, productRepository) => {
1262
+ return new CategoryHasuraGraphQLRepository(hasuraConfig, productRepository);
1263
+ },
1264
+ deps: ['HasuraConfig', ProductHasuraGraphQLRepository],
1265
+ },
1266
+ {
1267
+ provide: 'ProductRepository',
1268
+ useExisting: ProductHasuraGraphQLRepository,
1269
+ },
1270
+ {
1271
+ provide: ProductHasuraGraphQLRepository,
1272
+ useFactory: (hasuraConfig) => {
1273
+ return new ProductHasuraGraphQLRepository(hasuraConfig);
1274
+ },
1275
+ deps: ['HasuraConfig'],
1276
+ },
1277
+ {
1278
+ provide: 'VariantRepository',
1279
+ useExisting: VariantHasuraGraphQLRepository,
1280
+ },
1281
+ {
1282
+ provide: VariantHasuraGraphQLRepository,
1283
+ useFactory: (hasuraConfig) => {
1284
+ return new VariantHasuraGraphQLRepository(hasuraConfig);
1285
+ },
1286
+ deps: ['HasuraConfig'],
1287
+ },
1288
+ ],
1289
+ }]
1290
+ }] });
2063
1291
 
2064
1292
  class AngularConnectModule {
2065
1293
  static initializeApp(defaultShop, options, nameOrConfig) {
2066
1294
  return {
2067
1295
  ngModule: AngularConnectModule,
2068
1296
  providers: [
2069
- {
2070
- provide: CATEGORY_STRUCTURE,
2071
- useClass: isNil(options?.oldCategoryStructure) || options?.oldCategoryStructure
2072
- ? OldCategoryStructureAdapter
2073
- : NewCategoryStructureAdapter,
2074
- },
2075
1297
  ...(isNil(defaultShop) ? [] : [{ provide: DEFAULT_SHOP, useValue: defaultShop }]),
2076
1298
  ...(isNil(options?.firebase) ? [] : [{ provide: FIREBASE_OPTIONS, useValue: options?.firebase }]),
2077
1299
  ...(isNil(options?.firebase) ? [] : [{ provide: FIREBASE_APP_NAME, useValue: nameOrConfig }]),
2078
1300
  ...(isNil(options?.elasticSearch) ? [] : [{ provide: ES_CONFIG, useValue: options.elasticSearch }]),
2079
1301
  ...(isNil(options?.hasura) ? [] : [{ provide: HASURA_OPTIONS, useValue: options.hasura }]),
2080
- ...(isNil(options?.backendUrl) ? [] : [{ provide: BACKEND_URL, useValue: options.backendUrl }]),
2081
1302
  ],
2082
1303
  };
2083
1304
  }
2084
1305
  }
2085
1306
  AngularConnectModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2086
- AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, imports: [AngularElasticSeachModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule] });
1307
+ AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, imports: [AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule] });
2087
1308
  AngularConnectModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, providers: [
2088
1309
  AuthService,
2089
1310
  CartService,
2090
- CatalogService,
2091
- CategoryService,
2092
1311
  CheckoutService,
2093
1312
  CheckoutSubscriptionService,
2094
1313
  CouponService,
2095
1314
  HomeShopService,
2096
1315
  OrderService,
2097
- ShippingService,
2098
- WishlistService,
2099
- ], imports: [AngularElasticSeachModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule] });
1316
+ ], imports: [AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule] });
2100
1317
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, decorators: [{
2101
1318
  type: NgModule,
2102
1319
  args: [{
2103
- imports: [AngularElasticSeachModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule],
1320
+ imports: [AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule],
2104
1321
  providers: [
2105
1322
  AuthService,
2106
1323
  CartService,
2107
- CatalogService,
2108
- CategoryService,
2109
1324
  CheckoutService,
2110
1325
  CheckoutSubscriptionService,
2111
1326
  CouponService,
2112
1327
  HomeShopService,
2113
1328
  OrderService,
2114
- ShippingService,
2115
- WishlistService,
2116
1329
  ],
2117
1330
  }]
2118
1331
  }] });
@@ -2121,5 +1334,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2121
1334
  * Generated bundle index. Do not edit.
2122
1335
  */
2123
1336
 
2124
- export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CouponService, HomeShopService, OrderService, ProductSorts, ShippingService, UtilHelper, WishlistService };
1337
+ export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CheckoutService, CheckoutSubscriptionService, CouponService, HomeShopService, OrderService };
2125
1338
  //# sourceMappingURL=infrab4a-connect-angular.mjs.map