@infrab4a/connect-angular 4.17.3-beta.2 → 4.17.3-beta.20

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,20 +1,20 @@
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
- import * as i3 from '@angular/common/http';
17
+ import * as i1$2 from '@angular/common/http';
18
18
  import { __decorate, __metadata } from 'tslib';
19
19
  import { Type } from 'class-transformer';
20
20
 
@@ -1081,290 +1081,17 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
1081
1081
  args: ['UserRepository']
1082
1082
  }] }]; } });
1083
1083
 
1084
- class CouponService {
1085
- constructor(couponRepository, defaultShop, orderRepository, categoryRepository) {
1086
- this.couponRepository = couponRepository;
1087
- this.defaultShop = defaultShop;
1088
- this.orderRepository = orderRepository;
1089
- this.categoryRepository = categoryRepository;
1090
- this.emailIsFromCollaborator = (userEmail) => !!userEmail?.match(/@b4a.com.br/g);
1091
- }
1092
- checkCoupon(nickname, checkoutType, checkout, plan) {
1093
- return from(this.couponRepository
1094
- .find({
1095
- filters: {
1096
- nickname: { operator: Where.EQUALS, value: nickname },
1097
- active: { operator: Where.EQUALS, value: true },
1098
- },
1099
- })
1100
- .then((result) => result.data[0])).pipe(concatMap((coupon) => this.couponValidation(coupon, checkoutType)), concatMap((couponValid) => this.couponRulesValidation(couponValid, checkoutType, checkout, plan)), map((couponValidated) => couponValidated));
1101
- }
1102
- async couponValidation(coupon, checkoutType) {
1103
- if (!coupon)
1104
- throw 'Cupom inválido.';
1105
- if (coupon?.beginAt && coupon?.beginAt.getTime() > new Date().getTime())
1106
- throw 'Cupom inválido.';
1107
- if (coupon?.expiresIn && coupon?.expiresIn.getTime() < new Date().getTime())
1108
- throw 'Cupom expirado.';
1109
- const isInShop = coupon.shopAvailability === Shops.ALL || coupon.shopAvailability === this.defaultShop;
1110
- if (!isInShop)
1111
- throw 'Cupom inválido para loja.';
1112
- const isCheckoutType = coupon.checkoutType === CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
1113
- if (!isCheckoutType)
1114
- throw 'Cupom inválido. Erro de checkout.';
1115
- return coupon;
1116
- }
1117
- async couponRulesValidation(coupon, checkoutType, checkout, plan) {
1118
- if (checkoutType == CheckoutTypes.SUBSCRIPTION) {
1119
- if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
1120
- throw 'Cupom inválido para sua assinatura.';
1121
- return coupon;
1122
- }
1123
- const validUser = this.coupomUserValidation(coupon, checkout?.user);
1124
- if (!validUser)
1125
- throw 'Usuário não elegível.';
1126
- const couponUseLimits = this.getCouponUseLimits(coupon, checkoutType, checkout.user);
1127
- if (couponUseLimits.firstOrder) {
1128
- const ordersUser = await this.getOrdersFromUser(checkout.user.email.toLocaleLowerCase());
1129
- if (couponUseLimits.firstOrder && ordersUser.length >= 1)
1130
- throw 'Limite de uso atingido';
1131
- }
1132
- if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
1133
- const ordersCoupon = await this.getOrdersWithCoupon(coupon);
1134
- if (!couponUseLimits.unlimited && couponUseLimits.total && ordersCoupon.length >= couponUseLimits.total)
1135
- throw 'Limite de uso atingido.';
1136
- if (couponUseLimits.limitedPerUser) {
1137
- const ordersWithUser = this.countOrdersWithUser(ordersCoupon, checkout.user.email);
1138
- if (ordersWithUser > 0)
1139
- throw 'Limite de uso por usuário atingido.';
1140
- }
1141
- }
1142
- const hasProductCategories = await this.hasProductCategories(coupon, checkout);
1143
- if (!hasProductCategories)
1144
- throw 'Seu carrinho não possui produtos elegíveis para desconto.';
1145
- const hasMinSubTotal = await this.hasMinSubTotal(coupon, checkout);
1146
- if (!hasMinSubTotal) {
1147
- if (coupon.productsCategories?.length) {
1148
- 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.`;
1149
- }
1150
- throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido.`;
1151
- }
1152
- return coupon;
1153
- }
1154
- calcDiscountSubscription(coupon, checkout) {
1155
- let discount = 0;
1156
- if (coupon.discount.subscription.type == CouponTypes.ABSOLUTE)
1157
- discount = coupon.discount.subscription.value;
1158
- else
1159
- discount = checkout.subscriptionPlan.recurrencePrice * (coupon.discount.subscription.value / 100);
1160
- return of(discount);
1161
- }
1162
- async calcDiscountShopping(coupon, checkout) {
1163
- let discountInfo = null;
1164
- if (checkout.user.isSubscriber && coupon.discount.subscriber.value) {
1165
- discountInfo = await this.calcDiscountByType(coupon.discount.subscriber.type, coupon.discount.subscriber.value, coupon.productsCategories, checkout);
1166
- }
1167
- else {
1168
- discountInfo = await this.calcDiscountByType(coupon.discount.non_subscriber.type, coupon.discount.non_subscriber.value, coupon.productsCategories, checkout);
1169
- }
1170
- return { discount: discountInfo.discount, lineItems: discountInfo.lineItems };
1171
- }
1172
- async calcDiscountByType(type, value, categories, checkout) {
1173
- let discount = 0;
1174
- if (type == CouponTypes.SHIPPING) {
1175
- const subTotal = checkout.shipping.ShippingPrice;
1176
- const discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2);
1177
- return { discount, lineItems: checkout.lineItems };
1178
- }
1179
- const lineItensElegibleForDiscount = await this.getLineItensEligebleForDiscount(categories, checkout);
1180
- const subTotal = this.calcCheckoutSubtotal(lineItensElegibleForDiscount, checkout.user);
1181
- if (type == CouponTypes.ABSOLUTE) {
1182
- discount = value > subTotal ? subTotal : value;
1183
- }
1184
- else {
1185
- discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2);
1186
- }
1187
- const lineItems = this.calcLineItenDiscount(type, lineItensElegibleForDiscount, value, subTotal);
1188
- return { discount, lineItems };
1189
- }
1190
- async hasMinSubTotal(coupon, checkout) {
1191
- if (!coupon.minSubTotalValue)
1192
- return true;
1193
- const lineItensDiscount = await this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
1194
- const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user);
1195
- if (coupon.minSubTotalValue <= subTotal)
1196
- return true;
1197
- return false;
1198
- }
1199
- async hasProductCategories(coupon, checkout) {
1200
- if (!coupon.productsCategories || !coupon.productsCategories?.length) {
1201
- return true;
1202
- }
1203
- const couponCategories = await this.getCouponCategoriesId(coupon.productsCategories);
1204
- const hasCategories = checkout.lineItems?.filter((item) => {
1205
- if (item.isGift)
1206
- return false;
1207
- if (!item.categories || !item.categories?.length)
1208
- return true;
1209
- return item.categories.some((c) => couponCategories.some((cat) => cat == c));
1210
- });
1211
- return hasCategories.length ? true : false;
1212
- }
1213
- coupomUserValidation(coupon, user) {
1214
- if (!user || coupon.exclusivityType.includes(Exclusivities.ALL_USERS))
1215
- return true;
1216
- let userTypes = [];
1217
- if (coupon.exclusivityType.includes(Exclusivities.COLLABORATORS) &&
1218
- this.emailIsFromCollaborator(user.email.toLocaleLowerCase()))
1219
- userTypes.push(Exclusivities.COLLABORATORS);
1220
- if (coupon.exclusivityType.includes(Exclusivities.SPECIFIC_USER) &&
1221
- coupon.userExclusiveEmail.includes(user.email.toLocaleLowerCase()))
1222
- userTypes.push(Exclusivities.SPECIFIC_USER);
1223
- if (coupon.exclusivityType.includes(Exclusivities.ACTIVE_SUBSCRIBER) &&
1224
- user.isSubscriber &&
1225
- user.subscriptionPlan != '')
1226
- userTypes.push(Exclusivities.ACTIVE_SUBSCRIBER);
1227
- if (user.isSubscriber &&
1228
- user.subscriptionPlan == '' &&
1229
- coupon.exclusivityType.includes(Exclusivities.INACTIVE_SUBSCRIBER))
1230
- userTypes.push(Exclusivities.INACTIVE_SUBSCRIBER);
1231
- if (coupon.exclusivityType.includes(Exclusivities.NON_SUBSCRIBER) && !user.isSubscriber)
1232
- userTypes.push(Exclusivities.NON_SUBSCRIBER);
1233
- return coupon.exclusivityType.some((r) => userTypes.includes(r));
1234
- }
1235
- async getCouponCategoriesId(productsCategories) {
1236
- const couponCategories = [];
1237
- for (let index = 0; index < productsCategories.length; index++) {
1238
- const category = await this.categoryRepository.get({
1239
- id: productsCategories[index],
1240
- });
1241
- if (category) {
1242
- const children = await this.categoryRepository.getChildren(parseInt(productsCategories[index]));
1243
- couponCategories.push(category.id, ...children.map((c) => c.id.toString()));
1244
- }
1245
- }
1246
- return [...new Set(couponCategories)];
1247
- }
1248
- async getLineItensEligebleForDiscount(productsCategories, checkout) {
1249
- let lineItensDiscount = [];
1250
- const couponCategories = await this.getCouponCategoriesId(productsCategories);
1251
- if (productsCategories && productsCategories.length) {
1252
- lineItensDiscount = checkout.lineItems?.filter((item) => {
1253
- if (item.isGift)
1254
- return false;
1255
- if (item.categories?.length) {
1256
- return item.categories.some((c) => couponCategories.some((cat) => cat == c));
1257
- }
1258
- return true;
1259
- });
1260
- }
1261
- else {
1262
- lineItensDiscount = checkout.lineItems.filter((item) => !item.isGift);
1263
- }
1264
- return lineItensDiscount;
1265
- }
1266
- calcCheckoutSubtotal(lineItens, user) {
1267
- return (lineItens
1268
- ?.filter((item) => !item.isGift)
1269
- .reduce((acc, curr) => user?.isSubscriber && curr.price.subscriberPrice
1270
- ? acc + curr.price?.subscriberPrice * curr.quantity
1271
- : acc + curr.pricePaid * curr.quantity, 0) || 0);
1272
- }
1273
- async getOrdersWithCoupon(coupon) {
1274
- return await this.orderRepository
1275
- .find({
1276
- filters: {
1277
- coupon: { id: coupon.id },
1278
- status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1279
- },
1280
- })
1281
- .then((result) => result.data);
1282
- }
1283
- async getOrdersFromUser(email) {
1284
- return await this.orderRepository
1285
- .find({
1286
- filters: {
1287
- user: { email: { operator: Where.EQUALS, value: email } },
1288
- status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
1289
- },
1290
- })
1291
- .then((result) => result.data);
1292
- }
1293
- countOrdersWithUser(orders, email) {
1294
- return orders.filter((o) => o.user.email == email).length;
1295
- }
1296
- getCouponUseLimits(coupon, checkoutType, user) {
1297
- let couponUseLimits;
1298
- if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
1299
- if (coupon.exclusivityType.length === 1 &&
1300
- (coupon.exclusivityType.at(0) === Exclusivities.SPECIFIC_USER ||
1301
- coupon.exclusivityType.at(0) === Exclusivities.COLLABORATORS))
1302
- couponUseLimits = coupon.useLimits.non_subscriber;
1303
- else
1304
- couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
1305
- }
1306
- else {
1307
- couponUseLimits = coupon.useLimits.subscription;
1308
- }
1309
- return couponUseLimits;
1310
- }
1311
- calcLineItenDiscount(type, lineItems, couponDiscount, subTotal) {
1312
- let lineItemsDiscount = [];
1313
- if (type === CouponTypes.ABSOLUTE) {
1314
- const couponDiscountMax = couponDiscount > subTotal ? subTotal : couponDiscount;
1315
- lineItemsDiscount = lineItems.map((item) => {
1316
- if (item.isGift)
1317
- return item;
1318
- const totalItemPercentage = item.pricePaid / subTotal;
1319
- const discountItem = couponDiscountMax * totalItemPercentage;
1320
- return {
1321
- ...item,
1322
- discount: Number(discountItem.toFixed(2)),
1323
- };
1324
- });
1325
- }
1326
- else {
1327
- lineItemsDiscount = lineItems.map((item) => {
1328
- if (item.isGift)
1329
- return item;
1330
- const discountItem = item.pricePaid * (couponDiscount / 100);
1331
- return {
1332
- ...item,
1333
- discount: Number(discountItem.toFixed(2)),
1334
- };
1335
- });
1336
- }
1337
- return lineItemsDiscount;
1338
- }
1339
- }
1340
- 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 });
1341
- CouponService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, providedIn: 'root' });
1342
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, decorators: [{
1343
- type: Injectable,
1344
- args: [{
1345
- providedIn: 'root',
1346
- }]
1347
- }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1348
- type: Inject,
1349
- args: ['CouponRepository']
1350
- }] }, { type: i1$2.Shops, decorators: [{
1351
- type: Inject,
1352
- args: [DEFAULT_SHOP]
1353
- }] }, { type: undefined, decorators: [{
1354
- type: Inject,
1355
- args: ['OrderRepository']
1356
- }] }, { type: undefined, decorators: [{
1357
- type: Inject,
1358
- args: ['CategoryRepository']
1359
- }] }]; } });
1360
-
1361
1084
  class CheckoutService {
1362
- constructor(couponService, checkoutRepository, userRepository, defaultShop, dataPersistence) {
1363
- this.couponService = couponService;
1085
+ constructor(checkoutRepository, userRepository, defaultShop, dataPersistence, firebaseOptions, http) {
1364
1086
  this.checkoutRepository = checkoutRepository;
1365
1087
  this.userRepository = userRepository;
1366
1088
  this.defaultShop = defaultShop;
1367
1089
  this.dataPersistence = dataPersistence;
1090
+ this.firebaseOptions = firebaseOptions;
1091
+ this.http = http;
1092
+ this.checkoutUrl = null;
1093
+ this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`;
1094
+ // this.checkoutUrl = `http://docker.for.localhost:5001/b4astage-cb80a/southamerica-east1`
1368
1095
  }
1369
1096
  getCheckout(checkoutData) {
1370
1097
  return this.dataPersistence
@@ -1383,11 +1110,59 @@ class CheckoutService {
1383
1110
  clearCheckoutFromSession() {
1384
1111
  return this.dataPersistence.remove('checkoutId');
1385
1112
  }
1386
- calcDiscount(coupon) {
1387
- return this.getCheckout().pipe(concatMap(async (checkout) => await this.couponService.calcDiscountShopping(coupon, checkout)));
1113
+ resetCheckoutValues() {
1114
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutResetValues`, {
1115
+ checkoutId: checkout.id,
1116
+ })), concatMap(() => this.getCheckout()));
1117
+ }
1118
+ applyCouponDiscount(nickname, checkoutType) {
1119
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutApplyDiscount`, {
1120
+ checkoutId: checkout.id,
1121
+ coupon: nickname,
1122
+ checkoutType,
1123
+ })), concatMap(() => this.getCheckout()), map((checkout) => checkout.coupon));
1124
+ }
1125
+ removeCouponDiscount() {
1126
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutRemoveDiscount`, {
1127
+ checkoutId: checkout.id,
1128
+ })), concatMap(() => this.getCheckout()));
1129
+ }
1130
+ validateStockProducts() {
1131
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutValidateProductStock`, {
1132
+ checkoutId: checkout.id,
1133
+ })));
1388
1134
  }
1389
- checkCoupon(nickname, checkoutType) {
1390
- return this.getCheckout().pipe(concatMap((checkout) => this.couponService.checkCoupon(nickname, CheckoutTypes.ECOMMERCE, checkout, null).pipe()));
1135
+ selectShippingAddress(address) {
1136
+ return this.getCheckout().pipe(concatMap((checkout) => {
1137
+ return this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, shippingAddress: address, billingAddress: address }));
1138
+ }));
1139
+ }
1140
+ getAvailableShippingForProduct(productShipping) {
1141
+ return this.http.post(`${this.checkoutUrl}/checkoutGetAvailableShipping`, {
1142
+ checkoutId: null,
1143
+ productShipping,
1144
+ });
1145
+ }
1146
+ getAvailableShippingForCheckout() {
1147
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutGetAvailableShipping`, {
1148
+ checkoutId: checkout.id,
1149
+ productShipping: null,
1150
+ })));
1151
+ }
1152
+ selectShipping(option) {
1153
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutSelectShipping`, {
1154
+ checkoutId: checkout.id,
1155
+ shippingOption: option,
1156
+ })), concatMap(() => this.getCheckout()));
1157
+ }
1158
+ createOrder(checkoutPayload, paymentProvider, applicationVersion) {
1159
+ return this.http.post(`${this.checkoutUrl}/checkout`, {
1160
+ data: {
1161
+ ...checkoutPayload,
1162
+ applicationVersion,
1163
+ paymentProvider,
1164
+ },
1165
+ });
1391
1166
  }
1392
1167
  async createCheckout(checkoutData) {
1393
1168
  const checkout = await this.checkoutRepository.create({
@@ -1399,52 +1174,60 @@ class CheckoutService {
1399
1174
  return checkout;
1400
1175
  }
1401
1176
  }
1402
- 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 });
1177
+ 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 });
1403
1178
  CheckoutService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService });
1404
1179
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService, decorators: [{
1405
1180
  type: Injectable
1406
- }], ctorParameters: function () { return [{ type: CouponService }, { type: undefined, decorators: [{
1181
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1407
1182
  type: Inject,
1408
1183
  args: ['CheckoutRepository']
1409
1184
  }] }, { type: undefined, decorators: [{
1410
1185
  type: Inject,
1411
1186
  args: ['UserRepository']
1412
- }] }, { type: i1$2.Shops, decorators: [{
1187
+ }] }, { type: i1$3.Shops, decorators: [{
1413
1188
  type: Inject,
1414
1189
  args: [DEFAULT_SHOP]
1415
1190
  }] }, { type: undefined, decorators: [{
1416
1191
  type: Inject,
1417
1192
  args: [PERSISTENCE_PROVIDER]
1418
- }] }]; } });
1193
+ }] }, { type: undefined, decorators: [{
1194
+ type: Inject,
1195
+ args: [FIREBASE_OPTIONS]
1196
+ }] }, { type: i1$2.HttpClient }]; } });
1419
1197
 
1420
1198
  class CartService {
1421
- constructor(authService, checkoutService, defaultShop, firebaseOptions, productRepository, categoryRepository, variantRepository, buy2WinRepository, http) {
1199
+ constructor(authService, checkoutService, defaultShop, firebaseOptions,
1200
+ // @Inject('ProductRepository') private readonly productRepository: ProductRepository,
1201
+ // @Inject('CategoryRepository') private readonly categoryRepository: CategoryRepository,
1202
+ // @Inject('VariantRepository') private readonly variantRepository: VariantRepository,
1203
+ // @Inject('Buy2WinRepository') private readonly buy2WinRepository: Buy2WinFirestoreRepository,
1204
+ http) {
1422
1205
  this.authService = authService;
1423
1206
  this.checkoutService = checkoutService;
1424
1207
  this.defaultShop = defaultShop;
1425
1208
  this.firebaseOptions = firebaseOptions;
1426
- this.productRepository = productRepository;
1427
- this.categoryRepository = categoryRepository;
1428
- this.variantRepository = variantRepository;
1429
- this.buy2WinRepository = buy2WinRepository;
1430
1209
  this.http = http;
1431
1210
  this.cartSubject = new Subject();
1432
1211
  this.checkoutUrl = null;
1433
- this.updateLineItemInCart = (lineItem, quantity, checkout) => (isNil(checkout) ? this.checkoutService.getCheckout() : of(checkout)).pipe(concatMap((checkoutLoaded) => {
1434
- const items = [];
1435
- const index = checkoutLoaded.lineItems?.map((checkoutItem) => checkoutItem.id).indexOf(lineItem.id);
1436
- const isGift = checkoutLoaded.lineItems?.[index]?.isGift;
1437
- if (index > -1) {
1438
- checkoutLoaded.lineItems[index].quantity += quantity;
1439
- checkoutLoaded.lineItems[index].pricePaid = isGift ? 0 : lineItem.pricePaid;
1440
- checkoutLoaded.lineItems[index].price = lineItem.price;
1441
- }
1442
- else
1443
- checkoutLoaded.lineItems = items.concat(checkoutLoaded.lineItems ? checkoutLoaded.lineItems.concat([lineItem]) : [lineItem]);
1444
- return this.checkoutService
1445
- .updateCheckoutLineItems(checkoutLoaded)
1446
- .pipe(map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)));
1447
- }));
1212
+ // private updateLineItemInCart = (lineItem: LineItem, quantity: number, checkout?: Checkout): Observable<Cart> =>
1213
+ // (isNil(checkout) ? this.checkoutService.getCheckout() : of(checkout)).pipe(
1214
+ // concatMap((checkoutLoaded) => {
1215
+ // const items: LineItem[] = []
1216
+ // const index = checkoutLoaded.lineItems?.map((checkoutItem) => checkoutItem.id).indexOf(lineItem.id)
1217
+ // const isGift = checkoutLoaded.lineItems?.[index]?.isGift
1218
+ // if (index > -1) {
1219
+ // checkoutLoaded.lineItems[index].quantity += quantity
1220
+ // checkoutLoaded.lineItems[index].pricePaid = isGift ? 0 : lineItem.pricePaid
1221
+ // checkoutLoaded.lineItems[index].price = lineItem.price
1222
+ // } else
1223
+ // checkoutLoaded.lineItems = items.concat(
1224
+ // checkoutLoaded.lineItems ? checkoutLoaded.lineItems.concat([lineItem]) : [lineItem],
1225
+ // )
1226
+ // return this.checkoutService
1227
+ // .updateCheckoutLineItems(checkoutLoaded)
1228
+ // .pipe(map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)))
1229
+ // }),
1230
+ // )
1448
1231
  this.generateCartObject = (items) => items?.reduce((cart, item) => ({
1449
1232
  ...cart,
1450
1233
  [item.id]: LineItem.toInstance({
@@ -1452,63 +1235,8 @@ class CartService {
1452
1235
  quantity: (cart[item.id]?.quantity || 0) + (item.quantity ? item.quantity : 1),
1453
1236
  }),
1454
1237
  }), {}) || {};
1455
- this.buildLineItem = async ({ checkout, item, quantity, }) => {
1456
- const product = await this.getProductData(item.id);
1457
- item.quantity = item?.quantity || checkout?.lineItems?.find((lineItem) => lineItem.id === item.id)?.quantity || 0;
1458
- if (this.checkMaxStock(product.stock.quantity, item.quantity || 0, quantity || 0))
1459
- throw new Error('Desculpe! Temos apenas ' + product.stock?.quantity + ' em estoque.');
1460
- const image = item.image || item.images?.shift();
1461
- const { id, name, EAN, slug, weight, sku, type } = item;
1462
- const isGift = item?.isGift || null;
1463
- const pricePaid = isGift
1464
- ? 0
1465
- : this.getProductPrice({
1466
- product: LineItem.toInstance(product),
1467
- shop: checkout.shop || this.defaultShop,
1468
- isSubscriber: checkout.user?.isSubscriber,
1469
- });
1470
- RoundProductPricesHelper.roundProductPrices(item);
1471
- RoundProductPricesHelper.roundProductPrices(product);
1472
- return {
1473
- checkout,
1474
- lineItem: LineItem.toInstance({
1475
- id,
1476
- name: name ?? product.name,
1477
- EAN: EAN ?? product.EAN,
1478
- brand: product.brand,
1479
- slug: slug ?? product.slug,
1480
- sku: sku ?? product.sku,
1481
- stock: product.stock,
1482
- price: this.roundPrice(product.price),
1483
- image,
1484
- weight: weight ?? product.weight,
1485
- quantity: (item.quantity || 0) + (quantity || 0),
1486
- pricePaid,
1487
- discount: 0,
1488
- categories: product.categories || product.category?.id ? [product.category?.id, ...product.categories] : [],
1489
- category: product.category,
1490
- isGift: isGift ?? null,
1491
- costPrice: isGift ? 0 : product.costPrice ?? 0,
1492
- type,
1493
- label: product.label,
1494
- }),
1495
- };
1496
- };
1497
- this.getProductPrice = ({ product, isSubscriber, }) => {
1498
- const info = product.price;
1499
- if (product.isGift)
1500
- return 0;
1501
- return isSubscriber && info.subscriberPrice > 0
1502
- ? Number(info.subscriberPrice.toFixed(2))
1503
- : Number(info.price.toFixed(2));
1504
- };
1505
- this.checkMaxStock = (currentStock, currentItemQtd, quantityToAdd) => {
1506
- const maxStock = currentStock || 0;
1507
- const currentItemAmount = currentItemQtd || 0;
1508
- return currentItemAmount + quantityToAdd > maxStock;
1509
- };
1510
- // this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`
1511
- this.checkoutUrl = `http://docker.for.localhost:5001/b4astage-cb80a/southamerica-east1`;
1238
+ this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`;
1239
+ // this.checkoutUrl = `http://docker.for.localhost:5001/b4astage-cb80a/southamerica-east1`
1512
1240
  }
1513
1241
  addItem(item, quantity = 1) {
1514
1242
  return this.checkoutService.getCheckout().pipe(concatMap((checkout) => {
@@ -1573,7 +1301,6 @@ class CartService {
1573
1301
  return this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user }));
1574
1302
  }), concatMap((checkout) => {
1575
1303
  console.log('getCheckout User', checkout);
1576
- this.user = user;
1577
1304
  return this.http.post(`${this.checkoutUrl}/checkoutUpdateUserCart`, {
1578
1305
  checkoutId: checkout.id,
1579
1306
  });
@@ -1609,169 +1336,42 @@ class CartService {
1609
1336
  this.buildCartFromCheckout(checkout).subscribe((cart) => this.cartSubject.next(cart));
1610
1337
  return this.cartSubject;
1611
1338
  }
1612
- /**
1613
- * @deprecated The method should not be used
1614
- */
1615
- getVariantPriceDiscount(item) {
1616
- 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)));
1617
- }
1339
+ // /**
1340
+ // * @deprecated The method should not be used
1341
+ // */
1342
+ // getVariantPriceDiscount(item: LineItem): Observable<number> {
1343
+ // return this.authService.getUser().pipe(
1344
+ // concatMap((user) =>
1345
+ // iif(
1346
+ // () => user.isSubscriber && !!item.price.subscriberPrice,
1347
+ // of(item.price.subscriberPrice),
1348
+ // of(item.price.price),
1349
+ // ),
1350
+ // ),
1351
+ // catchError(() => of(item.price.price)),
1352
+ // )
1353
+ // }
1618
1354
  clearCart() {
1619
1355
  return this.checkoutService.getCheckout().pipe(map((checkout) => {
1620
1356
  this.checkoutService.clearCheckoutFromSession();
1621
1357
  return checkout;
1622
1358
  }), concatMap((oldCheckout) => this.buildCartFromCheckout(oldCheckout)), tap((cart) => this.cartSubject.next(cart)));
1623
1359
  }
1624
- buildCartFromCheckout(checkoutData) {
1625
- return this.checkoutService.getCheckout(checkoutData).pipe(map((checkout) => checkout.lineItems), concatMap((lineItems) => of(this.generateCartObject(lineItems))));
1626
- }
1627
- roundPrice(productPrice) {
1628
- const { price, fullPrice, subscriberPrice } = productPrice;
1629
- return {
1630
- ...productPrice,
1631
- price: Number(price.toFixed(2)),
1632
- fullPrice: Number(fullPrice.toFixed(2)),
1633
- ...(subscriberPrice && { subscriberPrice: Number(subscriberPrice.toFixed(2)) }),
1634
- };
1635
- }
1636
- async getProductData(productId) {
1637
- let product;
1638
- let variant;
1639
- try {
1640
- product = await this.productRepository.get({ id: productId });
1641
- }
1642
- catch (error) {
1643
- if (!(error instanceof NotFoundError))
1644
- throw error;
1645
- const { data: variants } = await this.variantRepository.find({ filters: { id: productId } });
1646
- variant = variants.shift();
1647
- if (!variant)
1648
- throw error;
1649
- product = await this.productRepository.get({ id: variant.productId });
1650
- }
1651
- return {
1652
- ...product.toPlain(),
1653
- ...(variant && { ...variant.toPlain() }),
1654
- };
1655
- }
1656
- getGifts() {
1657
- return this.checkoutService.getCheckout().pipe(mergeMap(async (checkout) => {
1658
- const notGiftItems = checkout.lineItems ? checkout.lineItems.filter((item) => !item.isGift) : [];
1659
- if (!notGiftItems.length)
1660
- return { ...checkout, lineItems: [] };
1661
- const campaigns = await this.buy2WinRepository
1662
- .find({
1663
- filters: {
1664
- active: { operator: Where.EQUALS, value: true },
1665
- },
1666
- })
1667
- .then((data) => data.data.filter((campaign) => campaign.shop === Shops.ALL || campaign.shop === this.defaultShop));
1668
- if (!campaigns.length)
1669
- return { ...checkout, lineItems: notGiftItems };
1670
- const elegibleCampaigns = [];
1671
- for (const campaign of campaigns) {
1672
- const today = new Date().getTime();
1673
- if (!(campaign.startDate.getTime() <= today) && !(campaign.endDate.getTime() >= today))
1674
- continue;
1675
- if (campaign.activeCategory) {
1676
- const categoriesCampaing = campaign.categories.map((c) => c.id.toString());
1677
- const categoriesCampaingFullTree = [];
1678
- for (const id of categoriesCampaing) {
1679
- const children = await this.categoryRepository.getChildren(parseInt(id));
1680
- categoriesCampaingFullTree.push(id, ...children.map((c) => c.id.toString()));
1681
- }
1682
- const categoriesCampaingTree = [...new Set(categoriesCampaingFullTree)];
1683
- const filterProductsCategories = notGiftItems.filter((l) => {
1684
- if (!l.categories || !l.categories?.length)
1685
- return true;
1686
- return l.categories.some((c) => categoriesCampaingTree.some((cat) => cat == c));
1687
- });
1688
- if (filterProductsCategories.length) {
1689
- const cartValuelWithCategories = filterProductsCategories.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1690
- const cartItensQuantityWithCategories = filterProductsCategories.reduce((a, b) => a + b.quantity, 0);
1691
- const hasMinValue = campaign.cartValueMin && cartValuelWithCategories >= campaign.cartValueMin;
1692
- const hasMinQuantity = campaign.cartItensQuantityMin && cartItensQuantityWithCategories >= campaign.cartItensQuantityMin;
1693
- if (hasMinQuantity || hasMinValue)
1694
- elegibleCampaigns.push(campaign);
1695
- }
1696
- }
1697
- else {
1698
- const cartTotal = notGiftItems.reduce((a, b) => a + b.pricePaid * b.quantity, 0);
1699
- const cartItensQuantity = notGiftItems.reduce((a, b) => a + b.quantity, 0);
1700
- const hasMinValue = campaign.cartValue && campaign.cartValue > 0 && campaign.cartValue <= cartTotal;
1701
- const hasMinQuantity = campaign.cartItensQuantityMin && cartItensQuantity >= campaign.cartItensQuantityMin;
1702
- if (hasMinQuantity || hasMinValue)
1703
- elegibleCampaigns.push(campaign);
1704
- }
1705
- }
1706
- if (!elegibleCampaigns.length)
1707
- return { ...checkout, lineItems: notGiftItems };
1708
- const campaingnProducts = [];
1709
- for (const campaign of elegibleCampaigns) {
1710
- let elegibleProducts = [];
1711
- for (const product of campaign.products) {
1712
- const { data: productData } = await this.productRepository.find({ filters: { sku: product } });
1713
- if (!productData.length)
1714
- continue;
1715
- const gift = productData.shift();
1716
- if (gift.stock.quantity < 1)
1717
- continue;
1718
- elegibleProducts.push(gift);
1719
- }
1720
- campaingnProducts.push(elegibleProducts);
1721
- }
1722
- if (!campaingnProducts.length)
1723
- return { ...checkout, lineItems: notGiftItems };
1724
- const gifts = this.giftToLineItems([].concat(...campaingnProducts));
1725
- return { ...checkout, lineItems: notGiftItems.concat(gifts) };
1726
- }), concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)), map((checkout) => this.generateCartObject(checkout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1727
- }
1728
- giftToLineItems(items) {
1729
- return items.map((item) => {
1730
- const { brand, categories, category, id, name, price, sku, slug, stock, weight, EAN } = item;
1731
- const image = item?.miniatures?.length ? item.miniatures[0] : item.images[0];
1732
- return LineItem.toInstance({
1733
- brand,
1734
- categories,
1735
- category,
1736
- id: id.toString(),
1737
- name,
1738
- price,
1739
- sku,
1740
- slug,
1741
- stock,
1742
- weight,
1743
- EAN,
1744
- image,
1745
- pricePaid: 0,
1746
- quantity: 1,
1747
- isGift: true,
1748
- });
1749
- });
1360
+ buildCartFromCheckout(checkoutData) {
1361
+ return this.checkoutService.getCheckout(checkoutData).pipe(map((checkout) => checkout.lineItems), concatMap((lineItems) => of(this.generateCartObject(lineItems))));
1750
1362
  }
1751
1363
  }
1752
- 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 });
1364
+ 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 });
1753
1365
  CartService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService });
1754
1366
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService, decorators: [{
1755
1367
  type: Injectable
1756
- }], ctorParameters: function () { return [{ type: AuthService }, { type: CheckoutService }, { type: i1$2.Shops, decorators: [{
1368
+ }], ctorParameters: function () { return [{ type: AuthService }, { type: CheckoutService }, { type: i1$3.Shops, decorators: [{
1757
1369
  type: Inject,
1758
1370
  args: [DEFAULT_SHOP]
1759
1371
  }] }, { type: undefined, decorators: [{
1760
1372
  type: Inject,
1761
1373
  args: [FIREBASE_OPTIONS]
1762
- }] }, { type: undefined, decorators: [{
1763
- type: Inject,
1764
- args: ['ProductRepository']
1765
- }] }, { type: undefined, decorators: [{
1766
- type: Inject,
1767
- args: ['CategoryRepository']
1768
- }] }, { type: undefined, decorators: [{
1769
- type: Inject,
1770
- args: ['VariantRepository']
1771
- }] }, { type: i1$2.Buy2WinFirestoreRepository, decorators: [{
1772
- type: Inject,
1773
- args: ['Buy2WinRepository']
1774
- }] }, { type: i3.HttpClient }]; } });
1374
+ }] }, { type: i1$2.HttpClient }]; } });
1775
1375
 
1776
1376
  class NewCategoryStructureAdapter {
1777
1377
  constructor(categoryRepository) {
@@ -2115,7 +1715,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2115
1715
  }] }, { type: undefined, decorators: [{
2116
1716
  type: Inject,
2117
1717
  args: [CATEGORY_STRUCTURE]
2118
- }] }, { type: i1$2.Shops, decorators: [{
1718
+ }] }, { type: i1$3.Shops, decorators: [{
2119
1719
  type: Inject,
2120
1720
  args: [DEFAULT_SHOP]
2121
1721
  }] }, { type: undefined, decorators: [{
@@ -2164,7 +1764,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2164
1764
  }] }, { type: undefined, decorators: [{
2165
1765
  type: Inject,
2166
1766
  args: [CATEGORY_STRUCTURE]
2167
- }] }, { type: i1$2.Shops, decorators: [{
1767
+ }] }, { type: i1$3.Shops, decorators: [{
2168
1768
  type: Inject,
2169
1769
  args: [DEFAULT_SHOP]
2170
1770
  }] }]; } });
@@ -2391,7 +1991,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2391
1991
  }], ctorParameters: function () { return [{ type: undefined, decorators: [{
2392
1992
  type: Inject,
2393
1993
  args: ['WishlistRepository']
2394
- }] }, { type: i1$2.Shops, decorators: [{
1994
+ }] }, { type: i1$3.Shops, decorators: [{
2395
1995
  type: Inject,
2396
1996
  args: [DEFAULT_SHOP]
2397
1997
  }] }, { type: undefined, decorators: [{
@@ -2414,6 +2014,271 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2414
2014
  args: ['LogRepository']
2415
2015
  }] }]; } });
2416
2016
 
2017
+ class CouponService {
2018
+ constructor(couponRepository, defaultShop, orderRepository, categoryRepository) {
2019
+ this.couponRepository = couponRepository;
2020
+ this.defaultShop = defaultShop;
2021
+ this.orderRepository = orderRepository;
2022
+ this.categoryRepository = categoryRepository;
2023
+ this.emailIsFromCollaborator = (userEmail) => !!userEmail?.match(/@b4a.com.br/g);
2024
+ }
2025
+ checkCoupon(nickname, checkoutType, checkout, plan) {
2026
+ return from(this.couponRepository
2027
+ .find({
2028
+ filters: {
2029
+ nickname: { operator: Where.EQUALS, value: nickname },
2030
+ active: { operator: Where.EQUALS, value: true },
2031
+ },
2032
+ })
2033
+ .then((result) => result.data[0])).pipe(concatMap((coupon) => this.couponValidation(coupon, checkoutType)), concatMap((couponValid) => this.couponRulesValidation(couponValid, checkoutType, checkout, plan)), map((couponValidated) => couponValidated));
2034
+ }
2035
+ async couponValidation(coupon, checkoutType) {
2036
+ if (!coupon)
2037
+ throw 'Cupom inválido.';
2038
+ if (coupon?.beginAt && coupon?.beginAt.getTime() > new Date().getTime())
2039
+ throw 'Cupom inválido.';
2040
+ if (coupon?.expiresIn && (coupon?.expiresIn).getTime() < new Date().getTime())
2041
+ throw 'Cupom expirado.';
2042
+ const isInShop = coupon.shopAvailability === Shops.ALL || coupon.shopAvailability === this.defaultShop;
2043
+ if (!isInShop)
2044
+ throw 'Cupom inválido para loja.';
2045
+ const isCheckoutType = coupon.checkoutType === CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
2046
+ if (!isCheckoutType)
2047
+ throw 'Cupom inválido. Erro de checkout.';
2048
+ return coupon;
2049
+ }
2050
+ async couponRulesValidation(coupon, checkoutType, checkout, plan) {
2051
+ if (checkoutType == CheckoutTypes.SUBSCRIPTION) {
2052
+ if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
2053
+ throw 'Cupom inválido para sua assinatura.';
2054
+ return coupon;
2055
+ }
2056
+ const validUser = this.coupomUserValidation(coupon, checkout?.user);
2057
+ if (!validUser)
2058
+ throw 'Usuário não elegível.';
2059
+ const couponUseLimits = this.getCouponUseLimits(coupon, checkoutType, checkout.user);
2060
+ if (couponUseLimits.firstOrder) {
2061
+ const ordersUser = await this.getOrdersFromUser(checkout.user.email.toLocaleLowerCase());
2062
+ if (couponUseLimits.firstOrder && ordersUser.length >= 1)
2063
+ throw 'Limite de uso atingido';
2064
+ }
2065
+ if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
2066
+ const ordersCoupon = await this.getOrdersWithCoupon(coupon);
2067
+ if (!couponUseLimits.unlimited && couponUseLimits.total && ordersCoupon.length >= couponUseLimits.total)
2068
+ throw 'Limite de uso atingido.';
2069
+ if (couponUseLimits.limitedPerUser) {
2070
+ const ordersWithUser = this.countOrdersWithUser(ordersCoupon, checkout.user.email);
2071
+ if (ordersWithUser > 0)
2072
+ throw 'Limite de uso por usuário atingido.';
2073
+ }
2074
+ }
2075
+ const hasProductCategories = await this.hasProductCategories(coupon, checkout);
2076
+ if (!hasProductCategories)
2077
+ throw 'Seu carrinho não possui produtos elegíveis para desconto.';
2078
+ const hasMinSubTotal = await this.hasMinSubTotal(coupon, checkout);
2079
+ if (!hasMinSubTotal) {
2080
+ if (coupon.productsCategories?.length) {
2081
+ 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.`;
2082
+ }
2083
+ throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido.`;
2084
+ }
2085
+ return coupon;
2086
+ }
2087
+ calcDiscountSubscription(coupon, checkout) {
2088
+ let discount = 0;
2089
+ if (coupon.discount.subscription.type == CouponTypes.ABSOLUTE)
2090
+ discount = coupon.discount.subscription.value;
2091
+ else
2092
+ discount = checkout.subscriptionPlan.recurrencePrice * (coupon.discount.subscription.value / 100);
2093
+ return of(discount);
2094
+ }
2095
+ // public async calcDiscountShopping(
2096
+ // coupon: Coupon,
2097
+ // checkout: Partial<Checkout>,
2098
+ // ): Promise<{ discount: number; lineItems: LineItem[] }> {
2099
+ // let discountInfo: { discount: number; lineItems: LineItem[] } = null
2100
+ // if (checkout.user.isSubscriber && coupon.discount.subscriber.value) {
2101
+ // discountInfo = await this.calcDiscountByType(
2102
+ // coupon.discount.subscriber.type,
2103
+ // coupon.discount.subscriber.value,
2104
+ // coupon.productsCategories,
2105
+ // checkout,
2106
+ // )
2107
+ // } else {
2108
+ // discountInfo = await this.calcDiscountByType(
2109
+ // coupon.discount.non_subscriber.type,
2110
+ // coupon.discount.non_subscriber.value,
2111
+ // coupon.productsCategories,
2112
+ // checkout,
2113
+ // )
2114
+ // }
2115
+ // return { discount: discountInfo.discount, lineItems: discountInfo.lineItems }
2116
+ // }
2117
+ // private async calcDiscountByType(
2118
+ // type: CouponTypes,
2119
+ // value: number,
2120
+ // categories: string[],
2121
+ // checkout: Partial<Checkout>,
2122
+ // ): Promise<{ discount: number; lineItems: LineItem[] }> {
2123
+ // let discount = 0
2124
+ // if (type == CouponTypes.SHIPPING) {
2125
+ // const subTotal = checkout.shipping.ShippingPrice
2126
+ // const discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2)
2127
+ // return { discount, lineItems: checkout.lineItems }
2128
+ // }
2129
+ // const lineItensElegibleForDiscount = await this.getLineItensEligebleForDiscount(categories, checkout)
2130
+ // const subTotal = this.calcCheckoutSubtotal(lineItensElegibleForDiscount, checkout.user)
2131
+ // if (type == CouponTypes.ABSOLUTE) {
2132
+ // discount = value > subTotal ? subTotal : value
2133
+ // } else {
2134
+ // discount = +(subTotal * ((value > 100 ? 100 : value) / 100)).toFixed(2)
2135
+ // }
2136
+ // const lineItems = this.calcLineItenDiscount(type, lineItensElegibleForDiscount, value, subTotal)
2137
+ // return { discount, lineItems }
2138
+ // }
2139
+ async hasMinSubTotal(coupon, checkout) {
2140
+ if (!coupon.minSubTotalValue)
2141
+ return true;
2142
+ const lineItensDiscount = await this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
2143
+ const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user);
2144
+ if (coupon.minSubTotalValue <= subTotal)
2145
+ return true;
2146
+ return false;
2147
+ }
2148
+ async hasProductCategories(coupon, checkout) {
2149
+ if (!coupon.productsCategories || !coupon.productsCategories?.length) {
2150
+ return true;
2151
+ }
2152
+ const couponCategories = await this.getCouponCategoriesId(coupon.productsCategories);
2153
+ const hasCategories = checkout.lineItems?.filter((item) => {
2154
+ if (item.isGift)
2155
+ return false;
2156
+ if (!item.categories || !item.categories?.length)
2157
+ return true;
2158
+ return item.categories.some((c) => couponCategories.some((cat) => cat == c));
2159
+ });
2160
+ return hasCategories.length ? true : false;
2161
+ }
2162
+ coupomUserValidation(coupon, user) {
2163
+ if (!user || coupon.exclusivityType.includes(Exclusivities.ALL_USERS))
2164
+ return true;
2165
+ let userTypes = [];
2166
+ if (coupon.exclusivityType.includes(Exclusivities.COLLABORATORS) &&
2167
+ this.emailIsFromCollaborator(user.email.toLocaleLowerCase()))
2168
+ userTypes.push(Exclusivities.COLLABORATORS);
2169
+ if (coupon.exclusivityType.includes(Exclusivities.SPECIFIC_USER) &&
2170
+ coupon.userExclusiveEmail.includes(user.email.toLocaleLowerCase()))
2171
+ userTypes.push(Exclusivities.SPECIFIC_USER);
2172
+ if (coupon.exclusivityType.includes(Exclusivities.ACTIVE_SUBSCRIBER) &&
2173
+ user.isSubscriber &&
2174
+ user.subscriptionPlan != '')
2175
+ userTypes.push(Exclusivities.ACTIVE_SUBSCRIBER);
2176
+ if (user.isSubscriber &&
2177
+ user.subscriptionPlan == '' &&
2178
+ coupon.exclusivityType.includes(Exclusivities.INACTIVE_SUBSCRIBER))
2179
+ userTypes.push(Exclusivities.INACTIVE_SUBSCRIBER);
2180
+ if (coupon.exclusivityType.includes(Exclusivities.NON_SUBSCRIBER) && !user.isSubscriber)
2181
+ userTypes.push(Exclusivities.NON_SUBSCRIBER);
2182
+ return coupon.exclusivityType.some((r) => userTypes.includes(r));
2183
+ }
2184
+ async getCouponCategoriesId(productsCategories) {
2185
+ const couponCategories = [];
2186
+ for (let index = 0; index < productsCategories.length; index++) {
2187
+ const category = await this.categoryRepository.get({
2188
+ id: productsCategories[index],
2189
+ });
2190
+ if (category) {
2191
+ const children = await this.categoryRepository.getChildren(parseInt(productsCategories[index]));
2192
+ couponCategories.push(category.id, ...children.map((c) => c.id.toString()));
2193
+ }
2194
+ }
2195
+ return [...new Set(couponCategories)];
2196
+ }
2197
+ async getLineItensEligebleForDiscount(productsCategories, checkout) {
2198
+ let lineItensDiscount = [];
2199
+ const couponCategories = await this.getCouponCategoriesId(productsCategories);
2200
+ if (productsCategories && productsCategories.length) {
2201
+ lineItensDiscount = checkout.lineItems?.filter((item) => {
2202
+ if (item.isGift)
2203
+ return false;
2204
+ if (item.categories?.length) {
2205
+ return item.categories.some((c) => couponCategories.some((cat) => cat == c));
2206
+ }
2207
+ return true;
2208
+ });
2209
+ }
2210
+ else {
2211
+ lineItensDiscount = checkout.lineItems.filter((item) => !item.isGift);
2212
+ }
2213
+ return lineItensDiscount;
2214
+ }
2215
+ calcCheckoutSubtotal(lineItens, user) {
2216
+ return (lineItens
2217
+ ?.filter((item) => !item.isGift)
2218
+ .reduce((acc, curr) => user?.isSubscriber && curr.price.subscriberPrice
2219
+ ? acc + curr.price?.subscriberPrice * curr.quantity
2220
+ : acc + curr.pricePaid * curr.quantity, 0) || 0);
2221
+ }
2222
+ async getOrdersWithCoupon(coupon) {
2223
+ return await this.orderRepository
2224
+ .find({
2225
+ filters: {
2226
+ coupon: { id: coupon.id },
2227
+ status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
2228
+ },
2229
+ })
2230
+ .then((result) => result.data);
2231
+ }
2232
+ async getOrdersFromUser(email) {
2233
+ return await this.orderRepository
2234
+ .find({
2235
+ filters: {
2236
+ user: { email: { operator: Where.EQUALS, value: email } },
2237
+ status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
2238
+ },
2239
+ })
2240
+ .then((result) => result.data);
2241
+ }
2242
+ countOrdersWithUser(orders, email) {
2243
+ return orders.filter((o) => o.user.email == email).length;
2244
+ }
2245
+ getCouponUseLimits(coupon, checkoutType, user) {
2246
+ let couponUseLimits;
2247
+ if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
2248
+ if (coupon.exclusivityType.length === 1 &&
2249
+ (coupon.exclusivityType.at(0) === Exclusivities.SPECIFIC_USER ||
2250
+ coupon.exclusivityType.at(0) === Exclusivities.COLLABORATORS))
2251
+ couponUseLimits = coupon.useLimits.non_subscriber;
2252
+ else
2253
+ couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
2254
+ }
2255
+ else {
2256
+ couponUseLimits = coupon.useLimits.subscription;
2257
+ }
2258
+ return couponUseLimits;
2259
+ }
2260
+ }
2261
+ 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 });
2262
+ CouponService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, providedIn: 'root' });
2263
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, decorators: [{
2264
+ type: Injectable,
2265
+ args: [{
2266
+ providedIn: 'root',
2267
+ }]
2268
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
2269
+ type: Inject,
2270
+ args: ['CouponRepository']
2271
+ }] }, { type: i1$3.Shops, decorators: [{
2272
+ type: Inject,
2273
+ args: [DEFAULT_SHOP]
2274
+ }] }, { type: undefined, decorators: [{
2275
+ type: Inject,
2276
+ args: ['OrderRepository']
2277
+ }] }, { type: undefined, decorators: [{
2278
+ type: Inject,
2279
+ args: ['CategoryRepository']
2280
+ }] }]; } });
2281
+
2417
2282
  class CheckoutSubscriptionService {
2418
2283
  constructor(checkoutSubscriptionRepository, dataPersistence, couponService) {
2419
2284
  this.checkoutSubscriptionRepository = checkoutSubscriptionRepository;
@@ -2588,7 +2453,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2588
2453
  }] }, { type: undefined, decorators: [{
2589
2454
  type: Inject,
2590
2455
  args: ['ProductRepository']
2591
- }] }, { type: i1$2.Shops, decorators: [{
2456
+ }] }, { type: i1$3.Shops, decorators: [{
2592
2457
  type: Inject,
2593
2458
  args: [DEFAULT_SHOP]
2594
2459
  }] }]; } });
@@ -2610,97 +2475,11 @@ OrderService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "1
2610
2475
  OrderService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService });
2611
2476
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService, decorators: [{
2612
2477
  type: Injectable
2613
- }], ctorParameters: function () { return [{ type: i1$1.Firestore }, { type: i1$2.OrderFirestoreRepository, decorators: [{
2478
+ }], ctorParameters: function () { return [{ type: i1$1.Firestore }, { type: i1$3.OrderFirestoreRepository, decorators: [{
2614
2479
  type: Inject,
2615
2480
  args: ['OrderRepository']
2616
2481
  }] }]; } });
2617
2482
 
2618
- class ShippingService {
2619
- constructor(http, apiUrl, homeService) {
2620
- this.http = http;
2621
- this.apiUrl = apiUrl;
2622
- this.homeService = homeService;
2623
- }
2624
- getShippingMethods(shop, zip, weightGrams, totalPrice, personId, subscriptionPlan) {
2625
- return combineLatest([
2626
- this.homeService.getHomeData(),
2627
- this.http.get(`${this.apiUrl}open/checkshippingcompany?personId=${personId}&postalCode=${zip}&weightGrams=${weightGrams}`),
2628
- ]).pipe(map(([datas, shippingMethodsResponse]) => {
2629
- let shippingMethods = shippingMethodsResponse.result;
2630
- if (!shippingMethods.length)
2631
- return [];
2632
- shippingMethods = shippingMethods.map((shippingMethod) => {
2633
- if (shippingMethod.ShippingCompanyName == 'Same Day EG')
2634
- shippingMethod.ShippingCompanyName = 'Same Day';
2635
- return shippingMethod;
2636
- });
2637
- const datasSameDayNotAvaliable = datas.sameDayNotAvaliable;
2638
- if (this.isHolidays(datasSameDayNotAvaliable)) {
2639
- shippingMethods = shippingMethods.filter((method) => method.serviceName !== 'Same Day');
2640
- }
2641
- if (totalPrice >= 200) {
2642
- shippingMethods = shippingMethods.map((s) => {
2643
- if (s.serviceName !== 'Same Day')
2644
- return { ...s, totalPrice: 0 };
2645
- else
2646
- return s;
2647
- });
2648
- }
2649
- if (shop == Shops.GLAMSHOP)
2650
- return shippingMethods;
2651
- if (this.isFreeShippingBySubscription(shop, subscriptionPlan)) {
2652
- shippingMethods = shippingMethods.map((s) => {
2653
- if (s.serviceName == 'Same Day')
2654
- return { ...s, totalPrice: s.totalPrice / 2 };
2655
- else
2656
- return { ...s, totalPrice: 0 };
2657
- });
2658
- }
2659
- if (this.isHalfShippingBySubscription(shop, subscriptionPlan)) {
2660
- shippingMethods = shippingMethods.map((s) => {
2661
- return { ...s, totalPrice: s.totalPrice / 2 };
2662
- });
2663
- }
2664
- return shippingMethods;
2665
- }));
2666
- }
2667
- isFreeShippingBySubscription(shop, subscriptionPlan) {
2668
- if (!subscriptionPlan)
2669
- return false;
2670
- if (shop == Shops.MENSMARKET && subscriptionPlan == 'SELECT')
2671
- return true;
2672
- return false;
2673
- }
2674
- isHalfShippingBySubscription(shop, subscriptionPlan) {
2675
- if (!subscriptionPlan)
2676
- return false;
2677
- if (shop == Shops.MENSMARKET && subscriptionPlan == 'PRIME') {
2678
- return true;
2679
- }
2680
- return false;
2681
- }
2682
- isHolidays(datas) {
2683
- const today = new Date();
2684
- for (const key in datas) {
2685
- let start = new Date(`${today.getFullYear()}-${datas[key].beginDate}`);
2686
- let end = new Date(`${today.getFullYear()}-${datas[key].endDate}`);
2687
- if (start > end)
2688
- end = new Date(`${today.getFullYear() + 1}-${datas[key].endDate}`);
2689
- if (today >= start && today <= end)
2690
- return true;
2691
- }
2692
- return false;
2693
- }
2694
- }
2695
- 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 });
2696
- ShippingService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService });
2697
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: ShippingService, decorators: [{
2698
- type: Injectable
2699
- }], ctorParameters: function () { return [{ type: i3.HttpClient }, { type: undefined, decorators: [{
2700
- type: Inject,
2701
- args: [BACKEND_URL]
2702
- }] }, { type: HomeShopService }]; } });
2703
-
2704
2483
  class AngularConnectModule {
2705
2484
  static initializeApp(defaultShop, options, nameOrConfig) {
2706
2485
  return {
@@ -2726,7 +2505,7 @@ class AngularConnectModule {
2726
2505
  }
2727
2506
  }
2728
2507
  AngularConnectModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2729
- AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, imports: [i1$3.FirebaseAppModule, i2.StorageModule, AngularElasticSeachModule,
2508
+ AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, imports: [i1$4.FirebaseAppModule, i2.StorageModule, AngularElasticSeachModule,
2730
2509
  AngularVertexSeachModule,
2731
2510
  AngularFirebaseAuthModule,
2732
2511
  AngularFirestoreModule,
@@ -2741,7 +2520,6 @@ AngularConnectModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", ve
2741
2520
  CouponService,
2742
2521
  HomeShopService,
2743
2522
  OrderService,
2744
- ShippingService,
2745
2523
  WishlistService,
2746
2524
  {
2747
2525
  provide: UpdateUserImage,
@@ -2806,7 +2584,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2806
2584
  CouponService,
2807
2585
  HomeShopService,
2808
2586
  OrderService,
2809
- ShippingService,
2810
2587
  WishlistService,
2811
2588
  {
2812
2589
  provide: UpdateUserImage,
@@ -2834,5 +2611,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2834
2611
  * Generated bundle index. Do not edit.
2835
2612
  */
2836
2613
 
2837
- export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CookieDataPersistence, CouponService, HomeShopService, NewCategoryStructureAdapter, OldCategoryStructureAdapter, OrderService, ProductSorts, ShippingService, UtilHelper, WishlistService };
2614
+ export { AngularConnectModule, AngularFirebaseAuthModule, AngularFirestoreModule, AngularHasuraGraphQLModule, AuthService, CartService, CatalogService, CategoryService, CategoryWithTree, CheckoutService, CheckoutSubscriptionService, CookieDataPersistence, CouponService, HomeShopService, NewCategoryStructureAdapter, OldCategoryStructureAdapter, OrderService, ProductSorts, UtilHelper, WishlistService };
2838
2615
  //# sourceMappingURL=infrab4a-connect-angular.mjs.map