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

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