@infrab4a/connect-angular 3.9.1-beta2 → 3.9.1-beta3

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