@infrab4a/connect-angular 4.6.1-beta.3 → 4.6.1

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