@infrab4a/connect 5.3.0-beta.2 → 5.3.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/index.cjs.js +1990 -242
  2. package/index.esm.js +1976 -244
  3. package/package.json +4 -3
  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/models/product-base.d.ts +1 -0
  7. package/src/domain/catalog/models/product-review.d.ts +2 -0
  8. package/src/domain/catalog/models/product.d.ts +1 -0
  9. package/src/domain/catalog/models/types/brands-shop-menu.type.d.ts +13 -0
  10. package/src/domain/catalog/models/types/index.d.ts +1 -0
  11. package/src/domain/catalog/repositories/category-brand.repository.d.ts +4 -0
  12. package/src/domain/catalog/repositories/category.repository.d.ts +1 -0
  13. package/src/domain/catalog/repositories/index.d.ts +2 -0
  14. package/src/domain/catalog/repositories/product-catalog.repository.d.ts +17 -0
  15. package/src/domain/shopping/enums/index.d.ts +3 -0
  16. package/src/domain/shopping/enums/order-payment-status.enum.d.ts +10 -0
  17. package/src/domain/shopping/enums/pagarme-v5-payment-status.enum.d.ts +24 -0
  18. package/src/domain/shopping/enums/payment-providers.enum.d.ts +2 -1
  19. package/src/domain/shopping/enums/transaction-payment-methods.enum.d.ts +5 -0
  20. package/src/domain/shopping/factories/index.d.ts +1 -0
  21. package/src/domain/shopping/factories/mercado-pago-payment-method.factory.d.ts +11 -0
  22. package/src/domain/shopping/factories/payment-provider.factory.d.ts +2 -0
  23. package/src/domain/shopping/interfaces/payment-provider-card.interface.d.ts +10 -2
  24. package/src/domain/shopping/models/order.d.ts +7 -0
  25. package/src/domain/shopping/models/payment-transaction.d.ts +19 -2
  26. package/src/domain/shopping/models/payment.d.ts +3 -1
  27. package/src/domain/shopping/services/antifraud-card.service.d.ts +2 -0
  28. package/src/domain/shopping/types/card-info.type.d.ts +1 -0
  29. package/src/domain/shopping/types/checkout-paylod-request.type.d.ts +2 -7
  30. package/src/domain/shopping/types/index.d.ts +3 -0
  31. package/src/domain/shopping/types/mercado-pago-card.type.d.ts +14 -0
  32. package/src/domain/shopping/types/mercado-pago-credentials.type.d.ts +5 -0
  33. package/src/domain/shopping/types/pagarme-card.type.d.ts +9 -3
  34. package/src/domain/shopping/types/pagarme-credentials-v5.type.d.ts +4 -0
  35. package/src/domain/shopping/types/pagarme-credentials.type.d.ts +9 -3
  36. package/src/domain/shopping/types/payment-card-info.type.d.ts +3 -0
  37. package/src/domain/users/models/user-payment-method.d.ts +2 -0
  38. package/src/infra/firebase/firestore/repositories/catalog/category-brand-firestore.repository.d.ts +7 -0
  39. package/src/infra/firebase/firestore/repositories/catalog/category-firestore.repository.d.ts +1 -0
  40. package/src/infra/firebase/firestore/repositories/catalog/index.d.ts +1 -0
  41. package/src/infra/hasura-graphql/models/index.d.ts +1 -0
  42. package/src/infra/hasura-graphql/models/product-catalog-hasura-graphql.d.ts +16 -0
  43. package/src/infra/hasura-graphql/models/variant-hasura-graphql.d.ts +7 -0
  44. package/src/infra/hasura-graphql/repositories/catalog/category-hasura-graphql.repository.d.ts +1 -0
  45. package/src/infra/hasura-graphql/repositories/catalog/index.d.ts +1 -0
  46. package/src/infra/hasura-graphql/repositories/catalog/product-catalog-hasura-graphql.repository.d.ts +22 -0
  47. package/src/infra/hasura-graphql/repositories/catalog/variant-hasura-graphql.repository.d.ts +1 -0
  48. package/src/infra/hasura-graphql/repositories/catalog/wishlist-hasura-graphql.repository.d.ts +1 -0
  49. package/src/infra/index.d.ts +1 -0
  50. package/src/infra/mercado-pago/adapters/index.d.ts +3 -0
  51. package/src/infra/mercado-pago/adapters/mercado-pago-boleto-payment-axios.adapter.d.ts +8 -0
  52. package/src/infra/mercado-pago/adapters/mercado-pago-card-payment-axios.adapter.d.ts +20 -0
  53. package/src/infra/mercado-pago/adapters/mercado-pago-pix-payment-axios.adapter.d.ts +7 -0
  54. package/src/infra/mercado-pago/enums/index.d.ts +2 -0
  55. package/src/infra/mercado-pago/enums/mercado-pago-status-detail.enum.d.ts +33 -0
  56. package/src/infra/mercado-pago/enums/mercado-pago-status.enum.d.ts +10 -0
  57. package/src/infra/mercado-pago/helpers/index.d.ts +2 -0
  58. package/src/infra/mercado-pago/helpers/mercado-pago-request.helper.d.ts +60 -0
  59. package/src/infra/mercado-pago/helpers/mercado-pago-response.helper.d.ts +10 -0
  60. package/src/infra/mercado-pago/index.d.ts +4 -0
  61. package/src/infra/mercado-pago/types/index.d.ts +3 -0
  62. package/src/infra/mercado-pago/types/mercado-pago-request.type.d.ts +1 -0
  63. package/src/infra/mercado-pago/types/mercado-pago-response.type.d.ts +188 -0
  64. package/src/infra/mercado-pago/types/mercado-pago-status-detail.type.d.ts +2 -0
  65. package/src/infra/mercado-pago/types/mercado-pago-status.type.d.ts +2 -0
  66. package/src/infra/pagarme/adapters/helpers/index.d.ts +2 -0
  67. package/src/infra/pagarme/adapters/helpers/pagarme-v5-request.helper.d.ts +13 -0
  68. package/src/infra/pagarme/adapters/helpers/pagarme-v5-response.helper.d.ts +10 -0
  69. package/src/infra/pagarme/adapters/index.d.ts +2 -3
  70. package/src/infra/pagarme/adapters/v4/index.d.ts +3 -0
  71. package/src/infra/pagarme/adapters/{pagarme-bank-slip-payment-axios.adapter.d.ts → v4/pagarme-bank-slip-payment-axios.adapter.d.ts} +4 -4
  72. package/src/infra/pagarme/adapters/{pagarme-card-payment-axios.adapter.d.ts → v4/pagarme-card-payment-axios.adapter.d.ts} +7 -6
  73. package/src/infra/pagarme/adapters/{pagarme-pix-payment-axios.adapter.d.ts → v4/pagarme-pix-payment-axios.adapter.d.ts} +4 -4
  74. package/src/infra/pagarme/adapters/v5/index.d.ts +3 -0
  75. package/src/infra/pagarme/adapters/v5/pagarmev5-bank-slip-payment-axios.adapter.d.ts +11 -0
  76. package/src/infra/pagarme/adapters/v5/pagarmev5-card-payment-axios.adapter.d.ts +24 -0
  77. package/src/infra/pagarme/adapters/v5/pagarmev5-pix-payment-axios.adapter.d.ts +10 -0
  78. package/src/infra/pagarme/index.d.ts +1 -0
  79. package/src/infra/pagarme/types/index.d.ts +1 -0
  80. package/src/infra/pagarme/types/v5/index.d.ts +4 -0
  81. package/src/infra/pagarme/types/v5/pagarmev5-customer.type.d.ts +19 -0
  82. package/src/infra/pagarme/types/v5/pagarmev5-order-request-payload.type.d.ts +90 -0
  83. package/src/infra/pagarme/types/v5/pagarmev5-order-response.type.d.ts +126 -0
  84. package/src/infra/pagarme/types/v5/pagarmev5-postback-response.type.d.ts +11 -0
  85. package/src/utils/index.d.ts +2 -1
package/index.esm.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import 'reflect-metadata';
2
2
  import { __decorate, __metadata } from 'tslib';
3
3
  import { plainToInstance, instanceToPlain, Type } from 'class-transformer';
4
- import { parseISO, format, startOfDay, endOfDay, subDays, addDays } from 'date-fns';
4
+ import { parseISO, startOfDay, endOfDay, addHours, subDays, format, addDays } from 'date-fns';
5
5
  export { add, addBusinessDays, addDays, addMonths, addYears, endOfDay, format, formatISO9075, parseISO, startOfDay, sub, subDays } from 'date-fns';
6
+ import { utcToZonedTime } from 'date-fns-tz';
7
+ export { formatInTimeZone } from 'date-fns-tz';
6
8
  import { compact, get, isNil, isArray, first, last, flatten, isString, omit, each, unset, isObject, isEmpty, isDate, isBoolean, isInteger, isNumber, isNaN as isNaN$1, set, chunk, sortBy } from 'lodash';
7
9
  export { chunk, each, get, isBoolean, isDate, isEmpty, isInteger, isNaN, isNil, isNumber, isObject, isString, now, omit, pick, set, sortBy, unset } from 'lodash';
8
10
  import { debug } from 'debug';
@@ -36,6 +38,18 @@ var OrderBlockedType;
36
38
  OrderBlockedType["Boleto"] = "Boleto";
37
39
  })(OrderBlockedType || (OrderBlockedType = {}));
38
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
+
39
53
  var PagarmePaymentStatus;
40
54
  (function (PagarmePaymentStatus) {
41
55
  PagarmePaymentStatus["Em processamento"] = "processing";
@@ -48,6 +62,33 @@ var PagarmePaymentStatus;
48
62
  PagarmePaymentStatus["Chargedback"] = "chargedback";
49
63
  })(PagarmePaymentStatus || (PagarmePaymentStatus = {}));
50
64
 
65
+ var PagarMeV5PaymentStatus;
66
+ (function (PagarMeV5PaymentStatus) {
67
+ PagarMeV5PaymentStatus["Em processamento"] = "processing";
68
+ PagarMeV5PaymentStatus["Gerado"] = "generated";
69
+ PagarMeV5PaymentStatus["Visualizado"] = "viewed";
70
+ PagarMeV5PaymentStatus["Pago a menor"] = "underpaid";
71
+ PagarMeV5PaymentStatus["Pago a maior"] = "overpaid";
72
+ PagarMeV5PaymentStatus["Aguardando pagamento"] = "waiting_payment";
73
+ PagarMeV5PaymentStatus["Pago"] = "paid";
74
+ PagarMeV5PaymentStatus["Aguardando estorno"] = "pending_refund";
75
+ PagarMeV5PaymentStatus["Autorizada pendente de captura"] = "authorized_pending_capture";
76
+ PagarMeV5PaymentStatus["N\u00E3o autorizada"] = "not_authorized";
77
+ PagarMeV5PaymentStatus["Capturada"] = "captured";
78
+ PagarMeV5PaymentStatus["Aguardando captura"] = "waiting_capture";
79
+ PagarMeV5PaymentStatus["Com erro"] = "with_error";
80
+ PagarMeV5PaymentStatus["Estornado"] = "refunded";
81
+ PagarMeV5PaymentStatus["Cancelado"] = "voided";
82
+ PagarMeV5PaymentStatus["Falha"] = "failed";
83
+ })(PagarMeV5PaymentStatus || (PagarMeV5PaymentStatus = {}));
84
+ var PagarMeV5OrderStatus;
85
+ (function (PagarMeV5OrderStatus) {
86
+ PagarMeV5OrderStatus["Pendente"] = "pending";
87
+ PagarMeV5OrderStatus["Pago"] = "paid";
88
+ PagarMeV5OrderStatus["Cancelado"] = "canceled";
89
+ PagarMeV5OrderStatus["Falha"] = "failed";
90
+ })(PagarMeV5OrderStatus || (PagarMeV5OrderStatus = {}));
91
+
51
92
  var PaymentMethods;
52
93
  (function (PaymentMethods) {
53
94
  PaymentMethods["CARD"] = "card";
@@ -61,8 +102,16 @@ var PaymentProviders;
61
102
  PaymentProviders["PAGARME"] = "pagarMe";
62
103
  PaymentProviders["ADYEN"] = "adyen";
63
104
  PaymentProviders["GLAMPOINTS"] = "glampoints";
105
+ PaymentProviders["MERCADOPAGO"] = "mercadoPago";
64
106
  })(PaymentProviders || (PaymentProviders = {}));
65
107
 
108
+ var TransactionPaymentMethods;
109
+ (function (TransactionPaymentMethods) {
110
+ TransactionPaymentMethods["CARD"] = "credit_card";
111
+ TransactionPaymentMethods["BANKSLIP"] = "boleto";
112
+ TransactionPaymentMethods["PIX"] = "pix";
113
+ })(TransactionPaymentMethods || (TransactionPaymentMethods = {}));
114
+
66
115
  class BasePaymentMethodFactory {
67
116
  constructor(methods) {
68
117
  this.methods = methods;
@@ -87,6 +136,9 @@ class AntifraudProviderFactory {
87
136
  class GlampointsPaymentMethodFactory extends BasePaymentMethodFactory {
88
137
  }
89
138
 
139
+ class MercadoPagoPaymentMethodFactory extends BasePaymentMethodFactory {
140
+ }
141
+
90
142
  class PagarmePaymentMethodFactory extends BasePaymentMethodFactory {
91
143
  }
92
144
 
@@ -697,6 +749,30 @@ __decorate([
697
749
  ], Category.prototype, "filters", void 0);
698
750
  registerClass('Category', Category);
699
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
+
700
776
  class CategoryCollectionChildren extends BaseModel {
701
777
  static get identifiersFields() {
702
778
  return ['collectionId', 'categoryId'];
@@ -770,6 +846,11 @@ class ProductReview extends BaseModel {
770
846
  return ['id'];
771
847
  }
772
848
  }
849
+ __decorate([
850
+ Type(resolveClass('Product')),
851
+ __metadata("design:type", Product)
852
+ ], ProductReview.prototype, "product", void 0);
853
+ registerClass('ProductReview', ProductReview);
773
854
 
774
855
  class ProductBase extends BaseModel {
775
856
  get evaluation() {
@@ -1700,19 +1781,58 @@ class AntifraudCardService {
1700
1781
  constructor(orderRepository, orderBlockedRepository) {
1701
1782
  this.orderRepository = orderRepository;
1702
1783
  this.orderBlockedRepository = orderBlockedRepository;
1703
- this.LIMIT_ORDERS_DAY = 2;
1704
- this.LIMIT_ORDERS_WEEK = 7;
1705
- this.LIMIT_BLOCKED_ORDERS_DAY = 5;
1784
+ this.LIMIT_ORDERS_DAY = null;
1785
+ this.LIMIT_ORDERS_WEEK = null;
1706
1786
  }
1707
1787
  async validate(checkout, card) {
1788
+ this.setLimitsByUserType(checkout.user.isSubscriber);
1708
1789
  await this.validateBlockedOrderAttempts(checkout, card);
1709
1790
  await this.validateDayAndWeekOrderLimits(checkout, card);
1710
1791
  return true;
1711
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
+ }
1712
1832
  async validateBlockedOrderAttempts(checkout, card) {
1713
1833
  const isValid = await this.verifyBlockedOrderAttempts(checkout, card);
1714
1834
  if (!isValid) {
1715
- 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`, {
1716
1836
  checkoutId: checkout.id,
1717
1837
  userEmail: checkout.user.email,
1718
1838
  info: {
@@ -1726,7 +1846,7 @@ class AntifraudCardService {
1726
1846
  async validateDayAndWeekOrderLimits(checkout, card) {
1727
1847
  const isValid = await this.verifyDayAndWeekOrders(checkout, card);
1728
1848
  if (!isValid) {
1729
- 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', {
1730
1850
  checkoutId: checkout.id,
1731
1851
  userEmail: checkout.user.email,
1732
1852
  info: {
@@ -1745,7 +1865,7 @@ class AntifraudCardService {
1745
1865
  await this.createBlockedOrderRecord({
1746
1866
  checkout,
1747
1867
  card,
1748
- reason: 'More than 5 attempts have failed',
1868
+ reason: `More than ${this.LIMIT_BLOCKED_ORDERS_DAY} attempts have failed`,
1749
1869
  key: 'Failed attempts',
1750
1870
  period: 'day',
1751
1871
  });
@@ -1754,15 +1874,17 @@ class AntifraudCardService {
1754
1874
  return true;
1755
1875
  }
1756
1876
  getTodayDateRange() {
1757
- const day = `${format(new Date(), 'yyyy-MM-dd')}T00:00:00`;
1758
- const endOfDay = `${format(new Date(), 'yyyy-MM-dd')}T23:59:59`;
1759
- return { day, endOfDay };
1877
+ const timeZone = 'America/Sao_Paulo';
1878
+ const today = utcToZonedTime(new Date(), timeZone);
1879
+ const day = startOfDay(today);
1880
+ const endOfDay$1 = endOfDay(today);
1881
+ return { day: addHours(day, 3), endOfDay: addHours(endOfDay$1, 3) };
1760
1882
  }
1761
1883
  async getBlockedOrdersByMultipleCriteria(checkout, dateRange) {
1762
1884
  const { day, endOfDay } = dateRange;
1763
1885
  const dateFilter = [
1764
- { operator: Where.GTE, value: new Date(day) },
1765
- { operator: Where.LTE, value: new Date(endOfDay) },
1886
+ { operator: Where.GTE, value: day },
1887
+ { operator: Where.LTE, value: endOfDay },
1766
1888
  ];
1767
1889
  const [ordersBlockedWithCpf, ordersBlockedWithEmail, ordersBlockedWithCep, ordersBlockedWithPhone] = await Promise.all([
1768
1890
  this.getBlockedOrdersByCpf(checkout.user?.cpf, dateFilter),
@@ -1864,26 +1986,28 @@ class AntifraudCardService {
1864
1986
  }
1865
1987
  async validateDayOrderLimits(checkout, params) {
1866
1988
  const ordersPerDay = await this.validateOrdersByRange(params, this.getDateRange('day'));
1989
+ const limits = this.getLimitsByUserType('day', checkout.user.isSubscriber);
1867
1990
  return this.checkOrderLimitsAndBlock({
1868
1991
  checkout,
1869
1992
  orderCounts: ordersPerDay,
1870
- limit: this.LIMIT_ORDERS_DAY,
1993
+ limit: limits,
1871
1994
  period: 'day',
1872
1995
  });
1873
1996
  }
1874
1997
  async validateWeekOrderLimits(checkout, params) {
1875
1998
  const ordersPerWeek = await this.validateOrdersByRange(params, this.getDateRange('week'));
1999
+ const limits = this.getLimitsByUserType('week', checkout.user.isSubscriber);
1876
2000
  return this.checkOrderLimitsAndBlock({
1877
2001
  checkout,
1878
2002
  orderCounts: ordersPerWeek,
1879
- limit: this.LIMIT_ORDERS_WEEK,
2003
+ limit: limits,
1880
2004
  period: 'week',
1881
2005
  });
1882
2006
  }
1883
2007
  async checkOrderLimitsAndBlock(params) {
1884
2008
  const { checkout, orderCounts, limit, period } = params;
1885
2009
  for (const key in orderCounts) {
1886
- if (orderCounts[key] >= limit) {
2010
+ if (orderCounts[key] >= limit[key]) {
1887
2011
  await this.createBlockedOrderRecord({
1888
2012
  checkout,
1889
2013
  card: null,
@@ -4701,6 +4825,17 @@ const withCrudFirestore = (MixinBase) => {
4701
4825
  };
4702
4826
  };
4703
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
+
4704
4839
  class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4705
4840
  constructor({ firestore, interceptors }) {
4706
4841
  super({
@@ -4776,6 +4911,9 @@ class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFire
4776
4911
  isChild(_id, _parentId) {
4777
4912
  return;
4778
4913
  }
4914
+ async getBrandsWithProducts() {
4915
+ return;
4916
+ }
4779
4917
  }
4780
4918
  __decorate([
4781
4919
  Log(),
@@ -5786,6 +5924,9 @@ __decorate([
5786
5924
  __metadata("design:type", Product)
5787
5925
  ], KitProductHasuraGraphQL.prototype, "product", void 0);
5788
5926
 
5927
+ class ProductCatalogHasuraGraphQL extends Product {
5928
+ }
5929
+
5789
5930
  class ProductHasuraGraphQL extends Product {
5790
5931
  }
5791
5932
  __decorate([
@@ -6874,6 +7015,19 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
6874
7015
  categoryFilterRepository: this.categoryFilterRepository,
6875
7016
  });
6876
7017
  }
7018
+ async getBrandsWithProducts() {
7019
+ const fields = ['id', 'name', 'slug', 'brand_category', 'published', 'images'];
7020
+ const { brands_with_products_query: data, } = await this.query('brands_with_products_query', fields);
7021
+ return data.map((brand) => Category.toInstance({
7022
+ id: brand.id,
7023
+ name: brand.name,
7024
+ slug: brand.slug,
7025
+ brandCategory: brand.brand_category,
7026
+ shops: brand.shops,
7027
+ published: brand.published,
7028
+ images: brand.images,
7029
+ }));
7030
+ }
6877
7031
  }
6878
7032
  __decorate([
6879
7033
  Log(),
@@ -7138,83 +7292,7 @@ class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasu
7138
7292
  }
7139
7293
  }
7140
7294
 
7141
- class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7142
- constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7143
- super({
7144
- tableName: 'product_errors',
7145
- model: ProductErrorsHasuraGraphQL,
7146
- endpoint,
7147
- authOptions,
7148
- interceptors,
7149
- cache,
7150
- fields: [
7151
- {
7152
- productId: {
7153
- columnName: 'product_id',
7154
- to: (value) => +value,
7155
- from: (value) => value.toString(),
7156
- },
7157
- },
7158
- 'source',
7159
- 'error',
7160
- { createdAt: { columnName: 'created_at' } },
7161
- { updatedAt: { columnName: 'updated_at' } },
7162
- {
7163
- product: {
7164
- columnName: 'product',
7165
- foreignKeyColumn: { id: 'productId' },
7166
- fields: [
7167
- { id: { columnName: 'id', from: (value) => value.toString() } },
7168
- { productId: { columnName: 'main_product_id' } },
7169
- 'name',
7170
- 'published',
7171
- 'group',
7172
- 'validity',
7173
- { createdAt: { columnName: 'created_at' } },
7174
- { updatedAt: { columnName: 'updated_at' } },
7175
- ],
7176
- },
7177
- },
7178
- ],
7179
- });
7180
- this.productRepository = productRepository;
7181
- }
7182
- async get(params) {
7183
- const result = await super.get(params);
7184
- if (result instanceof VariantHasuraGraphQL) {
7185
- const product = await this.productRepository.get({ id: result.productId.toString() });
7186
- result.product.name = product.name;
7187
- result.product.group = product.group;
7188
- }
7189
- return result;
7190
- }
7191
- async find(params) {
7192
- const result = await super.find(params);
7193
- const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7194
- (isEmpty(item.product.name) || isEmpty(item.product.group) || isEmpty(item.product)));
7195
- if (variantsWithNoData.length > 0) {
7196
- const { data: products } = await this.productRepository.find({
7197
- filters: {
7198
- id: {
7199
- operator: Where.IN,
7200
- value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7201
- },
7202
- },
7203
- });
7204
- products.forEach((product) => {
7205
- result.data
7206
- .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7207
- .forEach((variant) => {
7208
- variant.product.name = product.name;
7209
- variant.product.group = product.group;
7210
- });
7211
- });
7212
- }
7213
- return result;
7214
- }
7215
- }
7216
-
7217
- const commonFields = [
7295
+ const commonFields$1 = [
7218
7296
  {
7219
7297
  id: {
7220
7298
  columnName: 'id',
@@ -7294,6 +7372,12 @@ const commonFields = [
7294
7372
  to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7295
7373
  },
7296
7374
  },
7375
+ {
7376
+ imagesCard: {
7377
+ columnName: 'images_card',
7378
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7379
+ },
7380
+ },
7297
7381
  'name',
7298
7382
  {
7299
7383
  price: {
@@ -7355,7 +7439,6 @@ const commonFields = [
7355
7439
  'weight',
7356
7440
  'gender',
7357
7441
  { intGender: { columnName: 'int_gender' } },
7358
- // { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
7359
7442
  { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7360
7443
  { isKit: { columnName: 'is_kit' } },
7361
7444
  { createdAt: { columnName: 'created_at' } },
@@ -7376,135 +7459,663 @@ const commonFields = [
7376
7459
  { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7377
7460
  { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7378
7461
  { daysOfUse: { columnName: 'days_of_use' } },
7462
+ // { showVariants: { columnName: 'show_variants' } },
7463
+ // { variantSlug: { columnName: 'variant_slug' } },
7379
7464
  ];
7380
- const fieldsConfiguration$2 = [
7381
- ...commonFields,
7382
- {
7383
- categories: {
7384
- columnName: 'categories',
7385
- fields: ['category_id'],
7386
- bindPersistData: (value) => ({
7387
- categories: { data: value.map((category) => ({ category_id: +category })) },
7388
- }),
7389
- to: (categories) => categories.map((categoryId) => +categoryId),
7390
- from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7391
- },
7392
- },
7393
- {
7394
- kitProducts: {
7395
- columnName: 'kit_products',
7396
- foreignKeyColumn: { productId: 'id' },
7397
- fields: [
7398
- { productId: { columnName: 'product_id' } },
7399
- { kitProductId: { columnName: 'kit_product_id' } },
7400
- 'quantity',
7401
- { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7402
- ],
7403
- },
7404
- },
7405
- {
7406
- reviews: {
7407
- columnName: 'reviews',
7408
- foreignKeyColumn: { product_id: 'id' },
7409
- fields: [
7410
- 'id',
7411
- 'shop',
7412
- 'rate',
7413
- 'author',
7414
- 'email',
7415
- 'location',
7416
- 'review',
7417
- 'status',
7418
- 'title',
7419
- { personId: { columnName: 'person_id' } },
7420
- 'points',
7421
- { orderId: { columnName: 'order_id' } },
7422
- { createdAt: { columnName: 'created_at' } },
7423
- { updatedAt: { columnName: 'updated_at' } },
7424
- ],
7425
- },
7426
- },
7427
- {
7428
- metadata: {
7429
- columnName: 'metadata',
7430
- fields: ['title', 'description'],
7431
- bindPersistData: (value) => ({
7432
- metadata: { data: value },
7433
- }),
7434
- },
7435
- },
7436
- {
7437
- variants: {
7438
- columnName: 'variants',
7439
- foreignKeyColumn: { product_id: 'id' },
7440
- fields: ['id', 'ean', 'grade', 'price', 'published', 'stock', 'tagsProfile'],
7441
- },
7442
- },
7443
- ];
7444
- class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7445
- get reviewsFields() {
7446
- return [
7447
- 'id',
7448
- 'shop',
7449
- 'rate',
7450
- 'author',
7451
- 'email',
7452
- 'location',
7453
- 'review',
7454
- 'status',
7455
- 'title',
7456
- { personId: { columnName: 'person_id' } },
7457
- 'points',
7458
- { orderId: { columnName: 'order_id' } },
7459
- { createdAt: { columnName: 'created_at' } },
7460
- { updatedAt: { columnName: 'updated_at' } },
7461
- ];
7462
- }
7465
+ class ProductCatalogHasuraGraphQLRepository extends withFindHasuraGraphQL(withHasuraGraphQL(Base)) {
7463
7466
  constructor({ endpoint, authOptions, interceptors, cache, }) {
7464
7467
  super({
7465
7468
  tableName: 'product',
7466
- model: ProductHasuraGraphQL,
7469
+ model: ProductCatalogHasuraGraphQL,
7467
7470
  endpoint,
7468
7471
  authOptions,
7469
7472
  interceptors,
7470
- fields: fieldsConfiguration$2,
7473
+ fields: commonFields$1,
7471
7474
  cache,
7472
7475
  });
7473
- this.bindReviewToModel = (plain) => ProductReview.toInstance({
7474
- ...is(omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id'])),
7475
- createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at,
7476
- updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at,
7477
- personId: plain.person_id,
7478
- orderId: plain.order_id,
7479
- });
7480
- this.bindReviewToHasura = (review) => ({
7481
- ...is(omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId'])),
7482
- person_id: review.personId,
7483
- order_id: review.orderId,
7484
- });
7485
7476
  }
7486
- async create(params) {
7487
- const { metadata, ...data } = params;
7488
- const product = await super.create(omit({ ...data, metadata: metadata || { description: null, title: null } }, ['reviews']));
7489
- try {
7490
- product.reviews = data.reviews && (await this.updateReviews(+product.id, data));
7491
- }
7492
- catch (error) {
7493
- await this.delete({ id: product.id });
7494
- throw error;
7477
+ async get({ id }, options) {
7478
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7479
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7480
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7481
+ if (cachedData) {
7482
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7483
+ return this.model.toInstance(deserialize(cachedData));
7484
+ }
7495
7485
  }
7496
- return product;
7497
- }
7498
- async get(identifiers, options) {
7499
- const product = Number.isNaN(+identifiers.id)
7500
- ? (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
7501
- .data?.[0]
7502
- : await super.get(identifiers, options);
7503
- if (product.productId)
7504
- throw new NotFoundError('Product not found, it is a variant');
7505
- product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, options));
7506
- return product;
7507
- }
7486
+ const product = await super
7487
+ .find({
7488
+ filters: {
7489
+ id,
7490
+ },
7491
+ limits: {
7492
+ limit: 1,
7493
+ },
7494
+ })
7495
+ .then((res) => res.data.at(0));
7496
+ if (!product)
7497
+ throw new NotFoundError(`Product not found`);
7498
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7499
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7500
+ await this.cache.cacheAdapter.set({
7501
+ key: cacheKey,
7502
+ data: serialize(product),
7503
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7504
+ });
7505
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7506
+ }
7507
+ return product;
7508
+ }
7509
+ async getByEAN(EAN, options) {
7510
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7511
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7512
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7513
+ if (cachedData) {
7514
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7515
+ return this.model.toInstance(deserialize(cachedData));
7516
+ }
7517
+ }
7518
+ const product = await super
7519
+ .find({
7520
+ filters: {
7521
+ EAN,
7522
+ },
7523
+ limits: {
7524
+ limit: 1,
7525
+ },
7526
+ })
7527
+ .then((res) => res.data.at(0));
7528
+ if (!product)
7529
+ return null;
7530
+ RoundProductPricesHelper.roundProductPrices(product);
7531
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7532
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7533
+ await this.cache.cacheAdapter.set({
7534
+ key: cacheKey,
7535
+ data: serialize(product),
7536
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7537
+ });
7538
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7539
+ }
7540
+ return product;
7541
+ }
7542
+ async find(params, optionsParams) {
7543
+ const { filters, fields, ...options } = params || {};
7544
+ const bindFields = fields ||
7545
+ this.fields
7546
+ .map((field) => (typeof field === 'string' ? field : Object.keys(field).shift()))
7547
+ .filter((field) => field !== 'reviews' && field !== 'categories');
7548
+ if (options.options?.minimal?.includes('price'))
7549
+ options.options?.minimal.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
7550
+ if (options.options?.maximum?.includes('price'))
7551
+ options.options?.maximum.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
7552
+ options.options?.minimal?.splice(options.options?.minimal.indexOf('price'), 1);
7553
+ options.options?.maximum?.splice(options.options?.maximum.indexOf('price'), 1);
7554
+ return super.find({
7555
+ ...options,
7556
+ filters: { ...filters },
7557
+ fields: [
7558
+ ...bindFields,
7559
+ ...(bindFields.includes('price')
7560
+ ? [
7561
+ 'subscriberPrice',
7562
+ 'subscriberDiscountPercentage',
7563
+ 'fullPrice',
7564
+ ]
7565
+ : []),
7566
+ ],
7567
+ }, optionsParams);
7568
+ }
7569
+ async findCatalog(params, mainGender, options) {
7570
+ const result = await this.find({
7571
+ ...params,
7572
+ filters: { ...params.filters, published: true },
7573
+ orderBy: {
7574
+ hasStock: 'desc',
7575
+ ...(!mainGender ? {} : { intGender: mainGender === 'female' ? 'desc' : 'asc' }),
7576
+ ...omit(params.orderBy, ['hasStock', 'intGender']),
7577
+ },
7578
+ }, options);
7579
+ return result;
7580
+ }
7581
+ }
7582
+ __decorate([
7583
+ Log(),
7584
+ __metadata("design:type", Function),
7585
+ __metadata("design:paramtypes", [Object, Object, Object]),
7586
+ __metadata("design:returntype", Promise)
7587
+ ], ProductCatalogHasuraGraphQLRepository.prototype, "findCatalog", null);
7588
+
7589
+ class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7590
+ constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7591
+ super({
7592
+ tableName: 'product_errors',
7593
+ model: ProductErrorsHasuraGraphQL,
7594
+ endpoint,
7595
+ authOptions,
7596
+ interceptors,
7597
+ cache,
7598
+ fields: [
7599
+ {
7600
+ productId: {
7601
+ columnName: 'product_id',
7602
+ to: (value) => +value,
7603
+ from: (value) => value.toString(),
7604
+ },
7605
+ },
7606
+ 'source',
7607
+ 'error',
7608
+ { createdAt: { columnName: 'created_at' } },
7609
+ { updatedAt: { columnName: 'updated_at' } },
7610
+ {
7611
+ product: {
7612
+ columnName: 'product',
7613
+ foreignKeyColumn: { id: 'productId' },
7614
+ fields: [
7615
+ { id: { columnName: 'id', from: (value) => value.toString() } },
7616
+ { productId: { columnName: 'main_product_id' } },
7617
+ 'name',
7618
+ 'published',
7619
+ 'group',
7620
+ 'validity',
7621
+ { createdAt: { columnName: 'created_at' } },
7622
+ { updatedAt: { columnName: 'updated_at' } },
7623
+ ],
7624
+ },
7625
+ },
7626
+ ],
7627
+ });
7628
+ this.productRepository = productRepository;
7629
+ }
7630
+ async get(params) {
7631
+ const result = await super.get(params);
7632
+ if (result instanceof VariantHasuraGraphQL) {
7633
+ const product = await this.productRepository.get({ id: result.productId.toString() });
7634
+ result.product.name = product.name;
7635
+ result.product.group = product.group;
7636
+ }
7637
+ return result;
7638
+ }
7639
+ async find(params) {
7640
+ const result = await super.find(params);
7641
+ const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7642
+ (isEmpty(item.product.name) || isEmpty(item.product.group) || isEmpty(item.product)));
7643
+ if (variantsWithNoData.length > 0) {
7644
+ const { data: products } = await this.productRepository.find({
7645
+ filters: {
7646
+ id: {
7647
+ operator: Where.IN,
7648
+ value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7649
+ },
7650
+ },
7651
+ });
7652
+ products.forEach((product) => {
7653
+ result.data
7654
+ .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7655
+ .forEach((variant) => {
7656
+ variant.product.name = product.name;
7657
+ variant.product.group = product.group;
7658
+ });
7659
+ });
7660
+ }
7661
+ return result;
7662
+ }
7663
+ }
7664
+
7665
+ const commonFields = [
7666
+ {
7667
+ id: {
7668
+ columnName: 'id',
7669
+ to: (value) => +value,
7670
+ from: (value) => value.toString(),
7671
+ },
7672
+ },
7673
+ { firestoreId: { columnName: 'firestore_id' } },
7674
+ { productId: { columnName: 'main_product_id' } },
7675
+ { CEST: { columnName: 'cest' } },
7676
+ { EAN: { columnName: 'ean' } },
7677
+ { NCM: { columnName: 'ncm' } },
7678
+ 'brand',
7679
+ { costPrice: { columnName: 'cost_price' } },
7680
+ {
7681
+ description: {
7682
+ columnName: 'description',
7683
+ from: (description, data) => ({
7684
+ description,
7685
+ differentials: data.differentials,
7686
+ whoMustUse: data.who_must_use,
7687
+ howToUse: data.how_to_use,
7688
+ brand: data.brand_description,
7689
+ ingredients: data.ingredients,
7690
+ purpose: data.purpose,
7691
+ }),
7692
+ bindFindFilter: (filters) => {
7693
+ return {
7694
+ ...(filters?.description && { description: filters.description }),
7695
+ ...(filters.differentials && { differentials: filters.differentials }),
7696
+ ...(filters.whoMustUse && {
7697
+ who_must_use: filters.whoMustUse,
7698
+ }),
7699
+ ...(filters.howToUse && {
7700
+ how_to_use: filters.howToUse,
7701
+ }),
7702
+ ...(filters.brand && {
7703
+ brand_description: filters.brand,
7704
+ }),
7705
+ ...(filters.ingredients && {
7706
+ ingredients: filters.ingredients,
7707
+ }),
7708
+ ...(filters.purpose && {
7709
+ purpose: filters.purpose,
7710
+ }),
7711
+ };
7712
+ },
7713
+ bindPersistData: (descriptionData) => ({
7714
+ ...(descriptionData?.description && { description: descriptionData.description }),
7715
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
7716
+ ...(descriptionData.whoMustUse && {
7717
+ who_must_use: descriptionData.whoMustUse,
7718
+ }),
7719
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
7720
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
7721
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
7722
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
7723
+ }),
7724
+ },
7725
+ },
7726
+ { differentials: { columnName: 'differentials' } },
7727
+ { whoMustUse: { columnName: 'who_must_use' } },
7728
+ { howToUse: { columnName: 'how_to_use' } },
7729
+ { brandDescription: { columnName: 'brand_description' } },
7730
+ { ingredients: { columnName: 'ingredients' } },
7731
+ { purpose: { columnName: 'purpose' } },
7732
+ { hasVariants: { columnName: 'has_variants' } },
7733
+ {
7734
+ images: {
7735
+ columnName: 'images',
7736
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7737
+ },
7738
+ },
7739
+ {
7740
+ miniatures: {
7741
+ columnName: 'miniatures',
7742
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7743
+ },
7744
+ },
7745
+ {
7746
+ imagesCard: {
7747
+ columnName: 'images_card',
7748
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7749
+ },
7750
+ },
7751
+ 'name',
7752
+ {
7753
+ price: {
7754
+ columnName: 'price',
7755
+ from: (price, data) => ({
7756
+ price,
7757
+ fullPrice: data.full_price,
7758
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
7759
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
7760
+ subscriberPrice: data.subscriber_price,
7761
+ }),
7762
+ bindFindFilter: (filters) => {
7763
+ return {
7764
+ ...((filters?.price || filters?.price === 0) && { price: filters.price }),
7765
+ ...((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice }),
7766
+ ...((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
7767
+ subscriber_discount_percentage: filters.subscriberDiscountPercentage,
7768
+ }),
7769
+ ...((filters.subscriberPrice || filters.subscriberPrice === 0) && {
7770
+ subscriber_price: filters.subscriberPrice,
7771
+ }),
7772
+ ...((filters.fullPriceDiscountPercentage || filters.fullPriceDiscountPercentage === 0) && {
7773
+ full_price_discount_percentage: filters.fullPriceDiscountPercentage,
7774
+ }),
7775
+ };
7776
+ },
7777
+ bindPersistData: (priceData) => ({
7778
+ ...(priceData?.price >= 0 && { price: priceData.price }),
7779
+ ...(priceData.fullPrice >= 0 && { full_price: priceData.fullPrice }),
7780
+ ...(priceData.subscriberDiscountPercentage >= 0 && {
7781
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
7782
+ }),
7783
+ ...(priceData.subscriberPrice >= 0 && { subscriber_price: priceData.subscriberPrice }),
7784
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
7785
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
7786
+ }),
7787
+ }),
7788
+ },
7789
+ },
7790
+ { fullPrice: { columnName: 'full_price' } },
7791
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
7792
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
7793
+ { subscriberPrice: { columnName: 'subscriber_price' } },
7794
+ 'published',
7795
+ 'outlet',
7796
+ 'label',
7797
+ 'sku',
7798
+ {
7799
+ stock: {
7800
+ columnName: 'stock',
7801
+ from: (quantity) => ({ quantity }),
7802
+ to: (value) => (isNil(value?.quantity) ? value : value?.quantity),
7803
+ },
7804
+ },
7805
+ { hasStock: { columnName: 'has_stock' } },
7806
+ 'slug',
7807
+ 'type',
7808
+ 'video',
7809
+ 'weight',
7810
+ 'gender',
7811
+ { intGender: { columnName: 'int_gender' } },
7812
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7813
+ { isKit: { columnName: 'is_kit' } },
7814
+ { createdAt: { columnName: 'created_at' } },
7815
+ { updatedAt: { columnName: 'updated_at' } },
7816
+ { rate: { columnName: 'rating' } },
7817
+ { reviewsTotal: { columnName: 'reviews_total' } },
7818
+ { shoppingCount: { columnName: 'shopping_count' } },
7819
+ { categoryId: { columnName: 'category_id' } },
7820
+ {
7821
+ category: {
7822
+ columnName: 'category',
7823
+ foreignKeyColumn: { id: 'categoryId' },
7824
+ fields: ['id', 'name', 'reference', 'slug'],
7825
+ },
7826
+ },
7827
+ 'group',
7828
+ 'validity',
7829
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7830
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7831
+ { daysOfUse: { columnName: 'days_of_use' } },
7832
+ // { showVariants: { columnName: 'show_variants' } },
7833
+ // { variantSlug: { columnName: 'variant_slug' } },
7834
+ ];
7835
+ const fieldsConfiguration$2 = [
7836
+ ...commonFields,
7837
+ {
7838
+ categories: {
7839
+ columnName: 'categories',
7840
+ fields: ['category_id'],
7841
+ bindPersistData: (value) => ({
7842
+ categories: { data: value.map((category) => ({ category_id: +category })) },
7843
+ }),
7844
+ to: (categories) => categories.map((categoryId) => +categoryId),
7845
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7846
+ },
7847
+ },
7848
+ {
7849
+ kitProducts: {
7850
+ columnName: 'kit_products',
7851
+ foreignKeyColumn: { productId: 'id' },
7852
+ fields: [
7853
+ { productId: { columnName: 'product_id' } },
7854
+ { kitProductId: { columnName: 'kit_product_id' } },
7855
+ 'quantity',
7856
+ { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7857
+ ],
7858
+ },
7859
+ },
7860
+ {
7861
+ reviews: {
7862
+ columnName: 'reviews',
7863
+ foreignKeyColumn: { product_id: 'id' },
7864
+ fields: [
7865
+ 'id',
7866
+ 'shop',
7867
+ 'rate',
7868
+ 'author',
7869
+ 'email',
7870
+ 'location',
7871
+ 'review',
7872
+ 'status',
7873
+ 'title',
7874
+ { personId: { columnName: 'person_id' } },
7875
+ 'points',
7876
+ { orderId: { columnName: 'order_id' } },
7877
+ { createdAt: { columnName: 'created_at' } },
7878
+ { updatedAt: { columnName: 'updated_at' } },
7879
+ ],
7880
+ },
7881
+ },
7882
+ {
7883
+ metadata: {
7884
+ columnName: 'metadata',
7885
+ fields: ['title', 'description'],
7886
+ bindPersistData: (value) => ({
7887
+ metadata: { data: value },
7888
+ }),
7889
+ },
7890
+ },
7891
+ {
7892
+ variants: {
7893
+ columnName: 'variants',
7894
+ foreignKeyColumn: { product_id: 'id' },
7895
+ fields: [
7896
+ 'id',
7897
+ 'name',
7898
+ 'ean',
7899
+ 'sku',
7900
+ {
7901
+ description: {
7902
+ columnName: 'description',
7903
+ from: (description, data) => ({
7904
+ description,
7905
+ differentials: data.differentials,
7906
+ whoMustUse: data.who_must_use,
7907
+ howToUse: data.how_to_use,
7908
+ brand: data.brand_description,
7909
+ ingredients: data.ingredients,
7910
+ purpose: data.purpose,
7911
+ }),
7912
+ bindFindFilter: (filters) => {
7913
+ return {
7914
+ ...(filters?.description && { description: filters.description }),
7915
+ ...(filters.differentials && { differentials: filters.differentials }),
7916
+ ...(filters.whoMustUse && {
7917
+ who_must_use: filters.whoMustUse,
7918
+ }),
7919
+ ...(filters.howToUse && {
7920
+ how_to_use: filters.howToUse,
7921
+ }),
7922
+ ...(filters.brand && {
7923
+ brand_description: filters.brand,
7924
+ }),
7925
+ ...(filters.ingredients && {
7926
+ ingredients: filters.ingredients,
7927
+ }),
7928
+ ...(filters.purpose && {
7929
+ purpose: filters.purpose,
7930
+ }),
7931
+ };
7932
+ },
7933
+ bindPersistData: (descriptionData) => ({
7934
+ ...(descriptionData?.description && { description: descriptionData.description }),
7935
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
7936
+ ...(descriptionData.whoMustUse && {
7937
+ who_must_use: descriptionData.whoMustUse,
7938
+ }),
7939
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
7940
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
7941
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
7942
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
7943
+ }),
7944
+ },
7945
+ },
7946
+ { differentials: { columnName: 'differentials' } },
7947
+ { whoMustUse: { columnName: 'who_must_use' } },
7948
+ { howToUse: { columnName: 'how_to_use' } },
7949
+ { brandDescription: { columnName: 'brand_description' } },
7950
+ { ingredients: { columnName: 'ingredients' } },
7951
+ { purpose: { columnName: 'purpose' } },
7952
+ {
7953
+ grade: {
7954
+ columnName: 'grade',
7955
+ type: HasuraGraphQLColumnType.Jsonb,
7956
+ },
7957
+ },
7958
+ {
7959
+ price: {
7960
+ columnName: 'price',
7961
+ from: (price, data) => ({
7962
+ price,
7963
+ fullPrice: data.full_price,
7964
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
7965
+ subscriberPrice: data.subscriber_price,
7966
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
7967
+ }),
7968
+ bindPersistData: (priceData) => ({
7969
+ ...((priceData?.price || 0) >= 0 && { price: priceData.price }),
7970
+ ...((priceData?.fullPrice || 0) >= 0 && { full_price: priceData.fullPrice }),
7971
+ ...((priceData?.subscriberDiscountPercentage || 0) >= 0 && {
7972
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
7973
+ }),
7974
+ ...((priceData?.subscriberPrice || 0) >= 0 && { subscriber_price: priceData.subscriberPrice }),
7975
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
7976
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
7977
+ }),
7978
+ }),
7979
+ },
7980
+ },
7981
+ { fullPrice: { columnName: 'full_price' } },
7982
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
7983
+ { subscriberPrice: { columnName: 'subscriber_price' } },
7984
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
7985
+ 'published',
7986
+ {
7987
+ stock: {
7988
+ columnName: 'stock',
7989
+ from: (quantity) => ({ quantity }),
7990
+ to: (value) => (isNil(value?.quantity) ? value : value?.quantity),
7991
+ },
7992
+ },
7993
+ {
7994
+ images: {
7995
+ columnName: 'images',
7996
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7997
+ },
7998
+ },
7999
+ {
8000
+ miniatures: {
8001
+ columnName: 'miniatures',
8002
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8003
+ },
8004
+ },
8005
+ {
8006
+ imagesCard: {
8007
+ columnName: 'images_card',
8008
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8009
+ },
8010
+ },
8011
+ { tagsProfile: { columnName: 'tags_profile' } },
8012
+ { tagsCollection: { columnName: 'tags_collection' } },
8013
+ // { variantSlug: { columnName: 'variant_slug' } },
8014
+ {
8015
+ reviews: {
8016
+ columnName: 'reviews',
8017
+ foreignKeyColumn: { product_id: 'id' },
8018
+ fields: [
8019
+ 'id',
8020
+ 'shop',
8021
+ 'rate',
8022
+ 'author',
8023
+ 'email',
8024
+ 'location',
8025
+ 'review',
8026
+ 'status',
8027
+ 'title',
8028
+ { personId: { columnName: 'person_id' } },
8029
+ 'points',
8030
+ { orderId: { columnName: 'order_id' } },
8031
+ { createdAt: { columnName: 'created_at' } },
8032
+ { updatedAt: { columnName: 'updated_at' } },
8033
+ ],
8034
+ },
8035
+ },
8036
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
8037
+ {
8038
+ metadata: {
8039
+ columnName: 'metadata',
8040
+ fields: ['title', 'description'],
8041
+ bindPersistData: (value) => ({
8042
+ metadata: { data: value },
8043
+ }),
8044
+ },
8045
+ },
8046
+ ],
8047
+ },
8048
+ },
8049
+ ];
8050
+ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8051
+ get reviewsFields() {
8052
+ return [
8053
+ 'id',
8054
+ 'shop',
8055
+ 'rate',
8056
+ 'author',
8057
+ 'email',
8058
+ 'location',
8059
+ 'review',
8060
+ 'status',
8061
+ 'title',
8062
+ { personId: { columnName: 'person_id' } },
8063
+ 'points',
8064
+ { orderId: { columnName: 'order_id' } },
8065
+ { createdAt: { columnName: 'created_at' } },
8066
+ { updatedAt: { columnName: 'updated_at' } },
8067
+ ];
8068
+ }
8069
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
8070
+ super({
8071
+ tableName: 'product',
8072
+ model: ProductHasuraGraphQL,
8073
+ endpoint,
8074
+ authOptions,
8075
+ interceptors,
8076
+ fields: fieldsConfiguration$2,
8077
+ cache,
8078
+ });
8079
+ this.bindReviewToModel = (plain) => ProductReview.toInstance({
8080
+ ...is(omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id'])),
8081
+ createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at,
8082
+ updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at,
8083
+ personId: plain.person_id,
8084
+ orderId: plain.order_id,
8085
+ });
8086
+ this.bindReviewToHasura = (review) => ({
8087
+ ...is(omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId'])),
8088
+ person_id: review.personId,
8089
+ order_id: review.orderId,
8090
+ });
8091
+ }
8092
+ async create(params) {
8093
+ const { metadata, ...data } = params;
8094
+ const product = await super.create(omit({ ...data, metadata: metadata || { description: null, title: null } }, ['reviews']));
8095
+ try {
8096
+ product.reviews = data.reviews && (await this.updateReviews(+product.id, data));
8097
+ }
8098
+ catch (error) {
8099
+ await this.delete({ id: product.id });
8100
+ throw error;
8101
+ }
8102
+ return product;
8103
+ }
8104
+ async get(identifiers, options) {
8105
+ const product = Number.isNaN(+identifiers.id)
8106
+ ? (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
8107
+ .data?.[0]
8108
+ : await super.get(identifiers, options);
8109
+ if (product.productId)
8110
+ throw new NotFoundError('Product not found, it is a variant');
8111
+ product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, false, options));
8112
+ if (!product.variants?.length) {
8113
+ for (const [index, variant] of product.variants.entries()) {
8114
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8115
+ }
8116
+ }
8117
+ return product;
8118
+ }
7508
8119
  async find(params, optionsParams) {
7509
8120
  const { filters, fields, ...options } = params || {};
7510
8121
  const bindFields = fields ||
@@ -7544,6 +8155,9 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7544
8155
  const result = await this.find({
7545
8156
  filters: {
7546
8157
  slug,
8158
+ productId: {
8159
+ operator: Where.ISNULL,
8160
+ },
7547
8161
  },
7548
8162
  fields: this.fields.map((field) => typeof field === 'string' ? field : Object.keys(field).shift()),
7549
8163
  options: {
@@ -7553,6 +8167,11 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7553
8167
  if (!result.data.length)
7554
8168
  return null;
7555
8169
  const product = result?.data?.shift();
8170
+ if (!product.variants?.length) {
8171
+ for (const [index, variant] of product.variants.entries()) {
8172
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8173
+ }
8174
+ }
7556
8175
  RoundProductPricesHelper.roundProductPrices(product);
7557
8176
  if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7558
8177
  const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
@@ -7732,7 +8351,8 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7732
8351
  const plainData = this.paramsToPlain({ metadata });
7733
8352
  if (!plainData.metadata)
7734
8353
  return null;
7735
- await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8354
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8355
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
7736
8356
  pk_columns: {
7737
8357
  value: { product_id: productId },
7738
8358
  type: 'product_metadata_pk_columns_input',
@@ -7744,6 +8364,14 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7744
8364
  required: true,
7745
8365
  },
7746
8366
  });
8367
+ if (!update_product_metadata_by_pk) {
8368
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8369
+ objects: {
8370
+ type: '[product_metadata_insert_input!]!',
8371
+ value: [{ product_id: productId, ...metadata }],
8372
+ },
8373
+ });
8374
+ }
7747
8375
  return plainData.metadata;
7748
8376
  }
7749
8377
  async getId(id) {
@@ -7754,7 +8382,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7754
8382
  return data?.[0]?.id;
7755
8383
  throw new NotFoundError(`Product with id ${id} not found`);
7756
8384
  }
7757
- async findReviewsByProduct(productId, options) {
8385
+ async findReviewsByProduct(productId, onlyApproved, options) {
7758
8386
  if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7759
8387
  const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
7760
8388
  const cachedData = await this.cache.cacheAdapter.get(cacheKey);
@@ -7767,10 +8395,16 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7767
8395
  where: {
7768
8396
  value: {
7769
8397
  product_id: { _eq: productId },
8398
+ ...(onlyApproved && { status: { _eq: true } }),
7770
8399
  },
7771
8400
  type: 'product_review_bool_exp',
7772
8401
  required: true,
7773
8402
  },
8403
+ order_by: {
8404
+ type: '[product_review_order_by]',
8405
+ value: [{ createdAt: 'desc' }],
8406
+ required: true,
8407
+ },
7774
8408
  });
7775
8409
  const reviews = data?.map((review) => this.bindReviewToModel(review));
7776
8410
  if (this.cache?.cacheAdapter && options?.cache?.enabled && reviews) {
@@ -7875,7 +8509,7 @@ __decorate([
7875
8509
  __decorate([
7876
8510
  Log(),
7877
8511
  __metadata("design:type", Function),
7878
- __metadata("design:paramtypes", [Number, Object]),
8512
+ __metadata("design:paramtypes", [Number, Boolean, Object]),
7879
8513
  __metadata("design:returntype", Promise)
7880
8514
  ], ProductHasuraGraphQLRepository.prototype, "findReviewsByProduct", null);
7881
8515
 
@@ -7907,7 +8541,25 @@ class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHas
7907
8541
  product: {
7908
8542
  columnName: 'product',
7909
8543
  foreignKeyColumn: { id: 'productId' },
7910
- fields: ['id', 'ean', 'sku', 'name', 'brand', 'slug', 'images', 'grade', 'gender'],
8544
+ fields: [
8545
+ 'id',
8546
+ {
8547
+ productId: {
8548
+ columnName: 'main_product_id',
8549
+ to: (value) => +value,
8550
+ from: (value) => value?.toString(),
8551
+ },
8552
+ },
8553
+ 'ean',
8554
+ 'sku',
8555
+ 'name',
8556
+ 'brand',
8557
+ 'slug',
8558
+ 'images',
8559
+ 'grade',
8560
+ 'gender',
8561
+ '',
8562
+ ],
7911
8563
  },
7912
8564
  },
7913
8565
  ],
@@ -8075,37 +8727,173 @@ const fieldsConfiguration$1 = [
8075
8727
  }),
8076
8728
  },
8077
8729
  },
8078
- { fullPrice: { columnName: 'full_price' } },
8079
- { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
8080
- { subscriberPrice: { columnName: 'subscriber_price' } },
8081
- { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
8082
- 'sku',
8730
+ { fullPrice: { columnName: 'full_price' } },
8731
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
8732
+ { subscriberPrice: { columnName: 'subscriber_price' } },
8733
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
8734
+ 'sku',
8735
+ {
8736
+ stock: {
8737
+ columnName: 'stock',
8738
+ from: (quantity) => ({ quantity }),
8739
+ to: (value) => (isNil(value?.quantity) ? value : value?.quantity),
8740
+ },
8741
+ },
8742
+ { hasStock: { columnName: 'has_stock' } },
8743
+ 'weight',
8744
+ { name: { to: () => '', from: () => undefined } },
8745
+ { hasVariants: { columnName: 'has_variants', to: () => false, from: () => undefined } },
8746
+ { createdAt: { columnName: 'created_at' } },
8747
+ { updatedAt: { columnName: 'updated_at' } },
8748
+ {
8749
+ grade: {
8750
+ columnName: 'grade',
8751
+ type: HasuraGraphQLColumnType.Jsonb,
8752
+ },
8753
+ },
8754
+ 'group',
8755
+ 'type',
8756
+ 'validity',
8757
+ 'published',
8758
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
8759
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
8760
+ { daysOfUse: { columnName: 'days_of_use' } },
8761
+ {
8762
+ images: {
8763
+ columnName: 'images',
8764
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8765
+ },
8766
+ },
8767
+ {
8768
+ miniatures: {
8769
+ columnName: 'miniatures',
8770
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8771
+ },
8772
+ },
8773
+ {
8774
+ imagesCard: {
8775
+ columnName: 'images_card',
8776
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8777
+ },
8778
+ },
8779
+ 'slug',
8780
+ 'brand',
8781
+ 'name',
8782
+ 'sku',
8783
+ { NCM: { columnName: 'ncm' } },
8784
+ { CEST: { columnName: 'cest' } },
8785
+ {
8786
+ description: {
8787
+ columnName: 'description',
8788
+ from: (description, data) => ({
8789
+ description,
8790
+ differentials: data.differentials,
8791
+ whoMustUse: data.who_must_use,
8792
+ howToUse: data.how_to_use,
8793
+ brand: data.brand_description,
8794
+ ingredients: data.ingredients,
8795
+ purpose: data.purpose,
8796
+ }),
8797
+ bindFindFilter: (filters) => {
8798
+ return {
8799
+ ...(filters?.description && { description: filters.description }),
8800
+ ...(filters.differentials && { differentials: filters.differentials }),
8801
+ ...(filters.whoMustUse && {
8802
+ who_must_use: filters.whoMustUse,
8803
+ }),
8804
+ ...(filters.howToUse && {
8805
+ how_to_use: filters.howToUse,
8806
+ }),
8807
+ ...(filters.brand && {
8808
+ brand_description: filters.brand,
8809
+ }),
8810
+ ...(filters.ingredients && {
8811
+ ingredients: filters.ingredients,
8812
+ }),
8813
+ ...(filters.purpose && {
8814
+ purpose: filters.purpose,
8815
+ }),
8816
+ };
8817
+ },
8818
+ bindPersistData: (descriptionData) => ({
8819
+ ...(descriptionData?.description && { description: descriptionData.description }),
8820
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
8821
+ ...(descriptionData.whoMustUse && {
8822
+ who_must_use: descriptionData.whoMustUse,
8823
+ }),
8824
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
8825
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
8826
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
8827
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
8828
+ }),
8829
+ },
8830
+ },
8831
+ { differentials: { columnName: 'differentials' } },
8832
+ { whoMustUse: { columnName: 'who_must_use' } },
8833
+ { howToUse: { columnName: 'how_to_use' } },
8834
+ { brandDescription: { columnName: 'brand_description' } },
8835
+ { ingredients: { columnName: 'ingredients' } },
8836
+ { purpose: { columnName: 'purpose' } },
8837
+ 'gender',
8838
+ { intGender: { columnName: 'int_gender' } },
8839
+ 'label',
8840
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
8841
+ { rate: { columnName: 'rating' } },
8842
+ { reviewsTotal: { columnName: 'reviews_total' } },
8843
+ { shoppingCount: { columnName: 'shopping_count' } },
8844
+ { categoryId: { columnName: 'category_id' } },
8845
+ {
8846
+ category: {
8847
+ columnName: 'category',
8848
+ foreignKeyColumn: { id: 'categoryId' },
8849
+ fields: ['id', 'name', 'reference', 'slug'],
8850
+ },
8851
+ },
8852
+ {
8853
+ categories: {
8854
+ columnName: 'categories',
8855
+ fields: ['category_id'],
8856
+ bindPersistData: (value) => ({
8857
+ categories: { data: value.map((category) => ({ category_id: +category })) },
8858
+ }),
8859
+ to: (categories) => categories.map((categoryId) => +categoryId),
8860
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
8861
+ },
8862
+ },
8083
8863
  {
8084
- stock: {
8085
- columnName: 'stock',
8086
- from: (quantity) => ({ quantity }),
8087
- to: (value) => (isNil(value?.quantity) ? value : value?.quantity),
8864
+ metadata: {
8865
+ columnName: 'metadata',
8866
+ fields: ['title', 'description'],
8867
+ bindPersistData: (value) => ({
8868
+ metadata: { data: value },
8869
+ }),
8088
8870
  },
8089
8871
  },
8090
- { hasStock: { columnName: 'has_stock' } },
8091
- 'weight',
8092
- { name: { to: () => '', from: () => undefined } },
8093
- { hasVariants: { columnName: 'has_variants', to: () => false, from: () => undefined } },
8094
- { createdAt: { columnName: 'created_at' } },
8095
- { updatedAt: { columnName: 'updated_at' } },
8096
8872
  {
8097
- grade: {
8098
- columnName: 'grade',
8099
- type: HasuraGraphQLColumnType.Jsonb,
8873
+ reviews: {
8874
+ columnName: 'reviews',
8875
+ foreignKeyColumn: { product_id: 'id' },
8876
+ fields: [
8877
+ 'id',
8878
+ 'shop',
8879
+ 'rate',
8880
+ 'author',
8881
+ 'email',
8882
+ 'location',
8883
+ 'review',
8884
+ 'status',
8885
+ 'title',
8886
+ { personId: { columnName: 'person_id' } },
8887
+ 'points',
8888
+ { orderId: { columnName: 'order_id' } },
8889
+ { createdAt: { columnName: 'created_at' } },
8890
+ { updatedAt: { columnName: 'updated_at' } },
8891
+ ],
8100
8892
  },
8101
8893
  },
8102
- 'group',
8103
- 'validity',
8104
- // { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
8105
- 'published',
8106
- { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
8107
- { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
8108
- { daysOfUse: { columnName: 'days_of_use' } },
8894
+ // { variantSlug: { columnName: 'variant_slug' } },
8895
+ { createdAt: { columnName: 'created_at' } },
8896
+ { updatedAt: { columnName: 'updated_at' } },
8109
8897
  ];
8110
8898
  class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8111
8899
  constructor({ endpoint, authOptions, interceptors, cache, }) {
@@ -8146,18 +8934,46 @@ class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
8146
8934
  return data.at(0);
8147
8935
  }
8148
8936
  async update(params) {
8149
- const { productId, id: checkId, ...data } = params;
8937
+ const { productId, id: checkId, metadata, ...data } = params;
8150
8938
  const dataWithProductId = this.paramsToPlain({ id: checkId, productId });
8151
8939
  if (!dataWithProductId.id) {
8152
8940
  throw new NotFoundError('Variant ID is required for update');
8153
8941
  }
8154
8942
  const id = await this.getId(dataWithProductId.id);
8155
8943
  const product = await super.update({ id, ...data });
8944
+ product.metadata = metadata && (await this.updateMetadata(+id, { metadata }));
8156
8945
  if (dataWithProductId.productId) {
8157
8946
  product.productId = dataWithProductId.productId;
8158
8947
  }
8159
8948
  return product;
8160
8949
  }
8950
+ async updateMetadata(productId, { metadata }) {
8951
+ const plainData = this.paramsToPlain({ metadata });
8952
+ if (!plainData.metadata)
8953
+ return null;
8954
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8955
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8956
+ pk_columns: {
8957
+ value: { product_id: productId },
8958
+ type: 'product_metadata_pk_columns_input',
8959
+ required: true,
8960
+ },
8961
+ _set: {
8962
+ value: omit(metadata, ['product_id']),
8963
+ type: 'product_metadata_set_input',
8964
+ required: true,
8965
+ },
8966
+ });
8967
+ if (!update_product_metadata_by_pk) {
8968
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8969
+ objects: {
8970
+ type: '[product_metadata_insert_input!]!',
8971
+ value: [{ product_id: productId, ...metadata }],
8972
+ },
8973
+ });
8974
+ }
8975
+ return plainData.metadata;
8976
+ }
8161
8977
  async getId(id) {
8162
8978
  if (!Number.isNaN(+id))
8163
8979
  return id;
@@ -8472,6 +9288,9 @@ class WishlistHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
8472
9288
  productId: +productId,
8473
9289
  });
8474
9290
  }
9291
+ async getBrandsWithProducts() {
9292
+ return;
9293
+ }
8475
9294
  }
8476
9295
  __decorate([
8477
9296
  Log(),
@@ -8498,6 +9317,438 @@ __decorate([
8498
9317
  __metadata("design:returntype", Promise)
8499
9318
  ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
8500
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
+
8501
9752
  class PagarmeBankSlipAxiosAdapter {
8502
9753
  constructor(credentials, paymentRepository) {
8503
9754
  this.credentials = credentials;
@@ -8638,6 +9889,211 @@ class PagarmePaymentOperationsHelper {
8638
9889
  }
8639
9890
  }
8640
9891
 
9892
+ class PagarMeV5RequestHelper {
9893
+ static build(checkout, method, card) {
9894
+ return {
9895
+ items: this.buildItems(checkout),
9896
+ customer: this.buildCustomer(checkout),
9897
+ shipping: this.buildShipping(checkout),
9898
+ payments: this.buildPayment(checkout, method, card),
9899
+ ...this.buildAdditionalInfo(checkout),
9900
+ };
9901
+ }
9902
+ static buildItems(checkout) {
9903
+ const isSubscriber = checkout.user?.isSubscriber ?? false;
9904
+ return checkout.lineItems
9905
+ .filter((item) => !item.isGift)
9906
+ .map((item) => {
9907
+ return {
9908
+ amount: Math.floor(item.pricePaid * 100),
9909
+ description: isSubscriber ? `${item.name} - ASSINANTE` : item.name,
9910
+ quantity: item.quantity,
9911
+ code: item.EAN,
9912
+ };
9913
+ });
9914
+ }
9915
+ static buildCustomer(checkout) {
9916
+ return {
9917
+ name: checkout.user.displayName,
9918
+ email: checkout.user.email,
9919
+ type: 'individual',
9920
+ document: checkout.user.cpf,
9921
+ phones: {
9922
+ home_phone: {
9923
+ country_code: '55',
9924
+ number: checkout.user.phone.slice(2),
9925
+ area_code: checkout.user.phone.slice(0, 2),
9926
+ },
9927
+ mobile_phone: {
9928
+ country_code: '55',
9929
+ number: checkout.user.phone.slice(2),
9930
+ area_code: checkout.user.phone.slice(0, 2),
9931
+ },
9932
+ },
9933
+ address: {
9934
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
9935
+ line_2: `${checkout.billingAddress.extension}`,
9936
+ zip_code: checkout.shippingAddress.zip,
9937
+ city: checkout.billingAddress.city,
9938
+ state: checkout.billingAddress.state,
9939
+ country: 'BR',
9940
+ },
9941
+ };
9942
+ }
9943
+ static buildShipping(checkout) {
9944
+ return {
9945
+ amount: Math.floor(checkout.shipping.ShippingPrice * 100),
9946
+ description: `${checkout.shipping.ShippingCompanyName} - ${checkout.shipping.description}`,
9947
+ recipient_name: checkout.shippingAddress.recipient,
9948
+ recipient_phone: checkout.user.phone,
9949
+ address: {
9950
+ line_1: `${checkout.shippingAddress.number}, ${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9951
+ line_2: `${checkout.shippingAddress.extension}`,
9952
+ zip_code: checkout.shippingAddress.zip,
9953
+ city: checkout.shippingAddress.city,
9954
+ state: checkout.shippingAddress.state,
9955
+ country: 'BR',
9956
+ },
9957
+ };
9958
+ }
9959
+ static buildPayment(checkout, method, card) {
9960
+ return [
9961
+ {
9962
+ payment_method: method,
9963
+ amount: Math.floor(checkout.totalPrice * 100),
9964
+ ...(method === 'pix' && {
9965
+ pix: this.getPixOrder(),
9966
+ }),
9967
+ ...(method === 'boleto' && {
9968
+ boleto: this.getBoletoOrder(),
9969
+ }),
9970
+ ...(method === 'credit_card' && {
9971
+ credit_card: this.getCardOrder(checkout, card),
9972
+ }),
9973
+ },
9974
+ ];
9975
+ }
9976
+ static getPixOrder() {
9977
+ return {
9978
+ expires_at: format(addDays(new Date(), 1), 'yyyy-MM-dd'),
9979
+ };
9980
+ }
9981
+ static getBoletoOrder() {
9982
+ return {
9983
+ due_at: format(addDays(new Date(), 3), 'yyyy-MM-dd'),
9984
+ instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
9985
+ type: 'DM',
9986
+ document_number: new Date().getTime().toString(),
9987
+ };
9988
+ }
9989
+ static getCardOrder(checkout, card) {
9990
+ return {
9991
+ installments: card.installments,
9992
+ statement_descriptor: checkout.shop === Shops.GLAMSHOP ? 'Glam' : 'Mens Market',
9993
+ card_id: card.cardId,
9994
+ card: {
9995
+ cvv: card.cardCvv,
9996
+ billing_address: {
9997
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
9998
+ zip_code: checkout.billingAddress.zip,
9999
+ city: checkout.billingAddress.city,
10000
+ state: checkout.billingAddress.state,
10001
+ country: 'BR',
10002
+ },
10003
+ },
10004
+ };
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
+ }
10014
+ }
10015
+
10016
+ class PagarMeV5ResponseHelper {
10017
+ static build(method, checkout, response) {
10018
+ return Payment.toInstance({
10019
+ createdAt: new Date(),
10020
+ updatedAt: new Date(),
10021
+ userId: checkout.user.id,
10022
+ checkoutId: checkout.id,
10023
+ totalPrice: checkout.totalPrice,
10024
+ paymentProvider: PaymentProviders.PAGARME,
10025
+ pagarMeOrderId: response.id,
10026
+ transaction: this.buildPaymentTransaction(method, response),
10027
+ });
10028
+ }
10029
+ static buildPaymentTransaction(method, response) {
10030
+ const charger = response.charges.at(0);
10031
+ const transaction = charger.last_transaction;
10032
+ return PaymentTransaction.toInstance({
10033
+ acquirer_name: 'pagar_me',
10034
+ amount: charger.amount,
10035
+ currency: charger.currency,
10036
+ gateway_id: charger.gateway_id,
10037
+ status: this.getPaymentStatus(transaction.status),
10038
+ payment_method: charger.payment_method,
10039
+ date_created: charger.created_at,
10040
+ date_updated: charger.updated_at,
10041
+ paid_amount: charger.paid_amount,
10042
+ paid_at: charger.paid_at,
10043
+ order_id: response.id,
10044
+ charger_id: charger.id,
10045
+ tid: charger.id,
10046
+ id: charger.id,
10047
+ ...(method == TransactionPaymentMethods.BANKSLIP && this.getBoletoReponse(transaction)),
10048
+ ...(method == TransactionPaymentMethods.PIX && this.getPixReponse(transaction)),
10049
+ ...(method == TransactionPaymentMethods.CARD && this.getCardReponse(transaction)),
10050
+ });
10051
+ }
10052
+ static getPaymentStatus(status) {
10053
+ if (status == PagarMeV5PaymentStatus.Gerado)
10054
+ return PagarMeV5PaymentStatus['Aguardando pagamento'];
10055
+ if (status == PagarMeV5PaymentStatus.Capturada)
10056
+ return PagarMeV5PaymentStatus.Pago;
10057
+ return status;
10058
+ }
10059
+ static getBoletoReponse(transaction) {
10060
+ return {
10061
+ boleto_url: transaction.url?.toString(),
10062
+ boleto_barcode: transaction.line?.toString(),
10063
+ boleto_qr_code: transaction.qr_code?.toString(),
10064
+ boleto_expiration_date: transaction.due_at?.toString(),
10065
+ boleto_instructions: transaction.instructions?.toString(),
10066
+ boleto_nosso_numero: transaction.nosso_numero?.toString(),
10067
+ boleto_type: transaction.type?.toString(),
10068
+ boleto_document_number: transaction.document_number?.toString(),
10069
+ };
10070
+ }
10071
+ static getPixReponse(transaction) {
10072
+ return {
10073
+ pix_qr_code: transaction.qr_code?.toString(),
10074
+ pix_qr_code_url: transaction.qr_code_url?.toString(),
10075
+ pix_expiration_date: transaction.expires_at?.toString(),
10076
+ };
10077
+ }
10078
+ static getCardReponse(transaction) {
10079
+ return {
10080
+ soft_descriptor: transaction.statement_descriptor?.toString(),
10081
+ acquirer_name: transaction.acquirer_name?.toString(),
10082
+ acquirer_id: transaction.acquirer_tid?.toString(),
10083
+ acquirer_nsu: transaction.acquirer_nsu?.toString(),
10084
+ acquirer_auth_code: transaction.acquirer_auth_code?.toString(),
10085
+ acquirer_message: transaction.acquirer_message?.toString(),
10086
+ acquirer_return_code: transaction.acquirer_return_code?.toString(),
10087
+ installments: transaction.installments ?? null,
10088
+ card_holder_name: transaction.card?.holder_name?.toString(),
10089
+ card_last_digits: transaction.card?.last_four_digits?.toString(),
10090
+ card_first_digits: transaction.card?.first_six_digits?.toString(),
10091
+ card_brand: transaction.card?.brand?.toString(),
10092
+ card_id: transaction.card?.id?.toString(),
10093
+ };
10094
+ }
10095
+ }
10096
+
8641
10097
  class PagarmeCardAxiosAdapter {
8642
10098
  constructor(credentials, paymentRepository, orderBlockedRepository) {
8643
10099
  this.credentials = credentials;
@@ -8694,8 +10150,9 @@ class PagarmeCardAxiosAdapter {
8694
10150
  });
8695
10151
  }
8696
10152
  }
8697
- async createCardHash(bu) {
8698
- const key = bu === BusinessUnitEnum.SHOP ? this.credentials.SHOP_API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
10153
+ async createCardHash(bu, shop) {
10154
+ const credentials = shop && shop == Shops.MENSMARKET ? this.credentials[Shops.MENSMARKET] : this.credentials[Shops.GLAMSHOP];
10155
+ const key = bu === BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
8699
10156
  try {
8700
10157
  const { data } = await axios({
8701
10158
  method: 'GET',
@@ -8858,6 +10315,281 @@ class PagarmePixAxiosAdapter {
8858
10315
  }
8859
10316
  }
8860
10317
 
10318
+ class PagarmeV5BankSlipAxiosAdapter {
10319
+ constructor(credentials, paymentRepository) {
10320
+ this.credentials = credentials;
10321
+ this.paymentRepository = paymentRepository;
10322
+ }
10323
+ async pay(checkout) {
10324
+ try {
10325
+ const payload = PagarMeV5RequestHelper.build(checkout, 'boleto');
10326
+ console.warn('[PAGARME BOLETO DATA TO SEND]', JSON.stringify(payload));
10327
+ const { data } = await axios({
10328
+ method: 'POST',
10329
+ url: `${this.credentials.URL}/orders`,
10330
+ headers: {
10331
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10332
+ 'Content-Type': 'application/json',
10333
+ },
10334
+ data: payload,
10335
+ });
10336
+ console.warn('[PAGARME RESPONSE BOLETO DATA]', JSON.stringify(data));
10337
+ if (data.status === PagarMeV5OrderStatus.Falha ||
10338
+ data.charges.at(0).status === PagarMeV5OrderStatus.Falha ||
10339
+ (data.charges.at(0).last_transaction.status !== PagarMeV5PaymentStatus.Gerado &&
10340
+ data.charges.at(0).last_transaction.status !== PagarMeV5PaymentStatus['Em processamento'])) {
10341
+ return Promise.reject(new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
10342
+ checkoutId: checkout.id,
10343
+ userEmail: checkout.user.email,
10344
+ info: data.charges.at(0).last_transaction?.gateway_response,
10345
+ }));
10346
+ }
10347
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(TransactionPaymentMethods.BANKSLIP, checkout, data));
10348
+ return payment;
10349
+ }
10350
+ catch (error) {
10351
+ if (error instanceof AxiosError) {
10352
+ console.error('error data: ', JSON.stringify(error.response?.data));
10353
+ }
10354
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
10355
+ checkoutId: checkout.id,
10356
+ userEmail: checkout.user.email,
10357
+ info: error.response?.data,
10358
+ });
10359
+ }
10360
+ }
10361
+ async getBoletoTransaction(paymentId) {
10362
+ try {
10363
+ const { data } = await axios({
10364
+ method: 'GET',
10365
+ url: `${this.credentials.URL}/charges/${paymentId}`,
10366
+ headers: {
10367
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10368
+ 'Content-Type': 'application/json',
10369
+ },
10370
+ });
10371
+ const payment = await this.paymentRepository.get({
10372
+ id: data.id,
10373
+ });
10374
+ return payment.transaction;
10375
+ }
10376
+ catch (error) {
10377
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
10378
+ paymentId,
10379
+ info: error.response.data,
10380
+ });
10381
+ }
10382
+ }
10383
+ }
10384
+
10385
+ class PagarmeV5CardAxiosAdapter {
10386
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
10387
+ this.credentials = credentials;
10388
+ this.paymentRepository = paymentRepository;
10389
+ this.orderBlockedRepository = orderBlockedRepository;
10390
+ }
10391
+ async pay(checkout, card) {
10392
+ try {
10393
+ const payload = PagarMeV5RequestHelper.build(checkout, 'credit_card', card);
10394
+ console.warn('[PAGARME CARD DATA TO SEND]', JSON.stringify(payload));
10395
+ const { data } = await axios({
10396
+ method: 'POST',
10397
+ url: `${this.credentials.URL}/orders`,
10398
+ headers: {
10399
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10400
+ 'Content-Type': 'application/json',
10401
+ },
10402
+ data: payload,
10403
+ });
10404
+ console.warn('[RESPONSE PAGARME CARD DATA]', JSON.stringify(data));
10405
+ if (data.status == PagarMeV5OrderStatus.Falha ||
10406
+ data.charges.at(0).status !== PagarMeV5OrderStatus.Pago ||
10407
+ data.charges.at(0).last_transaction.status !== PagarMeV5PaymentStatus.Capturada) {
10408
+ await PagarmeBlockedOrderHelper.createBlockedOrderForUnauthorizedCard({
10409
+ checkout,
10410
+ card,
10411
+ orderBlockedRepository: this.orderBlockedRepository,
10412
+ });
10413
+ throw PagarmeBlockedOrderHelper.createPaymentError(checkout, data);
10414
+ }
10415
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(TransactionPaymentMethods.CARD, checkout, data));
10416
+ return payment;
10417
+ }
10418
+ catch (error) {
10419
+ if (error instanceof PaymentError) {
10420
+ throw error;
10421
+ }
10422
+ if (error instanceof AxiosError) {
10423
+ console.error('error data: ', JSON.stringify(error.response?.data));
10424
+ }
10425
+ throw PagarmeBlockedOrderHelper.createGenericPaymentError(checkout, error.response?.data);
10426
+ }
10427
+ }
10428
+ async addCard(card, customer) {
10429
+ try {
10430
+ const { id } = await this.createOrUpdateCustomer(customer);
10431
+ const { data } = await axios({
10432
+ method: 'POST',
10433
+ url: `${this.credentials.URL}/customers/${id}/cards`,
10434
+ headers: {
10435
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10436
+ 'Content-Type': 'application/json',
10437
+ },
10438
+ data: {
10439
+ number: card.number,
10440
+ holder_name: card.name,
10441
+ holder_document: card.cpf,
10442
+ exp_month: card.expirationDate.split('/').at(0),
10443
+ exp_year: card.expirationDate.split('/').at(1),
10444
+ cvv: card.cvv,
10445
+ billing_address: {
10446
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
10447
+ line_2: `${customer.billingAddress.extension}`,
10448
+ zip_code: customer.billingAddress.zip,
10449
+ city: customer.billingAddress.city,
10450
+ state: customer.billingAddress.state,
10451
+ country: 'BR',
10452
+ },
10453
+ },
10454
+ });
10455
+ return data;
10456
+ }
10457
+ catch (error) {
10458
+ console.warn(JSON.stringify(error));
10459
+ throw error;
10460
+ }
10461
+ }
10462
+ async createCardHash(bu, shop) {
10463
+ const credentials = shop && shop == Shops.MENSMARKET ? this.credentials[Shops.MENSMARKET] : this.credentials[Shops.GLAMSHOP];
10464
+ const key = bu === BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
10465
+ try {
10466
+ const { data } = await axios({
10467
+ method: 'GET',
10468
+ headers: {
10469
+ 'content-type': 'application/json',
10470
+ },
10471
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
10472
+ data: JSON.stringify({
10473
+ api_key: key,
10474
+ }),
10475
+ });
10476
+ return data;
10477
+ }
10478
+ catch (error) {
10479
+ throw new BusinessError('Houve uma falha gerar o hash', {
10480
+ info: error.response.data,
10481
+ });
10482
+ }
10483
+ }
10484
+ async getCardByToken(customerId, token) {
10485
+ try {
10486
+ const { data } = await axios({
10487
+ method: 'GET',
10488
+ url: `${this.credentials.URL}/cards/${token}`,
10489
+ data: {
10490
+ api_key: this.credentials.API_KEY,
10491
+ },
10492
+ });
10493
+ return data;
10494
+ }
10495
+ catch (error) {
10496
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + token, {
10497
+ info: error.response.data,
10498
+ });
10499
+ }
10500
+ }
10501
+ async createTransaction(info) {
10502
+ return info;
10503
+ }
10504
+ async createOrUpdateCustomer(customer) {
10505
+ try {
10506
+ const { data } = await axios({
10507
+ method: 'POST',
10508
+ url: `${this.credentials.URL}/customers`,
10509
+ headers: {
10510
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10511
+ 'Content-Type': 'application/json',
10512
+ },
10513
+ data: {
10514
+ name: customer.displayName,
10515
+ email: customer.email,
10516
+ document: customer.cpf,
10517
+ type: 'individual',
10518
+ document_type: 'CPF',
10519
+ address: {
10520
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
10521
+ line_2: `${customer.billingAddress.extension}`,
10522
+ zip_code: customer.billingAddress.zip,
10523
+ city: customer.billingAddress.city,
10524
+ state: customer.billingAddress.state,
10525
+ country: 'BR',
10526
+ },
10527
+ birthdate: format(new Date(customer.birthday), 'MM/dd/yyyy'),
10528
+ phones: {
10529
+ home_phone: {
10530
+ country_code: '55',
10531
+ number: customer.phone.slice(2),
10532
+ area_code: customer.phone.slice(0, 2),
10533
+ },
10534
+ mobile_phone: {
10535
+ country_code: '55',
10536
+ number: customer.phone.slice(2),
10537
+ area_code: customer.phone.slice(0, 2),
10538
+ },
10539
+ },
10540
+ },
10541
+ });
10542
+ return data;
10543
+ }
10544
+ catch (error) {
10545
+ console.warn(error);
10546
+ throw error;
10547
+ }
10548
+ }
10549
+ }
10550
+
10551
+ class PagarmeV5PixAxiosAdapter {
10552
+ constructor(credentials, paymentRepository) {
10553
+ this.credentials = credentials;
10554
+ this.paymentRepository = paymentRepository;
10555
+ }
10556
+ async pay(checkout) {
10557
+ try {
10558
+ const payload = PagarMeV5RequestHelper.build(checkout, 'pix');
10559
+ console.warn('[PAGARME PIX DATA TO SEND]', JSON.stringify(payload));
10560
+ const { data } = await axios({
10561
+ method: 'POST',
10562
+ url: `${this.credentials.URL}/orders`,
10563
+ headers: {
10564
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10565
+ 'Content-Type': 'application/json',
10566
+ },
10567
+ data: payload,
10568
+ });
10569
+ console.warn('[RESPONSE PAGARME PIX DATA]', JSON.stringify(data));
10570
+ if (data.status == PagarMeV5OrderStatus.Falha || data.status == PagarMeV5OrderStatus.Cancelado) {
10571
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
10572
+ checkoutId: checkout.id,
10573
+ userEmail: checkout.user.email,
10574
+ info: data.charges.at(0).last_transaction?.gateway_response,
10575
+ });
10576
+ }
10577
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(TransactionPaymentMethods.PIX, checkout, data));
10578
+ return payment;
10579
+ }
10580
+ catch (error) {
10581
+ if (error instanceof AxiosError) {
10582
+ console.error('error data: ', JSON.stringify(error.response?.data));
10583
+ }
10584
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
10585
+ checkoutId: checkout.id,
10586
+ userEmail: checkout.user.email,
10587
+ info: error.response?.data,
10588
+ });
10589
+ }
10590
+ }
10591
+ }
10592
+
8861
10593
  class VertexAxiosAdapter {
8862
10594
  constructor(config) {
8863
10595
  this.config = config;
@@ -9011,4 +10743,4 @@ class ProductsVertexSearch {
9011
10743
  }
9012
10744
  }
9013
10745
 
9014
- 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, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, 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, 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 };