@infrab4a/connect-angular 4.10.0-beta.11 → 4.10.0-beta.12

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 (62) hide show
  1. package/esm2020/angular-connect.module.mjs +133 -0
  2. package/esm2020/angular-elastic-search.module.mjs +34 -0
  3. package/esm2020/angular-firebase-auth.module.mjs +115 -0
  4. package/esm2020/angular-firestore.module.mjs +499 -0
  5. package/esm2020/angular-hasura-graphql.module.mjs +287 -0
  6. package/{esm2022 → esm2020}/persistence/cookie-data-persistence.mjs +4 -4
  7. package/{esm2022 → esm2020}/services/auth.service.mjs +6 -6
  8. package/{esm2022 → esm2020}/services/cart.service.mjs +6 -6
  9. package/{esm2022 → esm2020}/services/catalog/adapters/new-category-structure.adapter.mjs +6 -6
  10. package/{esm2022 → esm2020}/services/catalog/adapters/old-category-structure.adapter.mjs +6 -6
  11. package/{esm2022 → esm2020}/services/catalog/catalog.service.mjs +6 -6
  12. package/{esm2022 → esm2020}/services/catalog/category.service.mjs +6 -6
  13. package/{esm2022 → esm2020}/services/catalog/models/category-with-tree.model.mjs +1 -1
  14. package/{esm2022 → esm2020}/services/catalog/wishlist.service.mjs +6 -6
  15. package/{esm2022 → esm2020}/services/checkout-subscription.service.mjs +6 -6
  16. package/{esm2022 → esm2020}/services/checkout.service.mjs +6 -6
  17. package/{esm2022 → esm2020}/services/coupon.service.mjs +6 -6
  18. package/{esm2022 → esm2020}/services/home-shop.service.mjs +6 -6
  19. package/{esm2022 → esm2020}/services/order.service.mjs +6 -6
  20. package/{esm2022 → esm2020}/services/shipping.service.mjs +6 -6
  21. package/fesm2015/infrab4a-connect-angular.mjs +2534 -0
  22. package/fesm2015/infrab4a-connect-angular.mjs.map +1 -0
  23. package/{fesm2022 → fesm2020}/infrab4a-connect-angular.mjs +535 -535
  24. package/{fesm2022 → fesm2020}/infrab4a-connect-angular.mjs.map +1 -1
  25. package/package.json +12 -6
  26. package/esm2022/angular-connect.module.mjs +0 -133
  27. package/esm2022/angular-elastic-search.module.mjs +0 -34
  28. package/esm2022/angular-firebase-auth.module.mjs +0 -115
  29. package/esm2022/angular-firestore.module.mjs +0 -499
  30. package/esm2022/angular-hasura-graphql.module.mjs +0 -287
  31. /package/{esm2022 → esm2020}/consts/backend-url.const.mjs +0 -0
  32. /package/{esm2022 → esm2020}/consts/category-structure.mjs +0 -0
  33. /package/{esm2022 → esm2020}/consts/default-shop.const.mjs +0 -0
  34. /package/{esm2022 → esm2020}/consts/es-config.const.mjs +0 -0
  35. /package/{esm2022 → esm2020}/consts/firebase-const.mjs +0 -0
  36. /package/{esm2022 → esm2020}/consts/hasura-options.const.mjs +0 -0
  37. /package/{esm2022 → esm2020}/consts/index.mjs +0 -0
  38. /package/{esm2022 → esm2020}/consts/persistence.const.mjs +0 -0
  39. /package/{esm2022 → esm2020}/consts/storage-base-url.const.mjs +0 -0
  40. /package/{esm2022 → esm2020}/helpers/index.mjs +0 -0
  41. /package/{esm2022 → esm2020}/helpers/mobile-operation-system-checker.helper.mjs +0 -0
  42. /package/{esm2022 → esm2020}/index.mjs +0 -0
  43. /package/{esm2022 → esm2020}/infrab4a-connect-angular.mjs +0 -0
  44. /package/{esm2022 → esm2020}/persistence/data-persistence.mjs +0 -0
  45. /package/{esm2022 → esm2020}/persistence/index.mjs +0 -0
  46. /package/{esm2022 → esm2020}/services/catalog/adapters/category-structure.adapter.mjs +0 -0
  47. /package/{esm2022 → esm2020}/services/catalog/adapters/index.mjs +0 -0
  48. /package/{esm2022 → esm2020}/services/catalog/enums/index.mjs +0 -0
  49. /package/{esm2022 → esm2020}/services/catalog/enums/product-sorts.enum.mjs +0 -0
  50. /package/{esm2022 → esm2020}/services/catalog/index.mjs +0 -0
  51. /package/{esm2022 → esm2020}/services/catalog/models/index.mjs +0 -0
  52. /package/{esm2022 → esm2020}/services/catalog/types/index.mjs +0 -0
  53. /package/{esm2022 → esm2020}/services/catalog/types/product-sort.type.mjs +0 -0
  54. /package/{esm2022 → esm2020}/services/helpers/index.mjs +0 -0
  55. /package/{esm2022 → esm2020}/services/helpers/util.helper.mjs +0 -0
  56. /package/{esm2022 → esm2020}/services/index.mjs +0 -0
  57. /package/{esm2022 → esm2020}/services/types/index.mjs +0 -0
  58. /package/{esm2022 → esm2020}/services/types/required-checkout-data.type.mjs +0 -0
  59. /package/{esm2022 → esm2020}/services/types/required-checkout-subscription-data.type.mjs +0 -0
  60. /package/{esm2022 → esm2020}/services/types/shipping-methods.type.mjs +0 -0
  61. /package/{esm2022 → esm2020}/types/firebase-app-config.type.mjs +0 -0
  62. /package/{esm2022 → esm2020}/types/index.mjs +0 -0
@@ -0,0 +1,2534 @@
1
+ import * as i0 from '@angular/core';
2
+ import { NgModule, InjectionToken, PLATFORM_ID, Injectable, Inject } from '@angular/core';
3
+ import * as i1$4 from '@angular/fire/app';
4
+ import { FirebaseApp, provideFirebaseApp, getApp, initializeApp } from '@angular/fire/app';
5
+ import * as i2 from '@angular/fire/storage';
6
+ import { Storage, provideStorage, getStorage } from '@angular/fire/storage';
7
+ import * as i1$2 from '@infrab4a/connect';
8
+ import { ProductsIndex, AxiosAdapter, Authentication, AuthenticationFirebaseAuthService, Register, RegisterFirebaseAuthService, SignOut, RecoveryPassword, ConnectFirestoreService, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, CampaignHashtagFirestoreRepository, CampaignDashboardFirestoreRepository, SubscriptionEditionFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, ShopSettingsFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, SubscriptionMaterializationFirestoreRepository, SubscriptionSummaryFirestoreRepository, ProductVariantFirestoreRepository, OrderBlockedFirestoreRepository, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository, ProductReviewsHasuraGraphQLRepository, VariantHasuraGraphQLRepository, ProductStockNotificationHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, Where, Shops, CheckoutTypes, CouponTypes, Exclusivities, OrderStatus, isNil, NotFoundError, Checkout, pick, LineItem, RoundProductPricesHelper, set, InvalidArgumentError, Category, PersonTypes, Wishlist, CheckoutSubscription, Product, RequiredArgumentError, add, Order, UpdateUserImage, FirebaseFileUploaderService } from '@infrab4a/connect';
9
+ import * as i1 from '@angular/fire/auth';
10
+ import { Auth, provideAuth, getAuth, getIdToken, authState } from '@angular/fire/auth';
11
+ import { isPlatformBrowser, isPlatformServer } from '@angular/common';
12
+ import * as i1$1 from '@angular/fire/firestore';
13
+ import { Firestore, provideFirestore, initializeFirestore, memoryLocalCache, docSnapshots, doc } from '@angular/fire/firestore';
14
+ import cookie from 'js-cookie';
15
+ import { of, from, combineLatest, throwError, Subject, iif, forkJoin } from 'rxjs';
16
+ import { map, mergeMap, catchError, concatMap, tap } from 'rxjs/operators';
17
+ import { __awaiter, __decorate, __metadata } from 'tslib';
18
+ import { Type } from 'class-transformer';
19
+ import * as i1$3 from '@angular/common/http';
20
+
21
+ const ES_CONFIG = 'ES_CONFIG';
22
+
23
+ class AngularElasticSeachModule {
24
+ static initializeApp(options) {
25
+ return {
26
+ ngModule: AngularElasticSeachModule,
27
+ providers: [{ provide: ES_CONFIG, useValue: options }],
28
+ };
29
+ }
30
+ }
31
+ AngularElasticSeachModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
32
+ AngularElasticSeachModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule });
33
+ AngularElasticSeachModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, providers: [
34
+ {
35
+ provide: ProductsIndex,
36
+ useFactory: (configuration) => new ProductsIndex(new AxiosAdapter(configuration)),
37
+ deps: [ES_CONFIG],
38
+ },
39
+ ] });
40
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularElasticSeachModule, decorators: [{
41
+ type: NgModule,
42
+ args: [{
43
+ providers: [
44
+ {
45
+ provide: ProductsIndex,
46
+ useFactory: (configuration) => new ProductsIndex(new AxiosAdapter(configuration)),
47
+ deps: [ES_CONFIG],
48
+ },
49
+ ],
50
+ }]
51
+ }] });
52
+
53
+ const BACKEND_URL = 'BACKEND_URL';
54
+
55
+ const CATEGORY_STRUCTURE = 'CATEGORY_STRUCTURE';
56
+
57
+ const DEFAULT_SHOP = 'DEFAULT_SHOP';
58
+
59
+ const FIREBASE_APP_NAME = new InjectionToken('firebaseAppName');
60
+ const FIREBASE_OPTIONS = new InjectionToken('firebaseOptions');
61
+
62
+ const HASURA_OPTIONS = 'HASURA_OPTIONS';
63
+
64
+ const PERSISTENCE_PROVIDER = 'PERSISTENCE_PROVIDER';
65
+
66
+ class AngularFirebaseAuthModule {
67
+ static initializeApp(options, nameOrConfig) {
68
+ return {
69
+ ngModule: AngularFirebaseAuthModule,
70
+ providers: [
71
+ { provide: FIREBASE_OPTIONS, useValue: options },
72
+ { provide: FIREBASE_APP_NAME, useValue: nameOrConfig },
73
+ ],
74
+ };
75
+ }
76
+ }
77
+ AngularFirebaseAuthModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
78
+ AngularFirebaseAuthModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, imports: [i1.AuthModule] });
79
+ AngularFirebaseAuthModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, providers: [
80
+ {
81
+ provide: 'Authentication',
82
+ useFactory: (authenticationService, userRepository) => {
83
+ return new Authentication(authenticationService, userRepository);
84
+ },
85
+ deps: ['AuthenticationService', 'UserRepository'],
86
+ },
87
+ {
88
+ provide: 'AuthenticationService',
89
+ useFactory: (angularFireAuth) => {
90
+ return new AuthenticationFirebaseAuthService(angularFireAuth);
91
+ },
92
+ deps: [Auth],
93
+ },
94
+ {
95
+ provide: 'Register',
96
+ useFactory: (registerService, userRepository) => {
97
+ return new Register(registerService, userRepository);
98
+ },
99
+ deps: ['RegisterService', 'UserRepository'],
100
+ },
101
+ {
102
+ provide: 'RegisterService',
103
+ useFactory: (angularFireAuth) => {
104
+ return new RegisterFirebaseAuthService(angularFireAuth);
105
+ },
106
+ deps: [Auth],
107
+ },
108
+ {
109
+ provide: 'SignOut',
110
+ useFactory: (authenticationService) => {
111
+ return new SignOut(authenticationService);
112
+ },
113
+ deps: ['AuthenticationService'],
114
+ },
115
+ {
116
+ provide: 'RecoveryPassword',
117
+ useFactory: (authenticationService) => {
118
+ return new RecoveryPassword(authenticationService);
119
+ },
120
+ deps: ['AuthenticationService'],
121
+ },
122
+ ], imports: [provideAuth((injector) => getAuth(injector.get(FirebaseApp)))] });
123
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, decorators: [{
124
+ type: NgModule,
125
+ args: [{
126
+ imports: [provideAuth((injector) => getAuth(injector.get(FirebaseApp)))],
127
+ providers: [
128
+ {
129
+ provide: 'Authentication',
130
+ useFactory: (authenticationService, userRepository) => {
131
+ return new Authentication(authenticationService, userRepository);
132
+ },
133
+ deps: ['AuthenticationService', 'UserRepository'],
134
+ },
135
+ {
136
+ provide: 'AuthenticationService',
137
+ useFactory: (angularFireAuth) => {
138
+ return new AuthenticationFirebaseAuthService(angularFireAuth);
139
+ },
140
+ deps: [Auth],
141
+ },
142
+ {
143
+ provide: 'Register',
144
+ useFactory: (registerService, userRepository) => {
145
+ return new Register(registerService, userRepository);
146
+ },
147
+ deps: ['RegisterService', 'UserRepository'],
148
+ },
149
+ {
150
+ provide: 'RegisterService',
151
+ useFactory: (angularFireAuth) => {
152
+ return new RegisterFirebaseAuthService(angularFireAuth);
153
+ },
154
+ deps: [Auth],
155
+ },
156
+ {
157
+ provide: 'SignOut',
158
+ useFactory: (authenticationService) => {
159
+ return new SignOut(authenticationService);
160
+ },
161
+ deps: ['AuthenticationService'],
162
+ },
163
+ {
164
+ provide: 'RecoveryPassword',
165
+ useFactory: (authenticationService) => {
166
+ return new RecoveryPassword(authenticationService);
167
+ },
168
+ deps: ['AuthenticationService'],
169
+ },
170
+ ],
171
+ }]
172
+ }] });
173
+
174
+ class MobileOperationSystemCheckerHelper {
175
+ static isAppleDevice() {
176
+ var _a, _b;
177
+ return (['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(navigator === null || navigator === void 0 ? void 0 : navigator.platform) ||
178
+ (((_b = (_a = navigator === null || navigator === void 0 ? void 0 : navigator.userAgent) === null || _a === void 0 ? void 0 : _a.includes) === null || _b === void 0 ? void 0 : _b.call(_a, 'Mac')) && 'ontouchend' in (document || {})));
179
+ }
180
+ }
181
+
182
+ class AngularFirestoreModule {
183
+ static initializeApp(options, nameOrConfig) {
184
+ return {
185
+ ngModule: AngularFirestoreModule,
186
+ providers: [
187
+ { provide: FIREBASE_OPTIONS, useValue: options.firebase },
188
+ { provide: FIREBASE_APP_NAME, useValue: nameOrConfig },
189
+ { provide: ES_CONFIG, useValue: options.elasticSearch },
190
+ ],
191
+ };
192
+ }
193
+ }
194
+ AngularFirestoreModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
195
+ AngularFirestoreModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, imports: [AngularElasticSeachModule, i1$1.FirestoreModule] });
196
+ AngularFirestoreModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, providers: [
197
+ {
198
+ provide: 'FirestoreOptions',
199
+ useFactory: (firestore, platformId) => ({
200
+ firestore: new ConnectFirestoreService(firestore),
201
+ interceptors: {
202
+ request: (request) => {
203
+ if (isPlatformBrowser(platformId))
204
+ return request;
205
+ const interval = setInterval(() => { }, 100);
206
+ request.interval = interval;
207
+ return request;
208
+ },
209
+ response: (response, request) => {
210
+ if (isPlatformBrowser(platformId))
211
+ return response;
212
+ clearInterval(request.interval);
213
+ return response;
214
+ },
215
+ },
216
+ }),
217
+ deps: [Firestore, PLATFORM_ID],
218
+ },
219
+ {
220
+ provide: 'BeautyProfileRepository',
221
+ useFactory: (config, userRepository) => {
222
+ return new UserBeautyProfileFirestoreRepository(config, userRepository);
223
+ },
224
+ deps: ['FirestoreOptions', 'UserRepository'],
225
+ },
226
+ {
227
+ provide: 'Buy2WinRepository',
228
+ useFactory: (options) => {
229
+ return new Buy2WinFirestoreRepository(options);
230
+ },
231
+ deps: ['FirestoreOptions'],
232
+ },
233
+ {
234
+ provide: CategoryFirestoreRepository,
235
+ useFactory: (options) => {
236
+ return new CategoryFirestoreRepository(options);
237
+ },
238
+ deps: ['FirestoreOptions'],
239
+ },
240
+ {
241
+ provide: 'CheckoutRepository',
242
+ useFactory: (options) => {
243
+ return new CheckoutFirestoreRepository(options);
244
+ },
245
+ deps: ['FirestoreOptions'],
246
+ },
247
+ {
248
+ provide: 'CheckoutSubscriptionRepository',
249
+ useFactory: (options) => {
250
+ return new CheckoutSubscriptionFirestoreRepository(options);
251
+ },
252
+ deps: ['FirestoreOptions'],
253
+ },
254
+ {
255
+ provide: 'CouponRepository',
256
+ useFactory: (options) => {
257
+ return new CouponFirestoreRepository(options);
258
+ },
259
+ deps: ['FirestoreOptions'],
260
+ },
261
+ {
262
+ provide: 'CampaignHashtagRepository',
263
+ useFactory: (options) => {
264
+ return new CampaignHashtagFirestoreRepository(options);
265
+ },
266
+ deps: ['FirestoreOptions'],
267
+ },
268
+ {
269
+ provide: 'CampaignDashboardRepository',
270
+ useFactory: (options) => {
271
+ return new CampaignDashboardFirestoreRepository(options);
272
+ },
273
+ deps: ['FirestoreOptions'],
274
+ },
275
+ {
276
+ provide: 'EditionRepository',
277
+ useFactory: (options, subscriptionRepository) => {
278
+ return new SubscriptionEditionFirestoreRepository(options, subscriptionRepository);
279
+ },
280
+ deps: ['FirestoreOptions', 'SubscriptionRepository'],
281
+ },
282
+ {
283
+ provide: 'HomeRepository',
284
+ useFactory: (options) => {
285
+ return new HomeFirestoreRepository(options);
286
+ },
287
+ deps: ['FirestoreOptions'],
288
+ },
289
+ {
290
+ provide: 'LeadRepository',
291
+ useFactory: (options) => {
292
+ return new LeadFirestoreRepository(options);
293
+ },
294
+ deps: ['FirestoreOptions'],
295
+ },
296
+ {
297
+ provide: 'LegacyOrderRepository',
298
+ useFactory: (options) => {
299
+ return new LegacyOrderFirestoreRepository(options);
300
+ },
301
+ deps: ['FirestoreOptions'],
302
+ },
303
+ {
304
+ provide: 'ShopMenuRepository',
305
+ useFactory: (options) => {
306
+ return new ShopMenuFirestoreRepository(options);
307
+ },
308
+ deps: ['FirestoreOptions'],
309
+ },
310
+ {
311
+ provide: 'OrderRepository',
312
+ useFactory: (options) => {
313
+ return new OrderFirestoreRepository(options);
314
+ },
315
+ deps: ['FirestoreOptions'],
316
+ },
317
+ {
318
+ provide: 'PaymentRepository',
319
+ useFactory: (options) => {
320
+ return new PaymentFirestoreRepository(options);
321
+ },
322
+ deps: ['FirestoreOptions'],
323
+ },
324
+ {
325
+ provide: ProductFirestoreRepository,
326
+ useFactory: (options) => {
327
+ return new ProductFirestoreRepository(options);
328
+ },
329
+ deps: ['FirestoreOptions'],
330
+ },
331
+ {
332
+ provide: 'ShopSettingsRepository',
333
+ useFactory: (options) => {
334
+ return new ShopSettingsFirestoreRepository(options);
335
+ },
336
+ deps: ['FirestoreOptions'],
337
+ },
338
+ {
339
+ provide: 'SubscriptionPaymentRepository',
340
+ useFactory: (options, subscriptionRepository) => {
341
+ return new SubscriptionPaymentFirestoreRepository(options, subscriptionRepository);
342
+ },
343
+ deps: ['FirestoreOptions', 'SubscriptionRepository'],
344
+ },
345
+ {
346
+ provide: 'SubscriptionPlanRepository',
347
+ useFactory: (options) => {
348
+ return new SubscriptionPlanFirestoreRepository(options);
349
+ },
350
+ deps: ['FirestoreOptions'],
351
+ },
352
+ {
353
+ provide: 'SubscriptionProductRepository',
354
+ useFactory: (options) => {
355
+ return new SubscriptionProductFirestoreRepository(options);
356
+ },
357
+ deps: ['FirestoreOptions'],
358
+ },
359
+ {
360
+ provide: 'SubscriptionRepository',
361
+ useFactory: (options) => {
362
+ return new SubscriptionFirestoreRepository(options);
363
+ },
364
+ deps: ['FirestoreOptions'],
365
+ },
366
+ {
367
+ provide: 'UserRepository',
368
+ useFactory: (options) => {
369
+ return new UserFirestoreRepository(options);
370
+ },
371
+ deps: ['FirestoreOptions'],
372
+ },
373
+ {
374
+ provide: 'UserAddressRepository',
375
+ useFactory: (options, userRepository) => {
376
+ return new UserAddressFirestoreRepository(options, userRepository);
377
+ },
378
+ deps: ['FirestoreOptions', 'UserRepository'],
379
+ },
380
+ {
381
+ provide: 'UserPaymentMethodRepository',
382
+ useFactory: (options, userRepository) => {
383
+ return new UserPaymentMethodFirestoreRepository(options, userRepository);
384
+ },
385
+ deps: ['FirestoreOptions', 'UserRepository'],
386
+ },
387
+ {
388
+ provide: 'SubscriptionMaterializationRepository',
389
+ useFactory: (options) => {
390
+ return new SubscriptionMaterializationFirestoreRepository(options);
391
+ },
392
+ deps: ['FirestoreOptions'],
393
+ },
394
+ {
395
+ provide: 'SubscriptionSummaryRepository',
396
+ useFactory: (options) => {
397
+ return new SubscriptionSummaryFirestoreRepository(options);
398
+ },
399
+ deps: ['FirestoreOptions'],
400
+ },
401
+ {
402
+ provide: ProductVariantFirestoreRepository,
403
+ useFactory: (options, productRepository) => {
404
+ return new ProductVariantFirestoreRepository(options, productRepository);
405
+ },
406
+ deps: ['FirestoreOptions', ProductFirestoreRepository],
407
+ },
408
+ {
409
+ provide: 'OrderBlockedRepository',
410
+ useFactory: (options) => {
411
+ return new OrderBlockedFirestoreRepository(options);
412
+ },
413
+ deps: ['FirestoreOptions'],
414
+ },
415
+ ], imports: [AngularElasticSeachModule,
416
+ provideFirestore((injector) => {
417
+ const platformId = injector.get(PLATFORM_ID);
418
+ if (isPlatformServer(platformId) || !MobileOperationSystemCheckerHelper.isAppleDevice())
419
+ return initializeFirestore(injector.get(FirebaseApp), {
420
+ ignoreUndefinedProperties: true,
421
+ });
422
+ const firestore = initializeFirestore(injector.get(FirebaseApp), {
423
+ experimentalForceLongPolling: true,
424
+ ignoreUndefinedProperties: true,
425
+ localCache: memoryLocalCache(),
426
+ });
427
+ return firestore;
428
+ })] });
429
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirestoreModule, decorators: [{
430
+ type: NgModule,
431
+ args: [{
432
+ imports: [
433
+ AngularElasticSeachModule,
434
+ provideFirestore((injector) => {
435
+ const platformId = injector.get(PLATFORM_ID);
436
+ if (isPlatformServer(platformId) || !MobileOperationSystemCheckerHelper.isAppleDevice())
437
+ return initializeFirestore(injector.get(FirebaseApp), {
438
+ ignoreUndefinedProperties: true,
439
+ });
440
+ const firestore = initializeFirestore(injector.get(FirebaseApp), {
441
+ experimentalForceLongPolling: true,
442
+ ignoreUndefinedProperties: true,
443
+ localCache: memoryLocalCache(),
444
+ });
445
+ return firestore;
446
+ }),
447
+ ],
448
+ providers: [
449
+ {
450
+ provide: 'FirestoreOptions',
451
+ useFactory: (firestore, platformId) => ({
452
+ firestore: new ConnectFirestoreService(firestore),
453
+ interceptors: {
454
+ request: (request) => {
455
+ if (isPlatformBrowser(platformId))
456
+ return request;
457
+ const interval = setInterval(() => { }, 100);
458
+ request.interval = interval;
459
+ return request;
460
+ },
461
+ response: (response, request) => {
462
+ if (isPlatformBrowser(platformId))
463
+ return response;
464
+ clearInterval(request.interval);
465
+ return response;
466
+ },
467
+ },
468
+ }),
469
+ deps: [Firestore, PLATFORM_ID],
470
+ },
471
+ {
472
+ provide: 'BeautyProfileRepository',
473
+ useFactory: (config, userRepository) => {
474
+ return new UserBeautyProfileFirestoreRepository(config, userRepository);
475
+ },
476
+ deps: ['FirestoreOptions', 'UserRepository'],
477
+ },
478
+ {
479
+ provide: 'Buy2WinRepository',
480
+ useFactory: (options) => {
481
+ return new Buy2WinFirestoreRepository(options);
482
+ },
483
+ deps: ['FirestoreOptions'],
484
+ },
485
+ {
486
+ provide: CategoryFirestoreRepository,
487
+ useFactory: (options) => {
488
+ return new CategoryFirestoreRepository(options);
489
+ },
490
+ deps: ['FirestoreOptions'],
491
+ },
492
+ {
493
+ provide: 'CheckoutRepository',
494
+ useFactory: (options) => {
495
+ return new CheckoutFirestoreRepository(options);
496
+ },
497
+ deps: ['FirestoreOptions'],
498
+ },
499
+ {
500
+ provide: 'CheckoutSubscriptionRepository',
501
+ useFactory: (options) => {
502
+ return new CheckoutSubscriptionFirestoreRepository(options);
503
+ },
504
+ deps: ['FirestoreOptions'],
505
+ },
506
+ {
507
+ provide: 'CouponRepository',
508
+ useFactory: (options) => {
509
+ return new CouponFirestoreRepository(options);
510
+ },
511
+ deps: ['FirestoreOptions'],
512
+ },
513
+ {
514
+ provide: 'CampaignHashtagRepository',
515
+ useFactory: (options) => {
516
+ return new CampaignHashtagFirestoreRepository(options);
517
+ },
518
+ deps: ['FirestoreOptions'],
519
+ },
520
+ {
521
+ provide: 'CampaignDashboardRepository',
522
+ useFactory: (options) => {
523
+ return new CampaignDashboardFirestoreRepository(options);
524
+ },
525
+ deps: ['FirestoreOptions'],
526
+ },
527
+ {
528
+ provide: 'EditionRepository',
529
+ useFactory: (options, subscriptionRepository) => {
530
+ return new SubscriptionEditionFirestoreRepository(options, subscriptionRepository);
531
+ },
532
+ deps: ['FirestoreOptions', 'SubscriptionRepository'],
533
+ },
534
+ {
535
+ provide: 'HomeRepository',
536
+ useFactory: (options) => {
537
+ return new HomeFirestoreRepository(options);
538
+ },
539
+ deps: ['FirestoreOptions'],
540
+ },
541
+ {
542
+ provide: 'LeadRepository',
543
+ useFactory: (options) => {
544
+ return new LeadFirestoreRepository(options);
545
+ },
546
+ deps: ['FirestoreOptions'],
547
+ },
548
+ {
549
+ provide: 'LegacyOrderRepository',
550
+ useFactory: (options) => {
551
+ return new LegacyOrderFirestoreRepository(options);
552
+ },
553
+ deps: ['FirestoreOptions'],
554
+ },
555
+ {
556
+ provide: 'ShopMenuRepository',
557
+ useFactory: (options) => {
558
+ return new ShopMenuFirestoreRepository(options);
559
+ },
560
+ deps: ['FirestoreOptions'],
561
+ },
562
+ {
563
+ provide: 'OrderRepository',
564
+ useFactory: (options) => {
565
+ return new OrderFirestoreRepository(options);
566
+ },
567
+ deps: ['FirestoreOptions'],
568
+ },
569
+ {
570
+ provide: 'PaymentRepository',
571
+ useFactory: (options) => {
572
+ return new PaymentFirestoreRepository(options);
573
+ },
574
+ deps: ['FirestoreOptions'],
575
+ },
576
+ {
577
+ provide: ProductFirestoreRepository,
578
+ useFactory: (options) => {
579
+ return new ProductFirestoreRepository(options);
580
+ },
581
+ deps: ['FirestoreOptions'],
582
+ },
583
+ {
584
+ provide: 'ShopSettingsRepository',
585
+ useFactory: (options) => {
586
+ return new ShopSettingsFirestoreRepository(options);
587
+ },
588
+ deps: ['FirestoreOptions'],
589
+ },
590
+ {
591
+ provide: 'SubscriptionPaymentRepository',
592
+ useFactory: (options, subscriptionRepository) => {
593
+ return new SubscriptionPaymentFirestoreRepository(options, subscriptionRepository);
594
+ },
595
+ deps: ['FirestoreOptions', 'SubscriptionRepository'],
596
+ },
597
+ {
598
+ provide: 'SubscriptionPlanRepository',
599
+ useFactory: (options) => {
600
+ return new SubscriptionPlanFirestoreRepository(options);
601
+ },
602
+ deps: ['FirestoreOptions'],
603
+ },
604
+ {
605
+ provide: 'SubscriptionProductRepository',
606
+ useFactory: (options) => {
607
+ return new SubscriptionProductFirestoreRepository(options);
608
+ },
609
+ deps: ['FirestoreOptions'],
610
+ },
611
+ {
612
+ provide: 'SubscriptionRepository',
613
+ useFactory: (options) => {
614
+ return new SubscriptionFirestoreRepository(options);
615
+ },
616
+ deps: ['FirestoreOptions'],
617
+ },
618
+ {
619
+ provide: 'UserRepository',
620
+ useFactory: (options) => {
621
+ return new UserFirestoreRepository(options);
622
+ },
623
+ deps: ['FirestoreOptions'],
624
+ },
625
+ {
626
+ provide: 'UserAddressRepository',
627
+ useFactory: (options, userRepository) => {
628
+ return new UserAddressFirestoreRepository(options, userRepository);
629
+ },
630
+ deps: ['FirestoreOptions', 'UserRepository'],
631
+ },
632
+ {
633
+ provide: 'UserPaymentMethodRepository',
634
+ useFactory: (options, userRepository) => {
635
+ return new UserPaymentMethodFirestoreRepository(options, userRepository);
636
+ },
637
+ deps: ['FirestoreOptions', 'UserRepository'],
638
+ },
639
+ {
640
+ provide: 'SubscriptionMaterializationRepository',
641
+ useFactory: (options) => {
642
+ return new SubscriptionMaterializationFirestoreRepository(options);
643
+ },
644
+ deps: ['FirestoreOptions'],
645
+ },
646
+ {
647
+ provide: 'SubscriptionSummaryRepository',
648
+ useFactory: (options) => {
649
+ return new SubscriptionSummaryFirestoreRepository(options);
650
+ },
651
+ deps: ['FirestoreOptions'],
652
+ },
653
+ {
654
+ provide: ProductVariantFirestoreRepository,
655
+ useFactory: (options, productRepository) => {
656
+ return new ProductVariantFirestoreRepository(options, productRepository);
657
+ },
658
+ deps: ['FirestoreOptions', ProductFirestoreRepository],
659
+ },
660
+ {
661
+ provide: 'OrderBlockedRepository',
662
+ useFactory: (options) => {
663
+ return new OrderBlockedFirestoreRepository(options);
664
+ },
665
+ deps: ['FirestoreOptions'],
666
+ },
667
+ ],
668
+ }]
669
+ }] });
670
+
671
+ class AngularHasuraGraphQLModule {
672
+ static initializeApp(options) {
673
+ return {
674
+ ngModule: AngularHasuraGraphQLModule,
675
+ providers: [{ provide: HASURA_OPTIONS, useValue: options }],
676
+ };
677
+ }
678
+ }
679
+ AngularHasuraGraphQLModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
680
+ AngularHasuraGraphQLModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule });
681
+ AngularHasuraGraphQLModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, providers: [
682
+ {
683
+ provide: 'HasuraConfig',
684
+ useFactory: (options, platformId) => ({
685
+ endpoint: options.endpoint,
686
+ authOptions: options.credentials,
687
+ interceptors: {
688
+ request: (request) => {
689
+ if (isPlatformBrowser(platformId))
690
+ return request;
691
+ const interval = setInterval(() => { }, 100);
692
+ request.interval = interval;
693
+ return request;
694
+ },
695
+ response: (response, request) => {
696
+ if (isPlatformBrowser(platformId))
697
+ return response;
698
+ clearInterval(request.interval);
699
+ return response;
700
+ },
701
+ },
702
+ }),
703
+ deps: [HASURA_OPTIONS, PLATFORM_ID],
704
+ },
705
+ {
706
+ provide: 'CategoryRepository',
707
+ useExisting: CategoryHasuraGraphQLRepository,
708
+ },
709
+ {
710
+ provide: CategoryHasuraGraphQLRepository,
711
+ useFactory: (options, productRepository, categoryFilterRepository) => {
712
+ return new CategoryHasuraGraphQLRepository(options, productRepository, categoryFilterRepository);
713
+ },
714
+ deps: ['HasuraConfig', ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
715
+ },
716
+ {
717
+ provide: 'ProductRepository',
718
+ useExisting: ProductHasuraGraphQLRepository,
719
+ },
720
+ {
721
+ provide: ProductHasuraGraphQLRepository,
722
+ useFactory: (hasuraConfig) => {
723
+ return new ProductHasuraGraphQLRepository(hasuraConfig);
724
+ },
725
+ deps: ['HasuraConfig'],
726
+ },
727
+ {
728
+ provide: 'ProductReviewsRepository',
729
+ useExisting: ProductReviewsHasuraGraphQLRepository,
730
+ },
731
+ {
732
+ provide: ProductReviewsHasuraGraphQLRepository,
733
+ useFactory: (hasuraConfig) => {
734
+ return new ProductReviewsHasuraGraphQLRepository(hasuraConfig);
735
+ },
736
+ deps: ['HasuraConfig'],
737
+ },
738
+ {
739
+ provide: 'VariantRepository',
740
+ useExisting: VariantHasuraGraphQLRepository,
741
+ },
742
+ {
743
+ provide: VariantHasuraGraphQLRepository,
744
+ useFactory: (hasuraConfig) => {
745
+ return new VariantHasuraGraphQLRepository(hasuraConfig);
746
+ },
747
+ deps: ['HasuraConfig'],
748
+ },
749
+ {
750
+ provide: 'ProductStockNotificationRepository',
751
+ useExisting: ProductStockNotificationHasuraGraphQLRepository,
752
+ },
753
+ {
754
+ provide: ProductStockNotificationHasuraGraphQLRepository,
755
+ useFactory: (hasuraConfig) => {
756
+ return new ProductStockNotificationHasuraGraphQLRepository(hasuraConfig);
757
+ },
758
+ deps: ['HasuraConfig'],
759
+ },
760
+ {
761
+ provide: 'CategoryFilterRepository',
762
+ useExisting: CategoryFilterHasuraGraphQLRepository,
763
+ },
764
+ {
765
+ provide: CategoryFilterHasuraGraphQLRepository,
766
+ useFactory: (options) => {
767
+ return new CategoryFilterHasuraGraphQLRepository(options);
768
+ },
769
+ deps: ['HasuraConfig'],
770
+ },
771
+ {
772
+ provide: 'FilterOptionRepository',
773
+ useExisting: FilterOptionHasuraGraphQLRepository,
774
+ },
775
+ {
776
+ provide: FilterOptionHasuraGraphQLRepository,
777
+ useFactory: (options) => {
778
+ return new FilterOptionHasuraGraphQLRepository(options);
779
+ },
780
+ deps: ['HasuraConfig'],
781
+ },
782
+ {
783
+ provide: 'FilterRepository',
784
+ useExisting: FilterHasuraGraphQLRepository,
785
+ },
786
+ {
787
+ provide: FilterHasuraGraphQLRepository,
788
+ useFactory: (options, filterOptionRepository, categoryFilterRepository) => {
789
+ return new FilterHasuraGraphQLRepository(options, filterOptionRepository, categoryFilterRepository);
790
+ },
791
+ deps: ['HasuraConfig', FilterOptionHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
792
+ },
793
+ {
794
+ provide: CategoryCollectionChildrenHasuraGraphQLRepository,
795
+ useFactory: (options) => new CategoryCollectionChildrenHasuraGraphQLRepository(options),
796
+ deps: ['HasuraConfig'],
797
+ },
798
+ {
799
+ provide: 'CategoryCollectionChildrenRepository',
800
+ useExisting: CategoryCollectionChildrenHasuraGraphQLRepository,
801
+ },
802
+ {
803
+ provide: WishlistHasuraGraphQLRepository,
804
+ useFactory: (options, categoryFilterRepository) => {
805
+ return new WishlistHasuraGraphQLRepository(options, categoryFilterRepository);
806
+ },
807
+ deps: ['HasuraConfig', CategoryFilterHasuraGraphQLRepository],
808
+ },
809
+ {
810
+ provide: 'WishlistRepository',
811
+ useExisting: WishlistHasuraGraphQLRepository,
812
+ },
813
+ ] });
814
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularHasuraGraphQLModule, decorators: [{
815
+ type: NgModule,
816
+ args: [{
817
+ providers: [
818
+ {
819
+ provide: 'HasuraConfig',
820
+ useFactory: (options, platformId) => ({
821
+ endpoint: options.endpoint,
822
+ authOptions: options.credentials,
823
+ interceptors: {
824
+ request: (request) => {
825
+ if (isPlatformBrowser(platformId))
826
+ return request;
827
+ const interval = setInterval(() => { }, 100);
828
+ request.interval = interval;
829
+ return request;
830
+ },
831
+ response: (response, request) => {
832
+ if (isPlatformBrowser(platformId))
833
+ return response;
834
+ clearInterval(request.interval);
835
+ return response;
836
+ },
837
+ },
838
+ }),
839
+ deps: [HASURA_OPTIONS, PLATFORM_ID],
840
+ },
841
+ {
842
+ provide: 'CategoryRepository',
843
+ useExisting: CategoryHasuraGraphQLRepository,
844
+ },
845
+ {
846
+ provide: CategoryHasuraGraphQLRepository,
847
+ useFactory: (options, productRepository, categoryFilterRepository) => {
848
+ return new CategoryHasuraGraphQLRepository(options, productRepository, categoryFilterRepository);
849
+ },
850
+ deps: ['HasuraConfig', ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
851
+ },
852
+ {
853
+ provide: 'ProductRepository',
854
+ useExisting: ProductHasuraGraphQLRepository,
855
+ },
856
+ {
857
+ provide: ProductHasuraGraphQLRepository,
858
+ useFactory: (hasuraConfig) => {
859
+ return new ProductHasuraGraphQLRepository(hasuraConfig);
860
+ },
861
+ deps: ['HasuraConfig'],
862
+ },
863
+ {
864
+ provide: 'ProductReviewsRepository',
865
+ useExisting: ProductReviewsHasuraGraphQLRepository,
866
+ },
867
+ {
868
+ provide: ProductReviewsHasuraGraphQLRepository,
869
+ useFactory: (hasuraConfig) => {
870
+ return new ProductReviewsHasuraGraphQLRepository(hasuraConfig);
871
+ },
872
+ deps: ['HasuraConfig'],
873
+ },
874
+ {
875
+ provide: 'VariantRepository',
876
+ useExisting: VariantHasuraGraphQLRepository,
877
+ },
878
+ {
879
+ provide: VariantHasuraGraphQLRepository,
880
+ useFactory: (hasuraConfig) => {
881
+ return new VariantHasuraGraphQLRepository(hasuraConfig);
882
+ },
883
+ deps: ['HasuraConfig'],
884
+ },
885
+ {
886
+ provide: 'ProductStockNotificationRepository',
887
+ useExisting: ProductStockNotificationHasuraGraphQLRepository,
888
+ },
889
+ {
890
+ provide: ProductStockNotificationHasuraGraphQLRepository,
891
+ useFactory: (hasuraConfig) => {
892
+ return new ProductStockNotificationHasuraGraphQLRepository(hasuraConfig);
893
+ },
894
+ deps: ['HasuraConfig'],
895
+ },
896
+ {
897
+ provide: 'CategoryFilterRepository',
898
+ useExisting: CategoryFilterHasuraGraphQLRepository,
899
+ },
900
+ {
901
+ provide: CategoryFilterHasuraGraphQLRepository,
902
+ useFactory: (options) => {
903
+ return new CategoryFilterHasuraGraphQLRepository(options);
904
+ },
905
+ deps: ['HasuraConfig'],
906
+ },
907
+ {
908
+ provide: 'FilterOptionRepository',
909
+ useExisting: FilterOptionHasuraGraphQLRepository,
910
+ },
911
+ {
912
+ provide: FilterOptionHasuraGraphQLRepository,
913
+ useFactory: (options) => {
914
+ return new FilterOptionHasuraGraphQLRepository(options);
915
+ },
916
+ deps: ['HasuraConfig'],
917
+ },
918
+ {
919
+ provide: 'FilterRepository',
920
+ useExisting: FilterHasuraGraphQLRepository,
921
+ },
922
+ {
923
+ provide: FilterHasuraGraphQLRepository,
924
+ useFactory: (options, filterOptionRepository, categoryFilterRepository) => {
925
+ return new FilterHasuraGraphQLRepository(options, filterOptionRepository, categoryFilterRepository);
926
+ },
927
+ deps: ['HasuraConfig', FilterOptionHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository],
928
+ },
929
+ {
930
+ provide: CategoryCollectionChildrenHasuraGraphQLRepository,
931
+ useFactory: (options) => new CategoryCollectionChildrenHasuraGraphQLRepository(options),
932
+ deps: ['HasuraConfig'],
933
+ },
934
+ {
935
+ provide: 'CategoryCollectionChildrenRepository',
936
+ useExisting: CategoryCollectionChildrenHasuraGraphQLRepository,
937
+ },
938
+ {
939
+ provide: WishlistHasuraGraphQLRepository,
940
+ useFactory: (options, categoryFilterRepository) => {
941
+ return new WishlistHasuraGraphQLRepository(options, categoryFilterRepository);
942
+ },
943
+ deps: ['HasuraConfig', CategoryFilterHasuraGraphQLRepository],
944
+ },
945
+ {
946
+ provide: 'WishlistRepository',
947
+ useExisting: WishlistHasuraGraphQLRepository,
948
+ },
949
+ ],
950
+ }]
951
+ }] });
952
+
953
+ const STORAGE_BASE_URL = 'STORAGE_BASE_URL';
954
+
955
+ class CookieDataPersistence {
956
+ get(key) {
957
+ return of(cookie.get(key));
958
+ }
959
+ remove(key) {
960
+ return of(cookie.remove(key));
961
+ }
962
+ set(key, value) {
963
+ return from(cookie.set(key, value)).pipe(map(() => { }));
964
+ }
965
+ }
966
+ CookieDataPersistence.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CookieDataPersistence, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
967
+ CookieDataPersistence.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CookieDataPersistence });
968
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CookieDataPersistence, decorators: [{
969
+ type: Injectable
970
+ }] });
971
+
972
+ class AuthService {
973
+ constructor(angularFireAuth, userRepository) {
974
+ this.angularFireAuth = angularFireAuth;
975
+ this.userRepository = userRepository;
976
+ }
977
+ getAuthstate() {
978
+ const observables = [this.getFireUser(), this.getUser()];
979
+ return combineLatest(observables).pipe(map(([fireUser, user]) => ({
980
+ user,
981
+ isAnonymous: fireUser === null || fireUser === void 0 ? void 0 : fireUser.isAnonymous,
982
+ })));
983
+ }
984
+ getUser() {
985
+ return this.getFireUser().pipe(map((user) => user === null || user === void 0 ? void 0 : user.uid), mergeMap((id) => (id ? from(this.userRepository.get({ id })).pipe(catchError(() => of(null))) : of(null))));
986
+ }
987
+ getTokenId() {
988
+ return from(getIdToken(this.angularFireAuth.currentUser));
989
+ }
990
+ getFireUser() {
991
+ return authState(this.angularFireAuth).pipe(catchError(() => of(null)));
992
+ }
993
+ }
994
+ 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 });
995
+ AuthService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AuthService });
996
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AuthService, decorators: [{
997
+ type: Injectable
998
+ }], ctorParameters: function () {
999
+ return [{ type: i1.Auth }, { type: undefined, decorators: [{
1000
+ type: Inject,
1001
+ args: ['UserRepository']
1002
+ }] }];
1003
+ } });
1004
+
1005
+ class CouponService {
1006
+ constructor(couponRepository, defaultShop, orderRepository, categoryRepository) {
1007
+ this.couponRepository = couponRepository;
1008
+ this.defaultShop = defaultShop;
1009
+ this.orderRepository = orderRepository;
1010
+ this.categoryRepository = categoryRepository;
1011
+ this.emailIsFromCollaborator = (userEmail) => !!(userEmail === null || userEmail === void 0 ? void 0 : userEmail.match(/@b4a.com.br/g));
1012
+ }
1013
+ checkCoupon(nickname, checkoutType, checkout, plan) {
1014
+ return from(this.couponRepository
1015
+ .find({
1016
+ filters: {
1017
+ nickname: { operator: Where.EQUALS, value: nickname },
1018
+ active: { operator: Where.EQUALS, value: true },
1019
+ },
1020
+ })
1021
+ .then((result) => result.data[0])).pipe(concatMap((coupon) => this.couponValidation(coupon, checkoutType)), concatMap((couponValid) => this.couponRulesValidation(couponValid, checkoutType, checkout, plan)), map((couponValidated) => couponValidated));
1022
+ }
1023
+ couponValidation(coupon, checkoutType) {
1024
+ return __awaiter(this, void 0, void 0, function* () {
1025
+ if (!coupon)
1026
+ throw 'Cupom inválido.';
1027
+ if ((coupon === null || coupon === void 0 ? void 0 : coupon.beginAt) && (coupon === null || coupon === void 0 ? void 0 : coupon.beginAt.getTime()) > new Date().getTime())
1028
+ throw 'Cupom inválido.';
1029
+ if ((coupon === null || coupon === void 0 ? void 0 : coupon.expiresIn) && (coupon === null || coupon === void 0 ? void 0 : coupon.expiresIn.getTime()) < new Date().getTime())
1030
+ throw 'Cupom expirado.';
1031
+ const isInShop = coupon.shopAvailability === Shops.ALL || coupon.shopAvailability === this.defaultShop;
1032
+ if (!isInShop)
1033
+ throw 'Cupom inválido para loja.';
1034
+ const isCheckoutType = coupon.checkoutType === CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
1035
+ if (!isCheckoutType)
1036
+ throw 'Cupom inválido. Erro de checkout.';
1037
+ return coupon;
1038
+ });
1039
+ }
1040
+ couponRulesValidation(coupon, checkoutType, checkout, plan) {
1041
+ return __awaiter(this, void 0, void 0, function* () {
1042
+ if (checkoutType == CheckoutTypes.SUBSCRIPTION) {
1043
+ if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
1044
+ throw 'Cupom inválido para sua assinatura.';
1045
+ return coupon;
1046
+ }
1047
+ const validUser = this.coupomUserValidation(coupon, checkout === null || checkout === void 0 ? void 0 : checkout.user);
1048
+ if (!validUser)
1049
+ throw 'Usuário não elegível.';
1050
+ const couponUseLimits = this.getCouponUseLimits(coupon, checkoutType, checkout.user);
1051
+ if (couponUseLimits.firstOrder) {
1052
+ const ordersUser = yield this.getOrdersFromUser(checkout.user.email.toLocaleLowerCase());
1053
+ if (couponUseLimits.firstOrder && ordersUser.length >= 1)
1054
+ throw 'Limite de uso atingido';
1055
+ }
1056
+ if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
1057
+ const ordersCoupon = yield this.getOrdersWithCoupon(coupon);
1058
+ if (!couponUseLimits.unlimited && couponUseLimits.total && ordersCoupon.length >= couponUseLimits.total)
1059
+ throw 'Limite de uso atingido.';
1060
+ if (couponUseLimits.limitedPerUser) {
1061
+ const ordersWithUser = this.countOrdersWithUser(ordersCoupon, checkout.user.email);
1062
+ if (ordersWithUser > 0)
1063
+ throw 'Limite de uso por usuário atingido.';
1064
+ }
1065
+ }
1066
+ const hasProductCategories = yield this.hasProductCategories(coupon, checkout);
1067
+ if (!hasProductCategories)
1068
+ throw 'Seu carrinho não possui produtos elegíveis para desconto.';
1069
+ const hasMinSubTotal = yield this.hasMinSubTotal(coupon, checkout);
1070
+ if (!hasMinSubTotal)
1071
+ throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido`;
1072
+ return coupon;
1073
+ });
1074
+ }
1075
+ calcDiscountSubscription(coupon, checkout) {
1076
+ let discount = 0;
1077
+ if (coupon.discount.subscription.type == CouponTypes.ABSOLUTE)
1078
+ discount = coupon.discount.subscription.value;
1079
+ else
1080
+ discount = checkout.subscriptionPlan.recurrencePrice * (coupon.discount.subscription.value / 100);
1081
+ return of(discount);
1082
+ }
1083
+ calcDiscountShopping(coupon, checkout) {
1084
+ return __awaiter(this, void 0, void 0, function* () {
1085
+ let discountInfo = null;
1086
+ if (checkout.user.isSubscriber && coupon.discount.subscriber.value) {
1087
+ discountInfo = yield this.calcDiscountByType(coupon.discount.subscriber.type, coupon.discount.subscriber.value, coupon.productsCategories, checkout);
1088
+ }
1089
+ else {
1090
+ discountInfo = yield this.calcDiscountByType(coupon.discount.non_subscriber.type, coupon.discount.non_subscriber.value, coupon.productsCategories, checkout);
1091
+ }
1092
+ return { discount: discountInfo.discount, lineItems: discountInfo.lineItems };
1093
+ });
1094
+ }
1095
+ calcDiscountByType(type, value, categories, checkout) {
1096
+ return __awaiter(this, void 0, void 0, function* () {
1097
+ let discount = 0;
1098
+ let lineItensElegibleForDiscount = yield this.getLineItensEligebleForDiscount(categories, checkout);
1099
+ const subTotal = this.calcCheckoutSubtotal(lineItensElegibleForDiscount, checkout.user);
1100
+ if (type == CouponTypes.ABSOLUTE) {
1101
+ discount = value > subTotal ? subTotal : value;
1102
+ }
1103
+ else {
1104
+ discount = subTotal * (value / 100);
1105
+ }
1106
+ const lineItems = this.calcLineItenDiscount(type, lineItensElegibleForDiscount, value, subTotal);
1107
+ return { discount, lineItems };
1108
+ });
1109
+ }
1110
+ hasMinSubTotal(coupon, checkout) {
1111
+ return __awaiter(this, void 0, void 0, function* () {
1112
+ if (!coupon.minSubTotalValue)
1113
+ return true;
1114
+ let lineItensDiscount = yield this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
1115
+ const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user);
1116
+ if (coupon.minSubTotalValue <= subTotal)
1117
+ return true;
1118
+ return false;
1119
+ });
1120
+ }
1121
+ hasProductCategories(coupon, checkout) {
1122
+ var _a;
1123
+ return __awaiter(this, void 0, void 0, function* () {
1124
+ if (!coupon.productsCategories || !coupon.productsCategories.length) {
1125
+ return true;
1126
+ }
1127
+ const couponCategories = yield this.getCouponCategoriesId(coupon.productsCategories);
1128
+ const hasCategories = (_a = checkout.lineItems) === null || _a === void 0 ? void 0 : _a.filter((i) => {
1129
+ var _a;
1130
+ if (!i.categories || !((_a = i.categories) === null || _a === void 0 ? void 0 : _a.length))
1131
+ return true;
1132
+ return i.categories.some((c) => couponCategories.some((cat) => cat == c));
1133
+ });
1134
+ return hasCategories.length ? true : false;
1135
+ });
1136
+ }
1137
+ coupomUserValidation(coupon, user) {
1138
+ if (!user || coupon.exclusivityType.includes(Exclusivities.ALL_USERS))
1139
+ return true;
1140
+ let userTypes = [];
1141
+ if (coupon.exclusivityType.includes(Exclusivities.COLLABORATORS) &&
1142
+ this.emailIsFromCollaborator(user.email.toLocaleLowerCase()))
1143
+ userTypes.push(Exclusivities.COLLABORATORS);
1144
+ if (coupon.exclusivityType.includes(Exclusivities.SPECIFIC_USER) &&
1145
+ coupon.userExclusiveEmail.includes(user.email.toLocaleLowerCase()))
1146
+ userTypes.push(Exclusivities.SPECIFIC_USER);
1147
+ if (coupon.exclusivityType.includes(Exclusivities.ACTIVE_SUBSCRIBER) &&
1148
+ user.isSubscriber &&
1149
+ user.subscriptionPlan != '')
1150
+ userTypes.push(Exclusivities.ACTIVE_SUBSCRIBER);
1151
+ if (user.isSubscriber &&
1152
+ user.subscriptionPlan == '' &&
1153
+ coupon.exclusivityType.includes(Exclusivities.INACTIVE_SUBSCRIBER))
1154
+ userTypes.push(Exclusivities.INACTIVE_SUBSCRIBER);
1155
+ if (coupon.exclusivityType.includes(Exclusivities.NON_SUBSCRIBER) && !user.isSubscriber)
1156
+ userTypes.push(Exclusivities.NON_SUBSCRIBER);
1157
+ return coupon.exclusivityType.some((r) => userTypes.includes(r));
1158
+ }
1159
+ getCouponCategoriesId(productsCategories) {
1160
+ return __awaiter(this, void 0, void 0, function* () {
1161
+ const couponCategories = [];
1162
+ for (let index = 0; index < productsCategories.length; index++) {
1163
+ const category = yield this.categoryRepository.get({
1164
+ id: productsCategories[index],
1165
+ });
1166
+ if (category) {
1167
+ const children = yield this.categoryRepository.getChildren(parseInt(productsCategories[index]));
1168
+ couponCategories.push(category.id, ...children.map((c) => c.id.toString()));
1169
+ }
1170
+ }
1171
+ return [...new Set(couponCategories)];
1172
+ });
1173
+ }
1174
+ getLineItensEligebleForDiscount(productsCategories, checkout) {
1175
+ var _a;
1176
+ return __awaiter(this, void 0, void 0, function* () {
1177
+ let lineItensDiscount = [];
1178
+ const couponCategories = yield this.getCouponCategoriesId(productsCategories);
1179
+ if (productsCategories && productsCategories.length) {
1180
+ lineItensDiscount = (_a = checkout.lineItems) === null || _a === void 0 ? void 0 : _a.filter((i) => {
1181
+ var _a;
1182
+ if ((_a = i.categories) === null || _a === void 0 ? void 0 : _a.length) {
1183
+ return i.categories.some((c) => couponCategories.some((cat) => cat == c));
1184
+ }
1185
+ return true;
1186
+ });
1187
+ }
1188
+ else {
1189
+ lineItensDiscount = checkout.lineItems;
1190
+ }
1191
+ return lineItensDiscount;
1192
+ });
1193
+ }
1194
+ calcCheckoutSubtotal(lineItens, user) {
1195
+ return ((lineItens === null || lineItens === void 0 ? void 0 : lineItens.reduce((acc, curr) => {
1196
+ var _a;
1197
+ return (user === null || user === void 0 ? void 0 : user.isSubscriber) && curr.price.subscriberPrice
1198
+ ? acc + ((_a = curr.price) === null || _a === void 0 ? void 0 : _a.subscriberPrice) * curr.quantity
1199
+ : acc + curr.pricePaid * curr.quantity;
1200
+ }, 0)) || 0);
1201
+ }
1202
+ getOrdersWithCoupon(coupon) {
1203
+ return __awaiter(this, void 0, void 0, function* () {
1204
+ return yield this.orderRepository
1205
+ .find({
1206
+ filters: {
1207
+ coupon: { id: coupon.id },
1208
+ status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1209
+ },
1210
+ })
1211
+ .then((result) => result.data);
1212
+ });
1213
+ }
1214
+ getOrdersFromUser(email) {
1215
+ return __awaiter(this, void 0, void 0, function* () {
1216
+ return yield this.orderRepository
1217
+ .find({
1218
+ filters: {
1219
+ user: { email: { operator: Where.EQUALS, value: email } },
1220
+ status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1221
+ },
1222
+ })
1223
+ .then((result) => result.data);
1224
+ });
1225
+ }
1226
+ countOrdersWithUser(orders, email) {
1227
+ return orders.filter((o) => o.user.email == email).length;
1228
+ }
1229
+ getCouponUseLimits(coupon, checkoutType, user) {
1230
+ let couponUseLimits;
1231
+ if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
1232
+ if (coupon.exclusivityType.length === 1 &&
1233
+ (coupon.exclusivityType.at(0) === Exclusivities.SPECIFIC_USER ||
1234
+ coupon.exclusivityType.at(0) === Exclusivities.COLLABORATORS))
1235
+ couponUseLimits = coupon.useLimits.non_subscriber;
1236
+ else
1237
+ couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
1238
+ }
1239
+ else {
1240
+ couponUseLimits = coupon.useLimits.subscription;
1241
+ }
1242
+ return couponUseLimits;
1243
+ }
1244
+ calcLineItenDiscount(type, lineItems, couponDiscount, subTotal) {
1245
+ let lineItemsDiscount = [];
1246
+ if (type === CouponTypes.ABSOLUTE) {
1247
+ const couponDiscountMax = couponDiscount > subTotal ? subTotal : couponDiscount;
1248
+ lineItemsDiscount = lineItems.map((item) => {
1249
+ const totalItemPercentage = item.pricePaid / subTotal;
1250
+ const discountItem = couponDiscountMax * totalItemPercentage;
1251
+ return Object.assign(Object.assign({}, item), { discount: Number(discountItem.toFixed(2)) });
1252
+ });
1253
+ }
1254
+ else {
1255
+ lineItemsDiscount = lineItems.map((item) => {
1256
+ const discountItem = item.pricePaid * (couponDiscount / 100);
1257
+ return Object.assign(Object.assign({}, item), { discount: Number(discountItem.toFixed(2)) });
1258
+ });
1259
+ }
1260
+ return lineItemsDiscount;
1261
+ }
1262
+ }
1263
+ 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 });
1264
+ CouponService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, providedIn: 'root' });
1265
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, decorators: [{
1266
+ type: Injectable,
1267
+ args: [{
1268
+ providedIn: 'root',
1269
+ }]
1270
+ }], ctorParameters: function () {
1271
+ return [{ type: undefined, decorators: [{
1272
+ type: Inject,
1273
+ args: ['CouponRepository']
1274
+ }] }, { type: i1$2.Shops, decorators: [{
1275
+ type: Inject,
1276
+ args: [DEFAULT_SHOP]
1277
+ }] }, { type: undefined, decorators: [{
1278
+ type: Inject,
1279
+ args: ['OrderRepository']
1280
+ }] }, { type: undefined, decorators: [{
1281
+ type: Inject,
1282
+ args: ['CategoryRepository']
1283
+ }] }];
1284
+ } });
1285
+
1286
+ class CheckoutService {
1287
+ constructor(couponService, checkoutRepository, userRepository, defaultShop, dataPersistence) {
1288
+ this.couponService = couponService;
1289
+ this.checkoutRepository = checkoutRepository;
1290
+ this.userRepository = userRepository;
1291
+ this.defaultShop = defaultShop;
1292
+ this.dataPersistence = dataPersistence;
1293
+ }
1294
+ getCheckout(checkoutData) {
1295
+ return this.dataPersistence
1296
+ .get('checkoutId')
1297
+ .pipe(concatMap((id) => (!isNil(id) ? this.checkoutRepository.get({ id }) : this.createCheckout(checkoutData))));
1298
+ }
1299
+ getUserByCheckout(checkoutId) {
1300
+ return from(this.checkoutRepository.get({ id: checkoutId })).pipe(concatMap((checkout) => { var _a; return ((_a = checkout === null || checkout === void 0 ? void 0 : checkout.user) === null || _a === void 0 ? void 0 : _a.id) ? of(checkout.user) : from(this.userRepository.get({ id: checkout.user.id })); }), concatMap((user) => of(user) || throwError(() => new NotFoundError('User is not found'))));
1301
+ }
1302
+ updateCheckoutLineItems(checkout) {
1303
+ return from(this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, lineItems: checkout.lineItems })));
1304
+ }
1305
+ updateCheckoutUser(checkout) {
1306
+ return from(this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, user: checkout.user })));
1307
+ }
1308
+ clearCheckoutFromSession() {
1309
+ return this.dataPersistence.remove('checkoutId');
1310
+ }
1311
+ calcDiscount(coupon) {
1312
+ return this.getCheckout().pipe(concatMap((checkout) => __awaiter(this, void 0, void 0, function* () { return yield this.couponService.calcDiscountShopping(coupon, checkout); })));
1313
+ }
1314
+ checkCoupon(nickname, checkoutType) {
1315
+ return this.getCheckout().pipe(concatMap((checkout) => this.couponService.checkCoupon(nickname, CheckoutTypes.ECOMMERCE, checkout, null).pipe()));
1316
+ }
1317
+ createCheckout(checkoutData) {
1318
+ return __awaiter(this, void 0, void 0, function* () {
1319
+ const checkout = yield this.checkoutRepository.create(Object.assign(Object.assign({ createdAt: new Date() }, Checkout.toInstance(pick(checkoutData, ['user', 'shop'])).toPlain()), { shop: (checkoutData === null || checkoutData === void 0 ? void 0 : checkoutData.shop) || this.defaultShop }));
1320
+ yield this.dataPersistence.set('checkoutId', checkout.id).toPromise();
1321
+ return checkout;
1322
+ });
1323
+ }
1324
+ }
1325
+ CheckoutService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService, deps: [{ token: CouponService }, { token: 'CheckoutRepository' }, { token: 'UserRepository' }, { token: DEFAULT_SHOP }, { token: PERSISTENCE_PROVIDER }], target: i0.ɵɵFactoryTarget.Injectable });
1326
+ CheckoutService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService });
1327
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService, decorators: [{
1328
+ type: Injectable
1329
+ }], ctorParameters: function () {
1330
+ return [{ type: CouponService }, { type: undefined, decorators: [{
1331
+ type: Inject,
1332
+ args: ['CheckoutRepository']
1333
+ }] }, { type: undefined, decorators: [{
1334
+ type: Inject,
1335
+ args: ['UserRepository']
1336
+ }] }, { type: i1$2.Shops, decorators: [{
1337
+ type: Inject,
1338
+ args: [DEFAULT_SHOP]
1339
+ }] }, { type: undefined, decorators: [{
1340
+ type: Inject,
1341
+ args: [PERSISTENCE_PROVIDER]
1342
+ }] }];
1343
+ } });
1344
+
1345
+ class CartService {
1346
+ constructor(authService, checkoutService, defaultShop, productRepository, categoryRepository, variantRepository, buy2WinRepository) {
1347
+ this.authService = authService;
1348
+ this.checkoutService = checkoutService;
1349
+ this.defaultShop = defaultShop;
1350
+ this.productRepository = productRepository;
1351
+ this.categoryRepository = categoryRepository;
1352
+ this.variantRepository = variantRepository;
1353
+ this.buy2WinRepository = buy2WinRepository;
1354
+ this.cartSubject = new Subject();
1355
+ this.updateLineItemInCart = (lineItem, quantity, checkout) => (isNil(checkout) ? this.checkoutService.getCheckout() : of(checkout)).pipe(concatMap((checkoutLoaded) => {
1356
+ var _a;
1357
+ const items = [];
1358
+ const index = (_a = checkoutLoaded.lineItems) === null || _a === void 0 ? void 0 : _a.map((checkoutItem) => checkoutItem.id).indexOf(lineItem.id);
1359
+ if (index > -1) {
1360
+ checkoutLoaded.lineItems[index].quantity += quantity;
1361
+ checkoutLoaded.lineItems[index].pricePaid = lineItem.pricePaid;
1362
+ checkoutLoaded.lineItems[index].price = lineItem.price;
1363
+ }
1364
+ else
1365
+ checkoutLoaded.lineItems = items.concat(checkoutLoaded.lineItems ? checkoutLoaded.lineItems.concat([lineItem]) : [lineItem]);
1366
+ return this.checkoutService
1367
+ .updateCheckoutLineItems(checkoutLoaded)
1368
+ .pipe(map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)));
1369
+ }));
1370
+ this.generateCartObject = (items) => (items === null || items === void 0 ? void 0 : items.reduce((cart, item) => {
1371
+ var _a;
1372
+ return (Object.assign(Object.assign({}, cart), { [item.id]: LineItem.toInstance(Object.assign(Object.assign({}, (cart[item.id] || item)), { quantity: (((_a = cart[item.id]) === null || _a === void 0 ? void 0 : _a.quantity) || 0) + (item.quantity ? item.quantity : 1) })) }));
1373
+ }, {})) || {};
1374
+ this.buildLineItem = ({ checkout, item, quantity, }) => __awaiter(this, void 0, void 0, function* () {
1375
+ var _a, _b, _c, _d, _e, _f, _g;
1376
+ const product = yield this.getProductData(item.id);
1377
+ item.quantity = (item === null || item === void 0 ? void 0 : item.quantity) || ((_b = (_a = checkout === null || checkout === void 0 ? void 0 : checkout.lineItems) === null || _a === void 0 ? void 0 : _a.find((lineItem) => lineItem.id === item.id)) === null || _b === void 0 ? void 0 : _b.quantity) || 0;
1378
+ if (this.checkMaxStock(product.stock.quantity, item.quantity || 0, quantity || 0))
1379
+ throw new Error('Desculpe! Temos apenas ' + ((_c = product.stock) === null || _c === void 0 ? void 0 : _c.quantity) + ' em estoque.');
1380
+ const image = item.image || ((_d = item.images) === null || _d === void 0 ? void 0 : _d.shift());
1381
+ const { id, name, EAN, slug, weight, sku, type } = item;
1382
+ const isGift = item.isGift || null;
1383
+ const pricePaid = this.getProductPrice({
1384
+ product: LineItem.toInstance(product),
1385
+ shop: checkout.shop || this.defaultShop,
1386
+ isSubscriber: (_e = checkout.user) === null || _e === void 0 ? void 0 : _e.isSubscriber,
1387
+ });
1388
+ RoundProductPricesHelper.roundProductPrices(item);
1389
+ RoundProductPricesHelper.roundProductPrices(product);
1390
+ return {
1391
+ checkout,
1392
+ lineItem: LineItem.toInstance({
1393
+ id,
1394
+ name: name !== null && name !== void 0 ? name : product.name,
1395
+ EAN: EAN !== null && EAN !== void 0 ? EAN : product.EAN,
1396
+ brand: product.brand,
1397
+ slug: slug !== null && slug !== void 0 ? slug : product.slug,
1398
+ sku: sku !== null && sku !== void 0 ? sku : product.sku,
1399
+ stock: product.stock,
1400
+ price: this.roundPrice(product.price),
1401
+ image,
1402
+ weight: weight !== null && weight !== void 0 ? weight : product.weight,
1403
+ quantity: (item.quantity || 0) + (quantity || 0),
1404
+ pricePaid,
1405
+ discount: 0,
1406
+ categories: (_f = product.categories) !== null && _f !== void 0 ? _f : [],
1407
+ isGift: isGift !== null && isGift !== void 0 ? isGift : null,
1408
+ costPrice: (_g = product.costPrice) !== null && _g !== void 0 ? _g : 0,
1409
+ type,
1410
+ }),
1411
+ };
1412
+ });
1413
+ this.getProductPrice = ({ product, isSubscriber, }) => {
1414
+ const info = product.price;
1415
+ if (product.isGift)
1416
+ return 0;
1417
+ return isSubscriber && info.subscriberPrice > 0
1418
+ ? Number(info.subscriberPrice.toFixed(2))
1419
+ : Number(info.price.toFixed(2));
1420
+ };
1421
+ this.checkMaxStock = (currentStock, currentItemQtd, quantityToAdd) => {
1422
+ const maxStock = currentStock || 0;
1423
+ const currentItemAmount = currentItemQtd || 0;
1424
+ return currentItemAmount + quantityToAdd > maxStock;
1425
+ };
1426
+ }
1427
+ addItem(item, quantity = 1) {
1428
+ return from(this.checkoutService.getCheckout()).pipe(concatMap((checkout) => __awaiter(this, void 0, void 0, function* () { return yield this.buildLineItem({ checkout, item, quantity: quantity || 1 }); })), mergeMap(({ checkout, lineItem }) => this.updateLineItemInCart(lineItem, quantity || 1, checkout)), tap((cart) => this.cartSubject.next(cart)));
1429
+ }
1430
+ decreaseItem(item) {
1431
+ return this.checkoutService.getCheckout().pipe(map((checkout) => {
1432
+ var _a;
1433
+ const checkoutItem = (_a = checkout.lineItems) === null || _a === void 0 ? void 0 : _a.find((lineItem) => lineItem.id === item.id);
1434
+ if (!isNil(checkoutItem))
1435
+ checkoutItem.quantity -= checkoutItem.quantity > 1 ? 1 : 0;
1436
+ return checkout;
1437
+ }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1438
+ }
1439
+ getCart(checkout) {
1440
+ this.buildCartFromCheckout(checkout).subscribe((cart) => this.cartSubject.next(cart));
1441
+ return this.cartSubject;
1442
+ }
1443
+ /**
1444
+ * @deprecated The method should not be used
1445
+ */
1446
+ getVariantPriceDiscount(item) {
1447
+ 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)));
1448
+ }
1449
+ removeItem(item) {
1450
+ return this.checkoutService.getCheckout().pipe(map((checkout) => {
1451
+ const index = checkout.lineItems.findIndex((lineItem) => lineItem.id === item.id);
1452
+ if (index >= 0)
1453
+ checkout.lineItems.splice(index, 1);
1454
+ return checkout;
1455
+ }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1456
+ }
1457
+ updateUserCart(user) {
1458
+ return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.checkoutService.updateCheckoutUser(Checkout.toInstance(Object.assign(Object.assign({}, checkout.toPlain()), { user })))), concatMap((checkout) => __awaiter(this, void 0, void 0, function* () {
1459
+ var _a, _b;
1460
+ return yield this.checkoutService
1461
+ .updateCheckoutLineItems(Checkout.toInstance(Object.assign(Object.assign({}, checkout.toPlain()), { lineItems: ((_a = checkout.lineItems) === null || _a === void 0 ? void 0 : _a.length)
1462
+ ? yield Promise.all((_b = checkout.lineItems) === null || _b === void 0 ? void 0 : _b.map((item) => __awaiter(this, void 0, void 0, function* () { return (yield this.buildLineItem({ checkout, item })).lineItem; })))
1463
+ : [] })))
1464
+ .toPromise();
1465
+ })), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1466
+ }
1467
+ clearCart() {
1468
+ return this.checkoutService.getCheckout().pipe(map((checkout) => {
1469
+ this.checkoutService.clearCheckoutFromSession();
1470
+ return checkout;
1471
+ }), concatMap((oldCheckout) => this.buildCartFromCheckout(oldCheckout)), tap((cart) => this.cartSubject.next(cart)));
1472
+ }
1473
+ buildCartFromCheckout(checkoutData) {
1474
+ return this.checkoutService.getCheckout(checkoutData).pipe(map((checkout) => checkout.lineItems), concatMap((lineItems) => of(this.generateCartObject(lineItems))));
1475
+ }
1476
+ roundPrice(productPrice) {
1477
+ const { price, fullPrice, subscriberPrice } = productPrice;
1478
+ return Object.assign(Object.assign(Object.assign({}, productPrice), { price: Number(price.toFixed(2)), fullPrice: Number(fullPrice.toFixed(2)) }), (subscriberPrice && { subscriberPrice: Number(subscriberPrice.toFixed(2)) }));
1479
+ }
1480
+ getProductData(productId) {
1481
+ return __awaiter(this, void 0, void 0, function* () {
1482
+ let product;
1483
+ let variant;
1484
+ try {
1485
+ product = yield this.productRepository.get({ id: productId });
1486
+ }
1487
+ catch (error) {
1488
+ if (!(error instanceof NotFoundError))
1489
+ throw error;
1490
+ const { data: variants } = yield this.variantRepository.find({ filters: { id: productId } });
1491
+ variant = variants.shift();
1492
+ if (!variant)
1493
+ throw error;
1494
+ product = yield this.productRepository.get({ id: variant.productId });
1495
+ }
1496
+ return Object.assign(Object.assign({}, product.toPlain()), (variant && Object.assign({}, variant.toPlain())));
1497
+ });
1498
+ }
1499
+ getGifts() {
1500
+ return this.checkoutService.getCheckout().pipe(mergeMap((checkout) => __awaiter(this, void 0, void 0, function* () {
1501
+ const notGiftItems = checkout.lineItems ? checkout.lineItems.filter((item) => !item.isGift) : [];
1502
+ if (!notGiftItems.length)
1503
+ return Object.assign(Object.assign({}, checkout), { lineItems: [] });
1504
+ const cartTotal = notGiftItems.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1505
+ const campaigns = yield this.buy2WinRepository
1506
+ .find({
1507
+ filters: {
1508
+ active: { operator: Where.EQUALS, value: true },
1509
+ shop: { operator: Where.EQUALS, value: this.defaultShop },
1510
+ },
1511
+ })
1512
+ .then((data) => data.data);
1513
+ if (!campaigns.length)
1514
+ return Object.assign(Object.assign({}, checkout), { lineItems: notGiftItems });
1515
+ const elegibleCampaigns = [];
1516
+ for (const campaign of campaigns) {
1517
+ const today = new Date().getTime();
1518
+ if (!(campaign.startDate.getTime() <= today) && !(campaign.endDate.getTime() >= today))
1519
+ continue;
1520
+ if (campaign.activeCategory) {
1521
+ const categoriesCampaing = campaign.categories.map((c) => c.id.toString());
1522
+ const categoriesCampaingFullTree = [];
1523
+ for (const id of categoriesCampaing) {
1524
+ const children = yield this.categoryRepository.getChildren(parseInt(id));
1525
+ categoriesCampaingFullTree.push(id, ...children.map((c) => c.id.toString()));
1526
+ }
1527
+ const categoriesCampaingTree = [...new Set(categoriesCampaingFullTree)];
1528
+ const filterProductsCategories = checkout.lineItems.filter((l) => {
1529
+ var _a;
1530
+ if (!l.categories || !((_a = l.categories) === null || _a === void 0 ? void 0 : _a.length))
1531
+ return true;
1532
+ return l.categories.some((c) => categoriesCampaingTree.some((cat) => cat == c));
1533
+ });
1534
+ if (filterProductsCategories.length) {
1535
+ const cartTotalCategories = filterProductsCategories.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1536
+ if (cartTotalCategories >= campaign.cartValueMin)
1537
+ elegibleCampaigns.push(campaign);
1538
+ }
1539
+ }
1540
+ else {
1541
+ if (campaign.cartValue && campaign.cartValue > 0) {
1542
+ if (campaign.cartValue <= cartTotal)
1543
+ elegibleCampaigns.push(campaign);
1544
+ }
1545
+ }
1546
+ }
1547
+ if (!elegibleCampaigns.length)
1548
+ return Object.assign(Object.assign({}, checkout), { lineItems: notGiftItems });
1549
+ const campaingnProducts = [];
1550
+ for (const campaign of elegibleCampaigns) {
1551
+ let elegibleProducts = [];
1552
+ for (const product of campaign.products) {
1553
+ const { data: productData } = yield this.productRepository.find({ filters: { sku: product } });
1554
+ if (!productData.length)
1555
+ continue;
1556
+ const gift = productData.shift();
1557
+ if (gift.stock.quantity < 1)
1558
+ continue;
1559
+ elegibleProducts.push(gift);
1560
+ }
1561
+ campaingnProducts.push(elegibleProducts);
1562
+ }
1563
+ if (!campaingnProducts.length)
1564
+ return Object.assign(Object.assign({}, checkout), { lineItems: notGiftItems });
1565
+ const gifts = this.giftToLineItems([].concat(...campaingnProducts));
1566
+ return Object.assign(Object.assign({}, checkout), { lineItems: notGiftItems.concat(gifts) });
1567
+ })), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1568
+ }
1569
+ giftToLineItems(items) {
1570
+ return items.map((item) => {
1571
+ var _a;
1572
+ const { brand, categories, id, name, price, sku, slug, stock, weight, EAN } = item;
1573
+ const image = ((_a = item === null || item === void 0 ? void 0 : item.miniatures) === null || _a === void 0 ? void 0 : _a.length) ? item.miniatures[0] : item.images[0];
1574
+ return LineItem.toInstance({
1575
+ brand,
1576
+ categories,
1577
+ id: id.toString(),
1578
+ name,
1579
+ price,
1580
+ sku,
1581
+ slug,
1582
+ stock,
1583
+ weight,
1584
+ EAN,
1585
+ image,
1586
+ pricePaid: 0,
1587
+ quantity: 1,
1588
+ isGift: true,
1589
+ });
1590
+ });
1591
+ }
1592
+ }
1593
+ 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 });
1594
+ CartService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService });
1595
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService, decorators: [{
1596
+ type: Injectable
1597
+ }], ctorParameters: function () {
1598
+ return [{ type: AuthService }, { type: CheckoutService }, { type: i1$2.Shops, decorators: [{
1599
+ type: Inject,
1600
+ args: [DEFAULT_SHOP]
1601
+ }] }, { type: undefined, decorators: [{
1602
+ type: Inject,
1603
+ args: ['ProductRepository']
1604
+ }] }, { type: undefined, decorators: [{
1605
+ type: Inject,
1606
+ args: ['CategoryRepository']
1607
+ }] }, { type: undefined, decorators: [{
1608
+ type: Inject,
1609
+ args: ['VariantRepository']
1610
+ }] }, { type: i1$2.Buy2WinFirestoreRepository, decorators: [{
1611
+ type: Inject,
1612
+ args: ['Buy2WinRepository']
1613
+ }] }];
1614
+ } });
1615
+
1616
+ class NewCategoryStructureAdapter {
1617
+ constructor(categoryRepository) {
1618
+ this.categoryRepository = categoryRepository;
1619
+ }
1620
+ buildProductFilterByCategory(category) {
1621
+ return __awaiter(this, void 0, void 0, function* () {
1622
+ const loadedCategory = yield this.getCategory(category);
1623
+ if (loadedCategory.isCollection)
1624
+ return { id: { operator: Where.IN, value: loadedCategory.products } };
1625
+ const categoryIds = [...(yield this.getAllCategoriesIdFromCategory(category)), category.id.toString()];
1626
+ return {
1627
+ category: {
1628
+ id: {
1629
+ operator: Where.IN,
1630
+ value: categoryIds,
1631
+ },
1632
+ },
1633
+ };
1634
+ });
1635
+ }
1636
+ getAllCategoriesIdFromCategory(category) {
1637
+ return __awaiter(this, void 0, void 0, function* () {
1638
+ return this.categoryRepository
1639
+ .getChildren(+category.id)
1640
+ .then((categories) => categories.map((category) => category.id.toString()));
1641
+ });
1642
+ }
1643
+ getCategory(category) {
1644
+ var _a;
1645
+ return __awaiter(this, void 0, void 0, function* () {
1646
+ const collectionCategory = category.isCollection ||
1647
+ (isNil(category.isCollection) && !((_a = category.products) === null || _a === void 0 ? void 0 : _a.length)) ||
1648
+ category.isWishlist ||
1649
+ category.brandCategory;
1650
+ return collectionCategory ? this.categoryRepository.get({ id: category.id }) : category;
1651
+ });
1652
+ }
1653
+ }
1654
+ NewCategoryStructureAdapter.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: NewCategoryStructureAdapter, deps: [{ token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1655
+ NewCategoryStructureAdapter.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: NewCategoryStructureAdapter });
1656
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: NewCategoryStructureAdapter, decorators: [{
1657
+ type: Injectable
1658
+ }], ctorParameters: function () {
1659
+ return [{ type: undefined, decorators: [{
1660
+ type: Inject,
1661
+ args: ['CategoryRepository']
1662
+ }] }];
1663
+ } });
1664
+
1665
+ class OldCategoryStructureAdapter {
1666
+ constructor(categoryRepository) {
1667
+ this.categoryRepository = categoryRepository;
1668
+ }
1669
+ buildProductFilterByCategory(category) {
1670
+ var _a;
1671
+ return __awaiter(this, void 0, void 0, function* () {
1672
+ const productsIds = ((_a = category.products) === null || _a === void 0 ? void 0 : _a.length)
1673
+ ? category.products
1674
+ : yield this.categoryRepository.get({ id: category.id }).then((categoryFound) => categoryFound.products);
1675
+ return { id: { operator: Where.IN, value: productsIds } };
1676
+ });
1677
+ }
1678
+ }
1679
+ OldCategoryStructureAdapter.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OldCategoryStructureAdapter, deps: [{ token: 'CategoryRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1680
+ OldCategoryStructureAdapter.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OldCategoryStructureAdapter });
1681
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OldCategoryStructureAdapter, decorators: [{
1682
+ type: Injectable
1683
+ }], ctorParameters: function () {
1684
+ return [{ type: undefined, decorators: [{
1685
+ type: Inject,
1686
+ args: ['CategoryRepository']
1687
+ }] }];
1688
+ } });
1689
+
1690
+ class CatalogService {
1691
+ constructor(productRepository, productStockNotificationRepository, categoryRepository, categoryStructureAdapter, shop, productIndex) {
1692
+ this.productRepository = productRepository;
1693
+ this.productStockNotificationRepository = productStockNotificationRepository;
1694
+ this.categoryRepository = categoryRepository;
1695
+ this.categoryStructureAdapter = categoryStructureAdapter;
1696
+ this.shop = shop;
1697
+ this.productIndex = productIndex;
1698
+ this.productsByTerm = {};
1699
+ this.buildFilterQuery = ({ clubDiscount, brands, prices, gender, tags, rate, customOptions, }) => {
1700
+ const filters = {};
1701
+ if (clubDiscount === null || clubDiscount === void 0 ? void 0 : clubDiscount.length)
1702
+ set(filters, 'price.subscriberDiscountPercentage', { operator: Where.IN, value: clubDiscount });
1703
+ if (brands === null || brands === void 0 ? void 0 : brands.length)
1704
+ filters.brand = { operator: Where.IN, value: brands };
1705
+ if (gender === null || gender === void 0 ? void 0 : gender.length)
1706
+ filters.gender = { operator: Where.IN, value: gender };
1707
+ if ((prices === null || prices === void 0 ? void 0 : prices.min) || (prices === null || prices === void 0 ? void 0 : prices.max))
1708
+ set(filters, prices.subscriberPrice ? 'price.subscriberPrice' : 'price.price', [
1709
+ ...(prices.min ? [{ operator: Where.GTE, value: Math.round(prices.min) }] : []),
1710
+ ...(prices.max ? [{ operator: Where.LTE, value: Math.ceil(prices.max) }] : []),
1711
+ ]);
1712
+ if (rate)
1713
+ filters.rate = { operator: Where.GTE, value: rate };
1714
+ if (tags === null || tags === void 0 ? void 0 : tags.length)
1715
+ filters.tags = { operator: Where.LIKE, value: tags };
1716
+ if (customOptions === null || customOptions === void 0 ? void 0 : customOptions.length)
1717
+ filters.filters = { operator: Where.LIKE, value: customOptions };
1718
+ return filters;
1719
+ };
1720
+ this.buildSortQuery = (sort) => {
1721
+ if (!sort || sort === 'most-relevant')
1722
+ return {};
1723
+ if (sort === 'best-sellers')
1724
+ return {
1725
+ shoppingCount: 'desc',
1726
+ rate: 'desc',
1727
+ stock: 'desc',
1728
+ name: 'asc',
1729
+ };
1730
+ if (sort === 'biggest-price')
1731
+ return { subscriberPrice: 'desc', rate: 'desc', shoppingCount: 'desc' };
1732
+ if (sort === 'lowest-price')
1733
+ return { subscriberPrice: 'asc', rate: 'desc', shoppingCount: 'desc' };
1734
+ if (sort === 'best-rating')
1735
+ return { rate: 'desc', shoppingCount: 'desc', stock: 'desc', name: 'asc' };
1736
+ if (sort === 'news')
1737
+ return { createdAt: 'desc' };
1738
+ if (sort === 'biggest-discount')
1739
+ return { subscriberDiscountPercentage: 'desc', rate: 'desc', shoppingCount: 'desc' };
1740
+ };
1741
+ this.buildLimitQuery = (options) => {
1742
+ const limit = (options === null || options === void 0 ? void 0 : options.perPage) || 20;
1743
+ return {
1744
+ limit,
1745
+ offset: (((options === null || options === void 0 ? void 0 : options.page) || 1) - 1) * limit,
1746
+ };
1747
+ };
1748
+ this.hasProfile = (options) => 'profile' in options;
1749
+ this.hasTerm = (options) => 'term' in options;
1750
+ this.hasCategory = (options) => 'category' in options;
1751
+ }
1752
+ fetchProducts(options) {
1753
+ var _a, _b, _c;
1754
+ return __awaiter(this, void 0, void 0, function* () {
1755
+ const limits = this.buildLimitQuery(options);
1756
+ if (this.hasProfile(options) && ((_a = options.filters) === null || _a === void 0 ? void 0 : _a.customOptions))
1757
+ throw new InvalidArgumentError(`It couldn't filled customOptions when profile is given`);
1758
+ if (this.hasProfile(options) && ((_b = options.filters) === null || _b === void 0 ? void 0 : _b.tags))
1759
+ throw new InvalidArgumentError(`It couldn't filled tags when profile is given`);
1760
+ if (this.hasTerm(options) && ((_c = options.filters) === null || _c === void 0 ? void 0 : _c.customOptions))
1761
+ throw new InvalidArgumentError(`It couldn't filled customOptions when term is given`);
1762
+ return yield this.findCatalog(options, limits).then(({ data, count: total, maximum, minimal, distinct }) => {
1763
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1764
+ return ({
1765
+ products: { data: data.map((product) => RoundProductPricesHelper.roundProductPrices(product)), total },
1766
+ pages: Math.ceil(total / limits.limit),
1767
+ prices: {
1768
+ price: { min: +((_b = (_a = minimal === null || minimal === void 0 ? void 0 : minimal.price) === null || _a === void 0 ? void 0 : _a.price) === null || _b === void 0 ? void 0 : _b.toFixed(2)), max: +((_d = (_c = maximum === null || maximum === void 0 ? void 0 : maximum.price) === null || _c === void 0 ? void 0 : _c.price) === null || _d === void 0 ? void 0 : _d.toFixed(2)) },
1769
+ subscriberPrice: {
1770
+ min: +((_f = (_e = minimal === null || minimal === void 0 ? void 0 : minimal.price) === null || _e === void 0 ? void 0 : _e.subscriberPrice) === null || _f === void 0 ? void 0 : _f.toFixed(2)),
1771
+ max: +((_h = (_g = maximum === null || maximum === void 0 ? void 0 : maximum.price) === null || _g === void 0 ? void 0 : _g.subscriberPrice) === null || _h === void 0 ? void 0 : _h.toFixed(2)),
1772
+ },
1773
+ },
1774
+ brands: distinct === null || distinct === void 0 ? void 0 : distinct.brand,
1775
+ });
1776
+ });
1777
+ });
1778
+ }
1779
+ addCustomerToStockNotification(shop, productId, name, email) {
1780
+ return __awaiter(this, void 0, void 0, function* () {
1781
+ return this.productStockNotificationRepository.addCustomerEmail(shop, productId, name, email);
1782
+ });
1783
+ }
1784
+ findCatalog(options, limits) {
1785
+ return __awaiter(this, void 0, void 0, function* () {
1786
+ if (this.hasTerm(options) && options.sort === 'most-relevant') {
1787
+ const productsIds = yield this.findCatalogIdsByElasticSearch(options.term);
1788
+ return this.findCatalogAndSortByMostRevelantByTerm(productsIds, options, limits);
1789
+ }
1790
+ if (this.hasCategory(options) && options.sort === 'most-relevant') {
1791
+ const mostRelevant = options.category.isWishlist ? [] : options.category.getMostRelevantByShop(this.shop);
1792
+ const productsIds = yield this.productRepository
1793
+ .findCatalog({
1794
+ fields: ['id'],
1795
+ filters: Object.assign(Object.assign({}, (yield this.buildMainFilter(options))), this.buildFilterQuery((options === null || options === void 0 ? void 0 : options.filters) || {})),
1796
+ })
1797
+ .then((products) => products.data.map((product) => product.id));
1798
+ return this.findCatalogAndSortByMostRevelant(mostRelevant, productsIds, options, limits);
1799
+ }
1800
+ const repoParams = Object.assign(Object.assign({ filters: Object.assign(Object.assign({}, (yield this.buildMainFilter(options))), this.buildFilterQuery((options === null || options === void 0 ? void 0 : options.filters) || {})) }, ((options === null || options === void 0 ? void 0 : options.sort) ? { orderBy: this.buildSortQuery(options === null || options === void 0 ? void 0 : options.sort) } : {})), { limits, options: Object.assign({ minimal: ['price'], maximum: ['price'] }, (!this.hasCategory(options) ? { distinct: ['brand'] } : {})) });
1801
+ if (['biggest-price', 'lowest-price', 'biggest-discount', 'best-rating'].includes(options.sort))
1802
+ return this.productRepository.findCatalog(repoParams);
1803
+ return this.productRepository.findCatalog(repoParams, (options === null || options === void 0 ? void 0 : options.mainGender) || this.shop === Shops.MENSMARKET ? 'male' : 'female');
1804
+ });
1805
+ }
1806
+ buildMainFilter({ category, profile, term, }) {
1807
+ return __awaiter(this, void 0, void 0, function* () {
1808
+ if (category)
1809
+ return this.categoryStructureAdapter.buildProductFilterByCategory(category);
1810
+ if (profile)
1811
+ return { tags: { operator: Where.LIKE, value: profile } };
1812
+ if (term)
1813
+ return this.productIndex
1814
+ .search(term, 999, this.shop)
1815
+ .then((data) => ({ id: { operator: Where.IN, value: data.hits.map(({ _source }) => _source.id) } }));
1816
+ });
1817
+ }
1818
+ findCatalogAndSortByMostRevelant(mostRelevants, productIds, options, limits) {
1819
+ return __awaiter(this, void 0, void 0, function* () {
1820
+ const mostRelevantProductsIds = [...new Set(mostRelevants.concat(productIds))];
1821
+ const totalResult = yield this.productRepository.findCatalog({
1822
+ filters: Object.assign({ id: { operator: Where.IN, value: mostRelevantProductsIds } }, this.buildFilterQuery((options === null || options === void 0 ? void 0 : options.filters) || {})),
1823
+ orderBy: this.buildSortQuery('best-sellers'),
1824
+ options: {
1825
+ minimal: ['price'],
1826
+ maximum: ['price'],
1827
+ distinct: ['brand'],
1828
+ },
1829
+ }, (options === null || options === void 0 ? void 0 : options.mainGender) || this.shop === Shops.MENSMARKET ? 'male' : 'female');
1830
+ const mostRelevantWithouyStock = totalResult.data.filter((product) => mostRelevants.includes(product.id) && product.stock.quantity <= 0);
1831
+ const firstProducts = totalResult.data
1832
+ .filter((product) => mostRelevants.includes(product.id) && product.stock.quantity > 0)
1833
+ .sort((a, b) => mostRelevants.indexOf(a.id) - mostRelevants.indexOf(b.id));
1834
+ const lastProducts = totalResult.data
1835
+ .filter((product) => !mostRelevants.includes(product.id))
1836
+ .concat(mostRelevantWithouyStock);
1837
+ const categoryMostRelevants = firstProducts.concat(lastProducts);
1838
+ const resultFinal = categoryMostRelevants.slice(limits.offset, limits.offset + limits.limit);
1839
+ return {
1840
+ data: resultFinal,
1841
+ count: totalResult.count,
1842
+ maximum: totalResult.maximum,
1843
+ minimal: totalResult.minimal,
1844
+ distinct: totalResult.distinct,
1845
+ };
1846
+ });
1847
+ }
1848
+ findCatalogAndSortByMostRevelantByTerm(productIds, options, limits) {
1849
+ return __awaiter(this, void 0, void 0, function* () {
1850
+ const totalResult = yield this.productRepository.findCatalog({
1851
+ fields: ['id', 'stock'],
1852
+ filters: Object.assign({ id: { operator: Where.IN, value: productIds } }, this.buildFilterQuery((options === null || options === void 0 ? void 0 : options.filters) || {})),
1853
+ options: {
1854
+ minimal: ['price'],
1855
+ maximum: ['price'],
1856
+ distinct: ['brand'],
1857
+ },
1858
+ }, (options === null || options === void 0 ? void 0 : options.mainGender) || this.shop === Shops.MENSMARKET ? 'male' : 'female');
1859
+ const stockData = totalResult.data.filter((product) => product.stock.quantity > 0);
1860
+ const stockOut = totalResult.data.filter((product) => product.stock.quantity <= 0);
1861
+ const productIdsStock = productIds.filter((product) => stockData.some((result) => result.id == product));
1862
+ const productIdsStockOut = productIds.filter((product) => stockOut.some((result) => result.id == product));
1863
+ const limitedProductId = productIdsStock
1864
+ .concat(productIdsStockOut)
1865
+ .slice(limits.offset, limits.offset + limits.limit);
1866
+ const orderedId = productIds.filter((product) => limitedProductId.includes(product));
1867
+ const productResult = yield this.productRepository.findCatalog({
1868
+ filters: {
1869
+ id: { operator: Where.IN, value: orderedId },
1870
+ },
1871
+ });
1872
+ return {
1873
+ data: limitedProductId.map((id) => productResult.data.find((product) => product.id === id)).filter(Boolean),
1874
+ count: totalResult.count,
1875
+ maximum: totalResult.maximum,
1876
+ minimal: totalResult.minimal,
1877
+ distinct: totalResult.distinct,
1878
+ };
1879
+ });
1880
+ }
1881
+ findCatalogIdsByElasticSearch(term) {
1882
+ return __awaiter(this, void 0, void 0, function* () {
1883
+ if (this.productsByTerm[term])
1884
+ return this.productsByTerm[term];
1885
+ return (this.productsByTerm[term] = yield this.productIndex
1886
+ .search(term, 999, this.shop)
1887
+ .then(({ hits: products }) => {
1888
+ const withStock = products.filter(({ _source }) => _source.stock.quantity > 0);
1889
+ const withOutStock = products.filter(({ _source }) => _source.stock.quantity <= 0);
1890
+ const sorted = [...withStock, ...withOutStock];
1891
+ return [...new Set(sorted.map(({ _source }) => _source.id))];
1892
+ }));
1893
+ });
1894
+ }
1895
+ }
1896
+ CatalogService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService, deps: [{ token: 'ProductRepository' }, { token: 'ProductStockNotificationRepository' }, { token: 'CategoryRepository' }, { token: CATEGORY_STRUCTURE }, { token: DEFAULT_SHOP }, { token: i1$2.ProductsIndex }], target: i0.ɵɵFactoryTarget.Injectable });
1897
+ CatalogService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService });
1898
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CatalogService, decorators: [{
1899
+ type: Injectable
1900
+ }], ctorParameters: function () {
1901
+ return [{ type: undefined, decorators: [{
1902
+ type: Inject,
1903
+ args: ['ProductRepository']
1904
+ }] }, { type: undefined, decorators: [{
1905
+ type: Inject,
1906
+ args: ['ProductStockNotificationRepository']
1907
+ }] }, { type: undefined, decorators: [{
1908
+ type: Inject,
1909
+ args: ['CategoryRepository']
1910
+ }] }, { type: undefined, decorators: [{
1911
+ type: Inject,
1912
+ args: [CATEGORY_STRUCTURE]
1913
+ }] }, { type: i1$2.Shops, decorators: [{
1914
+ type: Inject,
1915
+ args: [DEFAULT_SHOP]
1916
+ }] }, { type: i1$2.ProductsIndex }];
1917
+ } });
1918
+
1919
+ class CategoryService {
1920
+ constructor(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop) {
1921
+ this.productRepository = productRepository;
1922
+ this.categoryRepository = categoryRepository;
1923
+ this.categoryFilterRepository = categoryFilterRepository;
1924
+ this.categoryStructureAdapter = categoryStructureAdapter;
1925
+ this.shop = shop;
1926
+ }
1927
+ fetchBrands(category, options) {
1928
+ return __awaiter(this, void 0, void 0, function* () {
1929
+ const brands = yield this.productRepository
1930
+ .findCatalog({
1931
+ filters: yield this.categoryStructureAdapter.buildProductFilterByCategory(category),
1932
+ fields: ['brand'],
1933
+ }, (options === null || options === void 0 ? void 0 : options.mainGender) ? options === null || options === void 0 ? void 0 : options.mainGender : this.shop === Shops.MENSMARKET ? 'male' : 'female')
1934
+ .then(({ data }) => Object.keys(data.map((product) => product.brand).reduce((brands, brand) => (Object.assign(Object.assign({}, brands), { [brand]: true })), {})));
1935
+ return this.categoryRepository
1936
+ .find({ filters: { brandCategory: true, shop: (options === null || options === void 0 ? void 0 : options.shop) || this.shop }, orderBy: { name: 'asc' } })
1937
+ .then(({ data }) => data.filter((category) => brands.includes(category.conditions.brand)));
1938
+ });
1939
+ }
1940
+ fetchFilterOptions(category) {
1941
+ return __awaiter(this, void 0, void 0, function* () {
1942
+ return yield this.categoryFilterRepository
1943
+ .find({ filters: { categoryId: +category.id } })
1944
+ .then(({ data }) => data.map((categoryFilter) => categoryFilter.filter));
1945
+ });
1946
+ }
1947
+ }
1948
+ 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 });
1949
+ CategoryService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CategoryService });
1950
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CategoryService, decorators: [{
1951
+ type: Injectable
1952
+ }], ctorParameters: function () {
1953
+ return [{ type: undefined, decorators: [{
1954
+ type: Inject,
1955
+ args: ['ProductRepository']
1956
+ }] }, { type: undefined, decorators: [{
1957
+ type: Inject,
1958
+ args: ['CategoryRepository']
1959
+ }] }, { type: undefined, decorators: [{
1960
+ type: Inject,
1961
+ args: ['CategoryFilterRepository']
1962
+ }] }, { type: undefined, decorators: [{
1963
+ type: Inject,
1964
+ args: [CATEGORY_STRUCTURE]
1965
+ }] }, { type: i1$2.Shops, decorators: [{
1966
+ type: Inject,
1967
+ args: [DEFAULT_SHOP]
1968
+ }] }];
1969
+ } });
1970
+
1971
+ var ProductSorts;
1972
+ (function (ProductSorts) {
1973
+ ProductSorts["MOST_RELEVANT"] = "most-relevant";
1974
+ ProductSorts["BEST_SELLER"] = "best-sellers";
1975
+ ProductSorts["BIGGEST_PRICE"] = "biggest-price";
1976
+ ProductSorts["LOWEST_PRICE"] = "lowest-price";
1977
+ ProductSorts["BIGGEST_DISCOUNT"] = "biggest-discount";
1978
+ ProductSorts["BEST_RATING"] = "best-rating";
1979
+ ProductSorts["NEWS"] = "news";
1980
+ })(ProductSorts || (ProductSorts = {}));
1981
+
1982
+ class CategoryWithTree extends Category {
1983
+ }
1984
+ __decorate([
1985
+ Type(() => CategoryWithTree),
1986
+ __metadata("design:type", Array)
1987
+ ], CategoryWithTree.prototype, "children", void 0);
1988
+
1989
+ class WishlistService {
1990
+ constructor(wishlistRepository, shop, productRepository, categoryFilterRepository, categoryRepository, productStockNotificationRepository, productIndex) {
1991
+ this.wishlistRepository = wishlistRepository;
1992
+ this.shop = shop;
1993
+ const categoryStructureAdapter = new NewCategoryStructureAdapter(wishlistRepository);
1994
+ this.catalogService = new CatalogService(productRepository, productStockNotificationRepository, categoryRepository, categoryStructureAdapter, shop, productIndex);
1995
+ this.categoryService = new CategoryService(productRepository, categoryRepository, categoryFilterRepository, categoryStructureAdapter, shop);
1996
+ }
1997
+ getCatalogService() {
1998
+ return this.catalogService;
1999
+ }
2000
+ getCategoryService() {
2001
+ return this.categoryService;
2002
+ }
2003
+ create({ personId, title, description, published, userFullName, userPhoto, theme, bannerUrl, personType, personIsSubscriber, }) {
2004
+ return __awaiter(this, void 0, void 0, function* () {
2005
+ const data = {
2006
+ slug: '',
2007
+ name: title,
2008
+ description,
2009
+ metadatas: [
2010
+ {
2011
+ shop: this.shop,
2012
+ title: `${userFullName} - ${title}`,
2013
+ description: `${userFullName} - ${description}`,
2014
+ },
2015
+ ],
2016
+ shop: this.shop,
2017
+ shops: [this.shop],
2018
+ personId,
2019
+ personName: userFullName,
2020
+ personPhoto: userPhoto,
2021
+ brandCategory: false,
2022
+ published,
2023
+ theme,
2024
+ bannerUrl,
2025
+ personType: personType !== null && personType !== void 0 ? personType : PersonTypes.NONE,
2026
+ personIsSubscriber: personIsSubscriber !== null && personIsSubscriber !== void 0 ? personIsSubscriber : false,
2027
+ };
2028
+ const newWishlist = yield this.wishlistRepository.create(data);
2029
+ yield this.wishlistRepository.update({ id: newWishlist.id, slug: newWishlist.id });
2030
+ return Wishlist.toInstance(Object.assign(Object.assign({}, newWishlist.toPlain()), { slug: newWishlist.id }));
2031
+ });
2032
+ }
2033
+ update({ id, title, description, published, userFullName, userPhoto, theme, bannerUrl, personType, personIsSubscriber, }) {
2034
+ const data = {
2035
+ id,
2036
+ name: title,
2037
+ description,
2038
+ published,
2039
+ metadatas: [
2040
+ {
2041
+ shop: this.shop,
2042
+ title: `${userFullName} - ${title}`,
2043
+ description: `${userFullName} - ${description}`,
2044
+ },
2045
+ ],
2046
+ personName: userFullName,
2047
+ personPhoto: userPhoto,
2048
+ theme,
2049
+ bannerUrl,
2050
+ personType: personType !== null && personType !== void 0 ? personType : PersonTypes.NONE,
2051
+ personIsSubscriber: personIsSubscriber !== null && personIsSubscriber !== void 0 ? personIsSubscriber : false,
2052
+ };
2053
+ return this.wishlistRepository.update(data);
2054
+ }
2055
+ delete(wishlistId) {
2056
+ return this.wishlistRepository.delete({ id: wishlistId });
2057
+ }
2058
+ getWishlistBySlug(slug) {
2059
+ const [id] = slug.split('-');
2060
+ if (+id)
2061
+ return this.wishlistRepository.get({ id });
2062
+ return this.wishlistRepository.getWishlistBySlug(slug);
2063
+ }
2064
+ getWishlistsByPerson(personId) {
2065
+ return this.wishlistRepository.getWishlistByPerson(personId);
2066
+ }
2067
+ addProduct(wishlistId, productId) {
2068
+ return __awaiter(this, void 0, void 0, function* () {
2069
+ const wishlist = yield this.wishlistRepository.get({ id: wishlistId });
2070
+ const hasProduct = wishlist.products.some((p) => p == productId);
2071
+ if (!hasProduct) {
2072
+ wishlist.products = [...wishlist.products, productId];
2073
+ return this.wishlistRepository.update({ id: wishlistId, products: wishlist.products });
2074
+ }
2075
+ return wishlist;
2076
+ });
2077
+ }
2078
+ removeProduct(wishlistId, productId) {
2079
+ return __awaiter(this, void 0, void 0, function* () {
2080
+ const wishlist = yield this.wishlistRepository.get({ id: wishlistId });
2081
+ const productIndex = wishlist.products.findIndex((p) => p == productId);
2082
+ if (productIndex != -1) {
2083
+ wishlist.products.splice(productIndex, 1);
2084
+ if (!wishlist.products.length)
2085
+ return this.wishlistRepository.update({ id: wishlistId, products: { action: 'remove' } });
2086
+ return this.wishlistRepository.update({ id: wishlistId, products: wishlist.products });
2087
+ }
2088
+ return wishlist;
2089
+ });
2090
+ }
2091
+ }
2092
+ WishlistService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService, deps: [{ token: 'WishlistRepository' }, { token: DEFAULT_SHOP }, { token: 'ProductRepository' }, { token: 'CategoryFilterRepository' }, { token: 'CategoryRepository' }, { token: 'ProductStockNotificationRepository' }, { token: i1$2.ProductsIndex }], target: i0.ɵɵFactoryTarget.Injectable });
2093
+ WishlistService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService });
2094
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService, decorators: [{
2095
+ type: Injectable
2096
+ }], ctorParameters: function () {
2097
+ return [{ type: undefined, decorators: [{
2098
+ type: Inject,
2099
+ args: ['WishlistRepository']
2100
+ }] }, { type: i1$2.Shops, decorators: [{
2101
+ type: Inject,
2102
+ args: [DEFAULT_SHOP]
2103
+ }] }, { type: undefined, decorators: [{
2104
+ type: Inject,
2105
+ args: ['ProductRepository']
2106
+ }] }, { type: undefined, decorators: [{
2107
+ type: Inject,
2108
+ args: ['CategoryFilterRepository']
2109
+ }] }, { type: undefined, decorators: [{
2110
+ type: Inject,
2111
+ args: ['CategoryRepository']
2112
+ }] }, { type: undefined, decorators: [{
2113
+ type: Inject,
2114
+ args: ['ProductStockNotificationRepository']
2115
+ }] }, { type: i1$2.ProductsIndex }];
2116
+ } });
2117
+
2118
+ class CheckoutSubscriptionService {
2119
+ constructor(checkoutSubscriptionRepository, dataPersistence, couponService) {
2120
+ this.checkoutSubscriptionRepository = checkoutSubscriptionRepository;
2121
+ this.dataPersistence = dataPersistence;
2122
+ this.couponService = couponService;
2123
+ }
2124
+ getCheckoutSubscription(checkoutData) {
2125
+ return this.dataPersistence
2126
+ .get('checkoutSubscriptionId')
2127
+ .pipe(concatMap((id) => !isNil(id) ? this.checkoutSubscriptionRepository.get({ id }) : this.createCheckoutSubscription(checkoutData)));
2128
+ }
2129
+ clearCheckoutSubscriptionFromSession() {
2130
+ return this.dataPersistence.remove('checkoutSubscriptionId');
2131
+ }
2132
+ checkCoupon(nickname, userEmail) {
2133
+ return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService
2134
+ .checkCoupon(nickname, CheckoutTypes.SUBSCRIPTION, checkout, checkout.subscriptionPlan.name)
2135
+ .pipe()));
2136
+ }
2137
+ calcDiscountSubscription(coupon) {
2138
+ return this.getCheckoutSubscription().pipe(concatMap((checkout) => this.couponService.calcDiscountSubscription(coupon, checkout).pipe()));
2139
+ }
2140
+ createCheckoutSubscription(checkoutData) {
2141
+ return __awaiter(this, void 0, void 0, function* () {
2142
+ const checkout = yield this.checkoutSubscriptionRepository.create(Object.assign({ createdAt: new Date() }, CheckoutSubscription.toInstance(pick(checkoutData, ['user', 'shop'])).toPlain()));
2143
+ yield this.dataPersistence.set('checkoutSubscriptionId', checkout.id).toPromise();
2144
+ return checkout;
2145
+ });
2146
+ }
2147
+ }
2148
+ CheckoutSubscriptionService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutSubscriptionService, deps: [{ token: 'CheckoutSubscriptionRepository' }, { token: PERSISTENCE_PROVIDER }, { token: CouponService }], target: i0.ɵɵFactoryTarget.Injectable });
2149
+ CheckoutSubscriptionService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutSubscriptionService });
2150
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutSubscriptionService, decorators: [{
2151
+ type: Injectable
2152
+ }], ctorParameters: function () {
2153
+ return [{ type: undefined, decorators: [{
2154
+ type: Inject,
2155
+ args: ['CheckoutSubscriptionRepository']
2156
+ }] }, { type: undefined, decorators: [{
2157
+ type: Inject,
2158
+ args: [PERSISTENCE_PROVIDER]
2159
+ }] }, { type: CouponService }];
2160
+ } });
2161
+
2162
+ class UtilHelper {
2163
+ static createSlug(name) {
2164
+ return name
2165
+ .toLowerCase()
2166
+ .replace(/\s+/g, '-') // Replace spaces with -
2167
+ .replace(/[ãàáäâ]/g, 'a') // Replace spaces with -
2168
+ .replace(/[ẽèéëê]/g, 'e') // Replace spaces with -
2169
+ .replace(/[ìíïî]/g, 'i') // Replace spaces with -
2170
+ .replace(/[õòóöô]/g, 'o') // Replace spaces with -
2171
+ .replace(/[ùúüû]/g, 'u') // Replace spaces with -
2172
+ .replace(/[ñ]/g, 'n') // Replace spaces with -
2173
+ .replace(/[ç]/g, 'c') // Replace spaces with -
2174
+ .replace(/[&]/g, 'and') // Replace spaces with -
2175
+ .replace(/[^\w\-]+/g, '') // Remove all non-word chars
2176
+ .replace(/\-\-+/g, '-'); // Replace multiple - with single -
2177
+ }
2178
+ }
2179
+
2180
+ class HomeShopService {
2181
+ get homeId() {
2182
+ if (this.defaultShop === Shops.GLAMSHOP)
2183
+ return 'glamshop';
2184
+ if (this.defaultShop === Shops.MENSMARKET)
2185
+ return 'mens_market';
2186
+ return null;
2187
+ }
2188
+ constructor(categoryRepository, homeRepository, productRepository, defaultShop) {
2189
+ this.categoryRepository = categoryRepository;
2190
+ this.homeRepository = homeRepository;
2191
+ this.productRepository = productRepository;
2192
+ this.defaultShop = defaultShop;
2193
+ this.buildCategoryGroupWithRequiredData = (group) => {
2194
+ var _a, _b;
2195
+ return ({
2196
+ category: Category.toInstance(pick(((_a = group === null || group === void 0 ? void 0 : group.category) === null || _a === void 0 ? void 0 : _a.toPlain()) || {}, ['id', 'name', 'slug', 'conditions'])),
2197
+ products: ((_b = group === null || group === void 0 ? void 0 : group.products) === null || _b === void 0 ? void 0 : _b.map((product) => Product.toInstance(pick((product === null || product === void 0 ? void 0 : product.toPlain()) || {}, [
2198
+ 'id',
2199
+ 'price',
2200
+ 'reviews',
2201
+ 'hasVariants',
2202
+ 'slug',
2203
+ 'sku',
2204
+ 'stock',
2205
+ 'costPrice',
2206
+ 'images',
2207
+ 'miniatures',
2208
+ 'name',
2209
+ 'weight',
2210
+ 'rate',
2211
+ 'type',
2212
+ 'brand',
2213
+ ])))) || [],
2214
+ });
2215
+ };
2216
+ }
2217
+ getHomeData() {
2218
+ return this.getHomeConfiguration().pipe(map((home) => { var _a; return (((_a = home === null || home === void 0 ? void 0 : home.data) === null || _a === void 0 ? void 0 : _a.expiresAt) > new Date() ? home : null); }), concatMap((home) => home
2219
+ ? of(home)
2220
+ : forkJoin([
2221
+ this.getDiscoverProducts(this.gender),
2222
+ this.getFeaturedProducts(this.gender),
2223
+ this.getVerticalProducts(this.gender),
2224
+ ]).pipe(map(([discoverProducts, featuredProducts, verticalProducts]) => ({
2225
+ discoverProducts,
2226
+ featuredProducts,
2227
+ verticalProducts,
2228
+ })), concatMap((data) => this.saveHomeData(data)))));
2229
+ }
2230
+ getBanners(type) {
2231
+ return this.getHomeConfiguration().pipe(map((home) => {
2232
+ if (type === 'brand')
2233
+ return home.brandsCarousel;
2234
+ if (type === 'buyToWin')
2235
+ return [home.buyToWinBanner];
2236
+ if (type === 'block')
2237
+ return home.blockBanners;
2238
+ if (type === 'blog')
2239
+ return [home.blogBanner];
2240
+ return [];
2241
+ }));
2242
+ }
2243
+ getMinValueForFreeShipping() {
2244
+ return this.getHomeConfiguration().pipe(map((home) => home.minValueForFreeShipping));
2245
+ }
2246
+ getDiscoverProducts(gender) {
2247
+ return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.discoverCategories, undefined, gender)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
2248
+ }
2249
+ getFeaturedProducts(gender) {
2250
+ return this.getHomeConfiguration().pipe(concatMap((home) => from(this.categoryRepository.getCategoriesForHome(home.featuredCategories, undefined, gender)).pipe(map((groups) => groups.map(this.buildCategoryGroupWithRequiredData)))));
2251
+ }
2252
+ getVerticalProducts(gender) {
2253
+ 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({
2254
+ filters: Object.assign({ categories: { operator: Where.IN, value: [category.id] } }, (gender ? { tags: { operator: Where.IN, value: [gender] } } : {})),
2255
+ limits: { limit: 12 },
2256
+ })).pipe(map((products) => ({ category, products })))), map(({ category, products }) => ({ category, products: products.data })), map(this.buildCategoryGroupWithRequiredData))))));
2257
+ }
2258
+ getHomeConfiguration() {
2259
+ return of(this.homeConfiguration).pipe(concatMap((home) => home
2260
+ ? of(home)
2261
+ : !this.homeId
2262
+ ? throwError(new RequiredArgumentError(['homeId']))
2263
+ : from(this.homeRepository.get({ id: this.homeId })).pipe(tap((homeLoaded) => (this.homeConfiguration = homeLoaded)))));
2264
+ }
2265
+ saveHomeData(homeData) {
2266
+ const data = {
2267
+ createdAt: new Date(),
2268
+ expiresAt: add(new Date(), { hours: 1 }),
2269
+ data: homeData,
2270
+ };
2271
+ return from(this.homeRepository.update({
2272
+ id: this.homeId,
2273
+ data,
2274
+ })).pipe(tap(() => (this.homeConfiguration.data = data)), map(() => this.homeConfiguration));
2275
+ }
2276
+ get gender() {
2277
+ return this.homeId === 'mens_market' ? 'masculino' : undefined;
2278
+ }
2279
+ }
2280
+ 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 });
2281
+ HomeShopService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService });
2282
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: HomeShopService, decorators: [{
2283
+ type: Injectable
2284
+ }], ctorParameters: function () {
2285
+ return [{ type: undefined, decorators: [{
2286
+ type: Inject,
2287
+ args: ['CategoryRepository']
2288
+ }] }, { type: undefined, decorators: [{
2289
+ type: Inject,
2290
+ args: ['HomeRepository']
2291
+ }] }, { type: undefined, decorators: [{
2292
+ type: Inject,
2293
+ args: ['ProductRepository']
2294
+ }] }, { type: i1$2.Shops, decorators: [{
2295
+ type: Inject,
2296
+ args: [DEFAULT_SHOP]
2297
+ }] }];
2298
+ } });
2299
+
2300
+ class OrderService {
2301
+ constructor(angularFirestore, orderRepository) {
2302
+ this.angularFirestore = angularFirestore;
2303
+ this.orderRepository = orderRepository;
2304
+ this.orderSubject = new Subject();
2305
+ }
2306
+ getOrder(id) {
2307
+ docSnapshots(doc(this.angularFirestore, `${this.orderRepository.collectionName}/${id}`))
2308
+ .pipe(map((doc) => Order.toInstance(doc.data())))
2309
+ .subscribe((doc) => this.orderSubject.next(doc));
2310
+ return this.orderSubject;
2311
+ }
2312
+ }
2313
+ 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 });
2314
+ OrderService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService });
2315
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService, decorators: [{
2316
+ type: Injectable
2317
+ }], ctorParameters: function () {
2318
+ return [{ type: i1$1.Firestore }, { type: i1$2.OrderFirestoreRepository, decorators: [{
2319
+ type: Inject,
2320
+ args: ['OrderRepository']
2321
+ }] }];
2322
+ } });
2323
+
2324
+ class ShippingService {
2325
+ constructor(http, apiUrl, homeService) {
2326
+ this.http = http;
2327
+ this.apiUrl = apiUrl;
2328
+ this.homeService = homeService;
2329
+ }
2330
+ getShippingMethods(shop, zip, weightGrams, totalPrice, personId, subscriptionPlan) {
2331
+ return combineLatest([
2332
+ this.homeService.getHomeData(),
2333
+ this.http.get(`${this.apiUrl}open/checkshippingcompany?personId=${personId}&postalCode=${zip}&weightGrams=${weightGrams}`),
2334
+ ]).pipe(map(([datas, shippingMethodsResponse]) => {
2335
+ let shippingMethods = shippingMethodsResponse.result;
2336
+ if (!shippingMethods.length)
2337
+ return [];
2338
+ shippingMethods = shippingMethods.map((shippingMethod) => {
2339
+ if (shippingMethod.ShippingCompanyName == 'Same Day EG')
2340
+ shippingMethod.ShippingCompanyName = 'Same Day';
2341
+ return shippingMethod;
2342
+ });
2343
+ const datasSameDayNotAvaliable = datas.sameDayNotAvaliable;
2344
+ if (this.isHolidays(datasSameDayNotAvaliable)) {
2345
+ shippingMethods = shippingMethods.filter((method) => method.serviceName !== 'Same Day');
2346
+ }
2347
+ if (totalPrice >= 200) {
2348
+ shippingMethods = shippingMethods.map((s) => {
2349
+ if (s.serviceName !== 'Same Day')
2350
+ return Object.assign(Object.assign({}, s), { totalPrice: 0 });
2351
+ else
2352
+ return s;
2353
+ });
2354
+ }
2355
+ if (shop == Shops.GLAMSHOP)
2356
+ return shippingMethods;
2357
+ if (this.isFreeShippingBySubscription(shop, subscriptionPlan)) {
2358
+ shippingMethods = shippingMethods.map((s) => {
2359
+ if (s.serviceName == 'Same Day')
2360
+ return Object.assign(Object.assign({}, s), { totalPrice: s.totalPrice / 2 });
2361
+ else
2362
+ return Object.assign(Object.assign({}, s), { totalPrice: 0 });
2363
+ });
2364
+ }
2365
+ if (this.isHalfShippingBySubscription(shop, subscriptionPlan)) {
2366
+ shippingMethods = shippingMethods.map((s) => {
2367
+ return Object.assign(Object.assign({}, s), { totalPrice: s.totalPrice / 2 });
2368
+ });
2369
+ }
2370
+ return shippingMethods;
2371
+ }));
2372
+ }
2373
+ isFreeShippingBySubscription(shop, subscriptionPlan) {
2374
+ if (!subscriptionPlan)
2375
+ return false;
2376
+ if (shop == Shops.MENSMARKET && subscriptionPlan == 'SELECT')
2377
+ return true;
2378
+ return false;
2379
+ }
2380
+ isHalfShippingBySubscription(shop, subscriptionPlan) {
2381
+ if (!subscriptionPlan)
2382
+ return false;
2383
+ if (shop == Shops.MENSMARKET && subscriptionPlan == 'PRIME') {
2384
+ return true;
2385
+ }
2386
+ return false;
2387
+ }
2388
+ isHolidays(datas) {
2389
+ const today = new Date();
2390
+ for (const key in datas) {
2391
+ let start = new Date(`${today.getFullYear()}-${datas[key].beginDate}`);
2392
+ let end = new Date(`${today.getFullYear()}-${datas[key].endDate}`);
2393
+ if (start > end)
2394
+ end = new Date(`${today.getFullYear() + 1}-${datas[key].endDate}`);
2395
+ if (today >= start && today <= end)
2396
+ return true;
2397
+ }
2398
+ return false;
2399
+ }
2400
+ }
2401
+ ShippingService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService, deps: [{ token: i1$3.HttpClient }, { token: BACKEND_URL }, { token: HomeShopService }], target: i0.ɵɵFactoryTarget.Injectable });
2402
+ ShippingService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService });
2403
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService, decorators: [{
2404
+ type: Injectable
2405
+ }], ctorParameters: function () {
2406
+ return [{ type: i1$3.HttpClient }, { type: undefined, decorators: [{
2407
+ type: Inject,
2408
+ args: [BACKEND_URL]
2409
+ }] }, { type: HomeShopService }];
2410
+ } });
2411
+
2412
+ class AngularConnectModule {
2413
+ static initializeApp(defaultShop, options, nameOrConfig) {
2414
+ return {
2415
+ ngModule: AngularConnectModule,
2416
+ providers: [
2417
+ {
2418
+ provide: CATEGORY_STRUCTURE,
2419
+ useClass: isNil(options === null || options === void 0 ? void 0 : options.oldCategoryStructure) || (options === null || options === void 0 ? void 0 : options.oldCategoryStructure)
2420
+ ? OldCategoryStructureAdapter
2421
+ : NewCategoryStructureAdapter,
2422
+ },
2423
+ { provide: PERSISTENCE_PROVIDER, useClass: (options === null || options === void 0 ? void 0 : options.persistenceProvider) || CookieDataPersistence },
2424
+ ...(isNil(defaultShop) ? [] : [{ provide: DEFAULT_SHOP, useValue: defaultShop }]),
2425
+ ...(isNil(options === null || options === void 0 ? void 0 : options.firebase) ? [] : [{ provide: FIREBASE_OPTIONS, useValue: options === null || options === void 0 ? void 0 : options.firebase }]),
2426
+ ...(isNil(options === null || options === void 0 ? void 0 : options.firebase) ? [] : [{ provide: FIREBASE_APP_NAME, useValue: nameOrConfig }]),
2427
+ ...(isNil(options === null || options === void 0 ? void 0 : options.elasticSearch) ? [] : [{ provide: ES_CONFIG, useValue: options.elasticSearch }]),
2428
+ ...(isNil(options === null || options === void 0 ? void 0 : options.hasura) ? [] : [{ provide: HASURA_OPTIONS, useValue: options.hasura }]),
2429
+ ...(isNil(options === null || options === void 0 ? void 0 : options.backendUrl) ? [] : [{ provide: BACKEND_URL, useValue: options.backendUrl }]),
2430
+ ...(isNil(options === null || options === void 0 ? void 0 : options.storageBaseUrl) ? [] : [{ provide: STORAGE_BASE_URL, useValue: options.storageBaseUrl }]),
2431
+ ],
2432
+ };
2433
+ }
2434
+ }
2435
+ AngularConnectModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2436
+ AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, imports: [i1$4.FirebaseAppModule, i2.StorageModule, AngularElasticSeachModule,
2437
+ AngularFirebaseAuthModule,
2438
+ AngularFirestoreModule,
2439
+ AngularHasuraGraphQLModule] });
2440
+ AngularConnectModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, providers: [
2441
+ AuthService,
2442
+ CartService,
2443
+ CatalogService,
2444
+ CategoryService,
2445
+ CheckoutService,
2446
+ CheckoutSubscriptionService,
2447
+ CouponService,
2448
+ HomeShopService,
2449
+ OrderService,
2450
+ ShippingService,
2451
+ WishlistService,
2452
+ {
2453
+ provide: UpdateUserImage,
2454
+ useFactory: (userRepository, fileUploader) => {
2455
+ return new UpdateUserImage(userRepository, fileUploader);
2456
+ },
2457
+ deps: ['UserRepository', 'FileUploaderService'],
2458
+ },
2459
+ {
2460
+ provide: 'FileUploaderService',
2461
+ useFactory: (storage, baseUrl) => {
2462
+ return new FirebaseFileUploaderService(storage, baseUrl);
2463
+ },
2464
+ deps: [Storage, STORAGE_BASE_URL],
2465
+ },
2466
+ ], imports: [provideFirebaseApp((injector) => {
2467
+ const appName = injector.get(FIREBASE_APP_NAME) || '[DEFAULT]';
2468
+ try {
2469
+ return getApp(appName);
2470
+ }
2471
+ catch (error) {
2472
+ return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2473
+ }
2474
+ }),
2475
+ provideStorage((injector) => getStorage(injector.get(FirebaseApp))),
2476
+ AngularElasticSeachModule,
2477
+ AngularFirebaseAuthModule,
2478
+ AngularFirestoreModule,
2479
+ AngularHasuraGraphQLModule] });
2480
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, decorators: [{
2481
+ type: NgModule,
2482
+ args: [{
2483
+ imports: [
2484
+ provideFirebaseApp((injector) => {
2485
+ const appName = injector.get(FIREBASE_APP_NAME) || '[DEFAULT]';
2486
+ try {
2487
+ return getApp(appName);
2488
+ }
2489
+ catch (error) {
2490
+ return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2491
+ }
2492
+ }),
2493
+ provideStorage((injector) => getStorage(injector.get(FirebaseApp))),
2494
+ AngularElasticSeachModule,
2495
+ AngularFirebaseAuthModule,
2496
+ AngularFirestoreModule,
2497
+ AngularHasuraGraphQLModule,
2498
+ ],
2499
+ providers: [
2500
+ AuthService,
2501
+ CartService,
2502
+ CatalogService,
2503
+ CategoryService,
2504
+ CheckoutService,
2505
+ CheckoutSubscriptionService,
2506
+ CouponService,
2507
+ HomeShopService,
2508
+ OrderService,
2509
+ ShippingService,
2510
+ WishlistService,
2511
+ {
2512
+ provide: UpdateUserImage,
2513
+ useFactory: (userRepository, fileUploader) => {
2514
+ return new UpdateUserImage(userRepository, fileUploader);
2515
+ },
2516
+ deps: ['UserRepository', 'FileUploaderService'],
2517
+ },
2518
+ {
2519
+ provide: 'FileUploaderService',
2520
+ useFactory: (storage, baseUrl) => {
2521
+ return new FirebaseFileUploaderService(storage, baseUrl);
2522
+ },
2523
+ deps: [Storage, STORAGE_BASE_URL],
2524
+ },
2525
+ ],
2526
+ }]
2527
+ }] });
2528
+
2529
+ /**
2530
+ * Generated bundle index. Do not edit.
2531
+ */
2532
+
2533
+ export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CookieDataPersistence, CouponService, HomeShopService, NewCategoryStructureAdapter, OldCategoryStructureAdapter, OrderService, ProductSorts, ShippingService, UtilHelper, WishlistService };
2534
+ //# sourceMappingURL=infrab4a-connect-angular.mjs.map