@infrab4a/connect 5.3.0-beta.14 → 5.3.0-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/index.cjs.js +552 -10
  2. package/index.esm.js +545 -11
  3. package/package.json +1 -1
  4. package/src/domain/catalog/models/category-brand.d.ts +17 -0
  5. package/src/domain/catalog/models/index.d.ts +1 -0
  6. package/src/domain/catalog/repositories/category-brand.repository.d.ts +4 -0
  7. package/src/domain/catalog/repositories/index.d.ts +1 -0
  8. package/src/domain/shopping/enums/index.d.ts +1 -0
  9. package/src/domain/shopping/enums/order-payment-status.enum.d.ts +10 -0
  10. package/src/domain/shopping/enums/payment-providers.enum.d.ts +2 -1
  11. package/src/domain/shopping/factories/index.d.ts +1 -0
  12. package/src/domain/shopping/factories/mercado-pago-payment-method.factory.d.ts +11 -0
  13. package/src/domain/shopping/factories/payment-provider.factory.d.ts +2 -0
  14. package/src/domain/shopping/models/payment-transaction.d.ts +2 -0
  15. package/src/domain/shopping/models/payment.d.ts +1 -0
  16. package/src/domain/shopping/services/antifraud-card.service.d.ts +2 -0
  17. package/src/domain/shopping/types/checkout-paylod-request.type.d.ts +2 -7
  18. package/src/domain/shopping/types/index.d.ts +2 -0
  19. package/src/domain/shopping/types/mercado-pago-card.type.d.ts +14 -0
  20. package/src/domain/shopping/types/mercado-pago-credentials.type.d.ts +5 -0
  21. package/src/domain/shopping/types/payment-card-info.type.d.ts +3 -0
  22. package/src/infra/firebase/firestore/repositories/catalog/category-brand-firestore.repository.d.ts +7 -0
  23. package/src/infra/firebase/firestore/repositories/catalog/index.d.ts +1 -0
  24. package/src/infra/index.d.ts +1 -0
  25. package/src/infra/mercado-pago/adapters/index.d.ts +3 -0
  26. package/src/infra/mercado-pago/adapters/mercado-pago-boleto-payment-axios.adapter.d.ts +8 -0
  27. package/src/infra/mercado-pago/adapters/mercado-pago-card-payment-axios.adapter.d.ts +20 -0
  28. package/src/infra/mercado-pago/adapters/mercado-pago-pix-payment-axios.adapter.d.ts +7 -0
  29. package/src/infra/mercado-pago/enums/index.d.ts +2 -0
  30. package/src/infra/mercado-pago/enums/mercado-pago-status-detail.enum.d.ts +33 -0
  31. package/src/infra/mercado-pago/enums/mercado-pago-status.enum.d.ts +10 -0
  32. package/src/infra/mercado-pago/helpers/index.d.ts +2 -0
  33. package/src/infra/mercado-pago/helpers/mercado-pago-request.helper.d.ts +60 -0
  34. package/src/infra/mercado-pago/helpers/mercado-pago-response.helper.d.ts +10 -0
  35. package/src/infra/mercado-pago/index.d.ts +4 -0
  36. package/src/infra/mercado-pago/types/index.d.ts +3 -0
  37. package/src/infra/mercado-pago/types/mercado-pago-request.type.d.ts +1 -0
  38. package/src/infra/mercado-pago/types/mercado-pago-response.type.d.ts +188 -0
  39. package/src/infra/mercado-pago/types/mercado-pago-status-detail.type.d.ts +2 -0
  40. package/src/infra/mercado-pago/types/mercado-pago-status.type.d.ts +2 -0
  41. package/src/infra/pagarme/adapters/helpers/pagarme-v5-request.helper.d.ts +1 -0
  42. package/src/infra/pagarme/types/v5/pagarmev5-order-request-payload.type.d.ts +1 -0
package/index.esm.js CHANGED
@@ -38,6 +38,18 @@ var OrderBlockedType;
38
38
  OrderBlockedType["Boleto"] = "Boleto";
39
39
  })(OrderBlockedType || (OrderBlockedType = {}));
40
40
 
41
+ var OrderPaymentStatus;
42
+ (function (OrderPaymentStatus) {
43
+ OrderPaymentStatus["Em processamento"] = "processing";
44
+ OrderPaymentStatus["Autorizada"] = "authorized";
45
+ OrderPaymentStatus["Pago"] = "paid";
46
+ OrderPaymentStatus["Estornada"] = "refunded";
47
+ OrderPaymentStatus["Aguardando pagamento"] = "waiting_payment";
48
+ OrderPaymentStatus["Aguardando estorno"] = "pending_refund";
49
+ OrderPaymentStatus["Recusada/N\u00E3o autorizada"] = "refused";
50
+ OrderPaymentStatus["Chargedback"] = "chargedback";
51
+ })(OrderPaymentStatus || (OrderPaymentStatus = {}));
52
+
41
53
  var PagarmePaymentStatus;
42
54
  (function (PagarmePaymentStatus) {
43
55
  PagarmePaymentStatus["Em processamento"] = "processing";
@@ -90,6 +102,7 @@ var PaymentProviders;
90
102
  PaymentProviders["PAGARME"] = "pagarMe";
91
103
  PaymentProviders["ADYEN"] = "adyen";
92
104
  PaymentProviders["GLAMPOINTS"] = "glampoints";
105
+ PaymentProviders["MERCADOPAGO"] = "mercadoPago";
93
106
  })(PaymentProviders || (PaymentProviders = {}));
94
107
 
95
108
  var TransactionPaymentMethods;
@@ -123,6 +136,9 @@ class AntifraudProviderFactory {
123
136
  class GlampointsPaymentMethodFactory extends BasePaymentMethodFactory {
124
137
  }
125
138
 
139
+ class MercadoPagoPaymentMethodFactory extends BasePaymentMethodFactory {
140
+ }
141
+
126
142
  class PagarmePaymentMethodFactory extends BasePaymentMethodFactory {
127
143
  }
128
144
 
@@ -733,6 +749,30 @@ __decorate([
733
749
  ], Category.prototype, "filters", void 0);
734
750
  registerClass('Category', Category);
735
751
 
752
+ class BrandCategory extends BaseModel {
753
+ get glamImages() {
754
+ return this.images?.[Shops.GLAMSHOP]
755
+ ? this.images[Shops.GLAMSHOP]
756
+ : {
757
+ brandBanner: null,
758
+ brandBannerMobile: null,
759
+ image: null,
760
+ };
761
+ }
762
+ get mensImages() {
763
+ return this.images?.[Shops.MENSMARKET]
764
+ ? this.images[Shops.MENSMARKET]
765
+ : {
766
+ brandBanner: null,
767
+ brandBannerMobile: null,
768
+ image: null,
769
+ };
770
+ }
771
+ static get identifiersFields() {
772
+ return ['id'];
773
+ }
774
+ }
775
+
736
776
  class CategoryCollectionChildren extends BaseModel {
737
777
  static get identifiersFields() {
738
778
  return ['collectionId', 'categoryId'];
@@ -1741,19 +1781,58 @@ class AntifraudCardService {
1741
1781
  constructor(orderRepository, orderBlockedRepository) {
1742
1782
  this.orderRepository = orderRepository;
1743
1783
  this.orderBlockedRepository = orderBlockedRepository;
1744
- this.LIMIT_ORDERS_DAY = 2;
1745
- this.LIMIT_ORDERS_WEEK = 7;
1746
- this.LIMIT_BLOCKED_ORDERS_DAY = 5;
1784
+ this.LIMIT_ORDERS_DAY = null;
1785
+ this.LIMIT_ORDERS_WEEK = null;
1747
1786
  }
1748
1787
  async validate(checkout, card) {
1788
+ this.setLimitsByUserType(checkout.user.isSubscriber);
1749
1789
  await this.validateBlockedOrderAttempts(checkout, card);
1750
1790
  await this.validateDayAndWeekOrderLimits(checkout, card);
1751
1791
  return true;
1752
1792
  }
1793
+ setLimitsByUserType(isSubscriber) {
1794
+ this.LIMIT_ORDERS_DAY = {
1795
+ subscriber: {
1796
+ cpf: 4,
1797
+ email: 4,
1798
+ phone: 4,
1799
+ card: 4,
1800
+ zip: 4,
1801
+ },
1802
+ nonSubscriber: {
1803
+ cpf: 2,
1804
+ email: 2,
1805
+ phone: 2,
1806
+ card: 2,
1807
+ zip: 2,
1808
+ },
1809
+ };
1810
+ this.LIMIT_ORDERS_WEEK = {
1811
+ subscriber: {
1812
+ cpf: 12,
1813
+ email: 12,
1814
+ phone: 12,
1815
+ card: 12,
1816
+ zip: Infinity,
1817
+ },
1818
+ nonSubscriber: {
1819
+ cpf: 7,
1820
+ email: 7,
1821
+ phone: 7,
1822
+ card: 7,
1823
+ zip: Infinity,
1824
+ },
1825
+ };
1826
+ this.LIMIT_BLOCKED_ORDERS_DAY = isSubscriber ? 7 : 5;
1827
+ }
1828
+ getLimitsByUserType(type, isSubscriber) {
1829
+ const limits = type === 'day' ? this.LIMIT_ORDERS_DAY : this.LIMIT_ORDERS_WEEK;
1830
+ return isSubscriber ? limits['subscriber'] : limits['nonSubscriber'];
1831
+ }
1753
1832
  async validateBlockedOrderAttempts(checkout, card) {
1754
1833
  const isValid = await this.verifyBlockedOrderAttempts(checkout, card);
1755
1834
  if (!isValid) {
1756
- throw new FraudValidationError('Cliente com mais de 5 compras negadas/bloqueadas no dia', {
1835
+ throw new FraudValidationError(`Cliente com mais de ${this.LIMIT_BLOCKED_ORDERS_DAY} compras negadas/bloqueadas no dia`, {
1757
1836
  checkoutId: checkout.id,
1758
1837
  userEmail: checkout.user.email,
1759
1838
  info: {
@@ -1767,7 +1846,7 @@ class AntifraudCardService {
1767
1846
  async validateDayAndWeekOrderLimits(checkout, card) {
1768
1847
  const isValid = await this.verifyDayAndWeekOrders(checkout, card);
1769
1848
  if (!isValid) {
1770
- throw new FraudValidationError('Cliente tentando comprar mais de 2 vezes no dia ou 7 vezes na semana', {
1849
+ throw new FraudValidationError('Cliente tentando comprar mais do que o permitido no dia/semana', {
1771
1850
  checkoutId: checkout.id,
1772
1851
  userEmail: checkout.user.email,
1773
1852
  info: {
@@ -1786,7 +1865,7 @@ class AntifraudCardService {
1786
1865
  await this.createBlockedOrderRecord({
1787
1866
  checkout,
1788
1867
  card,
1789
- reason: 'More than 5 attempts have failed',
1868
+ reason: `More than ${this.LIMIT_BLOCKED_ORDERS_DAY} attempts have failed`,
1790
1869
  key: 'Failed attempts',
1791
1870
  period: 'day',
1792
1871
  });
@@ -1907,26 +1986,28 @@ class AntifraudCardService {
1907
1986
  }
1908
1987
  async validateDayOrderLimits(checkout, params) {
1909
1988
  const ordersPerDay = await this.validateOrdersByRange(params, this.getDateRange('day'));
1989
+ const limits = this.getLimitsByUserType('day', checkout.user.isSubscriber);
1910
1990
  return this.checkOrderLimitsAndBlock({
1911
1991
  checkout,
1912
1992
  orderCounts: ordersPerDay,
1913
- limit: this.LIMIT_ORDERS_DAY,
1993
+ limit: limits,
1914
1994
  period: 'day',
1915
1995
  });
1916
1996
  }
1917
1997
  async validateWeekOrderLimits(checkout, params) {
1918
1998
  const ordersPerWeek = await this.validateOrdersByRange(params, this.getDateRange('week'));
1999
+ const limits = this.getLimitsByUserType('week', checkout.user.isSubscriber);
1919
2000
  return this.checkOrderLimitsAndBlock({
1920
2001
  checkout,
1921
2002
  orderCounts: ordersPerWeek,
1922
- limit: this.LIMIT_ORDERS_WEEK,
2003
+ limit: limits,
1923
2004
  period: 'week',
1924
2005
  });
1925
2006
  }
1926
2007
  async checkOrderLimitsAndBlock(params) {
1927
2008
  const { checkout, orderCounts, limit, period } = params;
1928
2009
  for (const key in orderCounts) {
1929
- if (orderCounts[key] >= limit) {
2010
+ if (orderCounts[key] >= limit[key]) {
1930
2011
  await this.createBlockedOrderRecord({
1931
2012
  checkout,
1932
2013
  card: null,
@@ -4744,6 +4825,17 @@ const withCrudFirestore = (MixinBase) => {
4744
4825
  };
4745
4826
  };
4746
4827
 
4828
+ class BrandCategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4829
+ constructor({ firestore, interceptors, }) {
4830
+ super({
4831
+ firestore,
4832
+ collectionName: 'brandsCategory',
4833
+ model: BrandCategory,
4834
+ interceptors,
4835
+ });
4836
+ }
4837
+ }
4838
+
4747
4839
  class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4748
4840
  constructor({ firestore, interceptors }) {
4749
4841
  super({
@@ -9225,6 +9317,438 @@ __decorate([
9225
9317
  __metadata("design:returntype", Promise)
9226
9318
  ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
9227
9319
 
9320
+ class MercadoPagoRequestHelper {
9321
+ static build(data) {
9322
+ const { checkout, method, postback, card } = data;
9323
+ return {
9324
+ transaction_amount: +checkout.totalPrice.toFixed(2),
9325
+ notification_url: postback,
9326
+ metadata: {
9327
+ checkoutId: checkout.id,
9328
+ },
9329
+ payer: this.buildPayer(checkout, card),
9330
+ statement_descriptor: checkout.shop === Shops.GLAMSHOP ? 'Glam' : 'Mens Market',
9331
+ additional_info: {
9332
+ items: this.buildItems(checkout),
9333
+ },
9334
+ ...(method === 'credit_card' && this.buildCardPayment(card)),
9335
+ ...(method === 'pix' && this.buildPixPayment()),
9336
+ ...(method === 'boleto' && this.buildBoletoPayment(checkout)),
9337
+ };
9338
+ }
9339
+ static buildItems(checkout) {
9340
+ return checkout.lineItems
9341
+ .filter((item) => !item.isGift)
9342
+ .map((item) => {
9343
+ return {
9344
+ id: item.EAN,
9345
+ title: item.name,
9346
+ description: item.name,
9347
+ picture_url: item.image ?? null,
9348
+ category_id: item.category?.id ?? null,
9349
+ quantity: item.quantity,
9350
+ unit_price: +item.pricePaid.toFixed(2),
9351
+ };
9352
+ });
9353
+ }
9354
+ static buildPayer(checkout, card) {
9355
+ return {
9356
+ ...(card && { id: card.customerId }),
9357
+ first_name: checkout.user.firstName,
9358
+ last_name: checkout.user.lastName,
9359
+ email: checkout.user.email,
9360
+ identification: {
9361
+ type: 'CPF',
9362
+ number: checkout.user.cpf.replace(/\D/g, ''),
9363
+ },
9364
+ };
9365
+ }
9366
+ static buildFullPayer(checkout) {
9367
+ return {
9368
+ first_name: checkout.user.firstName,
9369
+ last_name: checkout.user.lastName,
9370
+ phone: {
9371
+ area_code: checkout.user.phone.substring(0, 2),
9372
+ number: checkout.user.phone.substring(2),
9373
+ },
9374
+ address: {
9375
+ zip_code: checkout.shippingAddress.zip,
9376
+ street_name: `${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9377
+ street_number: checkout.shippingAddress.number,
9378
+ neighborhood: checkout.shippingAddress.district,
9379
+ city: checkout.shippingAddress.city,
9380
+ federal_unit: checkout.shippingAddress.state,
9381
+ },
9382
+ };
9383
+ }
9384
+ static buildCardPayment(card) {
9385
+ return {
9386
+ installments: card.installments,
9387
+ token: card.cardId,
9388
+ binary_mode: true,
9389
+ capture: true,
9390
+ };
9391
+ }
9392
+ static buildPixPayment() {
9393
+ return {
9394
+ payment_method_id: 'pix',
9395
+ date_of_expiration: format(addDays(new Date(), 1), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
9396
+ };
9397
+ }
9398
+ static buildBoletoPayment(checkout) {
9399
+ return {
9400
+ payment_method_id: 'bolbradesco',
9401
+ date_of_expiration: format(addDays(new Date(), 3), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
9402
+ payer: {
9403
+ first_name: checkout.user.firstName,
9404
+ last_name: checkout.user.lastName,
9405
+ email: checkout.user.email,
9406
+ identification: {
9407
+ type: 'CPF',
9408
+ number: checkout.user.cpf.replace(/\D/g, ''),
9409
+ },
9410
+ phone: {
9411
+ area_code: checkout.user.phone.substring(0, 2),
9412
+ number: checkout.user.phone.substring(2),
9413
+ },
9414
+ address: {
9415
+ zip_code: checkout.shippingAddress.zip.replace(/\D/g, ''),
9416
+ street_name: `${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9417
+ street_number: checkout.shippingAddress.number,
9418
+ neighborhood: checkout.shippingAddress.district,
9419
+ city: checkout.shippingAddress.city,
9420
+ federal_unit: checkout.shippingAddress.state,
9421
+ },
9422
+ },
9423
+ };
9424
+ }
9425
+ }
9426
+
9427
+ class MercadoPagoResponseHelper {
9428
+ static build(method, checkout, response) {
9429
+ return Payment.toInstance({
9430
+ createdAt: new Date(),
9431
+ updatedAt: new Date(),
9432
+ userId: checkout.user.id,
9433
+ checkoutId: checkout.id,
9434
+ totalPrice: checkout.totalPrice,
9435
+ paymentProvider: PaymentProviders.MERCADOPAGO,
9436
+ mercadoPagoId: response.id,
9437
+ transaction: this.buildPaymentTransaction(method, response),
9438
+ });
9439
+ }
9440
+ static buildPaymentTransaction(method, response) {
9441
+ return PaymentTransaction.toInstance({
9442
+ id: response.id.toString(),
9443
+ acquirer_name: PaymentProviders.MERCADOPAGO,
9444
+ amount: response.transaction_amount,
9445
+ status: this.statusMapping(response.status),
9446
+ status_reason: response.status_detail?.toString(),
9447
+ payment_method: method,
9448
+ currency: response.currency_id?.toString(),
9449
+ paid_amount: response.transaction_details?.total_paid_amount ?? null,
9450
+ paid_at: response.date_approved ?? null,
9451
+ charger_id: response.charges_details?.at(0)?.id?.toString() ?? null,
9452
+ ...(method == TransactionPaymentMethods.PIX && this.getPixReponse(response)),
9453
+ ...(method == TransactionPaymentMethods.CARD && this.getCardReponse(response)),
9454
+ ...(method == TransactionPaymentMethods.BANKSLIP && this.getBoletoReponse(response)),
9455
+ });
9456
+ }
9457
+ static getBoletoReponse(response) {
9458
+ return {
9459
+ boleto_url: response.transaction_details?.external_resource_url?.toString(),
9460
+ boleto_barcode: response.transaction_details?.barcode?.content?.toString(),
9461
+ boleto_line: response.transaction_details?.digitable_line?.toString(),
9462
+ boleto_expiration_date: response.date_of_expiration?.toString(),
9463
+ boleto_document_number: response.transaction_details?.verification_code?.toString(),
9464
+ };
9465
+ }
9466
+ static getPixReponse(response) {
9467
+ return {
9468
+ pix_qr_code: response.point_of_interaction?.transaction_data?.qr_code,
9469
+ pix_expiration_date: response.date_of_expiration?.toString(),
9470
+ };
9471
+ }
9472
+ static getCardReponse(response) {
9473
+ return {
9474
+ soft_descriptor: response.statement_descriptor?.toString(),
9475
+ installments: response.installments,
9476
+ card_brand: response.payment_method_id?.toString(),
9477
+ card_first_digits: response.card?.first_six_digits?.toString(),
9478
+ card_last_digits: response.card?.last_four_digits?.toString(),
9479
+ card_id: response.card?.id?.toString(),
9480
+ card_holder_name: response.card?.cardholder?.name?.toString(),
9481
+ card_expiration_month: response.card?.expiration_month?.toString(),
9482
+ card_expiration_year: response.card?.expiration_year?.toString(),
9483
+ capture_method: response.payment_type_id?.toString(),
9484
+ authorization_code: response.authorization_code?.toString(),
9485
+ paid_amount: this.statusMapping(response.status) == 'paid' ? response.transaction_details?.total_paid_amount : null,
9486
+ paid_at: this.statusMapping(response.status) == 'paid' ? response.date_approved : null,
9487
+ };
9488
+ }
9489
+ static statusMapping(status) {
9490
+ const statusMap = {
9491
+ approved: 'paid',
9492
+ pending: 'waiting_payment',
9493
+ in_process: 'processing',
9494
+ rejected: 'refused',
9495
+ cancelled: 'refused',
9496
+ refunded: 'refunded',
9497
+ charged_back: 'chargedback',
9498
+ };
9499
+ return statusMap[status] || status;
9500
+ }
9501
+ }
9502
+
9503
+ class MercadoPagoBankSlipAxiosAdapter {
9504
+ constructor(credentials, paymentRepository) {
9505
+ this.credentials = credentials;
9506
+ this.paymentRepository = paymentRepository;
9507
+ }
9508
+ async pay(checkout) {
9509
+ try {
9510
+ const payload = MercadoPagoRequestHelper.build({
9511
+ checkout,
9512
+ method: 'boleto',
9513
+ postback: this.credentials.postback,
9514
+ });
9515
+ console.warn('[MERCADO PAGO BOLETO DATA TO SEND]', JSON.stringify(payload));
9516
+ const { data } = await axios({
9517
+ method: 'POST',
9518
+ url: `${this.credentials.url}/v1/payments`,
9519
+ headers: {
9520
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
9521
+ Authorization: `Bearer ${this.credentials.api_key}`,
9522
+ 'Content-Type': 'application/json',
9523
+ },
9524
+ data: payload,
9525
+ });
9526
+ console.warn('[MERCADO PAGO RESPONSE BOLETO DATA]', JSON.stringify(data));
9527
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(TransactionPaymentMethods.BANKSLIP, checkout, data));
9528
+ return payment;
9529
+ }
9530
+ catch (error) {
9531
+ if (error instanceof AxiosError) {
9532
+ console.warn(JSON.stringify(error.response.data.message));
9533
+ }
9534
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
9535
+ checkoutId: checkout.id,
9536
+ userEmail: checkout.user.email,
9537
+ info: error.response.data?.message || error.message?.toString(),
9538
+ });
9539
+ }
9540
+ }
9541
+ getBoletoTransaction(paymentId) {
9542
+ throw new Error('Method not implemented.');
9543
+ }
9544
+ }
9545
+
9546
+ class MercadoPagoCardAxiosAdapter {
9547
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
9548
+ this.credentials = credentials;
9549
+ this.paymentRepository = paymentRepository;
9550
+ this.orderBlockedRepository = orderBlockedRepository;
9551
+ }
9552
+ async pay(checkout, card) {
9553
+ try {
9554
+ const payload = await this.getPaymentPayload(checkout, card);
9555
+ console.warn('[MERCADO PAGO CARD DATA TO SEND]', JSON.stringify(payload));
9556
+ const { data } = await axios({
9557
+ method: 'POST',
9558
+ url: `${this.credentials.url}/v1/payments`,
9559
+ headers: {
9560
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
9561
+ Authorization: `Bearer ${this.credentials.api_key}`,
9562
+ 'Content-Type': 'application/json',
9563
+ },
9564
+ data: payload,
9565
+ });
9566
+ console.warn('[MERCADO PAGO RESPONSE CARD DATA]', JSON.stringify(data));
9567
+ if (data.status == MercadoPagoStatusEnum.rejected) {
9568
+ await this.orderBlockedRepository.createBlockedOrderOrPayment({
9569
+ checkout,
9570
+ blockType: 'Card not authorized',
9571
+ type: 'Card',
9572
+ limiteRange: 'day',
9573
+ card,
9574
+ });
9575
+ throw new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', {
9576
+ checkoutId: checkout.id,
9577
+ userEmail: checkout.user.email,
9578
+ info: data,
9579
+ });
9580
+ }
9581
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(TransactionPaymentMethods.CARD, checkout, data));
9582
+ return payment;
9583
+ }
9584
+ catch (error) {
9585
+ if (error instanceof AxiosError) {
9586
+ console.warn(JSON.stringify(error.response.data.message));
9587
+ }
9588
+ throw new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', {
9589
+ checkoutId: checkout.id,
9590
+ userEmail: checkout.user.email,
9591
+ info: error.response.data?.message || error.message?.toString(),
9592
+ });
9593
+ }
9594
+ }
9595
+ async getPaymentPayload(checkout, card) {
9596
+ const cardResponse = await this.getCardByToken(card.customerId, card.cardId, card.cardCvv);
9597
+ const payload = MercadoPagoRequestHelper.build({
9598
+ checkout,
9599
+ method: 'credit_card',
9600
+ postback: this.credentials.postback,
9601
+ card: {
9602
+ ...card,
9603
+ cardId: cardResponse.id,
9604
+ },
9605
+ });
9606
+ return payload;
9607
+ }
9608
+ async addCard(card, customer) {
9609
+ return;
9610
+ }
9611
+ async getCardByToken(customerId, token, cardCvv) {
9612
+ try {
9613
+ const payload = { cardId: token, customerId: customerId, securityCode: cardCvv };
9614
+ console.warn('payload getCardByToken', payload);
9615
+ const { data } = await axios({
9616
+ method: 'POST',
9617
+ url: `${this.credentials.url}/v1/card_tokens`,
9618
+ headers: {
9619
+ Authorization: `Bearer ${this.credentials.api_key}`,
9620
+ 'Content-Type': 'application/json',
9621
+ },
9622
+ data: payload,
9623
+ });
9624
+ return data;
9625
+ }
9626
+ catch (error) {
9627
+ if (error instanceof AxiosError) {
9628
+ console.warn(JSON.stringify(error.response.data.cause));
9629
+ }
9630
+ throw error;
9631
+ }
9632
+ }
9633
+ createCardHash(bu, shop, card) {
9634
+ return;
9635
+ }
9636
+ createTransaction(info) {
9637
+ return;
9638
+ }
9639
+ async createOrUpdateCustomer(customer) {
9640
+ const { data } = await axios({
9641
+ method: 'POST',
9642
+ url: `${this.credentials.url}/v1/customers`,
9643
+ headers: {
9644
+ Authorization: `Bearer ${this.credentials.api_key}`,
9645
+ 'Content-Type': 'application/json',
9646
+ },
9647
+ data: {
9648
+ email: customer.email,
9649
+ first_name: customer.firstName,
9650
+ last_name: customer.lastName,
9651
+ phone: {
9652
+ area_code: customer.phone.substring(0, 2),
9653
+ number: customer.phone.substring(2),
9654
+ },
9655
+ identification: {
9656
+ type: 'CPF',
9657
+ number: customer.cpf.replace(/\D/g, ''),
9658
+ },
9659
+ },
9660
+ });
9661
+ return data;
9662
+ }
9663
+ }
9664
+
9665
+ class MercadoPagoPixAxiosAdapter {
9666
+ constructor(credentials, paymentRepository) {
9667
+ this.credentials = credentials;
9668
+ this.paymentRepository = paymentRepository;
9669
+ }
9670
+ async pay(checkout) {
9671
+ try {
9672
+ const payload = MercadoPagoRequestHelper.build({
9673
+ checkout,
9674
+ method: 'pix',
9675
+ postback: this.credentials.postback,
9676
+ });
9677
+ console.warn('[MERCADO PAGO PIX DATA TO SEND]', JSON.stringify(payload));
9678
+ const { data } = await axios({
9679
+ method: 'POST',
9680
+ url: `${this.credentials.url}/v1/payments`,
9681
+ headers: {
9682
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
9683
+ Authorization: `Bearer ${this.credentials.api_key}`,
9684
+ 'Content-Type': 'application/json',
9685
+ },
9686
+ data: payload,
9687
+ });
9688
+ console.warn('[MERCADO PAGO RESPONSE PIX DATA]', JSON.stringify(data));
9689
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(TransactionPaymentMethods.PIX, checkout, data));
9690
+ return payment;
9691
+ }
9692
+ catch (error) {
9693
+ if (error instanceof AxiosError) {
9694
+ console.warn(JSON.stringify(error.response.data.message));
9695
+ }
9696
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
9697
+ checkoutId: checkout.id,
9698
+ userEmail: checkout.user.email,
9699
+ info: error.response.data?.message || error.message?.toString(),
9700
+ });
9701
+ }
9702
+ }
9703
+ }
9704
+
9705
+ var MercadoPagoStatusDetailEnum;
9706
+ (function (MercadoPagoStatusDetailEnum) {
9707
+ MercadoPagoStatusDetailEnum["accredited"] = "accredited";
9708
+ MercadoPagoStatusDetailEnum["partially_refunded"] = "partially_refunded";
9709
+ MercadoPagoStatusDetailEnum["pending_capture"] = "pending_capture";
9710
+ MercadoPagoStatusDetailEnum["offline_process"] = "offline_process";
9711
+ MercadoPagoStatusDetailEnum["pending_contingency"] = "pending_contingency";
9712
+ MercadoPagoStatusDetailEnum["pending_review_manual"] = "pending_review_manual";
9713
+ MercadoPagoStatusDetailEnum["pending_waiting_transfer"] = "pending_waiting_transfer";
9714
+ MercadoPagoStatusDetailEnum["pending_waiting_payment"] = "pending_waiting_payment";
9715
+ MercadoPagoStatusDetailEnum["pending_challenge"] = "pending_challenge";
9716
+ MercadoPagoStatusDetailEnum["bank_error"] = "bank_error";
9717
+ MercadoPagoStatusDetailEnum["cc_rejected_3ds_mandatory"] = "cc_rejected_3ds_mandatory";
9718
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_card_number"] = "cc_rejected_bad_filled_card_number";
9719
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_date"] = "cc_rejected_bad_filled_date";
9720
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_other"] = "cc_rejected_bad_filled_other";
9721
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_security_code"] = "cc_rejected_bad_filled_security_code";
9722
+ MercadoPagoStatusDetailEnum["cc_rejected_blacklist"] = "cc_rejected_blacklist";
9723
+ MercadoPagoStatusDetailEnum["cc_rejected_call_for_authorize"] = "cc_rejected_call_for_authorize";
9724
+ MercadoPagoStatusDetailEnum["cc_rejected_card_disabled"] = "cc_rejected_card_disabled";
9725
+ MercadoPagoStatusDetailEnum["cc_rejected_card_error"] = "cc_rejected_card_error";
9726
+ MercadoPagoStatusDetailEnum["cc_rejected_duplicated_payment"] = "cc_rejected_duplicated_payment";
9727
+ MercadoPagoStatusDetailEnum["cc_rejected_high_risk"] = "cc_rejected_high_risk";
9728
+ MercadoPagoStatusDetailEnum["cc_rejected_insufficient_amount"] = "cc_rejected_insufficient_amount";
9729
+ MercadoPagoStatusDetailEnum["cc_rejected_invalid_installments"] = "cc_rejected_invalid_installments";
9730
+ MercadoPagoStatusDetailEnum["cc_rejected_max_attempts"] = "cc_rejected_max_attempts";
9731
+ MercadoPagoStatusDetailEnum["cc_rejected_other_reason"] = "cc_rejected_other_reason";
9732
+ MercadoPagoStatusDetailEnum["cc_amount_rate_limit_exceeded"] = "cc_amount_rate_limit_exceeded";
9733
+ MercadoPagoStatusDetailEnum["rejected_insufficient_data"] = "rejected_insufficient_data";
9734
+ MercadoPagoStatusDetailEnum["rejected_by_bank"] = "rejected_by_bank";
9735
+ MercadoPagoStatusDetailEnum["rejected_by_regulations"] = "rejected_by_regulations";
9736
+ MercadoPagoStatusDetailEnum["insufficient_amount"] = "insufficient_amount";
9737
+ MercadoPagoStatusDetailEnum["cc_rejected_card_type_not_allowed"] = "cc_rejected_card_type_not_allowed";
9738
+ })(MercadoPagoStatusDetailEnum || (MercadoPagoStatusDetailEnum = {}));
9739
+
9740
+ var MercadoPagoStatusEnum;
9741
+ (function (MercadoPagoStatusEnum) {
9742
+ MercadoPagoStatusEnum["approved"] = "approved";
9743
+ MercadoPagoStatusEnum["authorized"] = "authorized";
9744
+ MercadoPagoStatusEnum["pending"] = "pending";
9745
+ MercadoPagoStatusEnum["in_process"] = "in_process";
9746
+ MercadoPagoStatusEnum["rejected"] = "rejected";
9747
+ MercadoPagoStatusEnum["cancelled"] = "cancelled";
9748
+ MercadoPagoStatusEnum["refunded"] = "refunded";
9749
+ MercadoPagoStatusEnum["charged_back"] = "charged_back";
9750
+ })(MercadoPagoStatusEnum || (MercadoPagoStatusEnum = {}));
9751
+
9228
9752
  class PagarmeBankSlipAxiosAdapter {
9229
9753
  constructor(credentials, paymentRepository) {
9230
9754
  this.credentials = credentials;
@@ -9372,15 +9896,17 @@ class PagarMeV5RequestHelper {
9372
9896
  customer: this.buildCustomer(checkout),
9373
9897
  shipping: this.buildShipping(checkout),
9374
9898
  payments: this.buildPayment(checkout, method, card),
9899
+ ...this.buildAdditionalInfo(checkout),
9375
9900
  };
9376
9901
  }
9377
9902
  static buildItems(checkout) {
9903
+ const isSubscriber = checkout.user?.isSubscriber ?? false;
9378
9904
  return checkout.lineItems
9379
9905
  .filter((item) => !item.isGift)
9380
9906
  .map((item) => {
9381
9907
  return {
9382
9908
  amount: Math.floor(item.pricePaid * 100),
9383
- description: item.name,
9909
+ description: isSubscriber ? `${item.name} - ASSINANTE` : item.name,
9384
9910
  quantity: item.quantity,
9385
9911
  code: item.EAN,
9386
9912
  };
@@ -9477,6 +10003,14 @@ class PagarMeV5RequestHelper {
9477
10003
  },
9478
10004
  };
9479
10005
  }
10006
+ static buildAdditionalInfo(checkout) {
10007
+ const isSubscriber = checkout.user?.isSubscriber ?? false;
10008
+ if (isSubscriber)
10009
+ return {
10010
+ antifraude_enabled: false,
10011
+ };
10012
+ return {};
10013
+ }
9480
10014
  }
9481
10015
 
9482
10016
  class PagarMeV5ResponseHelper {
@@ -10209,4 +10743,4 @@ class ProductsVertexSearch {
10209
10743
  }
10210
10744
  }
10211
10745
 
10212
- export { AccessoryImportances, Address, AdyenCardAxiosAdapter, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BrandEquityOptions, BusinessError, BusinessUnitEnum, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, FraudValidationError, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, Group, GroupFirestoreRepository, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, NotFoundError, ObsEmitter, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderBlockedType, OrderFirestoreRepository, OrderStatus, PagarMeV5OrderStatus, PagarMeV5PaymentStatus, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, PagarmeV5BankSlipAxiosAdapter, PagarmeV5CardAxiosAdapter, PagarmeV5PixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductCatalogHasuraGraphQL, ProductCatalogHasuraGraphQLRepository, ProductErrors, ProductErrorsHasuraGraphQL, ProductErrorsHasuraGraphQLRepository, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductReview, ProductReviewHasuraGraphQLRepository, ProductSpents, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RestCacheAdapter, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, StockLimitError, StockOutError, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, TransactionPaymentMethods, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, deserialize, getClass, is, isDebuggable, isUUID, parseDateTime, registerClass, resolveClass, serialize, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };
10746
+ export { AccessoryImportances, Address, AdyenCardAxiosAdapter, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BrandCategory, BrandCategoryFirestoreRepository, BrandEquityOptions, BusinessError, BusinessUnitEnum, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, FraudValidationError, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, Group, GroupFirestoreRepository, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, MercadoPagoBankSlipAxiosAdapter, MercadoPagoCardAxiosAdapter, MercadoPagoPaymentMethodFactory, MercadoPagoPixAxiosAdapter, MercadoPagoRequestHelper, MercadoPagoResponseHelper, MercadoPagoStatusDetailEnum, MercadoPagoStatusEnum, NotFoundError, ObsEmitter, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderBlockedType, OrderFirestoreRepository, OrderPaymentStatus, OrderStatus, PagarMeV5OrderStatus, PagarMeV5PaymentStatus, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, PagarmeV5BankSlipAxiosAdapter, PagarmeV5CardAxiosAdapter, PagarmeV5PixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductCatalogHasuraGraphQL, ProductCatalogHasuraGraphQLRepository, ProductErrors, ProductErrorsHasuraGraphQL, ProductErrorsHasuraGraphQLRepository, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductReview, ProductReviewHasuraGraphQLRepository, ProductSpents, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RestCacheAdapter, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, StockLimitError, StockOutError, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, TransactionPaymentMethods, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, deserialize, getClass, is, isDebuggable, isUUID, parseDateTime, registerClass, resolveClass, serialize, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };