@infrab4a/connect-angular 4.17.3-beta.8 → 4.18.0

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,22 @@
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
- import * as i2$1 from '@angular/fire/storage';
5
+ import * as i2 from '@angular/fire/app-check';
6
+ import { provideAppCheck, initializeAppCheck } from '@angular/fire/app-check';
7
+ import * as i3 from '@angular/fire/storage';
6
8
  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, set, InvalidArgumentError, RoundProductPricesHelper, isEmpty, Category, PersonTypes, WishlistLogType, Wishlist, CheckoutSubscription, Product, RequiredArgumentError, add, Order, UpdateUserImage, FirebaseFileUploaderService } from '@infrab4a/connect';
9
+ import * as i1$3 from '@infrab4a/connect';
10
+ 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
11
  import * as i1 from '@angular/fire/auth';
10
- import { Auth, provideAuth, getAuth, getIdToken, authState } from '@angular/fire/auth';
12
+ import { Auth, provideAuth, initializeAuth, indexedDBLocalPersistence, browserLocalPersistence, getAuth, getIdToken, authState } from '@angular/fire/auth';
11
13
  import { isPlatformBrowser, isPlatformServer } from '@angular/common';
12
14
  import * as i1$1 from '@angular/fire/firestore';
13
15
  import { Firestore, provideFirestore, initializeFirestore, memoryLocalCache, docSnapshots, doc } from '@angular/fire/firestore';
14
16
  import cookie from 'js-cookie';
15
17
  import { of, from, combineLatest, throwError, Subject, forkJoin } from 'rxjs';
16
18
  import { map, mergeMap, catchError, concatMap, tap } from 'rxjs/operators';
17
- import * as i2 from '@angular/common/http';
19
+ import * as i1$2 from '@angular/common/http';
18
20
  import { __decorate, __metadata } from 'tslib';
19
21
  import { Type } from 'class-transformer';
20
22
 
@@ -57,7 +59,8 @@ const CATEGORY_STRUCTURE = 'CATEGORY_STRUCTURE';
57
59
  const DEFAULT_SHOP = 'DEFAULT_SHOP';
58
60
 
59
61
  const FIREBASE_APP_NAME = new InjectionToken('firebaseAppName');
60
- const FIREBASE_OPTIONS = new InjectionToken('firebaseOptions');
62
+ const FIREBASE_OPTIONS = new InjectionToken('firebaseOptions');
63
+ const APP_CHECK_PROVIDER = new InjectionToken('appCheckProvider');
61
64
 
62
65
  const HASURA_OPTIONS = 'HASURA_OPTIONS';
63
66
 
@@ -121,11 +124,37 @@ AngularFirebaseAuthModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0
121
124
  },
122
125
  deps: ['AuthenticationService'],
123
126
  },
124
- ], imports: [provideAuth((injector) => getAuth(injector.get(FirebaseApp)))] });
127
+ ], imports: [provideAuth((injector) => {
128
+ const app = injector.get(FirebaseApp);
129
+ try {
130
+ return initializeAuth(app, {
131
+ persistence: [indexedDBLocalPersistence, browserLocalPersistence],
132
+ });
133
+ }
134
+ catch (error) {
135
+ if (error instanceof Error)
136
+ console.error('Error initializing auth', error.message);
137
+ return getAuth(app);
138
+ }
139
+ })] });
125
140
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularFirebaseAuthModule, decorators: [{
126
141
  type: NgModule,
127
142
  args: [{
128
- imports: [provideAuth((injector) => getAuth(injector.get(FirebaseApp)))],
143
+ imports: [
144
+ provideAuth((injector) => {
145
+ const app = injector.get(FirebaseApp);
146
+ try {
147
+ return initializeAuth(app, {
148
+ persistence: [indexedDBLocalPersistence, browserLocalPersistence],
149
+ });
150
+ }
151
+ catch (error) {
152
+ if (error instanceof Error)
153
+ console.error('Error initializing auth', error.message);
154
+ return getAuth(app);
155
+ }
156
+ }),
157
+ ],
129
158
  providers: [
130
159
  {
131
160
  provide: 'Authentication',
@@ -1081,294 +1110,16 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
1081
1110
  args: ['UserRepository']
1082
1111
  }] }]; } });
1083
1112
 
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
1113
  class CheckoutService {
1362
- constructor(couponService, checkoutRepository, userRepository, defaultShop, dataPersistence, http) {
1363
- this.couponService = couponService;
1114
+ constructor(checkoutRepository, userRepository, defaultShop, dataPersistence, firebaseOptions, http) {
1364
1115
  this.checkoutRepository = checkoutRepository;
1365
1116
  this.userRepository = userRepository;
1366
1117
  this.defaultShop = defaultShop;
1367
1118
  this.dataPersistence = dataPersistence;
1119
+ this.firebaseOptions = firebaseOptions;
1368
1120
  this.http = http;
1369
1121
  this.checkoutUrl = null;
1370
- // this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`
1371
- this.checkoutUrl = `http://docker.for.localhost:5001/b4astage-cb80a/southamerica-east1`;
1122
+ this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`;
1372
1123
  }
1373
1124
  getCheckout(checkoutData) {
1374
1125
  return this.dataPersistence
@@ -1387,36 +1138,43 @@ class CheckoutService {
1387
1138
  clearCheckoutFromSession() {
1388
1139
  return this.dataPersistence.remove('checkoutId');
1389
1140
  }
1390
- // calcDiscount(coupon: Coupon) {
1391
- // return this.getCheckout().pipe(
1392
- // concatMap(async (checkout) => await this.couponService.calcDiscountShopping(coupon, checkout)),
1393
- // )
1394
- // }
1395
- checkCoupon(nickname, checkoutType) {
1141
+ resetCheckoutValues() {
1142
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutResetValues`, {
1143
+ checkoutId: checkout.id,
1144
+ })), concatMap(() => this.getCheckout()));
1145
+ }
1146
+ applyCouponDiscount(nickname, checkoutType) {
1396
1147
  return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutApplyDiscount`, {
1397
1148
  checkoutId: checkout.id,
1398
1149
  coupon: nickname,
1399
1150
  checkoutType,
1400
1151
  })), concatMap(() => this.getCheckout()), map((checkout) => checkout.coupon));
1401
- // return this.getCheckout().pipe(
1402
- // concatMap((checkout) => this.couponService.checkCoupon(nickname, CheckoutTypes.ECOMMERCE, checkout, null).pipe()),
1403
- // )
1152
+ }
1153
+ removeCouponDiscount() {
1154
+ return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutRemoveDiscount`, {
1155
+ checkoutId: checkout.id,
1156
+ })), concatMap(() => this.getCheckout()));
1404
1157
  }
1405
1158
  validateStockProducts() {
1406
1159
  return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutValidateProductStock`, {
1407
1160
  checkoutId: checkout.id,
1408
1161
  })));
1409
1162
  }
1410
- getShippingProduct(shippingProduct) {
1163
+ selectShippingAddress(address) {
1164
+ return this.getCheckout().pipe(concatMap((checkout) => {
1165
+ return this.checkoutRepository.update(Checkout.toInstance({ id: checkout.id, shippingAddress: address, billingAddress: address }));
1166
+ }));
1167
+ }
1168
+ getAvailableShippingForProduct(productShipping) {
1411
1169
  return this.http.post(`${this.checkoutUrl}/checkoutGetAvailableShipping`, {
1412
1170
  checkoutId: null,
1413
- shippingProduct,
1171
+ productShipping,
1414
1172
  });
1415
1173
  }
1416
- getAvailableShipping(productShipping) {
1174
+ getAvailableShippingForCheckout() {
1417
1175
  return this.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutGetAvailableShipping`, {
1418
1176
  checkoutId: checkout.id,
1419
- productShipping,
1177
+ productShipping: null,
1420
1178
  })));
1421
1179
  }
1422
1180
  selectShipping(option) {
@@ -1425,6 +1183,15 @@ class CheckoutService {
1425
1183
  shippingOption: option,
1426
1184
  })), concatMap(() => this.getCheckout()));
1427
1185
  }
1186
+ createOrder(checkoutPayload, paymentProvider, applicationVersion) {
1187
+ return this.http.post(`${this.checkoutUrl}/checkout`, {
1188
+ data: {
1189
+ ...checkoutPayload,
1190
+ applicationVersion,
1191
+ paymentProvider,
1192
+ },
1193
+ });
1194
+ }
1428
1195
  async createCheckout(checkoutData) {
1429
1196
  const checkout = await this.checkoutRepository.create({
1430
1197
  createdAt: new Date(),
@@ -1435,52 +1202,36 @@ class CheckoutService {
1435
1202
  return checkout;
1436
1203
  }
1437
1204
  }
1438
- 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 }, { token: i2.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
1205
+ 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 });
1439
1206
  CheckoutService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService });
1440
1207
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CheckoutService, decorators: [{
1441
1208
  type: Injectable
1442
- }], ctorParameters: function () { return [{ type: CouponService }, { type: undefined, decorators: [{
1209
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
1443
1210
  type: Inject,
1444
1211
  args: ['CheckoutRepository']
1445
1212
  }] }, { type: undefined, decorators: [{
1446
1213
  type: Inject,
1447
1214
  args: ['UserRepository']
1448
- }] }, { type: i1$2.Shops, decorators: [{
1215
+ }] }, { type: i1$3.Shops, decorators: [{
1449
1216
  type: Inject,
1450
1217
  args: [DEFAULT_SHOP]
1451
1218
  }] }, { type: undefined, decorators: [{
1452
1219
  type: Inject,
1453
1220
  args: [PERSISTENCE_PROVIDER]
1454
- }] }, { type: i2.HttpClient }]; } });
1221
+ }] }, { type: undefined, decorators: [{
1222
+ type: Inject,
1223
+ args: [FIREBASE_OPTIONS]
1224
+ }] }, { type: i1$2.HttpClient }]; } });
1455
1225
 
1456
1226
  class CartService {
1457
- constructor(authService, checkoutService, defaultShop, firebaseOptions, productRepository, categoryRepository, variantRepository, buy2WinRepository, http) {
1227
+ constructor(authService, checkoutService, defaultShop, firebaseOptions, http) {
1458
1228
  this.authService = authService;
1459
1229
  this.checkoutService = checkoutService;
1460
1230
  this.defaultShop = defaultShop;
1461
1231
  this.firebaseOptions = firebaseOptions;
1462
- this.productRepository = productRepository;
1463
- this.categoryRepository = categoryRepository;
1464
- this.variantRepository = variantRepository;
1465
- this.buy2WinRepository = buy2WinRepository;
1466
1232
  this.http = http;
1467
1233
  this.cartSubject = new Subject();
1468
1234
  this.checkoutUrl = null;
1469
- this.updateLineItemInCart = (lineItem, quantity, checkout) => (isNil(checkout) ? this.checkoutService.getCheckout() : of(checkout)).pipe(concatMap((checkoutLoaded) => {
1470
- const items = [];
1471
- const index = checkoutLoaded.lineItems?.map((checkoutItem) => checkoutItem.id).indexOf(lineItem.id);
1472
- const isGift = checkoutLoaded.lineItems?.[index]?.isGift;
1473
- if (index > -1) {
1474
- checkoutLoaded.lineItems[index].quantity += quantity;
1475
- checkoutLoaded.lineItems[index].pricePaid = isGift ? 0 : lineItem.pricePaid;
1476
- checkoutLoaded.lineItems[index].price = lineItem.price;
1477
- }
1478
- else
1479
- checkoutLoaded.lineItems = items.concat(checkoutLoaded.lineItems ? checkoutLoaded.lineItems.concat([lineItem]) : [lineItem]);
1480
- return this.checkoutService
1481
- .updateCheckoutLineItems(checkoutLoaded)
1482
- .pipe(map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)));
1483
- }));
1484
1235
  this.generateCartObject = (items) => items?.reduce((cart, item) => ({
1485
1236
  ...cart,
1486
1237
  [item.id]: LineItem.toInstance({
@@ -1488,123 +1239,41 @@ class CartService {
1488
1239
  quantity: (cart[item.id]?.quantity || 0) + (item.quantity ? item.quantity : 1),
1489
1240
  }),
1490
1241
  }), {}) || {};
1491
- // this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`
1492
- this.checkoutUrl = `http://docker.for.localhost:5001/b4astage-cb80a/southamerica-east1`;
1242
+ this.checkoutUrl = `https://southamerica-east1-${this.firebaseOptions.projectId}.cloudfunctions.net`;
1493
1243
  }
1494
1244
  addItem(item, quantity = 1) {
1495
- return this.checkoutService.getCheckout().pipe(concatMap((checkout) => {
1496
- console.log('getCheckout', checkout);
1497
- return this.http.post(`${this.checkoutUrl}/checkoutAddItemToCart`, {
1498
- checkoutId: checkout.id,
1499
- productId: item.id,
1500
- quantity,
1501
- });
1502
- }), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => {
1503
- console.log('updatedCheckout', updatedCheckout);
1504
- return this.generateCartObject(updatedCheckout.lineItems);
1505
- }), tap((cart) => this.cartSubject.next(cart)));
1506
- // return this.generateCartObject(checkoutUpdated.lineItems as LineItem[])
1507
- // return from(this.checkoutService.getCheckout()).pipe(
1508
- // concatMap(async (checkout) => await this.buildLineItem({ checkout, item, quantity: quantity || 1 })),
1509
- // mergeMap(({ checkout, lineItem }) => this.updateLineItemInCart(lineItem, quantity || 1, checkout as Checkout)),
1510
- // tap((cart) => this.cartSubject.next(cart)),
1511
- // )
1245
+ return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutAddItemToCart`, {
1246
+ checkoutId: checkout.id,
1247
+ productId: item.id,
1248
+ quantity,
1249
+ })), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1512
1250
  }
1513
1251
  decreaseItem(item) {
1514
1252
  return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutDecreaseProductFromCart`, {
1515
1253
  checkoutId: checkout.id,
1516
1254
  productId: item.id,
1517
1255
  quantity: 1,
1518
- })), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => {
1519
- console.log('updatedCheckout', updatedCheckout);
1520
- return this.generateCartObject(updatedCheckout.lineItems);
1521
- }), tap((cart) => this.cartSubject.next(cart)));
1522
- // return this.checkoutService.getCheckout().pipe(
1523
- // map((checkout) => {
1524
- // const checkoutItem = checkout.lineItems?.find((lineItem) => lineItem.id === item.id)
1525
- // if (!isNil(checkoutItem)) checkoutItem.quantity -= checkoutItem.quantity > 1 ? 1 : 0
1526
- // return checkout
1527
- // }),
1528
- // concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)),
1529
- // map((checkout) => this.generateCartObject(checkout.lineItems)),
1530
- // tap((cart) => this.cartSubject.next(cart)),
1531
- // )
1256
+ })), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1532
1257
  }
1533
1258
  removeItem(item) {
1534
1259
  return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.http.post(`${this.checkoutUrl}/checkoutRemoveProductFromCart`, {
1535
1260
  checkoutId: checkout.id,
1536
1261
  productId: item.id,
1537
- })), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => {
1538
- console.log('updatedCheckout', updatedCheckout);
1539
- return this.generateCartObject(updatedCheckout.lineItems);
1540
- }), tap((cart) => this.cartSubject.next(cart)));
1541
- // return this.checkoutService.getCheckout().pipe(
1542
- // map((checkout) => {
1543
- // const index = checkout.lineItems.findIndex((lineItem) => lineItem.id === item.id)
1544
- // if (index >= 0) checkout.lineItems.splice(index, 1)
1545
- // return checkout
1546
- // }),
1547
- // concatMap((checkout) => this.checkoutService.updateCheckoutLineItems(checkout)),
1548
- // map((checkout) => this.generateCartObject(checkout.lineItems)),
1549
- // tap((cart) => this.cartSubject.next(cart)),
1262
+ })), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => this.generateCartObject(updatedCheckout.lineItems)), tap((cart) => this.cartSubject.next(cart)));
1550
1263
  }
1551
1264
  updateUserCart(user) {
1552
- return this.checkoutService.getCheckout().pipe(concatMap((checkout) => {
1553
- console.log('getCheckout', checkout);
1554
- return this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user }));
1555
- }), concatMap((checkout) => {
1556
- console.log('getCheckout User', checkout);
1557
- this.user = user;
1265
+ return this.checkoutService.getCheckout().pipe(concatMap((checkout) => this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user }))), concatMap((checkout) => {
1558
1266
  return this.http.post(`${this.checkoutUrl}/checkoutUpdateUserCart`, {
1559
1267
  checkoutId: checkout.id,
1560
1268
  });
1561
1269
  }), concatMap(() => this.checkoutService.getCheckout()), map((updatedCheckout) => {
1562
- console.log('updatedCheckout', updatedCheckout);
1563
1270
  return this.generateCartObject(updatedCheckout.lineItems);
1564
1271
  }), tap((cart) => this.cartSubject.next(cart)));
1565
- // return this.checkoutService.getCheckout().pipe(
1566
- // concatMap((checkout) =>
1567
- // this.checkoutService.updateCheckoutUser(Checkout.toInstance({ ...checkout.toPlain(), user })),
1568
- // ),
1569
- // concatMap(
1570
- // async (checkout) =>
1571
- // await this.checkoutService
1572
- // .updateCheckoutLineItems(
1573
- // Checkout.toInstance({
1574
- // ...checkout.toPlain(),
1575
- // lineItems: checkout.lineItems?.length
1576
- // ? await Promise.all(
1577
- // checkout.lineItems?.map(async (item) => (await this.buildLineItem({ checkout, item })).lineItem),
1578
- // )
1579
- // : [],
1580
- // }),
1581
- // )
1582
- // .toPromise(),
1583
- // ),
1584
- // map((checkout) => this.generateCartObject(checkout.lineItems)),
1585
- // tap((cart) => (this.user = user)),
1586
- // tap((cart) => this.cartSubject.next(cart)),
1587
- // )
1588
1272
  }
1589
1273
  getCart(checkout) {
1590
1274
  this.buildCartFromCheckout(checkout).subscribe((cart) => this.cartSubject.next(cart));
1591
1275
  return this.cartSubject;
1592
1276
  }
1593
- // /**
1594
- // * @deprecated The method should not be used
1595
- // */
1596
- // getVariantPriceDiscount(item: LineItem): Observable<number> {
1597
- // return this.authService.getUser().pipe(
1598
- // concatMap((user) =>
1599
- // iif(
1600
- // () => user.isSubscriber && !!item.price.subscriberPrice,
1601
- // of(item.price.subscriberPrice),
1602
- // of(item.price.price),
1603
- // ),
1604
- // ),
1605
- // catchError(() => of(item.price.price)),
1606
- // )
1607
- // }
1608
1277
  clearCart() {
1609
1278
  return this.checkoutService.getCheckout().pipe(map((checkout) => {
1610
1279
  this.checkoutService.clearCheckoutFromSession();
@@ -1615,29 +1284,17 @@ class CartService {
1615
1284
  return this.checkoutService.getCheckout(checkoutData).pipe(map((checkout) => checkout.lineItems), concatMap((lineItems) => of(this.generateCartObject(lineItems))));
1616
1285
  }
1617
1286
  }
1618
- 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: i2.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
1287
+ 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 });
1619
1288
  CartService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService });
1620
1289
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CartService, decorators: [{
1621
1290
  type: Injectable
1622
- }], ctorParameters: function () { return [{ type: AuthService }, { type: CheckoutService }, { type: i1$2.Shops, decorators: [{
1291
+ }], ctorParameters: function () { return [{ type: AuthService }, { type: CheckoutService }, { type: i1$3.Shops, decorators: [{
1623
1292
  type: Inject,
1624
1293
  args: [DEFAULT_SHOP]
1625
1294
  }] }, { type: undefined, decorators: [{
1626
1295
  type: Inject,
1627
1296
  args: [FIREBASE_OPTIONS]
1628
- }] }, { type: undefined, decorators: [{
1629
- type: Inject,
1630
- args: ['ProductRepository']
1631
- }] }, { type: undefined, decorators: [{
1632
- type: Inject,
1633
- args: ['CategoryRepository']
1634
- }] }, { type: undefined, decorators: [{
1635
- type: Inject,
1636
- args: ['VariantRepository']
1637
- }] }, { type: i1$2.Buy2WinFirestoreRepository, decorators: [{
1638
- type: Inject,
1639
- args: ['Buy2WinRepository']
1640
- }] }, { type: i2.HttpClient }]; } });
1297
+ }] }, { type: i1$2.HttpClient }]; } });
1641
1298
 
1642
1299
  class NewCategoryStructureAdapter {
1643
1300
  constructor(categoryRepository) {
@@ -1981,7 +1638,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
1981
1638
  }] }, { type: undefined, decorators: [{
1982
1639
  type: Inject,
1983
1640
  args: [CATEGORY_STRUCTURE]
1984
- }] }, { type: i1$2.Shops, decorators: [{
1641
+ }] }, { type: i1$3.Shops, decorators: [{
1985
1642
  type: Inject,
1986
1643
  args: [DEFAULT_SHOP]
1987
1644
  }] }, { type: undefined, decorators: [{
@@ -2030,7 +1687,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2030
1687
  }] }, { type: undefined, decorators: [{
2031
1688
  type: Inject,
2032
1689
  args: [CATEGORY_STRUCTURE]
2033
- }] }, { type: i1$2.Shops, decorators: [{
1690
+ }] }, { type: i1$3.Shops, decorators: [{
2034
1691
  type: Inject,
2035
1692
  args: [DEFAULT_SHOP]
2036
1693
  }] }]; } });
@@ -2257,7 +1914,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2257
1914
  }], ctorParameters: function () { return [{ type: undefined, decorators: [{
2258
1915
  type: Inject,
2259
1916
  args: ['WishlistRepository']
2260
- }] }, { type: i1$2.Shops, decorators: [{
1917
+ }] }, { type: i1$3.Shops, decorators: [{
2261
1918
  type: Inject,
2262
1919
  args: [DEFAULT_SHOP]
2263
1920
  }] }, { type: undefined, decorators: [{
@@ -2280,6 +1937,227 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2280
1937
  args: ['LogRepository']
2281
1938
  }] }]; } });
2282
1939
 
1940
+ class CouponService {
1941
+ constructor(couponRepository, defaultShop, orderRepository, categoryRepository) {
1942
+ this.couponRepository = couponRepository;
1943
+ this.defaultShop = defaultShop;
1944
+ this.orderRepository = orderRepository;
1945
+ this.categoryRepository = categoryRepository;
1946
+ this.emailIsFromCollaborator = (userEmail) => !!userEmail?.match(/@b4a.com.br/g);
1947
+ }
1948
+ checkCoupon(nickname, checkoutType, checkout, plan) {
1949
+ return from(this.couponRepository
1950
+ .find({
1951
+ filters: {
1952
+ nickname: { operator: Where.EQUALS, value: nickname },
1953
+ active: { operator: Where.EQUALS, value: true },
1954
+ },
1955
+ })
1956
+ .then((result) => result.data[0])).pipe(concatMap((coupon) => this.couponValidation(coupon, checkoutType)), concatMap((couponValid) => this.couponRulesValidation(couponValid, checkoutType, checkout, plan)), map((couponValidated) => couponValidated));
1957
+ }
1958
+ async couponValidation(coupon, checkoutType) {
1959
+ if (!coupon)
1960
+ throw 'Cupom inválido.';
1961
+ if (coupon?.beginAt && coupon?.beginAt.getTime() > new Date().getTime())
1962
+ throw 'Cupom inválido.';
1963
+ if (coupon?.expiresIn && (coupon?.expiresIn).getTime() < new Date().getTime())
1964
+ throw 'Cupom expirado.';
1965
+ const isInShop = coupon.shopAvailability === Shops.ALL || coupon.shopAvailability === this.defaultShop;
1966
+ if (!isInShop)
1967
+ throw 'Cupom inválido para loja.';
1968
+ const isCheckoutType = coupon.checkoutType === CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
1969
+ if (!isCheckoutType)
1970
+ throw 'Cupom inválido. Erro de checkout.';
1971
+ return coupon;
1972
+ }
1973
+ async couponRulesValidation(coupon, checkoutType, checkout, plan) {
1974
+ if (checkoutType == CheckoutTypes.SUBSCRIPTION) {
1975
+ if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
1976
+ throw 'Cupom inválido para sua assinatura.';
1977
+ return coupon;
1978
+ }
1979
+ const validUser = this.coupomUserValidation(coupon, checkout?.user);
1980
+ if (!validUser)
1981
+ throw 'Usuário não elegível.';
1982
+ const couponUseLimits = this.getCouponUseLimits(coupon, checkoutType, checkout.user);
1983
+ if (couponUseLimits.firstOrder) {
1984
+ const ordersUser = await this.getOrdersFromUser(checkout.user.email.toLocaleLowerCase());
1985
+ if (couponUseLimits.firstOrder && ordersUser.length >= 1)
1986
+ throw 'Limite de uso atingido';
1987
+ }
1988
+ if (!couponUseLimits.unlimited || couponUseLimits.limitedPerUser) {
1989
+ const ordersCoupon = await this.getOrdersWithCoupon(coupon);
1990
+ if (!couponUseLimits.unlimited && couponUseLimits.total && ordersCoupon.length >= couponUseLimits.total)
1991
+ throw 'Limite de uso atingido.';
1992
+ if (couponUseLimits.limitedPerUser) {
1993
+ const ordersWithUser = this.countOrdersWithUser(ordersCoupon, checkout.user.email);
1994
+ if (ordersWithUser > 0)
1995
+ throw 'Limite de uso por usuário atingido.';
1996
+ }
1997
+ }
1998
+ const hasProductCategories = await this.hasProductCategories(coupon, checkout);
1999
+ if (!hasProductCategories)
2000
+ throw 'Seu carrinho não possui produtos elegíveis para desconto.';
2001
+ const hasMinSubTotal = await this.hasMinSubTotal(coupon, checkout);
2002
+ if (!hasMinSubTotal) {
2003
+ if (coupon.productsCategories?.length) {
2004
+ 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.`;
2005
+ }
2006
+ throw `Valor mínimo de ${Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(coupon.minSubTotalValue)} não atingido.`;
2007
+ }
2008
+ return coupon;
2009
+ }
2010
+ calcDiscountSubscription(coupon, checkout) {
2011
+ let discount = 0;
2012
+ if (coupon.discount.subscription.type == CouponTypes.ABSOLUTE)
2013
+ discount = coupon.discount.subscription.value;
2014
+ else
2015
+ discount = checkout.subscriptionPlan.recurrencePrice * (coupon.discount.subscription.value / 100);
2016
+ return of(discount);
2017
+ }
2018
+ async hasMinSubTotal(coupon, checkout) {
2019
+ if (!coupon.minSubTotalValue)
2020
+ return true;
2021
+ const lineItensDiscount = await this.getLineItensEligebleForDiscount(coupon.productsCategories, checkout);
2022
+ const subTotal = this.calcCheckoutSubtotal(lineItensDiscount, checkout.user);
2023
+ if (coupon.minSubTotalValue <= subTotal)
2024
+ return true;
2025
+ return false;
2026
+ }
2027
+ async hasProductCategories(coupon, checkout) {
2028
+ if (!coupon.productsCategories || !coupon.productsCategories?.length) {
2029
+ return true;
2030
+ }
2031
+ const couponCategories = await this.getCouponCategoriesId(coupon.productsCategories);
2032
+ const hasCategories = checkout.lineItems?.filter((item) => {
2033
+ if (item.isGift)
2034
+ return false;
2035
+ if (!item.categories || !item.categories?.length)
2036
+ return true;
2037
+ return item.categories.some((c) => couponCategories.some((cat) => cat == c));
2038
+ });
2039
+ return hasCategories.length ? true : false;
2040
+ }
2041
+ coupomUserValidation(coupon, user) {
2042
+ if (!user || coupon.exclusivityType.includes(Exclusivities.ALL_USERS))
2043
+ return true;
2044
+ let userTypes = [];
2045
+ if (coupon.exclusivityType.includes(Exclusivities.COLLABORATORS) &&
2046
+ this.emailIsFromCollaborator(user.email.toLocaleLowerCase()))
2047
+ userTypes.push(Exclusivities.COLLABORATORS);
2048
+ if (coupon.exclusivityType.includes(Exclusivities.SPECIFIC_USER) &&
2049
+ coupon.userExclusiveEmail.includes(user.email.toLocaleLowerCase()))
2050
+ userTypes.push(Exclusivities.SPECIFIC_USER);
2051
+ if (coupon.exclusivityType.includes(Exclusivities.ACTIVE_SUBSCRIBER) &&
2052
+ user.isSubscriber &&
2053
+ user.subscriptionPlan != '')
2054
+ userTypes.push(Exclusivities.ACTIVE_SUBSCRIBER);
2055
+ if (user.isSubscriber &&
2056
+ user.subscriptionPlan == '' &&
2057
+ coupon.exclusivityType.includes(Exclusivities.INACTIVE_SUBSCRIBER))
2058
+ userTypes.push(Exclusivities.INACTIVE_SUBSCRIBER);
2059
+ if (coupon.exclusivityType.includes(Exclusivities.NON_SUBSCRIBER) && !user.isSubscriber)
2060
+ userTypes.push(Exclusivities.NON_SUBSCRIBER);
2061
+ return coupon.exclusivityType.some((r) => userTypes.includes(r));
2062
+ }
2063
+ async getCouponCategoriesId(productsCategories) {
2064
+ const couponCategories = [];
2065
+ for (let index = 0; index < productsCategories.length; index++) {
2066
+ const category = await this.categoryRepository.get({
2067
+ id: productsCategories[index],
2068
+ });
2069
+ if (category) {
2070
+ const children = await this.categoryRepository.getChildren(parseInt(productsCategories[index]));
2071
+ couponCategories.push(category.id, ...children.map((c) => c.id.toString()));
2072
+ }
2073
+ }
2074
+ return [...new Set(couponCategories)];
2075
+ }
2076
+ async getLineItensEligebleForDiscount(productsCategories, checkout) {
2077
+ let lineItensDiscount = [];
2078
+ const couponCategories = await this.getCouponCategoriesId(productsCategories);
2079
+ if (productsCategories && productsCategories.length) {
2080
+ lineItensDiscount = checkout.lineItems?.filter((item) => {
2081
+ if (item.isGift)
2082
+ return false;
2083
+ if (item.categories?.length) {
2084
+ return item.categories.some((c) => couponCategories.some((cat) => cat == c));
2085
+ }
2086
+ return true;
2087
+ });
2088
+ }
2089
+ else {
2090
+ lineItensDiscount = checkout.lineItems.filter((item) => !item.isGift);
2091
+ }
2092
+ return lineItensDiscount;
2093
+ }
2094
+ calcCheckoutSubtotal(lineItens, user) {
2095
+ return (lineItens
2096
+ ?.filter((item) => !item.isGift)
2097
+ .reduce((acc, curr) => user?.isSubscriber && curr.price.subscriberPrice
2098
+ ? acc + curr.price?.subscriberPrice * curr.quantity
2099
+ : acc + curr.pricePaid * curr.quantity, 0) || 0);
2100
+ }
2101
+ async getOrdersWithCoupon(coupon) {
2102
+ return await this.orderRepository
2103
+ .find({
2104
+ filters: {
2105
+ coupon: { id: coupon.id },
2106
+ status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
2107
+ },
2108
+ })
2109
+ .then((result) => result.data);
2110
+ }
2111
+ async getOrdersFromUser(email) {
2112
+ return await this.orderRepository
2113
+ .find({
2114
+ filters: {
2115
+ user: { email: { operator: Where.EQUALS, value: email } },
2116
+ status: { operator: Where.NOTEQUALS, value: OrderStatus.CANCELADO },
2117
+ },
2118
+ })
2119
+ .then((result) => result.data);
2120
+ }
2121
+ countOrdersWithUser(orders, email) {
2122
+ return orders.filter((o) => o.user.email == email).length;
2123
+ }
2124
+ getCouponUseLimits(coupon, checkoutType, user) {
2125
+ let couponUseLimits;
2126
+ if (checkoutType == CheckoutTypes.ECOMMERCE || checkoutType == CheckoutTypes.ALL) {
2127
+ if (coupon.exclusivityType.length === 1 &&
2128
+ (coupon.exclusivityType.at(0) === Exclusivities.SPECIFIC_USER ||
2129
+ coupon.exclusivityType.at(0) === Exclusivities.COLLABORATORS))
2130
+ couponUseLimits = coupon.useLimits.non_subscriber;
2131
+ else
2132
+ couponUseLimits = user && user.isSubscriber ? coupon.useLimits.subscriber : coupon.useLimits.non_subscriber;
2133
+ }
2134
+ else {
2135
+ couponUseLimits = coupon.useLimits.subscription;
2136
+ }
2137
+ return couponUseLimits;
2138
+ }
2139
+ }
2140
+ 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 });
2141
+ CouponService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, providedIn: 'root' });
2142
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: CouponService, decorators: [{
2143
+ type: Injectable,
2144
+ args: [{
2145
+ providedIn: 'root',
2146
+ }]
2147
+ }], ctorParameters: function () { return [{ type: undefined, decorators: [{
2148
+ type: Inject,
2149
+ args: ['CouponRepository']
2150
+ }] }, { type: i1$3.Shops, decorators: [{
2151
+ type: Inject,
2152
+ args: [DEFAULT_SHOP]
2153
+ }] }, { type: undefined, decorators: [{
2154
+ type: Inject,
2155
+ args: ['OrderRepository']
2156
+ }] }, { type: undefined, decorators: [{
2157
+ type: Inject,
2158
+ args: ['CategoryRepository']
2159
+ }] }]; } });
2160
+
2283
2161
  class CheckoutSubscriptionService {
2284
2162
  constructor(checkoutSubscriptionRepository, dataPersistence, couponService) {
2285
2163
  this.checkoutSubscriptionRepository = checkoutSubscriptionRepository;
@@ -2454,7 +2332,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2454
2332
  }] }, { type: undefined, decorators: [{
2455
2333
  type: Inject,
2456
2334
  args: ['ProductRepository']
2457
- }] }, { type: i1$2.Shops, decorators: [{
2335
+ }] }, { type: i1$3.Shops, decorators: [{
2458
2336
  type: Inject,
2459
2337
  args: [DEFAULT_SHOP]
2460
2338
  }] }]; } });
@@ -2476,7 +2354,7 @@ OrderService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "1
2476
2354
  OrderService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService });
2477
2355
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: OrderService, decorators: [{
2478
2356
  type: Injectable
2479
- }], ctorParameters: function () { return [{ type: i1$1.Firestore }, { type: i1$2.OrderFirestoreRepository, decorators: [{
2357
+ }], ctorParameters: function () { return [{ type: i1$1.Firestore }, { type: i1$3.OrderFirestoreRepository, decorators: [{
2480
2358
  type: Inject,
2481
2359
  args: ['OrderRepository']
2482
2360
  }] }]; } });
@@ -2486,6 +2364,8 @@ class AngularConnectModule {
2486
2364
  return {
2487
2365
  ngModule: AngularConnectModule,
2488
2366
  providers: [
2367
+ { provide: FIREBASE_APP_NAME, useValue: nameOrConfig },
2368
+ { provide: APP_CHECK_PROVIDER, useValue: options.appCheckProvider },
2489
2369
  {
2490
2370
  provide: CATEGORY_STRUCTURE,
2491
2371
  useClass: isNil(options?.oldCategoryStructure) || options?.oldCategoryStructure
@@ -2495,7 +2375,6 @@ class AngularConnectModule {
2495
2375
  { provide: PERSISTENCE_PROVIDER, useClass: options?.persistenceProvider || CookieDataPersistence },
2496
2376
  ...(isNil(defaultShop) ? [] : [{ provide: DEFAULT_SHOP, useValue: defaultShop }]),
2497
2377
  ...(isNil(options?.firebase) ? [] : [{ provide: FIREBASE_OPTIONS, useValue: options?.firebase }]),
2498
- ...(isNil(options?.firebase) ? [] : [{ provide: FIREBASE_APP_NAME, useValue: nameOrConfig }]),
2499
2378
  ...(isNil(options?.elasticSearch) ? [] : [{ provide: ES_CONFIG, useValue: options.elasticSearch }]),
2500
2379
  ...(isNil(options?.vertexConfig) ? [] : [{ provide: VERTEX_CONFIG, useValue: options.vertexConfig }]),
2501
2380
  ...(isNil(options?.hasura) ? [] : [{ provide: HASURA_OPTIONS, useValue: options.hasura }]),
@@ -2506,7 +2385,7 @@ class AngularConnectModule {
2506
2385
  }
2507
2386
  }
2508
2387
  AngularConnectModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
2509
- AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, imports: [i1$3.FirebaseAppModule, i2$1.StorageModule, AngularElasticSeachModule,
2388
+ AngularConnectModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "15.1.0", ngImport: i0, type: AngularConnectModule, imports: [i1$4.FirebaseAppModule, i2.AppCheckModule, i3.StorageModule, AngularElasticSeachModule,
2510
2389
  AngularVertexSeachModule,
2511
2390
  AngularFirebaseAuthModule,
2512
2391
  AngularFirestoreModule,
@@ -2541,14 +2420,34 @@ AngularConnectModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", ve
2541
2420
  useExisting: ProductsVertexSearch,
2542
2421
  },
2543
2422
  ], imports: [provideFirebaseApp((injector) => {
2544
- const appName = injector.get(FIREBASE_APP_NAME) || '[DEFAULT]';
2423
+ const appName = injector.get(FIREBASE_APP_NAME);
2545
2424
  try {
2546
- return getApp(appName);
2425
+ const app = appName ? getApp(appName) : getApp();
2426
+ return app;
2547
2427
  }
2548
2428
  catch (error) {
2429
+ console.warn('Firebase app not found, initializing new app');
2430
+ if (error instanceof Error)
2431
+ console.error(error.message);
2549
2432
  return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2550
2433
  }
2551
2434
  }),
2435
+ provideAppCheck((injector) => {
2436
+ const app = injector.get(FirebaseApp);
2437
+ try {
2438
+ const provider = injector.get(APP_CHECK_PROVIDER);
2439
+ if (provider)
2440
+ return initializeAppCheck(app, {
2441
+ provider,
2442
+ isTokenAutoRefreshEnabled: true,
2443
+ });
2444
+ }
2445
+ catch (error) {
2446
+ if (error instanceof Error)
2447
+ console.error(error.message);
2448
+ return;
2449
+ }
2450
+ }),
2552
2451
  provideStorage((injector) => getStorage(injector.get(FirebaseApp))),
2553
2452
  AngularElasticSeachModule,
2554
2453
  AngularVertexSeachModule,
@@ -2560,14 +2459,34 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.0", ngImpor
2560
2459
  args: [{
2561
2460
  imports: [
2562
2461
  provideFirebaseApp((injector) => {
2563
- const appName = injector.get(FIREBASE_APP_NAME) || '[DEFAULT]';
2462
+ const appName = injector.get(FIREBASE_APP_NAME);
2564
2463
  try {
2565
- return getApp(appName);
2464
+ const app = appName ? getApp(appName) : getApp();
2465
+ return app;
2566
2466
  }
2567
2467
  catch (error) {
2468
+ console.warn('Firebase app not found, initializing new app');
2469
+ if (error instanceof Error)
2470
+ console.error(error.message);
2568
2471
  return initializeApp(injector.get(FIREBASE_OPTIONS), appName);
2569
2472
  }
2570
2473
  }),
2474
+ provideAppCheck((injector) => {
2475
+ const app = injector.get(FirebaseApp);
2476
+ try {
2477
+ const provider = injector.get(APP_CHECK_PROVIDER);
2478
+ if (provider)
2479
+ return initializeAppCheck(app, {
2480
+ provider,
2481
+ isTokenAutoRefreshEnabled: true,
2482
+ });
2483
+ }
2484
+ catch (error) {
2485
+ if (error instanceof Error)
2486
+ console.error(error.message);
2487
+ return;
2488
+ }
2489
+ }),
2571
2490
  provideStorage((injector) => getStorage(injector.get(FirebaseApp))),
2572
2491
  AngularElasticSeachModule,
2573
2492
  AngularVertexSeachModule,