@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.cjs.js CHANGED
@@ -6,6 +6,7 @@ require('reflect-metadata');
6
6
  var tslib = require('tslib');
7
7
  var classTransformer = require('class-transformer');
8
8
  var dateFns = require('date-fns');
9
+ var dateFnsTz = require('date-fns-tz');
9
10
  var lodash = require('lodash');
10
11
  var debug = require('debug');
11
12
  var serializeJavascript = require('serialize-javascript');
@@ -61,6 +62,18 @@ exports.OrderBlockedType = void 0;
61
62
  OrderBlockedType["Boleto"] = "Boleto";
62
63
  })(exports.OrderBlockedType || (exports.OrderBlockedType = {}));
63
64
 
65
+ exports.OrderPaymentStatus = void 0;
66
+ (function (OrderPaymentStatus) {
67
+ OrderPaymentStatus["Em processamento"] = "processing";
68
+ OrderPaymentStatus["Autorizada"] = "authorized";
69
+ OrderPaymentStatus["Pago"] = "paid";
70
+ OrderPaymentStatus["Estornada"] = "refunded";
71
+ OrderPaymentStatus["Aguardando pagamento"] = "waiting_payment";
72
+ OrderPaymentStatus["Aguardando estorno"] = "pending_refund";
73
+ OrderPaymentStatus["Recusada/N\u00E3o autorizada"] = "refused";
74
+ OrderPaymentStatus["Chargedback"] = "chargedback";
75
+ })(exports.OrderPaymentStatus || (exports.OrderPaymentStatus = {}));
76
+
64
77
  exports.PagarmePaymentStatus = void 0;
65
78
  (function (PagarmePaymentStatus) {
66
79
  PagarmePaymentStatus["Em processamento"] = "processing";
@@ -73,6 +86,33 @@ exports.PagarmePaymentStatus = void 0;
73
86
  PagarmePaymentStatus["Chargedback"] = "chargedback";
74
87
  })(exports.PagarmePaymentStatus || (exports.PagarmePaymentStatus = {}));
75
88
 
89
+ exports.PagarMeV5PaymentStatus = void 0;
90
+ (function (PagarMeV5PaymentStatus) {
91
+ PagarMeV5PaymentStatus["Em processamento"] = "processing";
92
+ PagarMeV5PaymentStatus["Gerado"] = "generated";
93
+ PagarMeV5PaymentStatus["Visualizado"] = "viewed";
94
+ PagarMeV5PaymentStatus["Pago a menor"] = "underpaid";
95
+ PagarMeV5PaymentStatus["Pago a maior"] = "overpaid";
96
+ PagarMeV5PaymentStatus["Aguardando pagamento"] = "waiting_payment";
97
+ PagarMeV5PaymentStatus["Pago"] = "paid";
98
+ PagarMeV5PaymentStatus["Aguardando estorno"] = "pending_refund";
99
+ PagarMeV5PaymentStatus["Autorizada pendente de captura"] = "authorized_pending_capture";
100
+ PagarMeV5PaymentStatus["N\u00E3o autorizada"] = "not_authorized";
101
+ PagarMeV5PaymentStatus["Capturada"] = "captured";
102
+ PagarMeV5PaymentStatus["Aguardando captura"] = "waiting_capture";
103
+ PagarMeV5PaymentStatus["Com erro"] = "with_error";
104
+ PagarMeV5PaymentStatus["Estornado"] = "refunded";
105
+ PagarMeV5PaymentStatus["Cancelado"] = "voided";
106
+ PagarMeV5PaymentStatus["Falha"] = "failed";
107
+ })(exports.PagarMeV5PaymentStatus || (exports.PagarMeV5PaymentStatus = {}));
108
+ exports.PagarMeV5OrderStatus = void 0;
109
+ (function (PagarMeV5OrderStatus) {
110
+ PagarMeV5OrderStatus["Pendente"] = "pending";
111
+ PagarMeV5OrderStatus["Pago"] = "paid";
112
+ PagarMeV5OrderStatus["Cancelado"] = "canceled";
113
+ PagarMeV5OrderStatus["Falha"] = "failed";
114
+ })(exports.PagarMeV5OrderStatus || (exports.PagarMeV5OrderStatus = {}));
115
+
76
116
  exports.PaymentMethods = void 0;
77
117
  (function (PaymentMethods) {
78
118
  PaymentMethods["CARD"] = "card";
@@ -86,8 +126,16 @@ exports.PaymentProviders = void 0;
86
126
  PaymentProviders["PAGARME"] = "pagarMe";
87
127
  PaymentProviders["ADYEN"] = "adyen";
88
128
  PaymentProviders["GLAMPOINTS"] = "glampoints";
129
+ PaymentProviders["MERCADOPAGO"] = "mercadoPago";
89
130
  })(exports.PaymentProviders || (exports.PaymentProviders = {}));
90
131
 
132
+ exports.TransactionPaymentMethods = void 0;
133
+ (function (TransactionPaymentMethods) {
134
+ TransactionPaymentMethods["CARD"] = "credit_card";
135
+ TransactionPaymentMethods["BANKSLIP"] = "boleto";
136
+ TransactionPaymentMethods["PIX"] = "pix";
137
+ })(exports.TransactionPaymentMethods || (exports.TransactionPaymentMethods = {}));
138
+
91
139
  class BasePaymentMethodFactory {
92
140
  constructor(methods) {
93
141
  this.methods = methods;
@@ -112,6 +160,9 @@ class AntifraudProviderFactory {
112
160
  class GlampointsPaymentMethodFactory extends BasePaymentMethodFactory {
113
161
  }
114
162
 
163
+ class MercadoPagoPaymentMethodFactory extends BasePaymentMethodFactory {
164
+ }
165
+
115
166
  class PagarmePaymentMethodFactory extends BasePaymentMethodFactory {
116
167
  }
117
168
 
@@ -722,6 +773,30 @@ tslib.__decorate([
722
773
  ], Category.prototype, "filters", void 0);
723
774
  registerClass('Category', Category);
724
775
 
776
+ class BrandCategory extends BaseModel {
777
+ get glamImages() {
778
+ return this.images?.[exports.Shops.GLAMSHOP]
779
+ ? this.images[exports.Shops.GLAMSHOP]
780
+ : {
781
+ brandBanner: null,
782
+ brandBannerMobile: null,
783
+ image: null,
784
+ };
785
+ }
786
+ get mensImages() {
787
+ return this.images?.[exports.Shops.MENSMARKET]
788
+ ? this.images[exports.Shops.MENSMARKET]
789
+ : {
790
+ brandBanner: null,
791
+ brandBannerMobile: null,
792
+ image: null,
793
+ };
794
+ }
795
+ static get identifiersFields() {
796
+ return ['id'];
797
+ }
798
+ }
799
+
725
800
  class CategoryCollectionChildren extends BaseModel {
726
801
  static get identifiersFields() {
727
802
  return ['collectionId', 'categoryId'];
@@ -795,6 +870,11 @@ class ProductReview extends BaseModel {
795
870
  return ['id'];
796
871
  }
797
872
  }
873
+ tslib.__decorate([
874
+ classTransformer.Type(resolveClass('Product')),
875
+ tslib.__metadata("design:type", Product)
876
+ ], ProductReview.prototype, "product", void 0);
877
+ registerClass('ProductReview', ProductReview);
798
878
 
799
879
  class ProductBase extends BaseModel {
800
880
  get evaluation() {
@@ -1725,19 +1805,58 @@ class AntifraudCardService {
1725
1805
  constructor(orderRepository, orderBlockedRepository) {
1726
1806
  this.orderRepository = orderRepository;
1727
1807
  this.orderBlockedRepository = orderBlockedRepository;
1728
- this.LIMIT_ORDERS_DAY = 2;
1729
- this.LIMIT_ORDERS_WEEK = 7;
1730
- this.LIMIT_BLOCKED_ORDERS_DAY = 5;
1808
+ this.LIMIT_ORDERS_DAY = null;
1809
+ this.LIMIT_ORDERS_WEEK = null;
1731
1810
  }
1732
1811
  async validate(checkout, card) {
1812
+ this.setLimitsByUserType(checkout.user.isSubscriber);
1733
1813
  await this.validateBlockedOrderAttempts(checkout, card);
1734
1814
  await this.validateDayAndWeekOrderLimits(checkout, card);
1735
1815
  return true;
1736
1816
  }
1817
+ setLimitsByUserType(isSubscriber) {
1818
+ this.LIMIT_ORDERS_DAY = {
1819
+ subscriber: {
1820
+ cpf: 4,
1821
+ email: 4,
1822
+ phone: 4,
1823
+ card: 4,
1824
+ zip: 4,
1825
+ },
1826
+ nonSubscriber: {
1827
+ cpf: 2,
1828
+ email: 2,
1829
+ phone: 2,
1830
+ card: 2,
1831
+ zip: 2,
1832
+ },
1833
+ };
1834
+ this.LIMIT_ORDERS_WEEK = {
1835
+ subscriber: {
1836
+ cpf: 12,
1837
+ email: 12,
1838
+ phone: 12,
1839
+ card: 12,
1840
+ zip: Infinity,
1841
+ },
1842
+ nonSubscriber: {
1843
+ cpf: 7,
1844
+ email: 7,
1845
+ phone: 7,
1846
+ card: 7,
1847
+ zip: Infinity,
1848
+ },
1849
+ };
1850
+ this.LIMIT_BLOCKED_ORDERS_DAY = isSubscriber ? 7 : 5;
1851
+ }
1852
+ getLimitsByUserType(type, isSubscriber) {
1853
+ const limits = type === 'day' ? this.LIMIT_ORDERS_DAY : this.LIMIT_ORDERS_WEEK;
1854
+ return isSubscriber ? limits['subscriber'] : limits['nonSubscriber'];
1855
+ }
1737
1856
  async validateBlockedOrderAttempts(checkout, card) {
1738
1857
  const isValid = await this.verifyBlockedOrderAttempts(checkout, card);
1739
1858
  if (!isValid) {
1740
- throw new FraudValidationError('Cliente com mais de 5 compras negadas/bloqueadas no dia', {
1859
+ throw new FraudValidationError(`Cliente com mais de ${this.LIMIT_BLOCKED_ORDERS_DAY} compras negadas/bloqueadas no dia`, {
1741
1860
  checkoutId: checkout.id,
1742
1861
  userEmail: checkout.user.email,
1743
1862
  info: {
@@ -1751,7 +1870,7 @@ class AntifraudCardService {
1751
1870
  async validateDayAndWeekOrderLimits(checkout, card) {
1752
1871
  const isValid = await this.verifyDayAndWeekOrders(checkout, card);
1753
1872
  if (!isValid) {
1754
- throw new FraudValidationError('Cliente tentando comprar mais de 2 vezes no dia ou 7 vezes na semana', {
1873
+ throw new FraudValidationError('Cliente tentando comprar mais do que o permitido no dia/semana', {
1755
1874
  checkoutId: checkout.id,
1756
1875
  userEmail: checkout.user.email,
1757
1876
  info: {
@@ -1770,7 +1889,7 @@ class AntifraudCardService {
1770
1889
  await this.createBlockedOrderRecord({
1771
1890
  checkout,
1772
1891
  card,
1773
- reason: 'More than 5 attempts have failed',
1892
+ reason: `More than ${this.LIMIT_BLOCKED_ORDERS_DAY} attempts have failed`,
1774
1893
  key: 'Failed attempts',
1775
1894
  period: 'day',
1776
1895
  });
@@ -1779,15 +1898,17 @@ class AntifraudCardService {
1779
1898
  return true;
1780
1899
  }
1781
1900
  getTodayDateRange() {
1782
- const day = `${dateFns.format(new Date(), 'yyyy-MM-dd')}T00:00:00`;
1783
- const endOfDay = `${dateFns.format(new Date(), 'yyyy-MM-dd')}T23:59:59`;
1784
- return { day, endOfDay };
1901
+ const timeZone = 'America/Sao_Paulo';
1902
+ const today = dateFnsTz.utcToZonedTime(new Date(), timeZone);
1903
+ const day = dateFns.startOfDay(today);
1904
+ const endOfDay = dateFns.endOfDay(today);
1905
+ return { day: dateFns.addHours(day, 3), endOfDay: dateFns.addHours(endOfDay, 3) };
1785
1906
  }
1786
1907
  async getBlockedOrdersByMultipleCriteria(checkout, dateRange) {
1787
1908
  const { day, endOfDay } = dateRange;
1788
1909
  const dateFilter = [
1789
- { operator: exports.Where.GTE, value: new Date(day) },
1790
- { operator: exports.Where.LTE, value: new Date(endOfDay) },
1910
+ { operator: exports.Where.GTE, value: day },
1911
+ { operator: exports.Where.LTE, value: endOfDay },
1791
1912
  ];
1792
1913
  const [ordersBlockedWithCpf, ordersBlockedWithEmail, ordersBlockedWithCep, ordersBlockedWithPhone] = await Promise.all([
1793
1914
  this.getBlockedOrdersByCpf(checkout.user?.cpf, dateFilter),
@@ -1889,26 +2010,28 @@ class AntifraudCardService {
1889
2010
  }
1890
2011
  async validateDayOrderLimits(checkout, params) {
1891
2012
  const ordersPerDay = await this.validateOrdersByRange(params, this.getDateRange('day'));
2013
+ const limits = this.getLimitsByUserType('day', checkout.user.isSubscriber);
1892
2014
  return this.checkOrderLimitsAndBlock({
1893
2015
  checkout,
1894
2016
  orderCounts: ordersPerDay,
1895
- limit: this.LIMIT_ORDERS_DAY,
2017
+ limit: limits,
1896
2018
  period: 'day',
1897
2019
  });
1898
2020
  }
1899
2021
  async validateWeekOrderLimits(checkout, params) {
1900
2022
  const ordersPerWeek = await this.validateOrdersByRange(params, this.getDateRange('week'));
2023
+ const limits = this.getLimitsByUserType('week', checkout.user.isSubscriber);
1901
2024
  return this.checkOrderLimitsAndBlock({
1902
2025
  checkout,
1903
2026
  orderCounts: ordersPerWeek,
1904
- limit: this.LIMIT_ORDERS_WEEK,
2027
+ limit: limits,
1905
2028
  period: 'week',
1906
2029
  });
1907
2030
  }
1908
2031
  async checkOrderLimitsAndBlock(params) {
1909
2032
  const { checkout, orderCounts, limit, period } = params;
1910
2033
  for (const key in orderCounts) {
1911
- if (orderCounts[key] >= limit) {
2034
+ if (orderCounts[key] >= limit[key]) {
1912
2035
  await this.createBlockedOrderRecord({
1913
2036
  checkout,
1914
2037
  card: null,
@@ -4726,6 +4849,17 @@ const withCrudFirestore = (MixinBase) => {
4726
4849
  };
4727
4850
  };
4728
4851
 
4852
+ class BrandCategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4853
+ constructor({ firestore, interceptors, }) {
4854
+ super({
4855
+ firestore,
4856
+ collectionName: 'brandsCategory',
4857
+ model: BrandCategory,
4858
+ interceptors,
4859
+ });
4860
+ }
4861
+ }
4862
+
4729
4863
  class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4730
4864
  constructor({ firestore, interceptors }) {
4731
4865
  super({
@@ -4801,6 +4935,9 @@ class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFire
4801
4935
  isChild(_id, _parentId) {
4802
4936
  return;
4803
4937
  }
4938
+ async getBrandsWithProducts() {
4939
+ return;
4940
+ }
4804
4941
  }
4805
4942
  tslib.__decorate([
4806
4943
  Log(),
@@ -5811,6 +5948,9 @@ tslib.__decorate([
5811
5948
  tslib.__metadata("design:type", Product)
5812
5949
  ], KitProductHasuraGraphQL.prototype, "product", void 0);
5813
5950
 
5951
+ class ProductCatalogHasuraGraphQL extends Product {
5952
+ }
5953
+
5814
5954
  class ProductHasuraGraphQL extends Product {
5815
5955
  }
5816
5956
  tslib.__decorate([
@@ -6899,6 +7039,19 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
6899
7039
  categoryFilterRepository: this.categoryFilterRepository,
6900
7040
  });
6901
7041
  }
7042
+ async getBrandsWithProducts() {
7043
+ const fields = ['id', 'name', 'slug', 'brand_category', 'published', 'images'];
7044
+ const { brands_with_products_query: data, } = await this.query('brands_with_products_query', fields);
7045
+ return data.map((brand) => Category.toInstance({
7046
+ id: brand.id,
7047
+ name: brand.name,
7048
+ slug: brand.slug,
7049
+ brandCategory: brand.brand_category,
7050
+ shops: brand.shops,
7051
+ published: brand.published,
7052
+ images: brand.images,
7053
+ }));
7054
+ }
6902
7055
  }
6903
7056
  tslib.__decorate([
6904
7057
  Log(),
@@ -7163,83 +7316,7 @@ class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasu
7163
7316
  }
7164
7317
  }
7165
7318
 
7166
- class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7167
- constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7168
- super({
7169
- tableName: 'product_errors',
7170
- model: ProductErrorsHasuraGraphQL,
7171
- endpoint,
7172
- authOptions,
7173
- interceptors,
7174
- cache,
7175
- fields: [
7176
- {
7177
- productId: {
7178
- columnName: 'product_id',
7179
- to: (value) => +value,
7180
- from: (value) => value.toString(),
7181
- },
7182
- },
7183
- 'source',
7184
- 'error',
7185
- { createdAt: { columnName: 'created_at' } },
7186
- { updatedAt: { columnName: 'updated_at' } },
7187
- {
7188
- product: {
7189
- columnName: 'product',
7190
- foreignKeyColumn: { id: 'productId' },
7191
- fields: [
7192
- { id: { columnName: 'id', from: (value) => value.toString() } },
7193
- { productId: { columnName: 'main_product_id' } },
7194
- 'name',
7195
- 'published',
7196
- 'group',
7197
- 'validity',
7198
- { createdAt: { columnName: 'created_at' } },
7199
- { updatedAt: { columnName: 'updated_at' } },
7200
- ],
7201
- },
7202
- },
7203
- ],
7204
- });
7205
- this.productRepository = productRepository;
7206
- }
7207
- async get(params) {
7208
- const result = await super.get(params);
7209
- if (result instanceof VariantHasuraGraphQL) {
7210
- const product = await this.productRepository.get({ id: result.productId.toString() });
7211
- result.product.name = product.name;
7212
- result.product.group = product.group;
7213
- }
7214
- return result;
7215
- }
7216
- async find(params) {
7217
- const result = await super.find(params);
7218
- const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7219
- (lodash.isEmpty(item.product.name) || lodash.isEmpty(item.product.group) || lodash.isEmpty(item.product)));
7220
- if (variantsWithNoData.length > 0) {
7221
- const { data: products } = await this.productRepository.find({
7222
- filters: {
7223
- id: {
7224
- operator: exports.Where.IN,
7225
- value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7226
- },
7227
- },
7228
- });
7229
- products.forEach((product) => {
7230
- result.data
7231
- .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7232
- .forEach((variant) => {
7233
- variant.product.name = product.name;
7234
- variant.product.group = product.group;
7235
- });
7236
- });
7237
- }
7238
- return result;
7239
- }
7240
- }
7241
-
7242
- const commonFields = [
7319
+ const commonFields$1 = [
7243
7320
  {
7244
7321
  id: {
7245
7322
  columnName: 'id',
@@ -7319,6 +7396,12 @@ const commonFields = [
7319
7396
  to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7320
7397
  },
7321
7398
  },
7399
+ {
7400
+ imagesCard: {
7401
+ columnName: 'images_card',
7402
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7403
+ },
7404
+ },
7322
7405
  'name',
7323
7406
  {
7324
7407
  price: {
@@ -7380,7 +7463,6 @@ const commonFields = [
7380
7463
  'weight',
7381
7464
  'gender',
7382
7465
  { intGender: { columnName: 'int_gender' } },
7383
- // { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
7384
7466
  { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7385
7467
  { isKit: { columnName: 'is_kit' } },
7386
7468
  { createdAt: { columnName: 'created_at' } },
@@ -7401,135 +7483,663 @@ const commonFields = [
7401
7483
  { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7402
7484
  { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7403
7485
  { daysOfUse: { columnName: 'days_of_use' } },
7486
+ // { showVariants: { columnName: 'show_variants' } },
7487
+ // { variantSlug: { columnName: 'variant_slug' } },
7404
7488
  ];
7405
- const fieldsConfiguration$2 = [
7406
- ...commonFields,
7407
- {
7408
- categories: {
7409
- columnName: 'categories',
7410
- fields: ['category_id'],
7411
- bindPersistData: (value) => ({
7412
- categories: { data: value.map((category) => ({ category_id: +category })) },
7413
- }),
7414
- to: (categories) => categories.map((categoryId) => +categoryId),
7415
- from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7416
- },
7417
- },
7418
- {
7419
- kitProducts: {
7420
- columnName: 'kit_products',
7421
- foreignKeyColumn: { productId: 'id' },
7422
- fields: [
7423
- { productId: { columnName: 'product_id' } },
7424
- { kitProductId: { columnName: 'kit_product_id' } },
7425
- 'quantity',
7426
- { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7427
- ],
7428
- },
7429
- },
7430
- {
7431
- reviews: {
7432
- columnName: 'reviews',
7433
- foreignKeyColumn: { product_id: 'id' },
7434
- fields: [
7435
- 'id',
7436
- 'shop',
7437
- 'rate',
7438
- 'author',
7439
- 'email',
7440
- 'location',
7441
- 'review',
7442
- 'status',
7443
- 'title',
7444
- { personId: { columnName: 'person_id' } },
7445
- 'points',
7446
- { orderId: { columnName: 'order_id' } },
7447
- { createdAt: { columnName: 'created_at' } },
7448
- { updatedAt: { columnName: 'updated_at' } },
7449
- ],
7450
- },
7451
- },
7452
- {
7453
- metadata: {
7454
- columnName: 'metadata',
7455
- fields: ['title', 'description'],
7456
- bindPersistData: (value) => ({
7457
- metadata: { data: value },
7458
- }),
7459
- },
7460
- },
7461
- {
7462
- variants: {
7463
- columnName: 'variants',
7464
- foreignKeyColumn: { product_id: 'id' },
7465
- fields: ['id', 'ean', 'grade', 'price', 'published', 'stock', 'tagsProfile'],
7466
- },
7467
- },
7468
- ];
7469
- class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7470
- get reviewsFields() {
7471
- return [
7472
- 'id',
7473
- 'shop',
7474
- 'rate',
7475
- 'author',
7476
- 'email',
7477
- 'location',
7478
- 'review',
7479
- 'status',
7480
- 'title',
7481
- { personId: { columnName: 'person_id' } },
7482
- 'points',
7483
- { orderId: { columnName: 'order_id' } },
7484
- { createdAt: { columnName: 'created_at' } },
7485
- { updatedAt: { columnName: 'updated_at' } },
7486
- ];
7487
- }
7489
+ class ProductCatalogHasuraGraphQLRepository extends withFindHasuraGraphQL(withHasuraGraphQL(Base)) {
7488
7490
  constructor({ endpoint, authOptions, interceptors, cache, }) {
7489
7491
  super({
7490
7492
  tableName: 'product',
7491
- model: ProductHasuraGraphQL,
7493
+ model: ProductCatalogHasuraGraphQL,
7492
7494
  endpoint,
7493
7495
  authOptions,
7494
7496
  interceptors,
7495
- fields: fieldsConfiguration$2,
7497
+ fields: commonFields$1,
7496
7498
  cache,
7497
7499
  });
7498
- this.bindReviewToModel = (plain) => ProductReview.toInstance({
7499
- ...is(lodash.omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id'])),
7500
- createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at,
7501
- updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at,
7502
- personId: plain.person_id,
7503
- orderId: plain.order_id,
7504
- });
7505
- this.bindReviewToHasura = (review) => ({
7506
- ...is(lodash.omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId'])),
7507
- person_id: review.personId,
7508
- order_id: review.orderId,
7509
- });
7510
7500
  }
7511
- async create(params) {
7512
- const { metadata, ...data } = params;
7513
- const product = await super.create(lodash.omit({ ...data, metadata: metadata || { description: null, title: null } }, ['reviews']));
7514
- try {
7515
- product.reviews = data.reviews && (await this.updateReviews(+product.id, data));
7516
- }
7517
- catch (error) {
7518
- await this.delete({ id: product.id });
7519
- throw error;
7501
+ async get({ id }, options) {
7502
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7503
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7504
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7505
+ if (cachedData) {
7506
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7507
+ return this.model.toInstance(deserialize(cachedData));
7508
+ }
7520
7509
  }
7521
- return product;
7522
- }
7523
- async get(identifiers, options) {
7524
- const product = Number.isNaN(+identifiers.id)
7525
- ? (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
7526
- .data?.[0]
7527
- : await super.get(identifiers, options);
7528
- if (product.productId)
7529
- throw new NotFoundError('Product not found, it is a variant');
7530
- product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, options));
7531
- return product;
7532
- }
7510
+ const product = await super
7511
+ .find({
7512
+ filters: {
7513
+ id,
7514
+ },
7515
+ limits: {
7516
+ limit: 1,
7517
+ },
7518
+ })
7519
+ .then((res) => res.data.at(0));
7520
+ if (!product)
7521
+ throw new NotFoundError(`Product not found`);
7522
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7523
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7524
+ await this.cache.cacheAdapter.set({
7525
+ key: cacheKey,
7526
+ data: serialize(product),
7527
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7528
+ });
7529
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7530
+ }
7531
+ return product;
7532
+ }
7533
+ async getByEAN(EAN, options) {
7534
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7535
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7536
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7537
+ if (cachedData) {
7538
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7539
+ return this.model.toInstance(deserialize(cachedData));
7540
+ }
7541
+ }
7542
+ const product = await super
7543
+ .find({
7544
+ filters: {
7545
+ EAN,
7546
+ },
7547
+ limits: {
7548
+ limit: 1,
7549
+ },
7550
+ })
7551
+ .then((res) => res.data.at(0));
7552
+ if (!product)
7553
+ return null;
7554
+ RoundProductPricesHelper.roundProductPrices(product);
7555
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7556
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7557
+ await this.cache.cacheAdapter.set({
7558
+ key: cacheKey,
7559
+ data: serialize(product),
7560
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7561
+ });
7562
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7563
+ }
7564
+ return product;
7565
+ }
7566
+ async find(params, optionsParams) {
7567
+ const { filters, fields, ...options } = params || {};
7568
+ const bindFields = fields ||
7569
+ this.fields
7570
+ .map((field) => (typeof field === 'string' ? field : Object.keys(field).shift()))
7571
+ .filter((field) => field !== 'reviews' && field !== 'categories');
7572
+ if (options.options?.minimal?.includes('price'))
7573
+ options.options?.minimal.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
7574
+ if (options.options?.maximum?.includes('price'))
7575
+ options.options?.maximum.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
7576
+ options.options?.minimal?.splice(options.options?.minimal.indexOf('price'), 1);
7577
+ options.options?.maximum?.splice(options.options?.maximum.indexOf('price'), 1);
7578
+ return super.find({
7579
+ ...options,
7580
+ filters: { ...filters },
7581
+ fields: [
7582
+ ...bindFields,
7583
+ ...(bindFields.includes('price')
7584
+ ? [
7585
+ 'subscriberPrice',
7586
+ 'subscriberDiscountPercentage',
7587
+ 'fullPrice',
7588
+ ]
7589
+ : []),
7590
+ ],
7591
+ }, optionsParams);
7592
+ }
7593
+ async findCatalog(params, mainGender, options) {
7594
+ const result = await this.find({
7595
+ ...params,
7596
+ filters: { ...params.filters, published: true },
7597
+ orderBy: {
7598
+ hasStock: 'desc',
7599
+ ...(!mainGender ? {} : { intGender: mainGender === 'female' ? 'desc' : 'asc' }),
7600
+ ...lodash.omit(params.orderBy, ['hasStock', 'intGender']),
7601
+ },
7602
+ }, options);
7603
+ return result;
7604
+ }
7605
+ }
7606
+ tslib.__decorate([
7607
+ Log(),
7608
+ tslib.__metadata("design:type", Function),
7609
+ tslib.__metadata("design:paramtypes", [Object, Object, Object]),
7610
+ tslib.__metadata("design:returntype", Promise)
7611
+ ], ProductCatalogHasuraGraphQLRepository.prototype, "findCatalog", null);
7612
+
7613
+ class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7614
+ constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7615
+ super({
7616
+ tableName: 'product_errors',
7617
+ model: ProductErrorsHasuraGraphQL,
7618
+ endpoint,
7619
+ authOptions,
7620
+ interceptors,
7621
+ cache,
7622
+ fields: [
7623
+ {
7624
+ productId: {
7625
+ columnName: 'product_id',
7626
+ to: (value) => +value,
7627
+ from: (value) => value.toString(),
7628
+ },
7629
+ },
7630
+ 'source',
7631
+ 'error',
7632
+ { createdAt: { columnName: 'created_at' } },
7633
+ { updatedAt: { columnName: 'updated_at' } },
7634
+ {
7635
+ product: {
7636
+ columnName: 'product',
7637
+ foreignKeyColumn: { id: 'productId' },
7638
+ fields: [
7639
+ { id: { columnName: 'id', from: (value) => value.toString() } },
7640
+ { productId: { columnName: 'main_product_id' } },
7641
+ 'name',
7642
+ 'published',
7643
+ 'group',
7644
+ 'validity',
7645
+ { createdAt: { columnName: 'created_at' } },
7646
+ { updatedAt: { columnName: 'updated_at' } },
7647
+ ],
7648
+ },
7649
+ },
7650
+ ],
7651
+ });
7652
+ this.productRepository = productRepository;
7653
+ }
7654
+ async get(params) {
7655
+ const result = await super.get(params);
7656
+ if (result instanceof VariantHasuraGraphQL) {
7657
+ const product = await this.productRepository.get({ id: result.productId.toString() });
7658
+ result.product.name = product.name;
7659
+ result.product.group = product.group;
7660
+ }
7661
+ return result;
7662
+ }
7663
+ async find(params) {
7664
+ const result = await super.find(params);
7665
+ const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7666
+ (lodash.isEmpty(item.product.name) || lodash.isEmpty(item.product.group) || lodash.isEmpty(item.product)));
7667
+ if (variantsWithNoData.length > 0) {
7668
+ const { data: products } = await this.productRepository.find({
7669
+ filters: {
7670
+ id: {
7671
+ operator: exports.Where.IN,
7672
+ value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7673
+ },
7674
+ },
7675
+ });
7676
+ products.forEach((product) => {
7677
+ result.data
7678
+ .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7679
+ .forEach((variant) => {
7680
+ variant.product.name = product.name;
7681
+ variant.product.group = product.group;
7682
+ });
7683
+ });
7684
+ }
7685
+ return result;
7686
+ }
7687
+ }
7688
+
7689
+ const commonFields = [
7690
+ {
7691
+ id: {
7692
+ columnName: 'id',
7693
+ to: (value) => +value,
7694
+ from: (value) => value.toString(),
7695
+ },
7696
+ },
7697
+ { firestoreId: { columnName: 'firestore_id' } },
7698
+ { productId: { columnName: 'main_product_id' } },
7699
+ { CEST: { columnName: 'cest' } },
7700
+ { EAN: { columnName: 'ean' } },
7701
+ { NCM: { columnName: 'ncm' } },
7702
+ 'brand',
7703
+ { costPrice: { columnName: 'cost_price' } },
7704
+ {
7705
+ description: {
7706
+ columnName: 'description',
7707
+ from: (description, data) => ({
7708
+ description,
7709
+ differentials: data.differentials,
7710
+ whoMustUse: data.who_must_use,
7711
+ howToUse: data.how_to_use,
7712
+ brand: data.brand_description,
7713
+ ingredients: data.ingredients,
7714
+ purpose: data.purpose,
7715
+ }),
7716
+ bindFindFilter: (filters) => {
7717
+ return {
7718
+ ...(filters?.description && { description: filters.description }),
7719
+ ...(filters.differentials && { differentials: filters.differentials }),
7720
+ ...(filters.whoMustUse && {
7721
+ who_must_use: filters.whoMustUse,
7722
+ }),
7723
+ ...(filters.howToUse && {
7724
+ how_to_use: filters.howToUse,
7725
+ }),
7726
+ ...(filters.brand && {
7727
+ brand_description: filters.brand,
7728
+ }),
7729
+ ...(filters.ingredients && {
7730
+ ingredients: filters.ingredients,
7731
+ }),
7732
+ ...(filters.purpose && {
7733
+ purpose: filters.purpose,
7734
+ }),
7735
+ };
7736
+ },
7737
+ bindPersistData: (descriptionData) => ({
7738
+ ...(descriptionData?.description && { description: descriptionData.description }),
7739
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
7740
+ ...(descriptionData.whoMustUse && {
7741
+ who_must_use: descriptionData.whoMustUse,
7742
+ }),
7743
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
7744
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
7745
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
7746
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
7747
+ }),
7748
+ },
7749
+ },
7750
+ { differentials: { columnName: 'differentials' } },
7751
+ { whoMustUse: { columnName: 'who_must_use' } },
7752
+ { howToUse: { columnName: 'how_to_use' } },
7753
+ { brandDescription: { columnName: 'brand_description' } },
7754
+ { ingredients: { columnName: 'ingredients' } },
7755
+ { purpose: { columnName: 'purpose' } },
7756
+ { hasVariants: { columnName: 'has_variants' } },
7757
+ {
7758
+ images: {
7759
+ columnName: 'images',
7760
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7761
+ },
7762
+ },
7763
+ {
7764
+ miniatures: {
7765
+ columnName: 'miniatures',
7766
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7767
+ },
7768
+ },
7769
+ {
7770
+ imagesCard: {
7771
+ columnName: 'images_card',
7772
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7773
+ },
7774
+ },
7775
+ 'name',
7776
+ {
7777
+ price: {
7778
+ columnName: 'price',
7779
+ from: (price, data) => ({
7780
+ price,
7781
+ fullPrice: data.full_price,
7782
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
7783
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
7784
+ subscriberPrice: data.subscriber_price,
7785
+ }),
7786
+ bindFindFilter: (filters) => {
7787
+ return {
7788
+ ...((filters?.price || filters?.price === 0) && { price: filters.price }),
7789
+ ...((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice }),
7790
+ ...((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
7791
+ subscriber_discount_percentage: filters.subscriberDiscountPercentage,
7792
+ }),
7793
+ ...((filters.subscriberPrice || filters.subscriberPrice === 0) && {
7794
+ subscriber_price: filters.subscriberPrice,
7795
+ }),
7796
+ ...((filters.fullPriceDiscountPercentage || filters.fullPriceDiscountPercentage === 0) && {
7797
+ full_price_discount_percentage: filters.fullPriceDiscountPercentage,
7798
+ }),
7799
+ };
7800
+ },
7801
+ bindPersistData: (priceData) => ({
7802
+ ...(priceData?.price >= 0 && { price: priceData.price }),
7803
+ ...(priceData.fullPrice >= 0 && { full_price: priceData.fullPrice }),
7804
+ ...(priceData.subscriberDiscountPercentage >= 0 && {
7805
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
7806
+ }),
7807
+ ...(priceData.subscriberPrice >= 0 && { subscriber_price: priceData.subscriberPrice }),
7808
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
7809
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
7810
+ }),
7811
+ }),
7812
+ },
7813
+ },
7814
+ { fullPrice: { columnName: 'full_price' } },
7815
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
7816
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
7817
+ { subscriberPrice: { columnName: 'subscriber_price' } },
7818
+ 'published',
7819
+ 'outlet',
7820
+ 'label',
7821
+ 'sku',
7822
+ {
7823
+ stock: {
7824
+ columnName: 'stock',
7825
+ from: (quantity) => ({ quantity }),
7826
+ to: (value) => (lodash.isNil(value?.quantity) ? value : value?.quantity),
7827
+ },
7828
+ },
7829
+ { hasStock: { columnName: 'has_stock' } },
7830
+ 'slug',
7831
+ 'type',
7832
+ 'video',
7833
+ 'weight',
7834
+ 'gender',
7835
+ { intGender: { columnName: 'int_gender' } },
7836
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7837
+ { isKit: { columnName: 'is_kit' } },
7838
+ { createdAt: { columnName: 'created_at' } },
7839
+ { updatedAt: { columnName: 'updated_at' } },
7840
+ { rate: { columnName: 'rating' } },
7841
+ { reviewsTotal: { columnName: 'reviews_total' } },
7842
+ { shoppingCount: { columnName: 'shopping_count' } },
7843
+ { categoryId: { columnName: 'category_id' } },
7844
+ {
7845
+ category: {
7846
+ columnName: 'category',
7847
+ foreignKeyColumn: { id: 'categoryId' },
7848
+ fields: ['id', 'name', 'reference', 'slug'],
7849
+ },
7850
+ },
7851
+ 'group',
7852
+ 'validity',
7853
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7854
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7855
+ { daysOfUse: { columnName: 'days_of_use' } },
7856
+ // { showVariants: { columnName: 'show_variants' } },
7857
+ // { variantSlug: { columnName: 'variant_slug' } },
7858
+ ];
7859
+ const fieldsConfiguration$2 = [
7860
+ ...commonFields,
7861
+ {
7862
+ categories: {
7863
+ columnName: 'categories',
7864
+ fields: ['category_id'],
7865
+ bindPersistData: (value) => ({
7866
+ categories: { data: value.map((category) => ({ category_id: +category })) },
7867
+ }),
7868
+ to: (categories) => categories.map((categoryId) => +categoryId),
7869
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7870
+ },
7871
+ },
7872
+ {
7873
+ kitProducts: {
7874
+ columnName: 'kit_products',
7875
+ foreignKeyColumn: { productId: 'id' },
7876
+ fields: [
7877
+ { productId: { columnName: 'product_id' } },
7878
+ { kitProductId: { columnName: 'kit_product_id' } },
7879
+ 'quantity',
7880
+ { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7881
+ ],
7882
+ },
7883
+ },
7884
+ {
7885
+ reviews: {
7886
+ columnName: 'reviews',
7887
+ foreignKeyColumn: { product_id: 'id' },
7888
+ fields: [
7889
+ 'id',
7890
+ 'shop',
7891
+ 'rate',
7892
+ 'author',
7893
+ 'email',
7894
+ 'location',
7895
+ 'review',
7896
+ 'status',
7897
+ 'title',
7898
+ { personId: { columnName: 'person_id' } },
7899
+ 'points',
7900
+ { orderId: { columnName: 'order_id' } },
7901
+ { createdAt: { columnName: 'created_at' } },
7902
+ { updatedAt: { columnName: 'updated_at' } },
7903
+ ],
7904
+ },
7905
+ },
7906
+ {
7907
+ metadata: {
7908
+ columnName: 'metadata',
7909
+ fields: ['title', 'description'],
7910
+ bindPersistData: (value) => ({
7911
+ metadata: { data: value },
7912
+ }),
7913
+ },
7914
+ },
7915
+ {
7916
+ variants: {
7917
+ columnName: 'variants',
7918
+ foreignKeyColumn: { product_id: 'id' },
7919
+ fields: [
7920
+ 'id',
7921
+ 'name',
7922
+ 'ean',
7923
+ 'sku',
7924
+ {
7925
+ description: {
7926
+ columnName: 'description',
7927
+ from: (description, data) => ({
7928
+ description,
7929
+ differentials: data.differentials,
7930
+ whoMustUse: data.who_must_use,
7931
+ howToUse: data.how_to_use,
7932
+ brand: data.brand_description,
7933
+ ingredients: data.ingredients,
7934
+ purpose: data.purpose,
7935
+ }),
7936
+ bindFindFilter: (filters) => {
7937
+ return {
7938
+ ...(filters?.description && { description: filters.description }),
7939
+ ...(filters.differentials && { differentials: filters.differentials }),
7940
+ ...(filters.whoMustUse && {
7941
+ who_must_use: filters.whoMustUse,
7942
+ }),
7943
+ ...(filters.howToUse && {
7944
+ how_to_use: filters.howToUse,
7945
+ }),
7946
+ ...(filters.brand && {
7947
+ brand_description: filters.brand,
7948
+ }),
7949
+ ...(filters.ingredients && {
7950
+ ingredients: filters.ingredients,
7951
+ }),
7952
+ ...(filters.purpose && {
7953
+ purpose: filters.purpose,
7954
+ }),
7955
+ };
7956
+ },
7957
+ bindPersistData: (descriptionData) => ({
7958
+ ...(descriptionData?.description && { description: descriptionData.description }),
7959
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
7960
+ ...(descriptionData.whoMustUse && {
7961
+ who_must_use: descriptionData.whoMustUse,
7962
+ }),
7963
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
7964
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
7965
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
7966
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
7967
+ }),
7968
+ },
7969
+ },
7970
+ { differentials: { columnName: 'differentials' } },
7971
+ { whoMustUse: { columnName: 'who_must_use' } },
7972
+ { howToUse: { columnName: 'how_to_use' } },
7973
+ { brandDescription: { columnName: 'brand_description' } },
7974
+ { ingredients: { columnName: 'ingredients' } },
7975
+ { purpose: { columnName: 'purpose' } },
7976
+ {
7977
+ grade: {
7978
+ columnName: 'grade',
7979
+ type: HasuraGraphQLColumnType.Jsonb,
7980
+ },
7981
+ },
7982
+ {
7983
+ price: {
7984
+ columnName: 'price',
7985
+ from: (price, data) => ({
7986
+ price,
7987
+ fullPrice: data.full_price,
7988
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
7989
+ subscriberPrice: data.subscriber_price,
7990
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
7991
+ }),
7992
+ bindPersistData: (priceData) => ({
7993
+ ...((priceData?.price || 0) >= 0 && { price: priceData.price }),
7994
+ ...((priceData?.fullPrice || 0) >= 0 && { full_price: priceData.fullPrice }),
7995
+ ...((priceData?.subscriberDiscountPercentage || 0) >= 0 && {
7996
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
7997
+ }),
7998
+ ...((priceData?.subscriberPrice || 0) >= 0 && { subscriber_price: priceData.subscriberPrice }),
7999
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
8000
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
8001
+ }),
8002
+ }),
8003
+ },
8004
+ },
8005
+ { fullPrice: { columnName: 'full_price' } },
8006
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
8007
+ { subscriberPrice: { columnName: 'subscriber_price' } },
8008
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
8009
+ 'published',
8010
+ {
8011
+ stock: {
8012
+ columnName: 'stock',
8013
+ from: (quantity) => ({ quantity }),
8014
+ to: (value) => (lodash.isNil(value?.quantity) ? value : value?.quantity),
8015
+ },
8016
+ },
8017
+ {
8018
+ images: {
8019
+ columnName: 'images',
8020
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8021
+ },
8022
+ },
8023
+ {
8024
+ miniatures: {
8025
+ columnName: 'miniatures',
8026
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8027
+ },
8028
+ },
8029
+ {
8030
+ imagesCard: {
8031
+ columnName: 'images_card',
8032
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8033
+ },
8034
+ },
8035
+ { tagsProfile: { columnName: 'tags_profile' } },
8036
+ { tagsCollection: { columnName: 'tags_collection' } },
8037
+ // { variantSlug: { columnName: 'variant_slug' } },
8038
+ {
8039
+ reviews: {
8040
+ columnName: 'reviews',
8041
+ foreignKeyColumn: { product_id: 'id' },
8042
+ fields: [
8043
+ 'id',
8044
+ 'shop',
8045
+ 'rate',
8046
+ 'author',
8047
+ 'email',
8048
+ 'location',
8049
+ 'review',
8050
+ 'status',
8051
+ 'title',
8052
+ { personId: { columnName: 'person_id' } },
8053
+ 'points',
8054
+ { orderId: { columnName: 'order_id' } },
8055
+ { createdAt: { columnName: 'created_at' } },
8056
+ { updatedAt: { columnName: 'updated_at' } },
8057
+ ],
8058
+ },
8059
+ },
8060
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
8061
+ {
8062
+ metadata: {
8063
+ columnName: 'metadata',
8064
+ fields: ['title', 'description'],
8065
+ bindPersistData: (value) => ({
8066
+ metadata: { data: value },
8067
+ }),
8068
+ },
8069
+ },
8070
+ ],
8071
+ },
8072
+ },
8073
+ ];
8074
+ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8075
+ get reviewsFields() {
8076
+ return [
8077
+ 'id',
8078
+ 'shop',
8079
+ 'rate',
8080
+ 'author',
8081
+ 'email',
8082
+ 'location',
8083
+ 'review',
8084
+ 'status',
8085
+ 'title',
8086
+ { personId: { columnName: 'person_id' } },
8087
+ 'points',
8088
+ { orderId: { columnName: 'order_id' } },
8089
+ { createdAt: { columnName: 'created_at' } },
8090
+ { updatedAt: { columnName: 'updated_at' } },
8091
+ ];
8092
+ }
8093
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
8094
+ super({
8095
+ tableName: 'product',
8096
+ model: ProductHasuraGraphQL,
8097
+ endpoint,
8098
+ authOptions,
8099
+ interceptors,
8100
+ fields: fieldsConfiguration$2,
8101
+ cache,
8102
+ });
8103
+ this.bindReviewToModel = (plain) => ProductReview.toInstance({
8104
+ ...is(lodash.omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id'])),
8105
+ createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at,
8106
+ updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at,
8107
+ personId: plain.person_id,
8108
+ orderId: plain.order_id,
8109
+ });
8110
+ this.bindReviewToHasura = (review) => ({
8111
+ ...is(lodash.omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId'])),
8112
+ person_id: review.personId,
8113
+ order_id: review.orderId,
8114
+ });
8115
+ }
8116
+ async create(params) {
8117
+ const { metadata, ...data } = params;
8118
+ const product = await super.create(lodash.omit({ ...data, metadata: metadata || { description: null, title: null } }, ['reviews']));
8119
+ try {
8120
+ product.reviews = data.reviews && (await this.updateReviews(+product.id, data));
8121
+ }
8122
+ catch (error) {
8123
+ await this.delete({ id: product.id });
8124
+ throw error;
8125
+ }
8126
+ return product;
8127
+ }
8128
+ async get(identifiers, options) {
8129
+ const product = Number.isNaN(+identifiers.id)
8130
+ ? (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
8131
+ .data?.[0]
8132
+ : await super.get(identifiers, options);
8133
+ if (product.productId)
8134
+ throw new NotFoundError('Product not found, it is a variant');
8135
+ product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, false, options));
8136
+ if (!product.variants?.length) {
8137
+ for (const [index, variant] of product.variants.entries()) {
8138
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8139
+ }
8140
+ }
8141
+ return product;
8142
+ }
7533
8143
  async find(params, optionsParams) {
7534
8144
  const { filters, fields, ...options } = params || {};
7535
8145
  const bindFields = fields ||
@@ -7569,6 +8179,9 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7569
8179
  const result = await this.find({
7570
8180
  filters: {
7571
8181
  slug,
8182
+ productId: {
8183
+ operator: exports.Where.ISNULL,
8184
+ },
7572
8185
  },
7573
8186
  fields: this.fields.map((field) => typeof field === 'string' ? field : Object.keys(field).shift()),
7574
8187
  options: {
@@ -7578,6 +8191,11 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7578
8191
  if (!result.data.length)
7579
8192
  return null;
7580
8193
  const product = result?.data?.shift();
8194
+ if (!product.variants?.length) {
8195
+ for (const [index, variant] of product.variants.entries()) {
8196
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8197
+ }
8198
+ }
7581
8199
  RoundProductPricesHelper.roundProductPrices(product);
7582
8200
  if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7583
8201
  const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
@@ -7757,7 +8375,8 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7757
8375
  const plainData = this.paramsToPlain({ metadata });
7758
8376
  if (!plainData.metadata)
7759
8377
  return null;
7760
- await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8378
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8379
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
7761
8380
  pk_columns: {
7762
8381
  value: { product_id: productId },
7763
8382
  type: 'product_metadata_pk_columns_input',
@@ -7769,6 +8388,14 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7769
8388
  required: true,
7770
8389
  },
7771
8390
  });
8391
+ if (!update_product_metadata_by_pk) {
8392
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8393
+ objects: {
8394
+ type: '[product_metadata_insert_input!]!',
8395
+ value: [{ product_id: productId, ...metadata }],
8396
+ },
8397
+ });
8398
+ }
7772
8399
  return plainData.metadata;
7773
8400
  }
7774
8401
  async getId(id) {
@@ -7779,7 +8406,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7779
8406
  return data?.[0]?.id;
7780
8407
  throw new NotFoundError(`Product with id ${id} not found`);
7781
8408
  }
7782
- async findReviewsByProduct(productId, options) {
8409
+ async findReviewsByProduct(productId, onlyApproved, options) {
7783
8410
  if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7784
8411
  const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
7785
8412
  const cachedData = await this.cache.cacheAdapter.get(cacheKey);
@@ -7792,10 +8419,16 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7792
8419
  where: {
7793
8420
  value: {
7794
8421
  product_id: { _eq: productId },
8422
+ ...(onlyApproved && { status: { _eq: true } }),
7795
8423
  },
7796
8424
  type: 'product_review_bool_exp',
7797
8425
  required: true,
7798
8426
  },
8427
+ order_by: {
8428
+ type: '[product_review_order_by]',
8429
+ value: [{ createdAt: 'desc' }],
8430
+ required: true,
8431
+ },
7799
8432
  });
7800
8433
  const reviews = data?.map((review) => this.bindReviewToModel(review));
7801
8434
  if (this.cache?.cacheAdapter && options?.cache?.enabled && reviews) {
@@ -7900,7 +8533,7 @@ tslib.__decorate([
7900
8533
  tslib.__decorate([
7901
8534
  Log(),
7902
8535
  tslib.__metadata("design:type", Function),
7903
- tslib.__metadata("design:paramtypes", [Number, Object]),
8536
+ tslib.__metadata("design:paramtypes", [Number, Boolean, Object]),
7904
8537
  tslib.__metadata("design:returntype", Promise)
7905
8538
  ], ProductHasuraGraphQLRepository.prototype, "findReviewsByProduct", null);
7906
8539
 
@@ -7932,7 +8565,25 @@ class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHas
7932
8565
  product: {
7933
8566
  columnName: 'product',
7934
8567
  foreignKeyColumn: { id: 'productId' },
7935
- fields: ['id', 'ean', 'sku', 'name', 'brand', 'slug', 'images', 'grade', 'gender'],
8568
+ fields: [
8569
+ 'id',
8570
+ {
8571
+ productId: {
8572
+ columnName: 'main_product_id',
8573
+ to: (value) => +value,
8574
+ from: (value) => value?.toString(),
8575
+ },
8576
+ },
8577
+ 'ean',
8578
+ 'sku',
8579
+ 'name',
8580
+ 'brand',
8581
+ 'slug',
8582
+ 'images',
8583
+ 'grade',
8584
+ 'gender',
8585
+ '',
8586
+ ],
7936
8587
  },
7937
8588
  },
7938
8589
  ],
@@ -8100,37 +8751,173 @@ const fieldsConfiguration$1 = [
8100
8751
  }),
8101
8752
  },
8102
8753
  },
8103
- { fullPrice: { columnName: 'full_price' } },
8104
- { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
8105
- { subscriberPrice: { columnName: 'subscriber_price' } },
8106
- { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
8107
- 'sku',
8754
+ { fullPrice: { columnName: 'full_price' } },
8755
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
8756
+ { subscriberPrice: { columnName: 'subscriber_price' } },
8757
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
8758
+ 'sku',
8759
+ {
8760
+ stock: {
8761
+ columnName: 'stock',
8762
+ from: (quantity) => ({ quantity }),
8763
+ to: (value) => (lodash.isNil(value?.quantity) ? value : value?.quantity),
8764
+ },
8765
+ },
8766
+ { hasStock: { columnName: 'has_stock' } },
8767
+ 'weight',
8768
+ { name: { to: () => '', from: () => undefined } },
8769
+ { hasVariants: { columnName: 'has_variants', to: () => false, from: () => undefined } },
8770
+ { createdAt: { columnName: 'created_at' } },
8771
+ { updatedAt: { columnName: 'updated_at' } },
8772
+ {
8773
+ grade: {
8774
+ columnName: 'grade',
8775
+ type: HasuraGraphQLColumnType.Jsonb,
8776
+ },
8777
+ },
8778
+ 'group',
8779
+ 'type',
8780
+ 'validity',
8781
+ 'published',
8782
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
8783
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
8784
+ { daysOfUse: { columnName: 'days_of_use' } },
8785
+ {
8786
+ images: {
8787
+ columnName: 'images',
8788
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8789
+ },
8790
+ },
8791
+ {
8792
+ miniatures: {
8793
+ columnName: 'miniatures',
8794
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8795
+ },
8796
+ },
8797
+ {
8798
+ imagesCard: {
8799
+ columnName: 'images_card',
8800
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8801
+ },
8802
+ },
8803
+ 'slug',
8804
+ 'brand',
8805
+ 'name',
8806
+ 'sku',
8807
+ { NCM: { columnName: 'ncm' } },
8808
+ { CEST: { columnName: 'cest' } },
8809
+ {
8810
+ description: {
8811
+ columnName: 'description',
8812
+ from: (description, data) => ({
8813
+ description,
8814
+ differentials: data.differentials,
8815
+ whoMustUse: data.who_must_use,
8816
+ howToUse: data.how_to_use,
8817
+ brand: data.brand_description,
8818
+ ingredients: data.ingredients,
8819
+ purpose: data.purpose,
8820
+ }),
8821
+ bindFindFilter: (filters) => {
8822
+ return {
8823
+ ...(filters?.description && { description: filters.description }),
8824
+ ...(filters.differentials && { differentials: filters.differentials }),
8825
+ ...(filters.whoMustUse && {
8826
+ who_must_use: filters.whoMustUse,
8827
+ }),
8828
+ ...(filters.howToUse && {
8829
+ how_to_use: filters.howToUse,
8830
+ }),
8831
+ ...(filters.brand && {
8832
+ brand_description: filters.brand,
8833
+ }),
8834
+ ...(filters.ingredients && {
8835
+ ingredients: filters.ingredients,
8836
+ }),
8837
+ ...(filters.purpose && {
8838
+ purpose: filters.purpose,
8839
+ }),
8840
+ };
8841
+ },
8842
+ bindPersistData: (descriptionData) => ({
8843
+ ...(descriptionData?.description && { description: descriptionData.description }),
8844
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
8845
+ ...(descriptionData.whoMustUse && {
8846
+ who_must_use: descriptionData.whoMustUse,
8847
+ }),
8848
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
8849
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
8850
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
8851
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
8852
+ }),
8853
+ },
8854
+ },
8855
+ { differentials: { columnName: 'differentials' } },
8856
+ { whoMustUse: { columnName: 'who_must_use' } },
8857
+ { howToUse: { columnName: 'how_to_use' } },
8858
+ { brandDescription: { columnName: 'brand_description' } },
8859
+ { ingredients: { columnName: 'ingredients' } },
8860
+ { purpose: { columnName: 'purpose' } },
8861
+ 'gender',
8862
+ { intGender: { columnName: 'int_gender' } },
8863
+ 'label',
8864
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
8865
+ { rate: { columnName: 'rating' } },
8866
+ { reviewsTotal: { columnName: 'reviews_total' } },
8867
+ { shoppingCount: { columnName: 'shopping_count' } },
8868
+ { categoryId: { columnName: 'category_id' } },
8869
+ {
8870
+ category: {
8871
+ columnName: 'category',
8872
+ foreignKeyColumn: { id: 'categoryId' },
8873
+ fields: ['id', 'name', 'reference', 'slug'],
8874
+ },
8875
+ },
8876
+ {
8877
+ categories: {
8878
+ columnName: 'categories',
8879
+ fields: ['category_id'],
8880
+ bindPersistData: (value) => ({
8881
+ categories: { data: value.map((category) => ({ category_id: +category })) },
8882
+ }),
8883
+ to: (categories) => categories.map((categoryId) => +categoryId),
8884
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
8885
+ },
8886
+ },
8108
8887
  {
8109
- stock: {
8110
- columnName: 'stock',
8111
- from: (quantity) => ({ quantity }),
8112
- to: (value) => (lodash.isNil(value?.quantity) ? value : value?.quantity),
8888
+ metadata: {
8889
+ columnName: 'metadata',
8890
+ fields: ['title', 'description'],
8891
+ bindPersistData: (value) => ({
8892
+ metadata: { data: value },
8893
+ }),
8113
8894
  },
8114
8895
  },
8115
- { hasStock: { columnName: 'has_stock' } },
8116
- 'weight',
8117
- { name: { to: () => '', from: () => undefined } },
8118
- { hasVariants: { columnName: 'has_variants', to: () => false, from: () => undefined } },
8119
- { createdAt: { columnName: 'created_at' } },
8120
- { updatedAt: { columnName: 'updated_at' } },
8121
8896
  {
8122
- grade: {
8123
- columnName: 'grade',
8124
- type: HasuraGraphQLColumnType.Jsonb,
8897
+ reviews: {
8898
+ columnName: 'reviews',
8899
+ foreignKeyColumn: { product_id: 'id' },
8900
+ fields: [
8901
+ 'id',
8902
+ 'shop',
8903
+ 'rate',
8904
+ 'author',
8905
+ 'email',
8906
+ 'location',
8907
+ 'review',
8908
+ 'status',
8909
+ 'title',
8910
+ { personId: { columnName: 'person_id' } },
8911
+ 'points',
8912
+ { orderId: { columnName: 'order_id' } },
8913
+ { createdAt: { columnName: 'created_at' } },
8914
+ { updatedAt: { columnName: 'updated_at' } },
8915
+ ],
8125
8916
  },
8126
8917
  },
8127
- 'group',
8128
- 'validity',
8129
- // { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
8130
- 'published',
8131
- { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
8132
- { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
8133
- { daysOfUse: { columnName: 'days_of_use' } },
8918
+ // { variantSlug: { columnName: 'variant_slug' } },
8919
+ { createdAt: { columnName: 'created_at' } },
8920
+ { updatedAt: { columnName: 'updated_at' } },
8134
8921
  ];
8135
8922
  class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8136
8923
  constructor({ endpoint, authOptions, interceptors, cache, }) {
@@ -8171,18 +8958,46 @@ class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
8171
8958
  return data.at(0);
8172
8959
  }
8173
8960
  async update(params) {
8174
- const { productId, id: checkId, ...data } = params;
8961
+ const { productId, id: checkId, metadata, ...data } = params;
8175
8962
  const dataWithProductId = this.paramsToPlain({ id: checkId, productId });
8176
8963
  if (!dataWithProductId.id) {
8177
8964
  throw new NotFoundError('Variant ID is required for update');
8178
8965
  }
8179
8966
  const id = await this.getId(dataWithProductId.id);
8180
8967
  const product = await super.update({ id, ...data });
8968
+ product.metadata = metadata && (await this.updateMetadata(+id, { metadata }));
8181
8969
  if (dataWithProductId.productId) {
8182
8970
  product.productId = dataWithProductId.productId;
8183
8971
  }
8184
8972
  return product;
8185
8973
  }
8974
+ async updateMetadata(productId, { metadata }) {
8975
+ const plainData = this.paramsToPlain({ metadata });
8976
+ if (!plainData.metadata)
8977
+ return null;
8978
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8979
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8980
+ pk_columns: {
8981
+ value: { product_id: productId },
8982
+ type: 'product_metadata_pk_columns_input',
8983
+ required: true,
8984
+ },
8985
+ _set: {
8986
+ value: lodash.omit(metadata, ['product_id']),
8987
+ type: 'product_metadata_set_input',
8988
+ required: true,
8989
+ },
8990
+ });
8991
+ if (!update_product_metadata_by_pk) {
8992
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8993
+ objects: {
8994
+ type: '[product_metadata_insert_input!]!',
8995
+ value: [{ product_id: productId, ...metadata }],
8996
+ },
8997
+ });
8998
+ }
8999
+ return plainData.metadata;
9000
+ }
8186
9001
  async getId(id) {
8187
9002
  if (!Number.isNaN(+id))
8188
9003
  return id;
@@ -8497,6 +9312,9 @@ class WishlistHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
8497
9312
  productId: +productId,
8498
9313
  });
8499
9314
  }
9315
+ async getBrandsWithProducts() {
9316
+ return;
9317
+ }
8500
9318
  }
8501
9319
  tslib.__decorate([
8502
9320
  Log(),
@@ -8523,6 +9341,438 @@ tslib.__decorate([
8523
9341
  tslib.__metadata("design:returntype", Promise)
8524
9342
  ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
8525
9343
 
9344
+ class MercadoPagoRequestHelper {
9345
+ static build(data) {
9346
+ const { checkout, method, postback, card } = data;
9347
+ return {
9348
+ transaction_amount: +checkout.totalPrice.toFixed(2),
9349
+ notification_url: postback,
9350
+ metadata: {
9351
+ checkoutId: checkout.id,
9352
+ },
9353
+ payer: this.buildPayer(checkout, card),
9354
+ statement_descriptor: checkout.shop === exports.Shops.GLAMSHOP ? 'Glam' : 'Mens Market',
9355
+ additional_info: {
9356
+ items: this.buildItems(checkout),
9357
+ },
9358
+ ...(method === 'credit_card' && this.buildCardPayment(card)),
9359
+ ...(method === 'pix' && this.buildPixPayment()),
9360
+ ...(method === 'boleto' && this.buildBoletoPayment(checkout)),
9361
+ };
9362
+ }
9363
+ static buildItems(checkout) {
9364
+ return checkout.lineItems
9365
+ .filter((item) => !item.isGift)
9366
+ .map((item) => {
9367
+ return {
9368
+ id: item.EAN,
9369
+ title: item.name,
9370
+ description: item.name,
9371
+ picture_url: item.image ?? null,
9372
+ category_id: item.category?.id ?? null,
9373
+ quantity: item.quantity,
9374
+ unit_price: +item.pricePaid.toFixed(2),
9375
+ };
9376
+ });
9377
+ }
9378
+ static buildPayer(checkout, card) {
9379
+ return {
9380
+ ...(card && { id: card.customerId }),
9381
+ first_name: checkout.user.firstName,
9382
+ last_name: checkout.user.lastName,
9383
+ email: checkout.user.email,
9384
+ identification: {
9385
+ type: 'CPF',
9386
+ number: checkout.user.cpf.replace(/\D/g, ''),
9387
+ },
9388
+ };
9389
+ }
9390
+ static buildFullPayer(checkout) {
9391
+ return {
9392
+ first_name: checkout.user.firstName,
9393
+ last_name: checkout.user.lastName,
9394
+ phone: {
9395
+ area_code: checkout.user.phone.substring(0, 2),
9396
+ number: checkout.user.phone.substring(2),
9397
+ },
9398
+ address: {
9399
+ zip_code: checkout.shippingAddress.zip,
9400
+ street_name: `${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9401
+ street_number: checkout.shippingAddress.number,
9402
+ neighborhood: checkout.shippingAddress.district,
9403
+ city: checkout.shippingAddress.city,
9404
+ federal_unit: checkout.shippingAddress.state,
9405
+ },
9406
+ };
9407
+ }
9408
+ static buildCardPayment(card) {
9409
+ return {
9410
+ installments: card.installments,
9411
+ token: card.cardId,
9412
+ binary_mode: true,
9413
+ capture: true,
9414
+ };
9415
+ }
9416
+ static buildPixPayment() {
9417
+ return {
9418
+ payment_method_id: 'pix',
9419
+ date_of_expiration: dateFns.format(dateFns.addDays(new Date(), 1), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
9420
+ };
9421
+ }
9422
+ static buildBoletoPayment(checkout) {
9423
+ return {
9424
+ payment_method_id: 'bolbradesco',
9425
+ date_of_expiration: dateFns.format(dateFns.addDays(new Date(), 3), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
9426
+ payer: {
9427
+ first_name: checkout.user.firstName,
9428
+ last_name: checkout.user.lastName,
9429
+ email: checkout.user.email,
9430
+ identification: {
9431
+ type: 'CPF',
9432
+ number: checkout.user.cpf.replace(/\D/g, ''),
9433
+ },
9434
+ phone: {
9435
+ area_code: checkout.user.phone.substring(0, 2),
9436
+ number: checkout.user.phone.substring(2),
9437
+ },
9438
+ address: {
9439
+ zip_code: checkout.shippingAddress.zip.replace(/\D/g, ''),
9440
+ street_name: `${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9441
+ street_number: checkout.shippingAddress.number,
9442
+ neighborhood: checkout.shippingAddress.district,
9443
+ city: checkout.shippingAddress.city,
9444
+ federal_unit: checkout.shippingAddress.state,
9445
+ },
9446
+ },
9447
+ };
9448
+ }
9449
+ }
9450
+
9451
+ class MercadoPagoResponseHelper {
9452
+ static build(method, checkout, response) {
9453
+ return Payment.toInstance({
9454
+ createdAt: new Date(),
9455
+ updatedAt: new Date(),
9456
+ userId: checkout.user.id,
9457
+ checkoutId: checkout.id,
9458
+ totalPrice: checkout.totalPrice,
9459
+ paymentProvider: exports.PaymentProviders.MERCADOPAGO,
9460
+ mercadoPagoId: response.id,
9461
+ transaction: this.buildPaymentTransaction(method, response),
9462
+ });
9463
+ }
9464
+ static buildPaymentTransaction(method, response) {
9465
+ return PaymentTransaction.toInstance({
9466
+ id: response.id.toString(),
9467
+ acquirer_name: exports.PaymentProviders.MERCADOPAGO,
9468
+ amount: response.transaction_amount,
9469
+ status: this.statusMapping(response.status),
9470
+ status_reason: response.status_detail?.toString(),
9471
+ payment_method: method,
9472
+ currency: response.currency_id?.toString(),
9473
+ paid_amount: response.transaction_details?.total_paid_amount ?? null,
9474
+ paid_at: response.date_approved ?? null,
9475
+ charger_id: response.charges_details?.at(0)?.id?.toString() ?? null,
9476
+ ...(method == exports.TransactionPaymentMethods.PIX && this.getPixReponse(response)),
9477
+ ...(method == exports.TransactionPaymentMethods.CARD && this.getCardReponse(response)),
9478
+ ...(method == exports.TransactionPaymentMethods.BANKSLIP && this.getBoletoReponse(response)),
9479
+ });
9480
+ }
9481
+ static getBoletoReponse(response) {
9482
+ return {
9483
+ boleto_url: response.transaction_details?.external_resource_url?.toString(),
9484
+ boleto_barcode: response.transaction_details?.barcode?.content?.toString(),
9485
+ boleto_line: response.transaction_details?.digitable_line?.toString(),
9486
+ boleto_expiration_date: response.date_of_expiration?.toString(),
9487
+ boleto_document_number: response.transaction_details?.verification_code?.toString(),
9488
+ };
9489
+ }
9490
+ static getPixReponse(response) {
9491
+ return {
9492
+ pix_qr_code: response.point_of_interaction?.transaction_data?.qr_code,
9493
+ pix_expiration_date: response.date_of_expiration?.toString(),
9494
+ };
9495
+ }
9496
+ static getCardReponse(response) {
9497
+ return {
9498
+ soft_descriptor: response.statement_descriptor?.toString(),
9499
+ installments: response.installments,
9500
+ card_brand: response.payment_method_id?.toString(),
9501
+ card_first_digits: response.card?.first_six_digits?.toString(),
9502
+ card_last_digits: response.card?.last_four_digits?.toString(),
9503
+ card_id: response.card?.id?.toString(),
9504
+ card_holder_name: response.card?.cardholder?.name?.toString(),
9505
+ card_expiration_month: response.card?.expiration_month?.toString(),
9506
+ card_expiration_year: response.card?.expiration_year?.toString(),
9507
+ capture_method: response.payment_type_id?.toString(),
9508
+ authorization_code: response.authorization_code?.toString(),
9509
+ paid_amount: this.statusMapping(response.status) == 'paid' ? response.transaction_details?.total_paid_amount : null,
9510
+ paid_at: this.statusMapping(response.status) == 'paid' ? response.date_approved : null,
9511
+ };
9512
+ }
9513
+ static statusMapping(status) {
9514
+ const statusMap = {
9515
+ approved: 'paid',
9516
+ pending: 'waiting_payment',
9517
+ in_process: 'processing',
9518
+ rejected: 'refused',
9519
+ cancelled: 'refused',
9520
+ refunded: 'refunded',
9521
+ charged_back: 'chargedback',
9522
+ };
9523
+ return statusMap[status] || status;
9524
+ }
9525
+ }
9526
+
9527
+ class MercadoPagoBankSlipAxiosAdapter {
9528
+ constructor(credentials, paymentRepository) {
9529
+ this.credentials = credentials;
9530
+ this.paymentRepository = paymentRepository;
9531
+ }
9532
+ async pay(checkout) {
9533
+ try {
9534
+ const payload = MercadoPagoRequestHelper.build({
9535
+ checkout,
9536
+ method: 'boleto',
9537
+ postback: this.credentials.postback,
9538
+ });
9539
+ console.warn('[MERCADO PAGO BOLETO DATA TO SEND]', JSON.stringify(payload));
9540
+ const { data } = await axios__default["default"]({
9541
+ method: 'POST',
9542
+ url: `${this.credentials.url}/v1/payments`,
9543
+ headers: {
9544
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
9545
+ Authorization: `Bearer ${this.credentials.api_key}`,
9546
+ 'Content-Type': 'application/json',
9547
+ },
9548
+ data: payload,
9549
+ });
9550
+ console.warn('[MERCADO PAGO RESPONSE BOLETO DATA]', JSON.stringify(data));
9551
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(exports.TransactionPaymentMethods.BANKSLIP, checkout, data));
9552
+ return payment;
9553
+ }
9554
+ catch (error) {
9555
+ if (error instanceof axios.AxiosError) {
9556
+ console.warn(JSON.stringify(error.response.data.message));
9557
+ }
9558
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
9559
+ checkoutId: checkout.id,
9560
+ userEmail: checkout.user.email,
9561
+ info: error.response.data?.message || error.message?.toString(),
9562
+ });
9563
+ }
9564
+ }
9565
+ getBoletoTransaction(paymentId) {
9566
+ throw new Error('Method not implemented.');
9567
+ }
9568
+ }
9569
+
9570
+ class MercadoPagoCardAxiosAdapter {
9571
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
9572
+ this.credentials = credentials;
9573
+ this.paymentRepository = paymentRepository;
9574
+ this.orderBlockedRepository = orderBlockedRepository;
9575
+ }
9576
+ async pay(checkout, card) {
9577
+ try {
9578
+ const payload = await this.getPaymentPayload(checkout, card);
9579
+ console.warn('[MERCADO PAGO CARD DATA TO SEND]', JSON.stringify(payload));
9580
+ const { data } = await axios__default["default"]({
9581
+ method: 'POST',
9582
+ url: `${this.credentials.url}/v1/payments`,
9583
+ headers: {
9584
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
9585
+ Authorization: `Bearer ${this.credentials.api_key}`,
9586
+ 'Content-Type': 'application/json',
9587
+ },
9588
+ data: payload,
9589
+ });
9590
+ console.warn('[MERCADO PAGO RESPONSE CARD DATA]', JSON.stringify(data));
9591
+ if (data.status == exports.MercadoPagoStatusEnum.rejected) {
9592
+ await this.orderBlockedRepository.createBlockedOrderOrPayment({
9593
+ checkout,
9594
+ blockType: 'Card not authorized',
9595
+ type: 'Card',
9596
+ limiteRange: 'day',
9597
+ card,
9598
+ });
9599
+ 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', {
9600
+ checkoutId: checkout.id,
9601
+ userEmail: checkout.user.email,
9602
+ info: data,
9603
+ });
9604
+ }
9605
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(exports.TransactionPaymentMethods.CARD, checkout, data));
9606
+ return payment;
9607
+ }
9608
+ catch (error) {
9609
+ if (error instanceof axios.AxiosError) {
9610
+ console.warn(JSON.stringify(error.response.data.message));
9611
+ }
9612
+ 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', {
9613
+ checkoutId: checkout.id,
9614
+ userEmail: checkout.user.email,
9615
+ info: error.response.data?.message || error.message?.toString(),
9616
+ });
9617
+ }
9618
+ }
9619
+ async getPaymentPayload(checkout, card) {
9620
+ const cardResponse = await this.getCardByToken(card.customerId, card.cardId, card.cardCvv);
9621
+ const payload = MercadoPagoRequestHelper.build({
9622
+ checkout,
9623
+ method: 'credit_card',
9624
+ postback: this.credentials.postback,
9625
+ card: {
9626
+ ...card,
9627
+ cardId: cardResponse.id,
9628
+ },
9629
+ });
9630
+ return payload;
9631
+ }
9632
+ async addCard(card, customer) {
9633
+ return;
9634
+ }
9635
+ async getCardByToken(customerId, token, cardCvv) {
9636
+ try {
9637
+ const payload = { cardId: token, customerId: customerId, securityCode: cardCvv };
9638
+ console.warn('payload getCardByToken', payload);
9639
+ const { data } = await axios__default["default"]({
9640
+ method: 'POST',
9641
+ url: `${this.credentials.url}/v1/card_tokens`,
9642
+ headers: {
9643
+ Authorization: `Bearer ${this.credentials.api_key}`,
9644
+ 'Content-Type': 'application/json',
9645
+ },
9646
+ data: payload,
9647
+ });
9648
+ return data;
9649
+ }
9650
+ catch (error) {
9651
+ if (error instanceof axios.AxiosError) {
9652
+ console.warn(JSON.stringify(error.response.data.cause));
9653
+ }
9654
+ throw error;
9655
+ }
9656
+ }
9657
+ createCardHash(bu, shop, card) {
9658
+ return;
9659
+ }
9660
+ createTransaction(info) {
9661
+ return;
9662
+ }
9663
+ async createOrUpdateCustomer(customer) {
9664
+ const { data } = await axios__default["default"]({
9665
+ method: 'POST',
9666
+ url: `${this.credentials.url}/v1/customers`,
9667
+ headers: {
9668
+ Authorization: `Bearer ${this.credentials.api_key}`,
9669
+ 'Content-Type': 'application/json',
9670
+ },
9671
+ data: {
9672
+ email: customer.email,
9673
+ first_name: customer.firstName,
9674
+ last_name: customer.lastName,
9675
+ phone: {
9676
+ area_code: customer.phone.substring(0, 2),
9677
+ number: customer.phone.substring(2),
9678
+ },
9679
+ identification: {
9680
+ type: 'CPF',
9681
+ number: customer.cpf.replace(/\D/g, ''),
9682
+ },
9683
+ },
9684
+ });
9685
+ return data;
9686
+ }
9687
+ }
9688
+
9689
+ class MercadoPagoPixAxiosAdapter {
9690
+ constructor(credentials, paymentRepository) {
9691
+ this.credentials = credentials;
9692
+ this.paymentRepository = paymentRepository;
9693
+ }
9694
+ async pay(checkout) {
9695
+ try {
9696
+ const payload = MercadoPagoRequestHelper.build({
9697
+ checkout,
9698
+ method: 'pix',
9699
+ postback: this.credentials.postback,
9700
+ });
9701
+ console.warn('[MERCADO PAGO PIX DATA TO SEND]', JSON.stringify(payload));
9702
+ const { data } = await axios__default["default"]({
9703
+ method: 'POST',
9704
+ url: `${this.credentials.url}/v1/payments`,
9705
+ headers: {
9706
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
9707
+ Authorization: `Bearer ${this.credentials.api_key}`,
9708
+ 'Content-Type': 'application/json',
9709
+ },
9710
+ data: payload,
9711
+ });
9712
+ console.warn('[MERCADO PAGO RESPONSE PIX DATA]', JSON.stringify(data));
9713
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(exports.TransactionPaymentMethods.PIX, checkout, data));
9714
+ return payment;
9715
+ }
9716
+ catch (error) {
9717
+ if (error instanceof axios.AxiosError) {
9718
+ console.warn(JSON.stringify(error.response.data.message));
9719
+ }
9720
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
9721
+ checkoutId: checkout.id,
9722
+ userEmail: checkout.user.email,
9723
+ info: error.response.data?.message || error.message?.toString(),
9724
+ });
9725
+ }
9726
+ }
9727
+ }
9728
+
9729
+ exports.MercadoPagoStatusDetailEnum = void 0;
9730
+ (function (MercadoPagoStatusDetailEnum) {
9731
+ MercadoPagoStatusDetailEnum["accredited"] = "accredited";
9732
+ MercadoPagoStatusDetailEnum["partially_refunded"] = "partially_refunded";
9733
+ MercadoPagoStatusDetailEnum["pending_capture"] = "pending_capture";
9734
+ MercadoPagoStatusDetailEnum["offline_process"] = "offline_process";
9735
+ MercadoPagoStatusDetailEnum["pending_contingency"] = "pending_contingency";
9736
+ MercadoPagoStatusDetailEnum["pending_review_manual"] = "pending_review_manual";
9737
+ MercadoPagoStatusDetailEnum["pending_waiting_transfer"] = "pending_waiting_transfer";
9738
+ MercadoPagoStatusDetailEnum["pending_waiting_payment"] = "pending_waiting_payment";
9739
+ MercadoPagoStatusDetailEnum["pending_challenge"] = "pending_challenge";
9740
+ MercadoPagoStatusDetailEnum["bank_error"] = "bank_error";
9741
+ MercadoPagoStatusDetailEnum["cc_rejected_3ds_mandatory"] = "cc_rejected_3ds_mandatory";
9742
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_card_number"] = "cc_rejected_bad_filled_card_number";
9743
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_date"] = "cc_rejected_bad_filled_date";
9744
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_other"] = "cc_rejected_bad_filled_other";
9745
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_security_code"] = "cc_rejected_bad_filled_security_code";
9746
+ MercadoPagoStatusDetailEnum["cc_rejected_blacklist"] = "cc_rejected_blacklist";
9747
+ MercadoPagoStatusDetailEnum["cc_rejected_call_for_authorize"] = "cc_rejected_call_for_authorize";
9748
+ MercadoPagoStatusDetailEnum["cc_rejected_card_disabled"] = "cc_rejected_card_disabled";
9749
+ MercadoPagoStatusDetailEnum["cc_rejected_card_error"] = "cc_rejected_card_error";
9750
+ MercadoPagoStatusDetailEnum["cc_rejected_duplicated_payment"] = "cc_rejected_duplicated_payment";
9751
+ MercadoPagoStatusDetailEnum["cc_rejected_high_risk"] = "cc_rejected_high_risk";
9752
+ MercadoPagoStatusDetailEnum["cc_rejected_insufficient_amount"] = "cc_rejected_insufficient_amount";
9753
+ MercadoPagoStatusDetailEnum["cc_rejected_invalid_installments"] = "cc_rejected_invalid_installments";
9754
+ MercadoPagoStatusDetailEnum["cc_rejected_max_attempts"] = "cc_rejected_max_attempts";
9755
+ MercadoPagoStatusDetailEnum["cc_rejected_other_reason"] = "cc_rejected_other_reason";
9756
+ MercadoPagoStatusDetailEnum["cc_amount_rate_limit_exceeded"] = "cc_amount_rate_limit_exceeded";
9757
+ MercadoPagoStatusDetailEnum["rejected_insufficient_data"] = "rejected_insufficient_data";
9758
+ MercadoPagoStatusDetailEnum["rejected_by_bank"] = "rejected_by_bank";
9759
+ MercadoPagoStatusDetailEnum["rejected_by_regulations"] = "rejected_by_regulations";
9760
+ MercadoPagoStatusDetailEnum["insufficient_amount"] = "insufficient_amount";
9761
+ MercadoPagoStatusDetailEnum["cc_rejected_card_type_not_allowed"] = "cc_rejected_card_type_not_allowed";
9762
+ })(exports.MercadoPagoStatusDetailEnum || (exports.MercadoPagoStatusDetailEnum = {}));
9763
+
9764
+ exports.MercadoPagoStatusEnum = void 0;
9765
+ (function (MercadoPagoStatusEnum) {
9766
+ MercadoPagoStatusEnum["approved"] = "approved";
9767
+ MercadoPagoStatusEnum["authorized"] = "authorized";
9768
+ MercadoPagoStatusEnum["pending"] = "pending";
9769
+ MercadoPagoStatusEnum["in_process"] = "in_process";
9770
+ MercadoPagoStatusEnum["rejected"] = "rejected";
9771
+ MercadoPagoStatusEnum["cancelled"] = "cancelled";
9772
+ MercadoPagoStatusEnum["refunded"] = "refunded";
9773
+ MercadoPagoStatusEnum["charged_back"] = "charged_back";
9774
+ })(exports.MercadoPagoStatusEnum || (exports.MercadoPagoStatusEnum = {}));
9775
+
8526
9776
  class PagarmeBankSlipAxiosAdapter {
8527
9777
  constructor(credentials, paymentRepository) {
8528
9778
  this.credentials = credentials;
@@ -8663,6 +9913,211 @@ class PagarmePaymentOperationsHelper {
8663
9913
  }
8664
9914
  }
8665
9915
 
9916
+ class PagarMeV5RequestHelper {
9917
+ static build(checkout, method, card) {
9918
+ return {
9919
+ items: this.buildItems(checkout),
9920
+ customer: this.buildCustomer(checkout),
9921
+ shipping: this.buildShipping(checkout),
9922
+ payments: this.buildPayment(checkout, method, card),
9923
+ ...this.buildAdditionalInfo(checkout),
9924
+ };
9925
+ }
9926
+ static buildItems(checkout) {
9927
+ const isSubscriber = checkout.user?.isSubscriber ?? false;
9928
+ return checkout.lineItems
9929
+ .filter((item) => !item.isGift)
9930
+ .map((item) => {
9931
+ return {
9932
+ amount: Math.floor(item.pricePaid * 100),
9933
+ description: isSubscriber ? `${item.name} - ASSINANTE` : item.name,
9934
+ quantity: item.quantity,
9935
+ code: item.EAN,
9936
+ };
9937
+ });
9938
+ }
9939
+ static buildCustomer(checkout) {
9940
+ return {
9941
+ name: checkout.user.displayName,
9942
+ email: checkout.user.email,
9943
+ type: 'individual',
9944
+ document: checkout.user.cpf,
9945
+ phones: {
9946
+ home_phone: {
9947
+ country_code: '55',
9948
+ number: checkout.user.phone.slice(2),
9949
+ area_code: checkout.user.phone.slice(0, 2),
9950
+ },
9951
+ mobile_phone: {
9952
+ country_code: '55',
9953
+ number: checkout.user.phone.slice(2),
9954
+ area_code: checkout.user.phone.slice(0, 2),
9955
+ },
9956
+ },
9957
+ address: {
9958
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
9959
+ line_2: `${checkout.billingAddress.extension}`,
9960
+ zip_code: checkout.shippingAddress.zip,
9961
+ city: checkout.billingAddress.city,
9962
+ state: checkout.billingAddress.state,
9963
+ country: 'BR',
9964
+ },
9965
+ };
9966
+ }
9967
+ static buildShipping(checkout) {
9968
+ return {
9969
+ amount: Math.floor(checkout.shipping.ShippingPrice * 100),
9970
+ description: `${checkout.shipping.ShippingCompanyName} - ${checkout.shipping.description}`,
9971
+ recipient_name: checkout.shippingAddress.recipient,
9972
+ recipient_phone: checkout.user.phone,
9973
+ address: {
9974
+ line_1: `${checkout.shippingAddress.number}, ${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9975
+ line_2: `${checkout.shippingAddress.extension}`,
9976
+ zip_code: checkout.shippingAddress.zip,
9977
+ city: checkout.shippingAddress.city,
9978
+ state: checkout.shippingAddress.state,
9979
+ country: 'BR',
9980
+ },
9981
+ };
9982
+ }
9983
+ static buildPayment(checkout, method, card) {
9984
+ return [
9985
+ {
9986
+ payment_method: method,
9987
+ amount: Math.floor(checkout.totalPrice * 100),
9988
+ ...(method === 'pix' && {
9989
+ pix: this.getPixOrder(),
9990
+ }),
9991
+ ...(method === 'boleto' && {
9992
+ boleto: this.getBoletoOrder(),
9993
+ }),
9994
+ ...(method === 'credit_card' && {
9995
+ credit_card: this.getCardOrder(checkout, card),
9996
+ }),
9997
+ },
9998
+ ];
9999
+ }
10000
+ static getPixOrder() {
10001
+ return {
10002
+ expires_at: dateFns.format(dateFns.addDays(new Date(), 1), 'yyyy-MM-dd'),
10003
+ };
10004
+ }
10005
+ static getBoletoOrder() {
10006
+ return {
10007
+ due_at: dateFns.format(dateFns.addDays(new Date(), 3), 'yyyy-MM-dd'),
10008
+ instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
10009
+ type: 'DM',
10010
+ document_number: new Date().getTime().toString(),
10011
+ };
10012
+ }
10013
+ static getCardOrder(checkout, card) {
10014
+ return {
10015
+ installments: card.installments,
10016
+ statement_descriptor: checkout.shop === exports.Shops.GLAMSHOP ? 'Glam' : 'Mens Market',
10017
+ card_id: card.cardId,
10018
+ card: {
10019
+ cvv: card.cardCvv,
10020
+ billing_address: {
10021
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
10022
+ zip_code: checkout.billingAddress.zip,
10023
+ city: checkout.billingAddress.city,
10024
+ state: checkout.billingAddress.state,
10025
+ country: 'BR',
10026
+ },
10027
+ },
10028
+ };
10029
+ }
10030
+ static buildAdditionalInfo(checkout) {
10031
+ const isSubscriber = checkout.user?.isSubscriber ?? false;
10032
+ if (isSubscriber)
10033
+ return {
10034
+ antifraude_enabled: false,
10035
+ };
10036
+ return {};
10037
+ }
10038
+ }
10039
+
10040
+ class PagarMeV5ResponseHelper {
10041
+ static build(method, checkout, response) {
10042
+ return Payment.toInstance({
10043
+ createdAt: new Date(),
10044
+ updatedAt: new Date(),
10045
+ userId: checkout.user.id,
10046
+ checkoutId: checkout.id,
10047
+ totalPrice: checkout.totalPrice,
10048
+ paymentProvider: exports.PaymentProviders.PAGARME,
10049
+ pagarMeOrderId: response.id,
10050
+ transaction: this.buildPaymentTransaction(method, response),
10051
+ });
10052
+ }
10053
+ static buildPaymentTransaction(method, response) {
10054
+ const charger = response.charges.at(0);
10055
+ const transaction = charger.last_transaction;
10056
+ return PaymentTransaction.toInstance({
10057
+ acquirer_name: 'pagar_me',
10058
+ amount: charger.amount,
10059
+ currency: charger.currency,
10060
+ gateway_id: charger.gateway_id,
10061
+ status: this.getPaymentStatus(transaction.status),
10062
+ payment_method: charger.payment_method,
10063
+ date_created: charger.created_at,
10064
+ date_updated: charger.updated_at,
10065
+ paid_amount: charger.paid_amount,
10066
+ paid_at: charger.paid_at,
10067
+ order_id: response.id,
10068
+ charger_id: charger.id,
10069
+ tid: charger.id,
10070
+ id: charger.id,
10071
+ ...(method == exports.TransactionPaymentMethods.BANKSLIP && this.getBoletoReponse(transaction)),
10072
+ ...(method == exports.TransactionPaymentMethods.PIX && this.getPixReponse(transaction)),
10073
+ ...(method == exports.TransactionPaymentMethods.CARD && this.getCardReponse(transaction)),
10074
+ });
10075
+ }
10076
+ static getPaymentStatus(status) {
10077
+ if (status == exports.PagarMeV5PaymentStatus.Gerado)
10078
+ return exports.PagarMeV5PaymentStatus['Aguardando pagamento'];
10079
+ if (status == exports.PagarMeV5PaymentStatus.Capturada)
10080
+ return exports.PagarMeV5PaymentStatus.Pago;
10081
+ return status;
10082
+ }
10083
+ static getBoletoReponse(transaction) {
10084
+ return {
10085
+ boleto_url: transaction.url?.toString(),
10086
+ boleto_barcode: transaction.line?.toString(),
10087
+ boleto_qr_code: transaction.qr_code?.toString(),
10088
+ boleto_expiration_date: transaction.due_at?.toString(),
10089
+ boleto_instructions: transaction.instructions?.toString(),
10090
+ boleto_nosso_numero: transaction.nosso_numero?.toString(),
10091
+ boleto_type: transaction.type?.toString(),
10092
+ boleto_document_number: transaction.document_number?.toString(),
10093
+ };
10094
+ }
10095
+ static getPixReponse(transaction) {
10096
+ return {
10097
+ pix_qr_code: transaction.qr_code?.toString(),
10098
+ pix_qr_code_url: transaction.qr_code_url?.toString(),
10099
+ pix_expiration_date: transaction.expires_at?.toString(),
10100
+ };
10101
+ }
10102
+ static getCardReponse(transaction) {
10103
+ return {
10104
+ soft_descriptor: transaction.statement_descriptor?.toString(),
10105
+ acquirer_name: transaction.acquirer_name?.toString(),
10106
+ acquirer_id: transaction.acquirer_tid?.toString(),
10107
+ acquirer_nsu: transaction.acquirer_nsu?.toString(),
10108
+ acquirer_auth_code: transaction.acquirer_auth_code?.toString(),
10109
+ acquirer_message: transaction.acquirer_message?.toString(),
10110
+ acquirer_return_code: transaction.acquirer_return_code?.toString(),
10111
+ installments: transaction.installments ?? null,
10112
+ card_holder_name: transaction.card?.holder_name?.toString(),
10113
+ card_last_digits: transaction.card?.last_four_digits?.toString(),
10114
+ card_first_digits: transaction.card?.first_six_digits?.toString(),
10115
+ card_brand: transaction.card?.brand?.toString(),
10116
+ card_id: transaction.card?.id?.toString(),
10117
+ };
10118
+ }
10119
+ }
10120
+
8666
10121
  class PagarmeCardAxiosAdapter {
8667
10122
  constructor(credentials, paymentRepository, orderBlockedRepository) {
8668
10123
  this.credentials = credentials;
@@ -8719,8 +10174,9 @@ class PagarmeCardAxiosAdapter {
8719
10174
  });
8720
10175
  }
8721
10176
  }
8722
- async createCardHash(bu) {
8723
- const key = bu === exports.BusinessUnitEnum.SHOP ? this.credentials.SHOP_API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
10177
+ async createCardHash(bu, shop) {
10178
+ const credentials = shop && shop == exports.Shops.MENSMARKET ? this.credentials[exports.Shops.MENSMARKET] : this.credentials[exports.Shops.GLAMSHOP];
10179
+ const key = bu === exports.BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
8724
10180
  try {
8725
10181
  const { data } = await axios__default["default"]({
8726
10182
  method: 'GET',
@@ -8883,6 +10339,281 @@ class PagarmePixAxiosAdapter {
8883
10339
  }
8884
10340
  }
8885
10341
 
10342
+ class PagarmeV5BankSlipAxiosAdapter {
10343
+ constructor(credentials, paymentRepository) {
10344
+ this.credentials = credentials;
10345
+ this.paymentRepository = paymentRepository;
10346
+ }
10347
+ async pay(checkout) {
10348
+ try {
10349
+ const payload = PagarMeV5RequestHelper.build(checkout, 'boleto');
10350
+ console.warn('[PAGARME BOLETO DATA TO SEND]', JSON.stringify(payload));
10351
+ const { data } = await axios__default["default"]({
10352
+ method: 'POST',
10353
+ url: `${this.credentials.URL}/orders`,
10354
+ headers: {
10355
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10356
+ 'Content-Type': 'application/json',
10357
+ },
10358
+ data: payload,
10359
+ });
10360
+ console.warn('[PAGARME RESPONSE BOLETO DATA]', JSON.stringify(data));
10361
+ if (data.status === exports.PagarMeV5OrderStatus.Falha ||
10362
+ data.charges.at(0).status === exports.PagarMeV5OrderStatus.Falha ||
10363
+ (data.charges.at(0).last_transaction.status !== exports.PagarMeV5PaymentStatus.Gerado &&
10364
+ data.charges.at(0).last_transaction.status !== exports.PagarMeV5PaymentStatus['Em processamento'])) {
10365
+ return Promise.reject(new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
10366
+ checkoutId: checkout.id,
10367
+ userEmail: checkout.user.email,
10368
+ info: data.charges.at(0).last_transaction?.gateway_response,
10369
+ }));
10370
+ }
10371
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(exports.TransactionPaymentMethods.BANKSLIP, checkout, data));
10372
+ return payment;
10373
+ }
10374
+ catch (error) {
10375
+ if (error instanceof axios.AxiosError) {
10376
+ console.error('error data: ', JSON.stringify(error.response?.data));
10377
+ }
10378
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
10379
+ checkoutId: checkout.id,
10380
+ userEmail: checkout.user.email,
10381
+ info: error.response?.data,
10382
+ });
10383
+ }
10384
+ }
10385
+ async getBoletoTransaction(paymentId) {
10386
+ try {
10387
+ const { data } = await axios__default["default"]({
10388
+ method: 'GET',
10389
+ url: `${this.credentials.URL}/charges/${paymentId}`,
10390
+ headers: {
10391
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10392
+ 'Content-Type': 'application/json',
10393
+ },
10394
+ });
10395
+ const payment = await this.paymentRepository.get({
10396
+ id: data.id,
10397
+ });
10398
+ return payment.transaction;
10399
+ }
10400
+ catch (error) {
10401
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
10402
+ paymentId,
10403
+ info: error.response.data,
10404
+ });
10405
+ }
10406
+ }
10407
+ }
10408
+
10409
+ class PagarmeV5CardAxiosAdapter {
10410
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
10411
+ this.credentials = credentials;
10412
+ this.paymentRepository = paymentRepository;
10413
+ this.orderBlockedRepository = orderBlockedRepository;
10414
+ }
10415
+ async pay(checkout, card) {
10416
+ try {
10417
+ const payload = PagarMeV5RequestHelper.build(checkout, 'credit_card', card);
10418
+ console.warn('[PAGARME CARD DATA TO SEND]', JSON.stringify(payload));
10419
+ const { data } = await axios__default["default"]({
10420
+ method: 'POST',
10421
+ url: `${this.credentials.URL}/orders`,
10422
+ headers: {
10423
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10424
+ 'Content-Type': 'application/json',
10425
+ },
10426
+ data: payload,
10427
+ });
10428
+ console.warn('[RESPONSE PAGARME CARD DATA]', JSON.stringify(data));
10429
+ if (data.status == exports.PagarMeV5OrderStatus.Falha ||
10430
+ data.charges.at(0).status !== exports.PagarMeV5OrderStatus.Pago ||
10431
+ data.charges.at(0).last_transaction.status !== exports.PagarMeV5PaymentStatus.Capturada) {
10432
+ await PagarmeBlockedOrderHelper.createBlockedOrderForUnauthorizedCard({
10433
+ checkout,
10434
+ card,
10435
+ orderBlockedRepository: this.orderBlockedRepository,
10436
+ });
10437
+ throw PagarmeBlockedOrderHelper.createPaymentError(checkout, data);
10438
+ }
10439
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(exports.TransactionPaymentMethods.CARD, checkout, data));
10440
+ return payment;
10441
+ }
10442
+ catch (error) {
10443
+ if (error instanceof PaymentError) {
10444
+ throw error;
10445
+ }
10446
+ if (error instanceof axios.AxiosError) {
10447
+ console.error('error data: ', JSON.stringify(error.response?.data));
10448
+ }
10449
+ throw PagarmeBlockedOrderHelper.createGenericPaymentError(checkout, error.response?.data);
10450
+ }
10451
+ }
10452
+ async addCard(card, customer) {
10453
+ try {
10454
+ const { id } = await this.createOrUpdateCustomer(customer);
10455
+ const { data } = await axios__default["default"]({
10456
+ method: 'POST',
10457
+ url: `${this.credentials.URL}/customers/${id}/cards`,
10458
+ headers: {
10459
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10460
+ 'Content-Type': 'application/json',
10461
+ },
10462
+ data: {
10463
+ number: card.number,
10464
+ holder_name: card.name,
10465
+ holder_document: card.cpf,
10466
+ exp_month: card.expirationDate.split('/').at(0),
10467
+ exp_year: card.expirationDate.split('/').at(1),
10468
+ cvv: card.cvv,
10469
+ billing_address: {
10470
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
10471
+ line_2: `${customer.billingAddress.extension}`,
10472
+ zip_code: customer.billingAddress.zip,
10473
+ city: customer.billingAddress.city,
10474
+ state: customer.billingAddress.state,
10475
+ country: 'BR',
10476
+ },
10477
+ },
10478
+ });
10479
+ return data;
10480
+ }
10481
+ catch (error) {
10482
+ console.warn(JSON.stringify(error));
10483
+ throw error;
10484
+ }
10485
+ }
10486
+ async createCardHash(bu, shop) {
10487
+ const credentials = shop && shop == exports.Shops.MENSMARKET ? this.credentials[exports.Shops.MENSMARKET] : this.credentials[exports.Shops.GLAMSHOP];
10488
+ const key = bu === exports.BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
10489
+ try {
10490
+ const { data } = await axios__default["default"]({
10491
+ method: 'GET',
10492
+ headers: {
10493
+ 'content-type': 'application/json',
10494
+ },
10495
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
10496
+ data: JSON.stringify({
10497
+ api_key: key,
10498
+ }),
10499
+ });
10500
+ return data;
10501
+ }
10502
+ catch (error) {
10503
+ throw new BusinessError('Houve uma falha gerar o hash', {
10504
+ info: error.response.data,
10505
+ });
10506
+ }
10507
+ }
10508
+ async getCardByToken(customerId, token) {
10509
+ try {
10510
+ const { data } = await axios__default["default"]({
10511
+ method: 'GET',
10512
+ url: `${this.credentials.URL}/cards/${token}`,
10513
+ data: {
10514
+ api_key: this.credentials.API_KEY,
10515
+ },
10516
+ });
10517
+ return data;
10518
+ }
10519
+ catch (error) {
10520
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + token, {
10521
+ info: error.response.data,
10522
+ });
10523
+ }
10524
+ }
10525
+ async createTransaction(info) {
10526
+ return info;
10527
+ }
10528
+ async createOrUpdateCustomer(customer) {
10529
+ try {
10530
+ const { data } = await axios__default["default"]({
10531
+ method: 'POST',
10532
+ url: `${this.credentials.URL}/customers`,
10533
+ headers: {
10534
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10535
+ 'Content-Type': 'application/json',
10536
+ },
10537
+ data: {
10538
+ name: customer.displayName,
10539
+ email: customer.email,
10540
+ document: customer.cpf,
10541
+ type: 'individual',
10542
+ document_type: 'CPF',
10543
+ address: {
10544
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
10545
+ line_2: `${customer.billingAddress.extension}`,
10546
+ zip_code: customer.billingAddress.zip,
10547
+ city: customer.billingAddress.city,
10548
+ state: customer.billingAddress.state,
10549
+ country: 'BR',
10550
+ },
10551
+ birthdate: dateFns.format(new Date(customer.birthday), 'MM/dd/yyyy'),
10552
+ phones: {
10553
+ home_phone: {
10554
+ country_code: '55',
10555
+ number: customer.phone.slice(2),
10556
+ area_code: customer.phone.slice(0, 2),
10557
+ },
10558
+ mobile_phone: {
10559
+ country_code: '55',
10560
+ number: customer.phone.slice(2),
10561
+ area_code: customer.phone.slice(0, 2),
10562
+ },
10563
+ },
10564
+ },
10565
+ });
10566
+ return data;
10567
+ }
10568
+ catch (error) {
10569
+ console.warn(error);
10570
+ throw error;
10571
+ }
10572
+ }
10573
+ }
10574
+
10575
+ class PagarmeV5PixAxiosAdapter {
10576
+ constructor(credentials, paymentRepository) {
10577
+ this.credentials = credentials;
10578
+ this.paymentRepository = paymentRepository;
10579
+ }
10580
+ async pay(checkout) {
10581
+ try {
10582
+ const payload = PagarMeV5RequestHelper.build(checkout, 'pix');
10583
+ console.warn('[PAGARME PIX DATA TO SEND]', JSON.stringify(payload));
10584
+ const { data } = await axios__default["default"]({
10585
+ method: 'POST',
10586
+ url: `${this.credentials.URL}/orders`,
10587
+ headers: {
10588
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10589
+ 'Content-Type': 'application/json',
10590
+ },
10591
+ data: payload,
10592
+ });
10593
+ console.warn('[RESPONSE PAGARME PIX DATA]', JSON.stringify(data));
10594
+ if (data.status == exports.PagarMeV5OrderStatus.Falha || data.status == exports.PagarMeV5OrderStatus.Cancelado) {
10595
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
10596
+ checkoutId: checkout.id,
10597
+ userEmail: checkout.user.email,
10598
+ info: data.charges.at(0).last_transaction?.gateway_response,
10599
+ });
10600
+ }
10601
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(exports.TransactionPaymentMethods.PIX, checkout, data));
10602
+ return payment;
10603
+ }
10604
+ catch (error) {
10605
+ if (error instanceof axios.AxiosError) {
10606
+ console.error('error data: ', JSON.stringify(error.response?.data));
10607
+ }
10608
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
10609
+ checkoutId: checkout.id,
10610
+ userEmail: checkout.user.email,
10611
+ info: error.response?.data,
10612
+ });
10613
+ }
10614
+ }
10615
+ }
10616
+
8886
10617
  class VertexAxiosAdapter {
8887
10618
  constructor(config) {
8888
10619
  this.config = config;
@@ -9084,6 +10815,10 @@ Object.defineProperty(exports, 'subDays', {
9084
10815
  enumerable: true,
9085
10816
  get: function () { return dateFns.subDays; }
9086
10817
  });
10818
+ Object.defineProperty(exports, 'formatInTimeZone', {
10819
+ enumerable: true,
10820
+ get: function () { return dateFnsTz.formatInTimeZone; }
10821
+ });
9087
10822
  Object.defineProperty(exports, 'chunk', {
9088
10823
  enumerable: true,
9089
10824
  get: function () { return lodash.chunk; }
@@ -9171,6 +10906,8 @@ exports.Base = Base;
9171
10906
  exports.BaseModel = BaseModel;
9172
10907
  exports.BeautyProfile = BeautyProfile;
9173
10908
  exports.BeautyQuestionsHelper = BeautyQuestionsHelper;
10909
+ exports.BrandCategory = BrandCategory;
10910
+ exports.BrandCategoryFirestoreRepository = BrandCategoryFirestoreRepository;
9174
10911
  exports.BusinessError = BusinessError;
9175
10912
  exports.Buy2Win = Buy2Win;
9176
10913
  exports.Buy2WinFirestoreRepository = Buy2WinFirestoreRepository;
@@ -9229,6 +10966,12 @@ exports.Log = Log;
9229
10966
  exports.LogDocument = LogDocument;
9230
10967
  exports.LogFirestoreRepository = LogFirestoreRepository;
9231
10968
  exports.Logger = Logger;
10969
+ exports.MercadoPagoBankSlipAxiosAdapter = MercadoPagoBankSlipAxiosAdapter;
10970
+ exports.MercadoPagoCardAxiosAdapter = MercadoPagoCardAxiosAdapter;
10971
+ exports.MercadoPagoPaymentMethodFactory = MercadoPagoPaymentMethodFactory;
10972
+ exports.MercadoPagoPixAxiosAdapter = MercadoPagoPixAxiosAdapter;
10973
+ exports.MercadoPagoRequestHelper = MercadoPagoRequestHelper;
10974
+ exports.MercadoPagoResponseHelper = MercadoPagoResponseHelper;
9232
10975
  exports.NotFoundError = NotFoundError;
9233
10976
  exports.ObsEmitter = ObsEmitter;
9234
10977
  exports.Order = Order;
@@ -9239,12 +10982,17 @@ exports.PagarmeBankSlipAxiosAdapter = PagarmeBankSlipAxiosAdapter;
9239
10982
  exports.PagarmeCardAxiosAdapter = PagarmeCardAxiosAdapter;
9240
10983
  exports.PagarmePaymentMethodFactory = PagarmePaymentMethodFactory;
9241
10984
  exports.PagarmePixAxiosAdapter = PagarmePixAxiosAdapter;
10985
+ exports.PagarmeV5BankSlipAxiosAdapter = PagarmeV5BankSlipAxiosAdapter;
10986
+ exports.PagarmeV5CardAxiosAdapter = PagarmeV5CardAxiosAdapter;
10987
+ exports.PagarmeV5PixAxiosAdapter = PagarmeV5PixAxiosAdapter;
9242
10988
  exports.Payment = Payment;
9243
10989
  exports.PaymentError = PaymentError;
9244
10990
  exports.PaymentFirestoreRepository = PaymentFirestoreRepository;
9245
10991
  exports.PaymentProviderFactory = PaymentProviderFactory;
9246
10992
  exports.PaymentTransaction = PaymentTransaction;
9247
10993
  exports.Product = Product;
10994
+ exports.ProductCatalogHasuraGraphQL = ProductCatalogHasuraGraphQL;
10995
+ exports.ProductCatalogHasuraGraphQLRepository = ProductCatalogHasuraGraphQLRepository;
9248
10996
  exports.ProductErrors = ProductErrors;
9249
10997
  exports.ProductErrorsHasuraGraphQL = ProductErrorsHasuraGraphQL;
9250
10998
  exports.ProductErrorsHasuraGraphQLRepository = ProductErrorsHasuraGraphQLRepository;