@infrab4a/connect-angular 4.17.3-beta.1 → 4.17.3-beta.10

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.
@@ -1,21 +1,21 @@
1
1
  import * as i0 from '@angular/core';
2
2
  import { NgModule, InjectionToken, PLATFORM_ID, Injectable, Inject } from '@angular/core';
3
- import * as i1$3 from '@angular/fire/app';
3
+ import * as i1$4 from '@angular/fire/app';
4
4
  import { FirebaseApp, provideFirebaseApp, getApp, initializeApp } from '@angular/fire/app';
5
5
  import * as i2 from '@angular/fire/storage';
6
6
  import { Storage, provideStorage, getStorage } from '@angular/fire/storage';
7
- import * as i1$2 from '@infrab4a/connect';
8
- import { ProductsIndex, AxiosAdapter, Authentication, AuthenticationFirebaseAuthService, Register, RegisterFirebaseAuthService, SignOut, RecoveryPassword, ConnectFirestoreService, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, CampaignHashtagFirestoreRepository, CampaignDashboardFirestoreRepository, SubscriptionEditionFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, ShopSettingsFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, SubscriptionMaterializationFirestoreRepository, SubscriptionSummaryFirestoreRepository, ProductVariantFirestoreRepository, OrderBlockedFirestoreRepository, LogFirestoreRepository, SequenceFirestoreRepository, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository, ProductReviewsHasuraGraphQLRepository, VariantHasuraGraphQLRepository, ProductStockNotificationHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryProductHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, ProductsVertexSearch, VertexAxiosAdapter, Where, Shops, CheckoutTypes, CouponTypes, Exclusivities, OrderStatus, isNil, NotFoundError, Checkout, pick, LineItem, RoundProductPricesHelper, set, InvalidArgumentError, isEmpty, Category, PersonTypes, WishlistLogType, Wishlist, CheckoutSubscription, Product, RequiredArgumentError, add, Order, UpdateUserImage, FirebaseFileUploaderService } from '@infrab4a/connect';
7
+ import * as i1$3 from '@infrab4a/connect';
8
+ import { ProductsIndex, AxiosAdapter, Authentication, AuthenticationFirebaseAuthService, Register, RegisterFirebaseAuthService, SignOut, RecoveryPassword, ConnectFirestoreService, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, CampaignHashtagFirestoreRepository, CampaignDashboardFirestoreRepository, SubscriptionEditionFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, ShopSettingsFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, SubscriptionMaterializationFirestoreRepository, SubscriptionSummaryFirestoreRepository, ProductVariantFirestoreRepository, OrderBlockedFirestoreRepository, LogFirestoreRepository, SequenceFirestoreRepository, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository, ProductReviewsHasuraGraphQLRepository, VariantHasuraGraphQLRepository, ProductStockNotificationHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryProductHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, ProductsVertexSearch, VertexAxiosAdapter, isNil, NotFoundError, Checkout, pick, LineItem, Where, set, InvalidArgumentError, RoundProductPricesHelper, isEmpty, Shops, Category, PersonTypes, WishlistLogType, Wishlist, CheckoutTypes, CouponTypes, Exclusivities, OrderStatus, CheckoutSubscription, Product, RequiredArgumentError, add, Order, UpdateUserImage, FirebaseFileUploaderService } from '@infrab4a/connect';
9
9
  import * as i1 from '@angular/fire/auth';
10
10
  import { Auth, provideAuth, getAuth, getIdToken, authState } from '@angular/fire/auth';
11
11
  import { isPlatformBrowser, isPlatformServer } from '@angular/common';
12
12
  import * as i1$1 from '@angular/fire/firestore';
13
13
  import { Firestore, provideFirestore, initializeFirestore, memoryLocalCache, docSnapshots, doc } from '@angular/fire/firestore';
14
14
  import cookie from 'js-cookie';
15
- import { of, from, combineLatest, throwError, Subject, iif, forkJoin } from 'rxjs';
15
+ import { of, from, combineLatest, throwError, Subject, forkJoin } from 'rxjs';
16
16
  import { map, mergeMap, catchError, concatMap, tap } from 'rxjs/operators';
17
17
  import { __awaiter, __decorate, __metadata } from 'tslib';
18
- import * as i3 from '@angular/common/http';
18
+ import * as i1$2 from '@angular/common/http';
19
19
  import { Type } from 'class-transformer';
20
20
 
21
21
  const ES_CONFIG = 'ES_CONFIG';
@@ -1084,312 +1084,17 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
1084
1084
  }] }];
1085
1085
  } });
1086
1086
 
1087
- class CouponService {
1088
- constructor(couponRepository, defaultShop, orderRepository, categoryRepository) {
1089
- this.couponRepository = couponRepository;
1090
- this.defaultShop = defaultShop;
1091
- this.orderRepository = orderRepository;
1092
- this.categoryRepository = categoryRepository;
1093
- this.emailIsFromCollaborator = (userEmail) => !!(userEmail === null || userEmail === void 0 ? void 0 : userEmail.match(/@b4a.com.br/g));
1094
- }
1095
- checkCoupon(nickname, checkoutType, checkout, plan) {
1096
- return from(this.couponRepository
1097
- .find({
1098
- filters: {
1099
- nickname: { operator: Where.EQUALS, value: nickname },
1100
- active: { operator: Where.EQUALS, value: true },
1101
- },
1102
- })
1103
- .then((result) => result.data[0])).pipe(concatMap((coupon) => this.couponValidation(coupon, checkoutType)), concatMap((couponValid) => this.couponRulesValidation(couponValid, checkoutType, checkout, plan)), map((couponValidated) => couponValidated));
1104
- }
1105
- couponValidation(coupon, checkoutType) {
1106
- return __awaiter(this, void 0, void 0, function* () {
1107
- if (!coupon)
1108
- throw 'Cupom inválido.';
1109
- if ((coupon === null || coupon === void 0 ? void 0 : coupon.beginAt) && (coupon === null || coupon === void 0 ? void 0 : coupon.beginAt.getTime()) > new Date().getTime())
1110
- throw 'Cupom inválido.';
1111
- if ((coupon === null || coupon === void 0 ? void 0 : coupon.expiresIn) && (coupon === null || coupon === void 0 ? void 0 : coupon.expiresIn.getTime()) < new Date().getTime())
1112
- throw 'Cupom expirado.';
1113
- const isInShop = coupon.shopAvailability === Shops.ALL || coupon.shopAvailability === this.defaultShop;
1114
- if (!isInShop)
1115
- throw 'Cupom inválido para loja.';
1116
- const isCheckoutType = coupon.checkoutType === CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
1117
- if (!isCheckoutType)
1118
- throw 'Cupom inválido. Erro de checkout.';
1119
- return coupon;
1120
- });
1121
- }
1122
- couponRulesValidation(coupon, checkoutType, checkout, plan) {
1123
- var _a;
1124
- return __awaiter(this, void 0, void 0, function* () {
1125
- if (checkoutType == CheckoutTypes.SUBSCRIPTION) {
1126
- if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
1127
- throw 'Cupom inválido para sua assinatura.';
1128
- return coupon;
1129
- }
1130
- const validUser = this.coupomUserValidation(coupon, checkout === null || checkout === void 0 ? void 0 : checkout.user);
1131
- if (!validUser)
1132
- throw 'Usuário não elegível.';
1133
- const couponUseLimits = this.getCouponUseLimits(coupon, checkoutType, checkout.user);
1134
- if (couponUseLimits.firstOrder) {
1135
- const ordersUser = yield this.getOrdersFromUser(checkout.user.email.toLocaleLowerCase());
1136
- if (couponUseLimits.firstOrder && ordersUser.length >= 1)
1137
- throw 'Limite de uso atingido';
1138
- }
1139
- if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
1140
- const ordersCoupon = yield this.getOrdersWithCoupon(coupon);
1141
- if (!couponUseLimits.unlimited && couponUseLimits.total && ordersCoupon.length >= couponUseLimits.total)
1142
- throw 'Limite de uso atingido.';
1143
- if (couponUseLimits.limitedPerUser) {
1144
- const ordersWithUser = this.countOrdersWithUser(ordersCoupon, checkout.user.email);
1145
- if (ordersWithUser > 0)
1146
- throw 'Limite de uso por usuário atingido.';
1147
- }
1148
- }
1149
- const hasProductCategories = yield this.hasProductCategories(coupon, checkout);
1150
- if (!hasProductCategories)
1151
- throw 'Seu carrinho não possui produtos elegíveis para desconto.';
1152
- const hasMinSubTotal = yield this.hasMinSubTotal(coupon, checkout);
1153
- if (!hasMinSubTotal) {
1154
- if ((_a = coupon.productsCategories) === null || _a === void 0 ? void 0 : _a.length) {
1155
- throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido na(s) categoria(s) elegíveis para o desconto.`;
1156
- }
1157
- throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido.`;
1158
- }
1159
- return coupon;
1160
- });
1161
- }
1162
- calcDiscountSubscription(coupon, checkout) {
1163
- let discount = 0;
1164
- if (coupon.discount.subscription.type == CouponTypes.ABSOLUTE)
1165
- discount = coupon.discount.subscription.value;
1166
- else
1167
- discount = checkout.subscriptionPlan.recurrencePrice * (coupon.discount.subscription.value / 100);
1168
- return of(discount);
1169
- }
1170
- calcDiscountShopping(coupon, checkout) {
1171
- return __awaiter(this, void 0, void 0, function* () {
1172
- let discountInfo = null;
1173
- if (checkout.user.isSubscriber && coupon.discount.subscriber.value) {
1174
- discountInfo = yield this.calcDiscountByType(coupon.discount.subscriber.type, coupon.discount.subscriber.value, coupon.productsCategories, checkout);
1175
- }
1176
- else {
1177
- discountInfo = yield this.calcDiscountByType(coupon.discount.non_subscriber.type, coupon.discount.non_subscriber.value, coupon.productsCategories, checkout);
1178
- }
1179
- return { discount: discountInfo.discount, lineItems: discountInfo.lineItems };
1180
- });
1181
- }
1182
- calcDiscountByType(type, value, categories, checkout) {
1183
- return __awaiter(this, void 0, void 0, function* () {
1184
- let discount = 0;
1185
- if (type == CouponTypes.SHIPPING) {
1186
- const subTotal = checkout.shipping.ShippingPrice;
1187
- const discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2);
1188
- return { discount, lineItems: checkout.lineItems };
1189
- }
1190
- const lineItensElegibleForDiscount = yield this.getLineItensEligebleForDiscount(categories, checkout);
1191
- const subTotal = this.calcCheckoutSubtotal(lineItensElegibleForDiscount, checkout.user);
1192
- if (type == CouponTypes.ABSOLUTE) {
1193
- discount = value > subTotal ? subTotal : value;
1194
- }
1195
- else {
1196
- discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2);
1197
- }
1198
- const lineItems = this.calcLineItenDiscount(type, lineItensElegibleForDiscount, value, subTotal);
1199
- return { discount, lineItems };
1200
- });
1201
- }
1202
- hasMinSubTotal(coupon, checkout) {
1203
- return __awaiter(this, void 0, void 0, function* () {
1204
- if (!coupon.minSubTotalValue)
1205
- return true;
1206
- const lineItensDiscount = yield this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
1207
- const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user);
1208
- if (coupon.minSubTotalValue <= subTotal)
1209
- return true;
1210
- return false;
1211
- });
1212
- }
1213
- hasProductCategories(coupon, checkout) {
1214
- var _a, _b;
1215
- return __awaiter(this, void 0, void 0, function* () {
1216
- if (!coupon.productsCategories || !((_a = coupon.productsCategories) === null || _a === void 0 ? void 0 : _a.length)) {
1217
- return true;
1218
- }
1219
- const couponCategories = yield this.getCouponCategoriesId(coupon.productsCategories);
1220
- const hasCategories = (_b = checkout.lineItems) === null || _b === void 0 ? void 0 : _b.filter((item) => {
1221
- var _a;
1222
- if (item.isGift)
1223
- return false;
1224
- if (!item.categories || !((_a = item.categories) === null || _a === void 0 ? void 0 : _a.length))
1225
- return true;
1226
- return item.categories.some((c) => couponCategories.some((cat) => cat == c));
1227
- });
1228
- return hasCategories.length ? true : false;
1229
- });
1230
- }
1231
- coupomUserValidation(coupon, user) {
1232
- if (!user || coupon.exclusivityType.includes(Exclusivities.ALL_USERS))
1233
- return true;
1234
- let userTypes = [];
1235
- if (coupon.exclusivityType.includes(Exclusivities.COLLABORATORS) &&
1236
- this.emailIsFromCollaborator(user.email.toLocaleLowerCase()))
1237
- userTypes.push(Exclusivities.COLLABORATORS);
1238
- if (coupon.exclusivityType.includes(Exclusivities.SPECIFIC_USER) &&
1239
- coupon.userExclusiveEmail.includes(user.email.toLocaleLowerCase()))
1240
- userTypes.push(Exclusivities.SPECIFIC_USER);
1241
- if (coupon.exclusivityType.includes(Exclusivities.ACTIVE_SUBSCRIBER) &&
1242
- user.isSubscriber &&
1243
- user.subscriptionPlan != '')
1244
- userTypes.push(Exclusivities.ACTIVE_SUBSCRIBER);
1245
- if (user.isSubscriber &&
1246
- user.subscriptionPlan == '' &&
1247
- coupon.exclusivityType.includes(Exclusivities.INACTIVE_SUBSCRIBER))
1248
- userTypes.push(Exclusivities.INACTIVE_SUBSCRIBER);
1249
- if (coupon.exclusivityType.includes(Exclusivities.NON_SUBSCRIBER) && !user.isSubscriber)
1250
- userTypes.push(Exclusivities.NON_SUBSCRIBER);
1251
- return coupon.exclusivityType.some((r) => userTypes.includes(r));
1252
- }
1253
- getCouponCategoriesId(productsCategories) {
1254
- return __awaiter(this, void 0, void 0, function* () {
1255
- const couponCategories = [];
1256
- for (let index = 0; index < productsCategories.length; index++) {
1257
- const category = yield this.categoryRepository.get({
1258
- id: productsCategories[index],
1259
- });
1260
- if (category) {
1261
- const children = yield this.categoryRepository.getChildren(parseInt(productsCategories[index]));
1262
- couponCategories.push(category.id, ...children.map((c) => c.id.toString()));
1263
- }
1264
- }
1265
- return [...new Set(couponCategories)];
1266
- });
1267
- }
1268
- getLineItensEligebleForDiscount(productsCategories, checkout) {
1269
- var _a;
1270
- return __awaiter(this, void 0, void 0, function* () {
1271
- let lineItensDiscount = [];
1272
- const couponCategories = yield this.getCouponCategoriesId(productsCategories);
1273
- if (productsCategories && productsCategories.length) {
1274
- lineItensDiscount = (_a = checkout.lineItems) === null || _a === void 0 ? void 0 : _a.filter((item) => {
1275
- var _a;
1276
- if (item.isGift)
1277
- return false;
1278
- if ((_a = item.categories) === null || _a === void 0 ? void 0 : _a.length) {
1279
- return item.categories.some((c) => couponCategories.some((cat) => cat == c));
1280
- }
1281
- return true;
1282
- });
1283
- }
1284
- else {
1285
- lineItensDiscount = checkout.lineItems.filter((item) => !item.isGift);
1286
- }
1287
- return lineItensDiscount;
1288
- });
1289
- }
1290
- calcCheckoutSubtotal(lineItens, user) {
1291
- return ((lineItens === null || lineItens === void 0 ? void 0 : lineItens.filter((item) => !item.isGift).reduce((acc, curr) => {
1292
- var _a;
1293
- return (user === null || user === void 0 ? void 0 : user.isSubscriber) && curr.price.subscriberPrice
1294
- ? acc + ((_a = curr.price) === null || _a === void 0 ? void 0 : _a.subscriberPrice) * curr.quantity
1295
- : acc + curr.pricePaid * curr.quantity;
1296
- }, 0)) || 0);
1297
- }
1298
- getOrdersWithCoupon(coupon) {
1299
- return __awaiter(this, void 0, void 0, function* () {
1300
- return yield this.orderRepository
1301
- .find({
1302
- filters: {
1303
- coupon: { id: coupon.id },
1304
- status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1305
- },
1306
- })
1307
- .then((result) => result.data);
1308
- });
1309
- }
1310
- getOrdersFromUser(email) {
1311
- return __awaiter(this, void 0, void 0, function* () {
1312
- return yield this.orderRepository
1313
- .find({
1314
- filters: {
1315
- user: { email: { operator: Where.EQUALS, value: email } },
1316
- status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1317
- },
1318
- })
1319
- .then((result) => result.data);
1320
- });
1321
- }
1322
- countOrdersWithUser(orders, email) {
1323
- return orders.filter((o) => o.user.email == email).length;
1324
- }
1325
- getCouponUseLimits(coupon, checkoutType, user) {
1326
- let couponUseLimits;
1327
- if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
1328
- if (coupon.exclusivityType.length === 1 &&
1329
- (coupon.exclusivityType.at(0) === Exclusivities.SPECIFIC_USER ||
1330
- coupon.exclusivityType.at(0) === Exclusivities.COLLABORATORS))
1331
- couponUseLimits = coupon.useLimits.non_subscriber;
1332
- else
1333
- couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
1334
- }
1335
- else {
1336
- couponUseLimits = coupon.useLimits.subscription;
1337
- }
1338
- return couponUseLimits;
1339
- }
1340
- calcLineItenDiscount(type, lineItems, couponDiscount, subTotal) {
1341
- let lineItemsDiscount = [];
1342
- if (type === CouponTypes.ABSOLUTE) {
1343
- const couponDiscountMax = couponDiscount > subTotal ? subTotal : couponDiscount;
1344
- lineItemsDiscount = lineItems.map((item) => {
1345
- if (item.isGift)
1346
- return item;
1347
- const totalItemPercentage = item.pricePaid / subTotal;
1348
- const discountItem = couponDiscountMax * totalItemPercentage;
1349
- return Object.assign(Object.assign({}, item), { discount: Number(discountItem.toFixed(2)) });
1350
- });
1351
- }
1352
- else {
1353
- lineItemsDiscount = lineItems.map((item) => {
1354
- if (item.isGift)
1355
- return item;
1356
- const discountItem = item.pricePaid * (couponDiscount / 100);
1357
- return Object.assign(Object.assign({}, item), { discount: Number(discountItem.toFixed(2)) });
1358
- });
1359
- }
1360
- return lineItemsDiscount;
1361
- }
1362
- }
1363
- 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 });
1364
- CouponService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, providedIn: 'root' });
1365
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, decorators: [{
1366
- type: Injectable,
1367
- args: [{
1368
- providedIn: 'root',
1369
- }]
1370
- }], ctorParameters: function () {
1371
- return [{ type: undefined, decorators: [{
1372
- type: Inject,
1373
- args: ['CouponRepository']
1374
- }] }, { type: i1$2.Shops, decorators: [{
1375
- type: Inject,
1376
- args: [DEFAULT_SHOP]
1377
- }] }, { type: undefined, decorators: [{
1378
- type: Inject,
1379
- args: ['OrderRepository']
1380
- }] }, { type: undefined, decorators: [{
1381
- type: Inject,
1382
- args: ['CategoryRepository']
1383
- }] }];
1384
- } });
1385
-
1386
1087
  class CheckoutService {
1387
- constructor(couponService, checkoutRepository, userRepository, defaultShop, dataPersistence) {
1388
- this.couponService = couponService;
1088
+ constructor(checkoutRepository, userRepository, defaultShop, dataPersistence, firebaseOptions, http) {
1389
1089
  this.checkoutRepository = checkoutRepository;
1390
1090
  this.userRepository = userRepository;
1391
1091
  this.defaultShop = defaultShop;
1392
1092
  this.dataPersistence = dataPersistence;
1093
+ this.firebaseOptions = firebaseOptions;
1094
+ this.http = http;
1095
+ this.checkoutUrl = null;
1096
+ this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`;
1097
+ // this.checkoutUrl = `http://docker.for.localhost:5001/b4astage-cb80a/southamerica-east1`
1393
1098
  }
1394
1099
  getCheckout(checkoutData) {
1395
1100
  return this.dataPersistence
@@ -1408,11 +1113,41 @@ class CheckoutService {
1408
1113
  clearCheckoutFromSession() {
1409
1114
  return this.dataPersistence.remove('checkoutId');
1410
1115
  }
1411
- calcDiscount(coupon) {
1412
- return this.getCheckout().pipe(concatMap((checkout) => __awaiter(this, void 0, void 0, function* () { return yield this.couponService.calcDiscountShopping(coupon, checkout); })));
1413
- }
1414
1116
  checkCoupon(nickname, checkoutType) {
1415
- return this.getCheckout().pipe(concatMap((checkout) => this.couponService.checkCoupon(nickname, CheckoutTypes.ECOMMERCE, checkout, null).pipe()));
1117
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutApplyDiscount`, {
1118
+ checkoutId: checkout.id,
1119
+ coupon: nickname,
1120
+ checkoutType,
1121
+ })), concatMap(() => this.getCheckout()), map((checkout) => checkout.coupon));
1122
+ }
1123
+ validateStockProducts() {
1124
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutValidateProductStock`, {
1125
+ checkoutId: checkout.id,
1126
+ })));
1127
+ }
1128
+ getAvailableShippingForProduct(productShipping) {
1129
+ return this.http.post(`${this.checkoutUrl}/checkoutGetAvailableShipping`, {
1130
+ checkoutId: null,
1131
+ productShipping,
1132
+ });
1133
+ }
1134
+ getAvailableShippingForCheckout() {
1135
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutGetAvailableShipping`, {
1136
+ checkoutId: checkout.id,
1137
+ productShipping: null,
1138
+ })));
1139
+ }
1140
+ selectShipping(option) {
1141
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutSelectShipping`, {
1142
+ checkoutId: checkout.id,
1143
+ shippingOption: option,
1144
+ })), concatMap(() => this.getCheckout()));
1145
+ }
1146
+ createOrder(checkoutPayload, paymentProvider, applicationVersion) {
1147
+ return this.http.post(`${this.checkoutUrl}/checkout`, {
1148
+ data: Object.assign(Object.assign({}, checkoutPayload), { applicationVersion,
1149
+ paymentProvider }),
1150
+ });
1416
1151
  }
1417
1152
  createCheckout(checkoutData) {
1418
1153
  return __awaiter(this, void 0, void 0, function* () {
@@ -1422,124 +1157,81 @@ class CheckoutService {
1422
1157
  });
1423
1158
  }
1424
1159
  }
1425
- 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 });
1160
+ CheckoutService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService, deps: [{ token: 'CheckoutRepository' }, { token: 'UserRepository' }, { token: DEFAULT_SHOP }, { token: PERSISTENCE_PROVIDER }, { token: FIREBASE_OPTIONS }, { token: i1$2.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
1426
1161
  CheckoutService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService });
1427
1162
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService, decorators: [{
1428
1163
  type: Injectable
1429
1164
  }], ctorParameters: function () {
1430
- return [{ type: CouponService }, { type: undefined, decorators: [{
1165
+ return [{ type: undefined, decorators: [{
1431
1166
  type: Inject,
1432
1167
  args: ['CheckoutRepository']
1433
1168
  }] }, { type: undefined, decorators: [{
1434
1169
  type: Inject,
1435
1170
  args: ['UserRepository']
1436
- }] }, { type: i1$2.Shops, decorators: [{
1171
+ }] }, { type: i1$3.Shops, decorators: [{
1437
1172
  type: Inject,
1438
1173
  args: [DEFAULT_SHOP]
1439
1174
  }] }, { type: undefined, decorators: [{
1440
1175
  type: Inject,
1441
1176
  args: [PERSISTENCE_PROVIDER]
1442
- }] }];
1177
+ }] }, { type: undefined, decorators: [{
1178
+ type: Inject,
1179
+ args: [FIREBASE_OPTIONS]
1180
+ }] }, { type: i1$2.HttpClient }];
1443
1181
  } });
1444
1182
 
1445
1183
  class CartService {
1446
- constructor(authService, checkoutService, defaultShop, firebaseOptions, productRepository, categoryRepository, variantRepository, buy2WinRepository, http) {
1184
+ constructor(authService, checkoutService, defaultShop, firebaseOptions,
1185
+ // @Inject('ProductRepository') private readonly productRepository: ProductRepository,
1186
+ // @Inject('CategoryRepository') private readonly categoryRepository: CategoryRepository,
1187
+ // @Inject('VariantRepository') private readonly variantRepository: VariantRepository,
1188
+ // @Inject('Buy2WinRepository') private readonly buy2WinRepository: Buy2WinFirestoreRepository,
1189
+ http) {
1447
1190
  this.authService = authService;
1448
1191
  this.checkoutService = checkoutService;
1449
1192
  this.defaultShop = defaultShop;
1450
1193
  this.firebaseOptions = firebaseOptions;
1451
- this.productRepository = productRepository;
1452
- this.categoryRepository = categoryRepository;
1453
- this.variantRepository = variantRepository;
1454
- this.buy2WinRepository = buy2WinRepository;
1455
1194
  this.http = http;
1456
1195
  this.cartSubject = new Subject();
1457
1196
  this.checkoutUrl = null;
1458
- this.updateLineItemInCart = (lineItem, quantity, checkout) => (isNil(checkout) ? this.checkoutService.getCheckout() : of(checkout)).pipe(concatMap((checkoutLoaded) => {
1459
- var _a, _b, _c;
1460
- const items = [];
1461
- const index = (_a = checkoutLoaded.lineItems) === null || _a === void 0 ? void 0 : _a.map((checkoutItem) => checkoutItem.id).indexOf(lineItem.id);
1462
- const isGift = (_c = (_b = checkoutLoaded.lineItems) === null || _b === void 0 ? void 0 : _b[index]) === null || _c === void 0 ? void 0 : _c.isGift;
1463
- if (index > -1) {
1464
- checkoutLoaded.lineItems[index].quantity += quantity;
1465
- checkoutLoaded.lineItems[index].pricePaid = isGift ? 0 : lineItem.pricePaid;
1466
- checkoutLoaded.lineItems[index].price = lineItem.price;
1467
- }
1468
- else
1469
- checkoutLoaded.lineItems = items.concat(checkoutLoaded.lineItems ? checkoutLoaded.lineItems.concat([lineItem]) : [lineItem]);
1470
- return this.checkoutService
1471
- .updateCheckoutLineItems(checkoutLoaded)
1472
- .pipe(map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)));
1473
- }));
1197
+ // private updateLineItemInCart = (lineItem: LineItem, quantity: number, checkout?: Checkout): Observable<Cart> =>
1198
+ // (isNil(checkout) ? this.checkoutService.getCheckout() : of(checkout)).pipe(
1199
+ // concatMap((checkoutLoaded) => {
1200
+ // const items: LineItem[] = []
1201
+ // const index = checkoutLoaded.lineItems?.map((checkoutItem) => checkoutItem.id).indexOf(lineItem.id)
1202
+ // const isGift = checkoutLoaded.lineItems?.[index]?.isGift
1203
+ // if (index > -1) {
1204
+ // checkoutLoaded.lineItems[index].quantity += quantity
1205
+ // checkoutLoaded.lineItems[index].pricePaid = isGift ? 0 : lineItem.pricePaid
1206
+ // checkoutLoaded.lineItems[index].price = lineItem.price
1207
+ // } else
1208
+ // checkoutLoaded.lineItems = items.concat(
1209
+ // checkoutLoaded.lineItems ? checkoutLoaded.lineItems.concat([lineItem]) : [lineItem],
1210
+ // )
1211
+ // return this.checkoutService
1212
+ // .updateCheckoutLineItems(checkoutLoaded)
1213
+ // .pipe(map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)))
1214
+ // }),
1215
+ // )
1474
1216
  this.generateCartObject = (items) => (items === null || items === void 0 ? void 0 : items.reduce((cart, item) => {
1475
1217
  var _a;
1476
1218
  return (Object.assign(Object.assign({}, cart), { [item.id]: LineItem.toInstance(Object.assign(Object.assign({}, (cart[item.id] || item)), { quantity: (((_a = cart[item.id]) === null || _a === void 0 ? void 0 : _a.quantity) || 0) + (item.quantity ? item.quantity : 1) })) }));
1477
1219
  }, {})) || {};
1478
- this.buildLineItem = ({ checkout, item, quantity, }) => __awaiter(this, void 0, void 0, function* () {
1479
- var _a, _b, _c, _d, _e, _f, _g, _h;
1480
- const product = yield this.getProductData(item.id);
1481
- item.quantity = (item === null || item === void 0 ? void 0 : item.quantity) || ((_b = (_a = checkout === null || checkout === void 0 ? void 0 : checkout.lineItems) === null || _a === void 0 ? void 0 : _a.find((lineItem) => lineItem.id === item.id)) === null || _b === void 0 ? void 0 : _b.quantity) || 0;
1482
- if (this.checkMaxStock(product.stock.quantity, item.quantity || 0, quantity || 0))
1483
- throw new Error('Desculpe! Temos apenas ' + ((_c = product.stock) === null || _c === void 0 ? void 0 : _c.quantity) + ' em estoque.');
1484
- const image = item.image || ((_d = item.images) === null || _d === void 0 ? void 0 : _d.shift());
1485
- const { id, name, EAN, slug, weight, sku, type } = item;
1486
- const isGift = (item === null || item === void 0 ? void 0 : item.isGift) || null;
1487
- const pricePaid = isGift
1488
- ? 0
1489
- : this.getProductPrice({
1490
- product: LineItem.toInstance(product),
1491
- shop: checkout.shop || this.defaultShop,
1492
- isSubscriber: (_e = checkout.user) === null || _e === void 0 ? void 0 : _e.isSubscriber,
1493
- });
1494
- RoundProductPricesHelper.roundProductPrices(item);
1495
- RoundProductPricesHelper.roundProductPrices(product);
1496
- return {
1497
- checkout,
1498
- lineItem: LineItem.toInstance({
1499
- id,
1500
- name: name !== null && name !== void 0 ? name : product.name,
1501
- EAN: EAN !== null && EAN !== void 0 ? EAN : product.EAN,
1502
- brand: product.brand,
1503
- slug: slug !== null && slug !== void 0 ? slug : product.slug,
1504
- sku: sku !== null && sku !== void 0 ? sku : product.sku,
1505
- stock: product.stock,
1506
- price: this.roundPrice(product.price),
1507
- image,
1508
- weight: weight !== null && weight !== void 0 ? weight : product.weight,
1509
- quantity: (item.quantity || 0) + (quantity || 0),
1510
- pricePaid,
1511
- discount: 0,
1512
- categories: product.categories || ((_f = product.category) === null || _f === void 0 ? void 0 : _f.id) ? [(_g = product.category) === null || _g === void 0 ? void 0 : _g.id, ...product.categories] : [],
1513
- category: product.category,
1514
- isGift: isGift !== null && isGift !== void 0 ? isGift : null,
1515
- costPrice: isGift ? 0 : (_h = product.costPrice) !== null && _h !== void 0 ? _h : 0,
1516
- type,
1517
- label: product.label,
1518
- }),
1519
- };
1520
- });
1521
- this.getProductPrice = ({ product, isSubscriber, }) => {
1522
- const info = product.price;
1523
- if (product.isGift)
1524
- return 0;
1525
- return isSubscriber && info.subscriberPrice > 0
1526
- ? Number(info.subscriberPrice.toFixed(2))
1527
- : Number(info.price.toFixed(2));
1528
- };
1529
- this.checkMaxStock = (currentStock, currentItemQtd, quantityToAdd) => {
1530
- const maxStock = currentStock || 0;
1531
- const currentItemAmount = currentItemQtd || 0;
1532
- return currentItemAmount + quantityToAdd > maxStock;
1533
- };
1534
- // this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`
1535
- this.checkoutUrl = `http://docker.for.localhost:5001/b4astage-cb80a/southamerica-east1`;
1220
+ this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`;
1221
+ // this.checkoutUrl = `http://docker.for.localhost:5001/b4astage-cb80a/southamerica-east1`
1536
1222
  }
1537
1223
  addItem(item, quantity = 1) {
1538
- return this.checkoutService.getCheckout().pipe(tap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutAddItemToCart`, {
1539
- checkoutId: checkout.id,
1540
- productId: item.id,
1541
- quantity,
1542
- })), tap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1224
+ return this.checkoutService.getCheckout().pipe(concatMap((checkout) => {
1225
+ console.log('getCheckout', checkout);
1226
+ return this.http.post(`${this.checkoutUrl}/checkoutAddItemToCart`, {
1227
+ checkoutId: checkout.id,
1228
+ productId: item.id,
1229
+ quantity,
1230
+ });
1231
+ }), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => {
1232
+ console.log('updatedCheckout', updatedCheckout);
1233
+ return this.generateCartObject(updatedCheckout.lineItems);
1234
+ }), tap((cart) => this.cartSubject.next(cart)));
1543
1235
  // return this.generateCartObject(checkoutUpdated.lineItems as LineItem[])
1544
1236
  // return from(this.checkoutService.getCheckout()).pipe(
1545
1237
  // concatMap(async (checkout) => await this.buildLineItem({ checkout, item, quantity: quantity || 1 })),
@@ -1548,11 +1240,14 @@ class CartService {
1548
1240
  // )
1549
1241
  }
1550
1242
  decreaseItem(item) {
1551
- return this.checkoutService.getCheckout().pipe(tap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutDecreaseProductFromCart`, {
1243
+ return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutDecreaseProductFromCart`, {
1552
1244
  checkoutId: checkout.id,
1553
1245
  productId: item.id,
1554
1246
  quantity: 1,
1555
- })), tap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1247
+ })), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => {
1248
+ console.log('updatedCheckout', updatedCheckout);
1249
+ return this.generateCartObject(updatedCheckout.lineItems);
1250
+ }), tap((cart) => this.cartSubject.next(cart)));
1556
1251
  // return this.checkoutService.getCheckout().pipe(
1557
1252
  // map((checkout) => {
1558
1253
  // const checkoutItem = checkout.lineItems?.find((lineItem) => lineItem.id === item.id)
@@ -1565,10 +1260,13 @@ class CartService {
1565
1260
  // )
1566
1261
  }
1567
1262
  removeItem(item) {
1568
- return this.checkoutService.getCheckout().pipe(tap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutRemoveProductFromCart`, {
1263
+ return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutRemoveProductFromCart`, {
1569
1264
  checkoutId: checkout.id,
1570
1265
  productId: item.id,
1571
- })), tap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1266
+ })), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => {
1267
+ console.log('updatedCheckout', updatedCheckout);
1268
+ return this.generateCartObject(updatedCheckout.lineItems);
1269
+ }), tap((cart) => this.cartSubject.next(cart)));
1572
1270
  // return this.checkoutService.getCheckout().pipe(
1573
1271
  // map((checkout) => {
1574
1272
  // const index = checkout.lineItems.findIndex((lineItem) => lineItem.id === item.id)
@@ -1580,9 +1278,18 @@ class CartService {
1580
1278
  // tap((cart) => this.cartSubject.next(cart)),
1581
1279
  }
1582
1280
  updateUserCart(user) {
1583
- return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.checkoutService.updateCheckoutUser(Checkout.toInstance(Object.assign(Object.assign({}, checkout.toPlain()), { user })))), tap(() => (this.user = user)), tap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutUpdateUserCart`, {
1584
- checkoutId: checkout.id,
1585
- })), tap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1281
+ return this.checkoutService.getCheckout().pipe(concatMap((checkout) => {
1282
+ console.log('getCheckout', checkout);
1283
+ return this.checkoutService.updateCheckoutUser(Checkout.toInstance(Object.assign(Object.assign({}, checkout.toPlain()), { user })));
1284
+ }), concatMap((checkout) => {
1285
+ console.log('getCheckout User', checkout);
1286
+ return this.http.post(`${this.checkoutUrl}/checkoutUpdateUserCart`, {
1287
+ checkoutId: checkout.id,
1288
+ });
1289
+ }), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => {
1290
+ console.log('updatedCheckout', updatedCheckout);
1291
+ return this.generateCartObject(updatedCheckout.lineItems);
1292
+ }), tap((cart) => this.cartSubject.next(cart)));
1586
1293
  // return this.checkoutService.getCheckout().pipe(
1587
1294
  // concatMap((checkout) =>
1588
1295
  // this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user })),
@@ -1611,166 +1318,43 @@ class CartService {
1611
1318
  this.buildCartFromCheckout(checkout).subscribe((cart) => this.cartSubject.next(cart));
1612
1319
  return this.cartSubject;
1613
1320
  }
1614
- /**
1615
- * @deprecated The method should not be used
1616
- */
1617
- getVariantPriceDiscount(item) {
1618
- 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)));
1619
- }
1321
+ // /**
1322
+ // * @deprecated The method should not be used
1323
+ // */
1324
+ // getVariantPriceDiscount(item: LineItem): Observable<number> {
1325
+ // return this.authService.getUser().pipe(
1326
+ // concatMap((user) =>
1327
+ // iif(
1328
+ // () => user.isSubscriber && !!item.price.subscriberPrice,
1329
+ // of(item.price.subscriberPrice),
1330
+ // of(item.price.price),
1331
+ // ),
1332
+ // ),
1333
+ // catchError(() => of(item.price.price)),
1334
+ // )
1335
+ // }
1620
1336
  clearCart() {
1621
1337
  return this.checkoutService.getCheckout().pipe(map((checkout) => {
1622
1338
  this.checkoutService.clearCheckoutFromSession();
1623
1339
  return checkout;
1624
1340
  }), concatMap((oldCheckout) => this.buildCartFromCheckout(oldCheckout)), tap((cart) => this.cartSubject.next(cart)));
1625
1341
  }
1626
- buildCartFromCheckout(checkoutData) {
1627
- return this.checkoutService.getCheckout(checkoutData).pipe(map((checkout) => checkout.lineItems), concatMap((lineItems) => of(this.generateCartObject(lineItems))));
1628
- }
1629
- roundPrice(productPrice) {
1630
- const { price, fullPrice, subscriberPrice } = productPrice;
1631
- return Object.assign(Object.assign(Object.assign({}, productPrice), { price: Number(price.toFixed(2)), fullPrice: Number(fullPrice.toFixed(2)) }), (subscriberPrice && { subscriberPrice: Number(subscriberPrice.toFixed(2)) }));
1632
- }
1633
- getProductData(productId) {
1634
- return __awaiter(this, void 0, void 0, function* () {
1635
- let product;
1636
- let variant;
1637
- try {
1638
- product = yield this.productRepository.get({ id: productId });
1639
- }
1640
- catch (error) {
1641
- if (!(error instanceof NotFoundError))
1642
- throw error;
1643
- const { data: variants } = yield this.variantRepository.find({ filters: { id: productId } });
1644
- variant = variants.shift();
1645
- if (!variant)
1646
- throw error;
1647
- product = yield this.productRepository.get({ id: variant.productId });
1648
- }
1649
- return Object.assign(Object.assign({}, product.toPlain()), (variant && Object.assign({}, variant.toPlain())));
1650
- });
1651
- }
1652
- getGifts() {
1653
- return this.checkoutService.getCheckout().pipe(mergeMap((checkout) => __awaiter(this, void 0, void 0, function* () {
1654
- const notGiftItems = checkout.lineItems ? checkout.lineItems.filter((item) => !item.isGift) : [];
1655
- if (!notGiftItems.length)
1656
- return Object.assign(Object.assign({}, checkout), { lineItems: [] });
1657
- const campaigns = yield this.buy2WinRepository
1658
- .find({
1659
- filters: {
1660
- active: { operator: Where.EQUALS, value: true },
1661
- },
1662
- })
1663
- .then((data) => data.data.filter((campaign) => campaign.shop === Shops.ALL || campaign.shop === this.defaultShop));
1664
- if (!campaigns.length)
1665
- return Object.assign(Object.assign({}, checkout), { lineItems: notGiftItems });
1666
- const elegibleCampaigns = [];
1667
- for (const campaign of campaigns) {
1668
- const today = new Date().getTime();
1669
- if (!(campaign.startDate.getTime() <= today) && !(campaign.endDate.getTime() >= today))
1670
- continue;
1671
- if (campaign.activeCategory) {
1672
- const categoriesCampaing = campaign.categories.map((c) => c.id.toString());
1673
- const categoriesCampaingFullTree = [];
1674
- for (const id of categoriesCampaing) {
1675
- const children = yield this.categoryRepository.getChildren(parseInt(id));
1676
- categoriesCampaingFullTree.push(id, ...children.map((c) => c.id.toString()));
1677
- }
1678
- const categoriesCampaingTree = [...new Set(categoriesCampaingFullTree)];
1679
- const filterProductsCategories = notGiftItems.filter((l) => {
1680
- var _a;
1681
- if (!l.categories || !((_a = l.categories) === null || _a === void 0 ? void 0 : _a.length))
1682
- return true;
1683
- return l.categories.some((c) => categoriesCampaingTree.some((cat) => cat == c));
1684
- });
1685
- if (filterProductsCategories.length) {
1686
- const cartValuelWithCategories = filterProductsCategories.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1687
- const cartItensQuantityWithCategories = filterProductsCategories.reduce((a, b) => a + b.quantity, 0);
1688
- const hasMinValue = campaign.cartValueMin && cartValuelWithCategories >= campaign.cartValueMin;
1689
- const hasMinQuantity = campaign.cartItensQuantityMin && cartItensQuantityWithCategories >= campaign.cartItensQuantityMin;
1690
- if (hasMinQuantity || hasMinValue)
1691
- elegibleCampaigns.push(campaign);
1692
- }
1693
- }
1694
- else {
1695
- const cartTotal = notGiftItems.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1696
- const cartItensQuantity = notGiftItems.reduce((a, b) => a + b.quantity, 0);
1697
- const hasMinValue = campaign.cartValue && campaign.cartValue > 0 && campaign.cartValue <= cartTotal;
1698
- const hasMinQuantity = campaign.cartItensQuantityMin && cartItensQuantity >= campaign.cartItensQuantityMin;
1699
- if (hasMinQuantity || hasMinValue)
1700
- elegibleCampaigns.push(campaign);
1701
- }
1702
- }
1703
- if (!elegibleCampaigns.length)
1704
- return Object.assign(Object.assign({}, checkout), { lineItems: notGiftItems });
1705
- const campaingnProducts = [];
1706
- for (const campaign of elegibleCampaigns) {
1707
- let elegibleProducts = [];
1708
- for (const product of campaign.products) {
1709
- const { data: productData } = yield this.productRepository.find({ filters: { sku: product } });
1710
- if (!productData.length)
1711
- continue;
1712
- const gift = productData.shift();
1713
- if (gift.stock.quantity < 1)
1714
- continue;
1715
- elegibleProducts.push(gift);
1716
- }
1717
- campaingnProducts.push(elegibleProducts);
1718
- }
1719
- if (!campaingnProducts.length)
1720
- return Object.assign(Object.assign({}, checkout), { lineItems: notGiftItems });
1721
- const gifts = this.giftToLineItems([].concat(...campaingnProducts));
1722
- return Object.assign(Object.assign({}, checkout), { lineItems: notGiftItems.concat(gifts) });
1723
- })), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1724
- }
1725
- giftToLineItems(items) {
1726
- return items.map((item) => {
1727
- var _a;
1728
- const { brand, categories, category, id, name, price, sku, slug, stock, weight, EAN } = item;
1729
- const image = ((_a = item === null || item === void 0 ? void 0 : item.miniatures) === null || _a === void 0 ? void 0 : _a.length) ? item.miniatures[0] : item.images[0];
1730
- return LineItem.toInstance({
1731
- brand,
1732
- categories,
1733
- category,
1734
- id: id.toString(),
1735
- name,
1736
- price,
1737
- sku,
1738
- slug,
1739
- stock,
1740
- weight,
1741
- EAN,
1742
- image,
1743
- pricePaid: 0,
1744
- quantity: 1,
1745
- isGift: true,
1746
- });
1747
- });
1748
- }
1342
+ buildCartFromCheckout(checkoutData) {
1343
+ return this.checkoutService.getCheckout(checkoutData).pipe(map((checkout) => checkout.lineItems), concatMap((lineItems) => of(this.generateCartObject(lineItems))));
1344
+ }
1749
1345
  }
1750
- 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: FIREBASE_OPTIONS }, { token: 'ProductRepository' }, { token: 'CategoryRepository' }, { token: 'VariantRepository' }, { token: 'Buy2WinRepository' }, { token: i3.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
1346
+ 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: FIREBASE_OPTIONS }, { token: i1$2.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
1751
1347
  CartService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService });
1752
1348
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService, decorators: [{
1753
1349
  type: Injectable
1754
1350
  }], ctorParameters: function () {
1755
- return [{ type: AuthService }, { type: CheckoutService }, { type: i1$2.Shops, decorators: [{
1351
+ return [{ type: AuthService }, { type: CheckoutService }, { type: i1$3.Shops, decorators: [{
1756
1352
  type: Inject,
1757
1353
  args: [DEFAULT_SHOP]
1758
1354
  }] }, { type: undefined, decorators: [{
1759
1355
  type: Inject,
1760
1356
  args: [FIREBASE_OPTIONS]
1761
- }] }, { type: undefined, decorators: [{
1762
- type: Inject,
1763
- args: ['ProductRepository']
1764
- }] }, { type: undefined, decorators: [{
1765
- type: Inject,
1766
- args: ['CategoryRepository']
1767
- }] }, { type: undefined, decorators: [{
1768
- type: Inject,
1769
- args: ['VariantRepository']
1770
- }] }, { type: i1$2.Buy2WinFirestoreRepository, decorators: [{
1771
- type: Inject,
1772
- args: ['Buy2WinRepository']
1773
- }] }, { type: i3.HttpClient }];
1357
+ }] }, { type: i1$2.HttpClient }];
1774
1358
  } });
1775
1359
 
1776
1360
  class NewCategoryStructureAdapter {
@@ -2111,7 +1695,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2111
1695
  }] }, { type: undefined, decorators: [{
2112
1696
  type: Inject,
2113
1697
  args: [CATEGORY_STRUCTURE]
2114
- }] }, { type: i1$2.Shops, decorators: [{
1698
+ }] }, { type: i1$3.Shops, decorators: [{
2115
1699
  type: Inject,
2116
1700
  args: [DEFAULT_SHOP]
2117
1701
  }] }, { type: undefined, decorators: [{
@@ -2166,7 +1750,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2166
1750
  }] }, { type: undefined, decorators: [{
2167
1751
  type: Inject,
2168
1752
  args: [CATEGORY_STRUCTURE]
2169
- }] }, { type: i1$2.Shops, decorators: [{
1753
+ }] }, { type: i1$3.Shops, decorators: [{
2170
1754
  type: Inject,
2171
1755
  args: [DEFAULT_SHOP]
2172
1756
  }] }];
@@ -2278,160 +1862,449 @@ class WishlistService {
2278
1862
  return this.wishlistRepository.update(data);
2279
1863
  });
2280
1864
  }
2281
- delete(wishlistId) {
1865
+ delete(wishlistId) {
1866
+ return __awaiter(this, void 0, void 0, function* () {
1867
+ const wishlist = yield this.findById(wishlistId);
1868
+ yield this.createWishlistLog(WishlistLogType.DELETE, wishlist);
1869
+ return this.wishlistRepository.delete({ id: wishlistId });
1870
+ });
1871
+ }
1872
+ getWishlistBySlug(slug) {
1873
+ const [id] = slug.split('-');
1874
+ if (+id)
1875
+ return this.wishlistRepository.get({ id });
1876
+ return this.wishlistRepository.getWishlistBySlug(slug);
1877
+ }
1878
+ getWishlistsByPerson(personId) {
1879
+ return this.wishlistRepository.getWishlistByPerson(personId);
1880
+ }
1881
+ addProduct(wishlistId, productId) {
1882
+ return __awaiter(this, void 0, void 0, function* () {
1883
+ const wishlist = yield this.wishlistRepository.get({ id: wishlistId });
1884
+ const hasProduct = wishlist.products.some((p) => p == productId);
1885
+ const wishlistData = yield this.findById(wishlistId);
1886
+ const productData = yield this.findProductById(productId);
1887
+ yield this.createWishlistLog(WishlistLogType.ADD_PRODUCT, wishlistData, productData);
1888
+ if (!hasProduct) {
1889
+ wishlist.products = [...wishlist.products, productId];
1890
+ yield this.wishlistRepository.addProduct(wishlistId, productId);
1891
+ }
1892
+ return wishlist;
1893
+ });
1894
+ }
1895
+ removeProduct(wishlistId, productId) {
1896
+ return __awaiter(this, void 0, void 0, function* () {
1897
+ const wishlist = yield this.wishlistRepository.get({ id: wishlistId });
1898
+ const productIndex = wishlist.products.findIndex((p) => p == productId);
1899
+ if (productIndex != -1) {
1900
+ wishlist.products.splice(productIndex, 1);
1901
+ const wishlistData = yield this.findById(wishlistId);
1902
+ const productData = yield this.findProductById(productId);
1903
+ yield this.createWishlistLog(WishlistLogType.REMOVE_PRODUCT, wishlistData, productData);
1904
+ yield this.wishlistRepository.removeProduct(wishlistId, productId);
1905
+ }
1906
+ return wishlist;
1907
+ });
1908
+ }
1909
+ findById(id) {
1910
+ return __awaiter(this, void 0, void 0, function* () {
1911
+ return this.wishlistRepository
1912
+ .find({
1913
+ fields: ['id', 'name', 'description', 'personId', 'personIsSubscriber', 'personType', 'personName'],
1914
+ filters: {
1915
+ id,
1916
+ },
1917
+ })
1918
+ .then((res) => res.data.at(0));
1919
+ });
1920
+ }
1921
+ findProductById(id) {
1922
+ return __awaiter(this, void 0, void 0, function* () {
1923
+ return this.productRepository
1924
+ .find({
1925
+ fields: ['id', 'sku', 'EAN', 'name', 'brand'],
1926
+ filters: {
1927
+ id,
1928
+ },
1929
+ })
1930
+ .then((res) => res.data.at(0));
1931
+ });
1932
+ }
1933
+ createWishlistLog(type, wishlist, product) {
1934
+ return __awaiter(this, void 0, void 0, function* () {
1935
+ switch (type) {
1936
+ case WishlistLogType.CREATE:
1937
+ case WishlistLogType.UPDATE:
1938
+ case WishlistLogType.DELETE:
1939
+ yield this.logRepository.create({
1940
+ collection: 'wishlist',
1941
+ date: new Date(),
1942
+ operation: WishlistLogType.CREATE ? 'CREATE' : WishlistLogType.UPDATE ? 'UPDATE' : 'DELETE',
1943
+ documentId: wishlist.id,
1944
+ document: {
1945
+ id: wishlist.id,
1946
+ shop: this.shop,
1947
+ name: wishlist.name,
1948
+ description: wishlist.description,
1949
+ published: wishlist.published,
1950
+ type: type,
1951
+ personType: wishlist.personType,
1952
+ personId: wishlist.personId,
1953
+ personName: wishlist.personName,
1954
+ personIsSubscriber: wishlist.personIsSubscriber,
1955
+ },
1956
+ });
1957
+ break;
1958
+ case WishlistLogType.ADD_PRODUCT:
1959
+ case WishlistLogType.REMOVE_PRODUCT:
1960
+ yield this.logRepository.create({
1961
+ collection: 'wishlist',
1962
+ date: new Date(),
1963
+ operation: 'UPDATE',
1964
+ documentId: wishlist.id,
1965
+ document: {
1966
+ id: wishlist.id,
1967
+ shop: this.shop,
1968
+ name: wishlist.name,
1969
+ description: wishlist.description,
1970
+ published: wishlist.published,
1971
+ type: type,
1972
+ personType: wishlist.personType,
1973
+ personId: wishlist.personId,
1974
+ personName: wishlist.personName,
1975
+ personIsSubscriber: wishlist.personIsSubscriber,
1976
+ productId: product.id,
1977
+ productEAN: product.EAN,
1978
+ productSKU: product.sku,
1979
+ productName: product.name,
1980
+ productBrand: product.brand,
1981
+ },
1982
+ });
1983
+ break;
1984
+ default:
1985
+ break;
1986
+ }
1987
+ });
1988
+ }
1989
+ }
1990
+ 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: 'ProductSearch' }, { token: 'LogRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
1991
+ WishlistService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService });
1992
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService, decorators: [{
1993
+ type: Injectable
1994
+ }], ctorParameters: function () {
1995
+ return [{ type: undefined, decorators: [{
1996
+ type: Inject,
1997
+ args: ['WishlistRepository']
1998
+ }] }, { type: i1$3.Shops, decorators: [{
1999
+ type: Inject,
2000
+ args: [DEFAULT_SHOP]
2001
+ }] }, { type: undefined, decorators: [{
2002
+ type: Inject,
2003
+ args: ['ProductRepository']
2004
+ }] }, { type: undefined, decorators: [{
2005
+ type: Inject,
2006
+ args: ['CategoryFilterRepository']
2007
+ }] }, { type: undefined, decorators: [{
2008
+ type: Inject,
2009
+ args: ['CategoryRepository']
2010
+ }] }, { type: undefined, decorators: [{
2011
+ type: Inject,
2012
+ args: ['ProductStockNotificationRepository']
2013
+ }] }, { type: undefined, decorators: [{
2014
+ type: Inject,
2015
+ args: ['ProductSearch']
2016
+ }] }, { type: undefined, decorators: [{
2017
+ type: Inject,
2018
+ args: ['LogRepository']
2019
+ }] }];
2020
+ } });
2021
+
2022
+ class CouponService {
2023
+ constructor(couponRepository, defaultShop, orderRepository, categoryRepository) {
2024
+ this.couponRepository = couponRepository;
2025
+ this.defaultShop = defaultShop;
2026
+ this.orderRepository = orderRepository;
2027
+ this.categoryRepository = categoryRepository;
2028
+ this.emailIsFromCollaborator = (userEmail) => !!(userEmail === null || userEmail === void 0 ? void 0 : userEmail.match(/@b4a.com.br/g));
2029
+ }
2030
+ checkCoupon(nickname, checkoutType, checkout, plan) {
2031
+ return from(this.couponRepository
2032
+ .find({
2033
+ filters: {
2034
+ nickname: { operator: Where.EQUALS, value: nickname },
2035
+ active: { operator: Where.EQUALS, value: true },
2036
+ },
2037
+ })
2038
+ .then((result) => result.data[0])).pipe(concatMap((coupon) => this.couponValidation(coupon, checkoutType)), concatMap((couponValid) => this.couponRulesValidation(couponValid, checkoutType, checkout, plan)), map((couponValidated) => couponValidated));
2039
+ }
2040
+ couponValidation(coupon, checkoutType) {
2041
+ return __awaiter(this, void 0, void 0, function* () {
2042
+ if (!coupon)
2043
+ throw 'Cupom inválido.';
2044
+ if ((coupon === null || coupon === void 0 ? void 0 : coupon.beginAt) && (coupon === null || coupon === void 0 ? void 0 : coupon.beginAt.getTime()) > new Date().getTime())
2045
+ throw 'Cupom inválido.';
2046
+ if ((coupon === null || coupon === void 0 ? void 0 : coupon.expiresIn) && (coupon === null || coupon === void 0 ? void 0 : coupon.expiresIn.getTime()) < new Date().getTime())
2047
+ throw 'Cupom expirado.';
2048
+ const isInShop = coupon.shopAvailability === Shops.ALL || coupon.shopAvailability === this.defaultShop;
2049
+ if (!isInShop)
2050
+ throw 'Cupom inválido para loja.';
2051
+ const isCheckoutType = coupon.checkoutType === CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
2052
+ if (!isCheckoutType)
2053
+ throw 'Cupom inválido. Erro de checkout.';
2054
+ return coupon;
2055
+ });
2056
+ }
2057
+ couponRulesValidation(coupon, checkoutType, checkout, plan) {
2058
+ var _a;
2059
+ return __awaiter(this, void 0, void 0, function* () {
2060
+ if (checkoutType == CheckoutTypes.SUBSCRIPTION) {
2061
+ if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
2062
+ throw 'Cupom inválido para sua assinatura.';
2063
+ return coupon;
2064
+ }
2065
+ const validUser = this.coupomUserValidation(coupon, checkout === null || checkout === void 0 ? void 0 : checkout.user);
2066
+ if (!validUser)
2067
+ throw 'Usuário não elegível.';
2068
+ const couponUseLimits = this.getCouponUseLimits(coupon, checkoutType, checkout.user);
2069
+ if (couponUseLimits.firstOrder) {
2070
+ const ordersUser = yield this.getOrdersFromUser(checkout.user.email.toLocaleLowerCase());
2071
+ if (couponUseLimits.firstOrder && ordersUser.length >= 1)
2072
+ throw 'Limite de uso atingido';
2073
+ }
2074
+ if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
2075
+ const ordersCoupon = yield this.getOrdersWithCoupon(coupon);
2076
+ if (!couponUseLimits.unlimited && couponUseLimits.total && ordersCoupon.length >= couponUseLimits.total)
2077
+ throw 'Limite de uso atingido.';
2078
+ if (couponUseLimits.limitedPerUser) {
2079
+ const ordersWithUser = this.countOrdersWithUser(ordersCoupon, checkout.user.email);
2080
+ if (ordersWithUser > 0)
2081
+ throw 'Limite de uso por usuário atingido.';
2082
+ }
2083
+ }
2084
+ const hasProductCategories = yield this.hasProductCategories(coupon, checkout);
2085
+ if (!hasProductCategories)
2086
+ throw 'Seu carrinho não possui produtos elegíveis para desconto.';
2087
+ const hasMinSubTotal = yield this.hasMinSubTotal(coupon, checkout);
2088
+ if (!hasMinSubTotal) {
2089
+ if ((_a = coupon.productsCategories) === null || _a === void 0 ? void 0 : _a.length) {
2090
+ throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido na(s) categoria(s) elegíveis para o desconto.`;
2091
+ }
2092
+ throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido.`;
2093
+ }
2094
+ return coupon;
2095
+ });
2096
+ }
2097
+ calcDiscountSubscription(coupon, checkout) {
2098
+ let discount = 0;
2099
+ if (coupon.discount.subscription.type == CouponTypes.ABSOLUTE)
2100
+ discount = coupon.discount.subscription.value;
2101
+ else
2102
+ discount = checkout.subscriptionPlan.recurrencePrice * (coupon.discount.subscription.value / 100);
2103
+ return of(discount);
2104
+ }
2105
+ // public async calcDiscountShopping(
2106
+ // coupon: Coupon,
2107
+ // checkout: Partial<Checkout>,
2108
+ // ): Promise<{ discount: number; lineItems: LineItem[] }> {
2109
+ // let discountInfo: { discount: number; lineItems: LineItem[] } = null
2110
+ // if (checkout.user.isSubscriber && coupon.discount.subscriber.value) {
2111
+ // discountInfo = await this.calcDiscountByType(
2112
+ // coupon.discount.subscriber.type,
2113
+ // coupon.discount.subscriber.value,
2114
+ // coupon.productsCategories,
2115
+ // checkout,
2116
+ // )
2117
+ // } else {
2118
+ // discountInfo = await this.calcDiscountByType(
2119
+ // coupon.discount.non_subscriber.type,
2120
+ // coupon.discount.non_subscriber.value,
2121
+ // coupon.productsCategories,
2122
+ // checkout,
2123
+ // )
2124
+ // }
2125
+ // return { discount: discountInfo.discount, lineItems: discountInfo.lineItems }
2126
+ // }
2127
+ // private async calcDiscountByType(
2128
+ // type: CouponTypes,
2129
+ // value: number,
2130
+ // categories: string[],
2131
+ // checkout: Partial<Checkout>,
2132
+ // ): Promise<{ discount: number; lineItems: LineItem[] }> {
2133
+ // let discount = 0
2134
+ // if (type == CouponTypes.SHIPPING) {
2135
+ // const subTotal = checkout.shipping.ShippingPrice
2136
+ // const discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2)
2137
+ // return { discount, lineItems: checkout.lineItems }
2138
+ // }
2139
+ // const lineItensElegibleForDiscount = await this.getLineItensEligebleForDiscount(categories, checkout)
2140
+ // const subTotal = this.calcCheckoutSubtotal(lineItensElegibleForDiscount, checkout.user)
2141
+ // if (type == CouponTypes.ABSOLUTE) {
2142
+ // discount = value > subTotal ? subTotal : value
2143
+ // } else {
2144
+ // discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2)
2145
+ // }
2146
+ // const lineItems = this.calcLineItenDiscount(type, lineItensElegibleForDiscount, value, subTotal)
2147
+ // return { discount, lineItems }
2148
+ // }
2149
+ hasMinSubTotal(coupon, checkout) {
2150
+ return __awaiter(this, void 0, void 0, function* () {
2151
+ if (!coupon.minSubTotalValue)
2152
+ return true;
2153
+ const lineItensDiscount = yield this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
2154
+ const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user);
2155
+ if (coupon.minSubTotalValue <= subTotal)
2156
+ return true;
2157
+ return false;
2158
+ });
2159
+ }
2160
+ hasProductCategories(coupon, checkout) {
2161
+ var _a, _b;
2282
2162
  return __awaiter(this, void 0, void 0, function* () {
2283
- const wishlist = yield this.findById(wishlistId);
2284
- yield this.createWishlistLog(WishlistLogType.DELETE, wishlist);
2285
- return this.wishlistRepository.delete({ id: wishlistId });
2163
+ if (!coupon.productsCategories || !((_a = coupon.productsCategories) === null || _a === void 0 ? void 0 : _a.length)) {
2164
+ return true;
2165
+ }
2166
+ const couponCategories = yield this.getCouponCategoriesId(coupon.productsCategories);
2167
+ const hasCategories = (_b = checkout.lineItems) === null || _b === void 0 ? void 0 : _b.filter((item) => {
2168
+ var _a;
2169
+ if (item.isGift)
2170
+ return false;
2171
+ if (!item.categories || !((_a = item.categories) === null || _a === void 0 ? void 0 : _a.length))
2172
+ return true;
2173
+ return item.categories.some((c) => couponCategories.some((cat) => cat == c));
2174
+ });
2175
+ return hasCategories.length ? true : false;
2286
2176
  });
2287
2177
  }
2288
- getWishlistBySlug(slug) {
2289
- const [id] = slug.split('-');
2290
- if (+id)
2291
- return this.wishlistRepository.get({ id });
2292
- return this.wishlistRepository.getWishlistBySlug(slug);
2293
- }
2294
- getWishlistsByPerson(personId) {
2295
- return this.wishlistRepository.getWishlistByPerson(personId);
2178
+ coupomUserValidation(coupon, user) {
2179
+ if (!user || coupon.exclusivityType.includes(Exclusivities.ALL_USERS))
2180
+ return true;
2181
+ let userTypes = [];
2182
+ if (coupon.exclusivityType.includes(Exclusivities.COLLABORATORS) &&
2183
+ this.emailIsFromCollaborator(user.email.toLocaleLowerCase()))
2184
+ userTypes.push(Exclusivities.COLLABORATORS);
2185
+ if (coupon.exclusivityType.includes(Exclusivities.SPECIFIC_USER) &&
2186
+ coupon.userExclusiveEmail.includes(user.email.toLocaleLowerCase()))
2187
+ userTypes.push(Exclusivities.SPECIFIC_USER);
2188
+ if (coupon.exclusivityType.includes(Exclusivities.ACTIVE_SUBSCRIBER) &&
2189
+ user.isSubscriber &&
2190
+ user.subscriptionPlan != '')
2191
+ userTypes.push(Exclusivities.ACTIVE_SUBSCRIBER);
2192
+ if (user.isSubscriber &&
2193
+ user.subscriptionPlan == '' &&
2194
+ coupon.exclusivityType.includes(Exclusivities.INACTIVE_SUBSCRIBER))
2195
+ userTypes.push(Exclusivities.INACTIVE_SUBSCRIBER);
2196
+ if (coupon.exclusivityType.includes(Exclusivities.NON_SUBSCRIBER) && !user.isSubscriber)
2197
+ userTypes.push(Exclusivities.NON_SUBSCRIBER);
2198
+ return coupon.exclusivityType.some((r) => userTypes.includes(r));
2296
2199
  }
2297
- addProduct(wishlistId, productId) {
2200
+ getCouponCategoriesId(productsCategories) {
2298
2201
  return __awaiter(this, void 0, void 0, function* () {
2299
- const wishlist = yield this.wishlistRepository.get({ id: wishlistId });
2300
- const hasProduct = wishlist.products.some((p) => p == productId);
2301
- const wishlistData = yield this.findById(wishlistId);
2302
- const productData = yield this.findProductById(productId);
2303
- yield this.createWishlistLog(WishlistLogType.ADD_PRODUCT, wishlistData, productData);
2304
- if (!hasProduct) {
2305
- wishlist.products = [...wishlist.products, productId];
2306
- yield this.wishlistRepository.addProduct(wishlistId, productId);
2202
+ const couponCategories = [];
2203
+ for (let index = 0; index < productsCategories.length; index++) {
2204
+ const category = yield this.categoryRepository.get({
2205
+ id: productsCategories[index],
2206
+ });
2207
+ if (category) {
2208
+ const children = yield this.categoryRepository.getChildren(parseInt(productsCategories[index]));
2209
+ couponCategories.push(category.id, ...children.map((c) => c.id.toString()));
2210
+ }
2307
2211
  }
2308
- return wishlist;
2212
+ return [...new Set(couponCategories)];
2309
2213
  });
2310
2214
  }
2311
- removeProduct(wishlistId, productId) {
2215
+ getLineItensEligebleForDiscount(productsCategories, checkout) {
2216
+ var _a;
2312
2217
  return __awaiter(this, void 0, void 0, function* () {
2313
- const wishlist = yield this.wishlistRepository.get({ id: wishlistId });
2314
- const productIndex = wishlist.products.findIndex((p) => p == productId);
2315
- if (productIndex != -1) {
2316
- wishlist.products.splice(productIndex, 1);
2317
- const wishlistData = yield this.findById(wishlistId);
2318
- const productData = yield this.findProductById(productId);
2319
- yield this.createWishlistLog(WishlistLogType.REMOVE_PRODUCT, wishlistData, productData);
2320
- yield this.wishlistRepository.removeProduct(wishlistId, productId);
2218
+ let lineItensDiscount = [];
2219
+ const couponCategories = yield this.getCouponCategoriesId(productsCategories);
2220
+ if (productsCategories && productsCategories.length) {
2221
+ lineItensDiscount = (_a = checkout.lineItems) === null || _a === void 0 ? void 0 : _a.filter((item) => {
2222
+ var _a;
2223
+ if (item.isGift)
2224
+ return false;
2225
+ if ((_a = item.categories) === null || _a === void 0 ? void 0 : _a.length) {
2226
+ return item.categories.some((c) => couponCategories.some((cat) => cat == c));
2227
+ }
2228
+ return true;
2229
+ });
2321
2230
  }
2322
- return wishlist;
2231
+ else {
2232
+ lineItensDiscount = checkout.lineItems.filter((item) => !item.isGift);
2233
+ }
2234
+ return lineItensDiscount;
2323
2235
  });
2324
2236
  }
2325
- findById(id) {
2237
+ calcCheckoutSubtotal(lineItens, user) {
2238
+ return ((lineItens === null || lineItens === void 0 ? void 0 : lineItens.filter((item) => !item.isGift).reduce((acc, curr) => {
2239
+ var _a;
2240
+ return (user === null || user === void 0 ? void 0 : user.isSubscriber) && curr.price.subscriberPrice
2241
+ ? acc + ((_a = curr.price) === null || _a === void 0 ? void 0 : _a.subscriberPrice) * curr.quantity
2242
+ : acc + curr.pricePaid * curr.quantity;
2243
+ }, 0)) || 0);
2244
+ }
2245
+ getOrdersWithCoupon(coupon) {
2326
2246
  return __awaiter(this, void 0, void 0, function* () {
2327
- return this.wishlistRepository
2247
+ return yield this.orderRepository
2328
2248
  .find({
2329
- fields: ['id', 'name', 'description', 'personId', 'personIsSubscriber', 'personType', 'personName'],
2330
2249
  filters: {
2331
- id,
2250
+ coupon: { id: coupon.id },
2251
+ status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
2332
2252
  },
2333
2253
  })
2334
- .then((res) => res.data.at(0));
2254
+ .then((result) => result.data);
2335
2255
  });
2336
2256
  }
2337
- findProductById(id) {
2257
+ getOrdersFromUser(email) {
2338
2258
  return __awaiter(this, void 0, void 0, function* () {
2339
- return this.productRepository
2259
+ return yield this.orderRepository
2340
2260
  .find({
2341
- fields: ['id', 'sku', 'EAN', 'name', 'brand'],
2342
2261
  filters: {
2343
- id,
2262
+ user: { email: { operator: Where.EQUALS, value: email } },
2263
+ status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
2344
2264
  },
2345
2265
  })
2346
- .then((res) => res.data.at(0));
2266
+ .then((result) => result.data);
2347
2267
  });
2348
2268
  }
2349
- createWishlistLog(type, wishlist, product) {
2350
- return __awaiter(this, void 0, void 0, function* () {
2351
- switch (type) {
2352
- case WishlistLogType.CREATE:
2353
- case WishlistLogType.UPDATE:
2354
- case WishlistLogType.DELETE:
2355
- yield this.logRepository.create({
2356
- collection: 'wishlist',
2357
- date: new Date(),
2358
- operation: WishlistLogType.CREATE ? 'CREATE' : WishlistLogType.UPDATE ? 'UPDATE' : 'DELETE',
2359
- documentId: wishlist.id,
2360
- document: {
2361
- id: wishlist.id,
2362
- shop: this.shop,
2363
- name: wishlist.name,
2364
- description: wishlist.description,
2365
- published: wishlist.published,
2366
- type: type,
2367
- personType: wishlist.personType,
2368
- personId: wishlist.personId,
2369
- personName: wishlist.personName,
2370
- personIsSubscriber: wishlist.personIsSubscriber,
2371
- },
2372
- });
2373
- break;
2374
- case WishlistLogType.ADD_PRODUCT:
2375
- case WishlistLogType.REMOVE_PRODUCT:
2376
- yield this.logRepository.create({
2377
- collection: 'wishlist',
2378
- date: new Date(),
2379
- operation: 'UPDATE',
2380
- documentId: wishlist.id,
2381
- document: {
2382
- id: wishlist.id,
2383
- shop: this.shop,
2384
- name: wishlist.name,
2385
- description: wishlist.description,
2386
- published: wishlist.published,
2387
- type: type,
2388
- personType: wishlist.personType,
2389
- personId: wishlist.personId,
2390
- personName: wishlist.personName,
2391
- personIsSubscriber: wishlist.personIsSubscriber,
2392
- productId: product.id,
2393
- productEAN: product.EAN,
2394
- productSKU: product.sku,
2395
- productName: product.name,
2396
- productBrand: product.brand,
2397
- },
2398
- });
2399
- break;
2400
- default:
2401
- break;
2402
- }
2403
- });
2269
+ countOrdersWithUser(orders, email) {
2270
+ return orders.filter((o) => o.user.email == email).length;
2271
+ }
2272
+ getCouponUseLimits(coupon, checkoutType, user) {
2273
+ let couponUseLimits;
2274
+ if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
2275
+ if (coupon.exclusivityType.length === 1 &&
2276
+ (coupon.exclusivityType.at(0) === Exclusivities.SPECIFIC_USER ||
2277
+ coupon.exclusivityType.at(0) === Exclusivities.COLLABORATORS))
2278
+ couponUseLimits = coupon.useLimits.non_subscriber;
2279
+ else
2280
+ couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
2281
+ }
2282
+ else {
2283
+ couponUseLimits = coupon.useLimits.subscription;
2284
+ }
2285
+ return couponUseLimits;
2404
2286
  }
2405
2287
  }
2406
- 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: 'ProductSearch' }, { token: 'LogRepository' }], target: i0.ɵɵFactoryTarget.Injectable });
2407
- WishlistService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService });
2408
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: WishlistService, decorators: [{
2409
- type: Injectable
2288
+ 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 });
2289
+ CouponService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, providedIn: 'root' });
2290
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, decorators: [{
2291
+ type: Injectable,
2292
+ args: [{
2293
+ providedIn: 'root',
2294
+ }]
2410
2295
  }], ctorParameters: function () {
2411
2296
  return [{ type: undefined, decorators: [{
2412
2297
  type: Inject,
2413
- args: ['WishlistRepository']
2414
- }] }, { type: i1$2.Shops, decorators: [{
2298
+ args: ['CouponRepository']
2299
+ }] }, { type: i1$3.Shops, decorators: [{
2415
2300
  type: Inject,
2416
2301
  args: [DEFAULT_SHOP]
2417
2302
  }] }, { type: undefined, decorators: [{
2418
2303
  type: Inject,
2419
- args: ['ProductRepository']
2420
- }] }, { type: undefined, decorators: [{
2421
- type: Inject,
2422
- args: ['CategoryFilterRepository']
2304
+ args: ['OrderRepository']
2423
2305
  }] }, { type: undefined, decorators: [{
2424
2306
  type: Inject,
2425
2307
  args: ['CategoryRepository']
2426
- }] }, { type: undefined, decorators: [{
2427
- type: Inject,
2428
- args: ['ProductStockNotificationRepository']
2429
- }] }, { type: undefined, decorators: [{
2430
- type: Inject,
2431
- args: ['ProductSearch']
2432
- }] }, { type: undefined, decorators: [{
2433
- type: Inject,
2434
- args: ['LogRepository']
2435
2308
  }] }];
2436
2309
  } });
2437
2310
 
@@ -2611,7 +2484,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2611
2484
  }] }, { type: undefined, decorators: [{
2612
2485
  type: Inject,
2613
2486
  args: ['ProductRepository']
2614
- }] }, { type: i1$2.Shops, decorators: [{
2487
+ }] }, { type: i1$3.Shops, decorators: [{
2615
2488
  type: Inject,
2616
2489
  args: [DEFAULT_SHOP]
2617
2490
  }] }];
@@ -2635,100 +2508,12 @@ OrderService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version
2635
2508
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService, decorators: [{
2636
2509
  type: Injectable
2637
2510
  }], ctorParameters: function () {
2638
- return [{ type: i1$1.Firestore }, { type: i1$2.OrderFirestoreRepository, decorators: [{
2511
+ return [{ type: i1$1.Firestore }, { type: i1$3.OrderFirestoreRepository, decorators: [{
2639
2512
  type: Inject,
2640
2513
  args: ['OrderRepository']
2641
2514
  }] }];
2642
2515
  } });
2643
2516
 
2644
- class ShippingService {
2645
- constructor(http, apiUrl, homeService) {
2646
- this.http = http;
2647
- this.apiUrl = apiUrl;
2648
- this.homeService = homeService;
2649
- }
2650
- getShippingMethods(shop, zip, weightGrams, totalPrice, personId, subscriptionPlan) {
2651
- return combineLatest([
2652
- this.homeService.getHomeData(),
2653
- this.http.get(`${this.apiUrl}open/checkshippingcompany?personId=${personId}&postalCode=${zip}&weightGrams=${weightGrams}`),
2654
- ]).pipe(map(([datas, shippingMethodsResponse]) => {
2655
- let shippingMethods = shippingMethodsResponse.result;
2656
- if (!shippingMethods.length)
2657
- return [];
2658
- shippingMethods = shippingMethods.map((shippingMethod) => {
2659
- if (shippingMethod.ShippingCompanyName == 'Same Day EG')
2660
- shippingMethod.ShippingCompanyName = 'Same Day';
2661
- return shippingMethod;
2662
- });
2663
- const datasSameDayNotAvaliable = datas.sameDayNotAvaliable;
2664
- if (this.isHolidays(datasSameDayNotAvaliable)) {
2665
- shippingMethods = shippingMethods.filter((method) => method.serviceName !== 'Same Day');
2666
- }
2667
- if (totalPrice >= 200) {
2668
- shippingMethods = shippingMethods.map((s) => {
2669
- if (s.serviceName !== 'Same Day')
2670
- return Object.assign(Object.assign({}, s), { totalPrice: 0 });
2671
- else
2672
- return s;
2673
- });
2674
- }
2675
- if (shop == Shops.GLAMSHOP)
2676
- return shippingMethods;
2677
- if (this.isFreeShippingBySubscription(shop, subscriptionPlan)) {
2678
- shippingMethods = shippingMethods.map((s) => {
2679
- if (s.serviceName == 'Same Day')
2680
- return Object.assign(Object.assign({}, s), { totalPrice: s.totalPrice / 2 });
2681
- else
2682
- return Object.assign(Object.assign({}, s), { totalPrice: 0 });
2683
- });
2684
- }
2685
- if (this.isHalfShippingBySubscription(shop, subscriptionPlan)) {
2686
- shippingMethods = shippingMethods.map((s) => {
2687
- return Object.assign(Object.assign({}, s), { totalPrice: s.totalPrice / 2 });
2688
- });
2689
- }
2690
- return shippingMethods;
2691
- }));
2692
- }
2693
- isFreeShippingBySubscription(shop, subscriptionPlan) {
2694
- if (!subscriptionPlan)
2695
- return false;
2696
- if (shop == Shops.MENSMARKET && subscriptionPlan == 'SELECT')
2697
- return true;
2698
- return false;
2699
- }
2700
- isHalfShippingBySubscription(shop, subscriptionPlan) {
2701
- if (!subscriptionPlan)
2702
- return false;
2703
- if (shop == Shops.MENSMARKET && subscriptionPlan == 'PRIME') {
2704
- return true;
2705
- }
2706
- return false;
2707
- }
2708
- isHolidays(datas) {
2709
- const today = new Date();
2710
- for (const key in datas) {
2711
- let start = new Date(`${today.getFullYear()}-${datas[key].beginDate}`);
2712
- let end = new Date(`${today.getFullYear()}-${datas[key].endDate}`);
2713
- if (start > end)
2714
- end = new Date(`${today.getFullYear() + 1}-${datas[key].endDate}`);
2715
- if (today >= start && today <= end)
2716
- return true;
2717
- }
2718
- return false;
2719
- }
2720
- }
2721
- ShippingService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService, deps: [{ token: i3.HttpClient }, { token: BACKEND_URL }, { token: HomeShopService }], target: i0.ɵɵFactoryTarget.Injectable });
2722
- ShippingService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService });
2723
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService, decorators: [{
2724
- type: Injectable
2725
- }], ctorParameters: function () {
2726
- return [{ type: i3.HttpClient }, { type: undefined, decorators: [{
2727
- type: Inject,
2728
- args: [BACKEND_URL]
2729
- }] }, { type: HomeShopService }];
2730
- } });
2731
-
2732
2517
  class AngularConnectModule {
2733
2518
  static initializeApp(defaultShop, options, nameOrConfig) {
2734
2519
  return {
@@ -2754,7 +2539,7 @@ class AngularConnectModule {
2754
2539
  }
2755
2540
  }
2756
2541
  AngularConnectModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2757
- AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, imports: [i1$3.FirebaseAppModule, i2.StorageModule, AngularElasticSeachModule,
2542
+ AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, imports: [i1$4.FirebaseAppModule, i2.StorageModule, AngularElasticSeachModule,
2758
2543
  AngularVertexSeachModule,
2759
2544
  AngularFirebaseAuthModule,
2760
2545
  AngularFirestoreModule,
@@ -2769,7 +2554,6 @@ AngularConnectModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", ve
2769
2554
  CouponService,
2770
2555
  HomeShopService,
2771
2556
  OrderService,
2772
- ShippingService,
2773
2557
  WishlistService,
2774
2558
  {
2775
2559
  provide: UpdateUserImage,
@@ -2834,7 +2618,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2834
2618
  CouponService,
2835
2619
  HomeShopService,
2836
2620
  OrderService,
2837
- ShippingService,
2838
2621
  WishlistService,
2839
2622
  {
2840
2623
  provide: UpdateUserImage,
@@ -2862,5 +2645,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2862
2645
  * Generated bundle index. Do not edit.
2863
2646
  */
2864
2647
 
2865
- export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CookieDataPersistence, CouponService, HomeShopService, NewCategoryStructureAdapter, OldCategoryStructureAdapter, OrderService, ProductSorts, ShippingService, UtilHelper, WishlistService };
2648
+ export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CookieDataPersistence, CouponService, HomeShopService, NewCategoryStructureAdapter, OldCategoryStructureAdapter, OrderService, ProductSorts, UtilHelper, WishlistService };
2866
2649
  //# sourceMappingURL=infrab4a-connect-angular.mjs.map