@infrab4a/connect-angular 4.0.0-beta.4 → 4.0.0-beta.41

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