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

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 +51 -0
  15. package/esm2020/services/catalog/category.service.mjs +29 -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 +1455 -978
  30. package/fesm2015/infrab4a-connect-angular.mjs.map +1 -1
  31. package/fesm2020/infrab4a-connect-angular.mjs +1445 -966
  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 +23 -0
  37. package/services/catalog/category.service.d.ts +11 -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, 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;
@@ -474,850 +1246,548 @@ class CartService {
474
1246
  }
475
1247
  /**
476
1248
  * @deprecated The method should not be used
477
- */
478
- getVariantPriceDiscount(item) {
479
- return this.authService.getUser().pipe(concatMap((user) => iif(() => user.isSubscriber && !!item.price.subscriberPrice, of(item.price.subscriberPrice), of(item.price.price))), catchError(() => of(item.price.price)));
480
- }
481
- removeItem(item) {
482
- return this.checkoutService.getCheckout().pipe(map((checkout) => {
483
- const index = checkout.lineItems.findIndex((lineItem) => lineItem.sku === item.sku);
484
- if (index >= 0)
485
- checkout.lineItems.splice(index, 1);
486
- return checkout;
487
- }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
488
- }
489
- updateUserCart(user) {
490
- 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
- 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
- }));
1249
+ */
1250
+ getVariantPriceDiscount(item) {
1251
+ return this.authService.getUser().pipe(concatMap((user) => iif(() => user.isSubscriber && !!item.price.subscriberPrice, of(item.price.subscriberPrice), of(item.price.price))), catchError(() => of(item.price.price)));
644
1252
  }
645
- getMinValueForFreeShipping() {
646
- return this.getHomeConfiguration().pipe(map((home) => home.minValueForFreeShipping));
1253
+ removeItem(item) {
1254
+ return this.checkoutService.getCheckout().pipe(map((checkout) => {
1255
+ const index = checkout.lineItems.findIndex((lineItem) => lineItem.id === item.id);
1256
+ if (index >= 0)
1257
+ checkout.lineItems.splice(index, 1);
1258
+ return checkout;
1259
+ }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
647
1260
  }
648
- getDiscoverProducts() {
649
- return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.discoverCategories)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
1261
+ updateUserCart(user) {
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* () {
1263
+ var _a, _b;
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)));
650
1270
  }
651
- getFeaturedProducts() {
652
- return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.featuredCategories)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
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)));
653
1276
  }
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))))));
1277
+ buildCartFromCheckout(checkoutData) {
1278
+ return this.checkoutService.getCheckout(checkoutData).pipe(map((checkout) => checkout.lineItems), concatMap((lineItems) => of(this.generateCartObject(lineItems))));
659
1279
  }
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)))));
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)) }));
666
1283
  }
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));
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
+ });
1302
+ }
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)));
1372
+ }
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 = (category, filters) => { };
1425
+ this.buildSortQuery = (sort) => {
1426
+ const query = {
1427
+ stock: 'desc',
1428
+ gender: 'asc',
1429
+ };
1430
+ return query;
707
1431
  };
1432
+ this.buildLimitQuery = (options) => {
1433
+ const limit = (options === null || options === void 0 ? void 0 : options.perPage) || 20;
1434
+ return {
1435
+ limit,
1436
+ offset: (((options === null || options === void 0 ? void 0 : options.page) || 1) - 1) * limit,
1437
+ };
1438
+ };
1439
+ }
1440
+ fetchProducts(category, options) {
1441
+ return __awaiter(this, void 0, void 0, function* () {
1442
+ const productsIds = category.products.length
1443
+ ? category.products
1444
+ : yield this.categoryRepository.get({ id: category.id }).then((categoryFound) => categoryFound.products);
1445
+ const limits = this.buildLimitQuery(options);
1446
+ return yield this.productRepository
1447
+ .find({
1448
+ filters: {
1449
+ id: { operator: Where.IN, value: productsIds },
1450
+ published: true,
1451
+ },
1452
+ limits,
1453
+ })
1454
+ .then(({ data, count: total }) => ({ products: data, pages: Math.ceil(total / limits.limit), total }));
1455
+ });
708
1456
  }
709
1457
  }
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
- }] });
1458
+ 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 });
1459
+ CatalogServiceprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService });
1460
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService, decorators: [{
1461
+ type: Injectable
1462
+ }], ctorParameters: function () {
1463
+ return [{ type: undefined, decorators: [{
1464
+ type: Inject,
1465
+ args: ['ProductRepository']
1466
+ }] }, { type: undefined, decorators: [{
1467
+ type: Inject,
1468
+ args: ['CategoryRepository']
1469
+ }] }];
1470
+ } });
820
1471
 
821
- class AngularElasticSeachModule {
822
- static initializeApp(options) {
823
- return {
824
- ngModule: AngularElasticSeachModule,
825
- providers: [{ provide: ES_CONFIG, useValue: options }],
826
- };
1472
+ class CategoryService {
1473
+ constructor(categoryFilterRepository) {
1474
+ this.categoryFilterRepository = categoryFilterRepository;
1475
+ }
1476
+ fetchSubCategories(category) {
1477
+ return __awaiter(this, void 0, void 0, function* () {
1478
+ return [];
1479
+ });
1480
+ }
1481
+ fetchFilterOptions(category, filters) {
1482
+ return __awaiter(this, void 0, void 0, function* () {
1483
+ const categoryFilters = category.filters && category.filters.length
1484
+ ? category.filters
1485
+ : yield this.categoryFilterRepository
1486
+ .find({ filters: { categoryId: +category.id } })
1487
+ .then(({ data }) => data.map((categoryFilter) => categoryFilter.filter));
1488
+ return (filters === null || filters === void 0 ? void 0 : filters.length)
1489
+ ? categoryFilters.filter((categoryFilter) => !filters || !filters.length || categoryFilter.options.some((option) => filters.includes(option.id)))
1490
+ : categoryFilters;
1491
+ });
827
1492
  }
828
1493
  }
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
- }] });
1494
+ CategoryService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CategoryService, deps: [{ token: 'CategoryFilterRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1495
+ CategoryServiceprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CategoryService });
1496
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CategoryService, decorators: [{
1497
+ type: Injectable
1498
+ }], ctorParameters: function () {
1499
+ return [{ type: undefined, decorators: [{
1500
+ type: Inject,
1501
+ args: ['CategoryFilterRepository']
1502
+ }] }];
1503
+ } });
854
1504
 
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
- };
1505
+ var ProductSorts;
1506
+ (function (ProductSorts) {
1507
+ ProductSorts["MOST_RELEVANT"] = "most-relevant";
1508
+ ProductSorts["BEST_SELLER"] = "best-sellers";
1509
+ ProductSorts["BIGGEST_PRICE"] = "biggest-price";
1510
+ ProductSorts["LOWEST_PRICE"] = "lowest-price";
1511
+ ProductSorts["BIGGEST_DISCOUNT"] = "biggest-discount";
1512
+ ProductSorts["BEST_RATING"] = "best-rating";
1513
+ })(ProductSorts || (ProductSorts = {}));
1514
+
1515
+ class CategoryWithTree extends Category {
1516
+ }
1517
+ __decorate([
1518
+ Type(() => CategoryWithTree),
1519
+ __metadata("design:type", Array)
1520
+ ], CategoryWithTree.prototype, "children", void 0);
1521
+
1522
+ class CheckoutSubscriptionService {
1523
+ constructor(checkoutSubscriptionRepository, subscriptionRepository, couponService) {
1524
+ this.checkoutSubscriptionRepository = checkoutSubscriptionRepository;
1525
+ this.subscriptionRepository = subscriptionRepository;
1526
+ this.couponService = couponService;
1527
+ }
1528
+ getCheckoutSubscription(checkoutData) {
1529
+ const checkoutId = cookie.get('checkoutSubscriptionId');
1530
+ if (!isNil(checkoutId))
1531
+ return from(this.checkoutSubscriptionRepository.get({ id: checkoutId }));
1532
+ return from(this.createCheckoutSubscription(checkoutData));
1533
+ }
1534
+ createCheckoutSubscription(checkoutData) {
1535
+ return __awaiter(this, void 0, void 0, function* () {
1536
+ const checkout = yield this.checkoutSubscriptionRepository.create(Object.assign({ createdAt: new Date() }, CheckoutSubscription.toInstance(pick(checkoutData, ['user', 'shop'])).toPlain()));
1537
+ cookie.set('checkoutSubscriptionId', checkout.id);
1538
+ return checkout;
1539
+ });
1540
+ }
1541
+ clearCheckoutSubscriptionFromSession() {
1542
+ cookie.remove('checkoutSubscriptionId');
1543
+ return of();
1544
+ }
1545
+ checkCoupon(nickname, userEmail) {
1546
+ return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService
1547
+ .checkCoupon(nickname, userEmail, CheckoutTypes.SUBSCRIPTION, checkout.subscriptionPlan.name, checkout, true)
1548
+ .pipe()));
1549
+ }
1550
+ calcDiscountSubscription(coupon) {
1551
+ return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService.calcDiscountSubscription(coupon, checkout).pipe()));
865
1552
  }
866
1553
  }
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
- }] });
1554
+ 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 });
1555
+ CheckoutSubscriptionServiceprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutSubscriptionService });
1556
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutSubscriptionService, decorators: [{
1557
+ type: Injectable
1558
+ }], ctorParameters: function () {
1559
+ return [{ type: undefined, decorators: [{
1560
+ type: Inject,
1561
+ args: ['CheckoutSubscriptionRepository']
1562
+ }] }, { type: undefined, decorators: [{
1563
+ type: Inject,
1564
+ args: ['SubscriptionRepository']
1565
+ }] }, { type: CouponService }];
1566
+ } });
1203
1567
 
1204
- class AngularHasuraGraphQLModule {
1205
- static initializeApp(options) {
1206
- return {
1207
- ngModule: AngularHasuraGraphQLModule,
1208
- providers: [{ provide: HASURA_OPTIONS, useValue: options }],
1568
+ class HomeShopService {
1569
+ constructor(categoryRepository, homeRepository, productRepository, defaultShop) {
1570
+ this.categoryRepository = categoryRepository;
1571
+ this.homeRepository = homeRepository;
1572
+ this.productRepository = productRepository;
1573
+ this.defaultShop = defaultShop;
1574
+ this.buildCategoryGroupWithRequiredData = (group) => {
1575
+ var _a, _b;
1576
+ return ({
1577
+ 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'])),
1578
+ 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()) || {}, [
1579
+ 'id',
1580
+ 'price',
1581
+ 'reviews',
1582
+ 'hasVariants',
1583
+ 'slug',
1584
+ 'sku',
1585
+ 'stock',
1586
+ 'costPrice',
1587
+ 'images',
1588
+ 'miniatures',
1589
+ 'name',
1590
+ 'weight',
1591
+ 'rate',
1592
+ 'type',
1593
+ ])))) || [],
1594
+ });
1595
+ };
1596
+ }
1597
+ get homeId() {
1598
+ if (this.defaultShop === Shops.GLAMSHOP)
1599
+ return 'glamshop';
1600
+ if (this.defaultShop === Shops.MENSMARKET)
1601
+ return 'mens_market';
1602
+ return null;
1603
+ }
1604
+ getHomeData() {
1605
+ 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
1606
+ ? of(home)
1607
+ : forkJoin([this.getDiscoverProducts(), this.getFeaturedProducts(), this.getVerticalProducts()]).pipe(map(([discoverProducts, featuredProducts, verticalProducts]) => ({
1608
+ discoverProducts,
1609
+ featuredProducts,
1610
+ verticalProducts,
1611
+ })), concatMap((data) => this.saveHomeData(data)))));
1612
+ }
1613
+ getBanners(type) {
1614
+ return this.getHomeConfiguration().pipe(map((home) => {
1615
+ if (type === 'brand')
1616
+ return home.brandsCarousel;
1617
+ if (type === 'buyToWin')
1618
+ return [home.buyToWinBanner];
1619
+ if (type === 'block')
1620
+ return home.blockBanners;
1621
+ if (type === 'blog')
1622
+ return [home.blogBanner];
1623
+ return [];
1624
+ }));
1625
+ }
1626
+ getMinValueForFreeShipping() {
1627
+ return this.getHomeConfiguration().pipe(map((home) => home.minValueForFreeShipping));
1628
+ }
1629
+ getDiscoverProducts() {
1630
+ return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.discoverCategories)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
1631
+ }
1632
+ getFeaturedProducts() {
1633
+ return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.featuredCategories)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
1634
+ }
1635
+ getVerticalProducts() {
1636
+ 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({
1637
+ filters: { categories: { operator: Where.IN, value: [category.id] } },
1638
+ limits: { limit: 12 },
1639
+ })).pipe(map((products) => ({ category, products })))), map(({ category, products }) => ({ category, products: products.data })), map(this.buildCategoryGroupWithRequiredData))))));
1640
+ }
1641
+ getHomeConfiguration() {
1642
+ return of(this.homeConfiguration).pipe(concatMap((home) => home
1643
+ ? of(home)
1644
+ : !this.homeId
1645
+ ? throwError(new RequiredArgumentError(['homeId']))
1646
+ : from(this.homeRepository.get({ id: this.homeId })).pipe(tap((homeLoaded) => (this.homeConfiguration = homeLoaded)))));
1647
+ }
1648
+ saveHomeData(homeData) {
1649
+ const data = {
1650
+ createdAt: new Date(),
1651
+ expiresAt: add(new Date(), { hours: 1 }),
1652
+ data: homeData,
1209
1653
  };
1654
+ return from(this.homeRepository.update({
1655
+ id: this.homeId,
1656
+ data,
1657
+ })).pipe(tap(() => (this.homeConfiguration.data = data)), map(() => this.homeConfiguration));
1210
1658
  }
1211
1659
  }
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
- }] });
1660
+ 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 });
1661
+ HomeShopServiceprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService });
1662
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService, decorators: [{
1663
+ type: Injectable
1664
+ }], ctorParameters: function () {
1665
+ return [{ type: undefined, decorators: [{
1666
+ type: Inject,
1667
+ args: ['CategoryRepository']
1668
+ }] }, { type: undefined, decorators: [{
1669
+ type: Inject,
1670
+ args: ['HomeRepository']
1671
+ }] }, { type: undefined, decorators: [{
1672
+ type: Inject,
1673
+ args: ['ProductRepository']
1674
+ }] }, { type: i3.Shops, decorators: [{
1675
+ type: Inject,
1676
+ args: [DEFAULT_SHOP]
1677
+ }] }];
1678
+ } });
1679
+
1680
+ class OrderService {
1681
+ constructor(angularFirestore, orderRepository) {
1682
+ this.angularFirestore = angularFirestore;
1683
+ this.orderRepository = orderRepository;
1684
+ this.orderSubject = new Subject();
1685
+ }
1686
+ getOrder(id) {
1687
+ docSnapshots(doc(this.angularFirestore, `${this.orderRepository.collectionName}/${id}`))
1688
+ .pipe(map((doc) => Order.toInstance(doc.data())))
1689
+ .subscribe((doc) => this.orderSubject.next(doc));
1690
+ return this.orderSubject;
1691
+ }
1692
+ }
1693
+ 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 });
1694
+ OrderService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService });
1695
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService, decorators: [{
1696
+ type: Injectable
1697
+ }], ctorParameters: function () {
1698
+ return [{ type: i1$2.Firestore }, { type: i3.OrderFirestoreRepository, decorators: [{
1699
+ type: Inject,
1700
+ args: ['OrderRepository']
1701
+ }] }];
1702
+ } });
1703
+
1704
+ class ShippingService {
1705
+ constructor(http, apiUrl, homeService) {
1706
+ this.http = http;
1707
+ this.apiUrl = apiUrl;
1708
+ this.homeService = homeService;
1709
+ }
1710
+ getShippingMethods(shop, zip, weightGrams, totalPrice, personId, subscriptionPlan) {
1711
+ return combineLatest([
1712
+ this.homeService.getHomeData(),
1713
+ this.http.get(`${this.apiUrl}open/checkshippingcompany?personId=${personId}&postalCode=${zip}&weightGrams=${weightGrams}`),
1714
+ ]).pipe(map(([datas, shippingMethodsResponse]) => {
1715
+ let shippingMethods = shippingMethodsResponse.result;
1716
+ if (!shippingMethods.length)
1717
+ return [];
1718
+ shippingMethods = shippingMethods.map((shippingMethod) => {
1719
+ if (shippingMethod.ShippingCompanyName == 'Same Day EG')
1720
+ shippingMethod.ShippingCompanyName = 'Same Day';
1721
+ return shippingMethod;
1722
+ });
1723
+ const datasSameDayNotAvaliable = datas.sameDayNotAvaliable;
1724
+ if (this.isHolidays(datasSameDayNotAvaliable)) {
1725
+ shippingMethods = shippingMethods.filter((method) => method.serviceName !== 'Same Day');
1726
+ }
1727
+ if (totalPrice >= 200) {
1728
+ shippingMethods = shippingMethods.map((s) => {
1729
+ if (s.serviceName !== 'Same Day')
1730
+ return Object.assign(Object.assign({}, s), { totalPrice: 0 });
1731
+ else
1732
+ return s;
1733
+ });
1734
+ }
1735
+ if (shop == Shops.GLAMSHOP)
1736
+ return shippingMethods;
1737
+ if (this.isFreeShippingBySubscription(shop, subscriptionPlan)) {
1738
+ shippingMethods = shippingMethods.map((s) => {
1739
+ if (s.serviceName == 'Same Day')
1740
+ return Object.assign(Object.assign({}, s), { totalPrice: s.totalPrice / 2 });
1741
+ else
1742
+ return Object.assign(Object.assign({}, s), { totalPrice: 0 });
1743
+ });
1744
+ }
1745
+ if (this.isHalfShippingBySubscription(shop, subscriptionPlan)) {
1746
+ shippingMethods = shippingMethods.map((s) => {
1747
+ return Object.assign(Object.assign({}, s), { totalPrice: s.totalPrice / 2 });
1748
+ });
1749
+ }
1750
+ return shippingMethods;
1751
+ }));
1752
+ }
1753
+ isFreeShippingBySubscription(shop, subscriptionPlan) {
1754
+ if (!subscriptionPlan)
1755
+ return false;
1756
+ if (shop == Shops.MENSMARKET && subscriptionPlan == 'SELECT')
1757
+ return true;
1758
+ return false;
1759
+ }
1760
+ isHalfShippingBySubscription(shop, subscriptionPlan) {
1761
+ if (!subscriptionPlan)
1762
+ return false;
1763
+ if (shop == Shops.MENSMARKET && subscriptionPlan == 'PRIME') {
1764
+ return true;
1765
+ }
1766
+ return false;
1767
+ }
1768
+ isHolidays(datas) {
1769
+ const today = new Date();
1770
+ for (const key in datas) {
1771
+ let start = new Date(`${today.getFullYear()}-${datas[key].beginDate}`);
1772
+ let end = new Date(`${today.getFullYear()}-${datas[key].endDate}`);
1773
+ if (start > end)
1774
+ end = new Date(`${today.getFullYear() + 1}-${datas[key].endDate}`);
1775
+ if (today >= start && today <= end)
1776
+ return true;
1777
+ }
1778
+ return false;
1779
+ }
1780
+ }
1781
+ 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 });
1782
+ ShippingService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService });
1783
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService, decorators: [{
1784
+ type: Injectable
1785
+ }], ctorParameters: function () {
1786
+ return [{ type: i1$3.HttpClient }, { type: undefined, decorators: [{
1787
+ type: Inject,
1788
+ args: [BACKEND_URL]
1789
+ }] }, { type: HomeShopService }];
1790
+ } });
1321
1791
 
1322
1792
  class AngularConnectModule {
1323
1793
  static initializeApp(defaultShop, options, nameOrConfig) {
@@ -1329,6 +1799,7 @@ class AngularConnectModule {
1329
1799
  ...(isNil(options === null || options === void 0 ? void 0 : options.firebase) ? [] : [{ provide: FIREBASE_APP_NAME, useValue: nameOrConfig }]),
1330
1800
  ...(isNil(options === null || options === void 0 ? void 0 : options.elasticSearch) ? [] : [{ provide: ES_CONFIG, useValue: options.elasticSearch }]),
1331
1801
  ...(isNil(options === null || options === void 0 ? void 0 : options.hasura) ? [] : [{ provide: HASURA_OPTIONS, useValue: options.hasura }]),
1802
+ ...(isNil(options === null || options === void 0 ? void 0 : options.backendUrl) ? [] : [{ provide: BACKEND_URL, useValue: options.backendUrl }]),
1332
1803
  ],
1333
1804
  };
1334
1805
  }
@@ -1338,11 +1809,14 @@ AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", ve
1338
1809
  AngularConnectModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, providers: [
1339
1810
  AuthService,
1340
1811
  CartService,
1812
+ CatalogService,
1813
+ CategoryService,
1341
1814
  CheckoutService,
1342
1815
  CheckoutSubscriptionService,
1343
1816
  CouponService,
1344
1817
  HomeShopService,
1345
1818
  OrderService,
1819
+ ShippingService,
1346
1820
  ], imports: [AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule] });
1347
1821
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, decorators: [{
1348
1822
  type: NgModule,
@@ -1351,11 +1825,14 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
1351
1825
  providers: [
1352
1826
  AuthService,
1353
1827
  CartService,
1828
+ CatalogService,
1829
+ CategoryService,
1354
1830
  CheckoutService,
1355
1831
  CheckoutSubscriptionService,
1356
1832
  CouponService,
1357
1833
  HomeShopService,
1358
1834
  OrderService,
1835
+ ShippingService,
1359
1836
  ],
1360
1837
  }]
1361
1838
  }] });
@@ -1364,5 +1841,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
1364
1841
  * Generated bundle index. Do not edit.
1365
1842
  */
1366
1843
 
1367
- export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CheckoutService, CheckoutSubscriptionService, CouponService, HomeShopService, OrderService };
1844
+ export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CouponService, HomeShopService, OrderService, ProductSorts, ShippingService };
1368
1845
  //# sourceMappingURL=infrab4a-connect-angular.mjs.map