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

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