@infrab4a/connect-angular 4.0.0-beta.3 → 4.0.0-beta.31

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