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