@infrab4a/connect 5.4.1-beta.0 → 5.5.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/index.cjs.js +1272 -162
  2. package/index.esm.js +1263 -163
  3. package/package.json +1 -1
  4. package/src/domain/catalog/models/category-brand.d.ts +17 -0
  5. package/src/domain/catalog/models/index.d.ts +1 -0
  6. package/src/domain/catalog/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/repositories/category-brand.repository.d.ts +4 -0
  10. package/src/domain/catalog/repositories/index.d.ts +2 -0
  11. package/src/domain/catalog/repositories/product-catalog.repository.d.ts +17 -0
  12. package/src/domain/shopping/enums/index.d.ts +1 -0
  13. package/src/domain/shopping/enums/order-payment-status.enum.d.ts +10 -0
  14. package/src/domain/shopping/enums/payment-providers.enum.d.ts +2 -1
  15. package/src/domain/shopping/factories/index.d.ts +1 -0
  16. package/src/domain/shopping/factories/mercado-pago-payment-method.factory.d.ts +11 -0
  17. package/src/domain/shopping/factories/payment-provider.factory.d.ts +2 -0
  18. package/src/domain/shopping/models/order.d.ts +1 -1
  19. package/src/domain/shopping/models/payment-transaction.d.ts +2 -0
  20. package/src/domain/shopping/models/payment.d.ts +1 -0
  21. package/src/domain/shopping/services/antifraud-card.service.d.ts +2 -0
  22. package/src/domain/shopping/types/checkout-paylod-request.type.d.ts +2 -7
  23. package/src/domain/shopping/types/index.d.ts +2 -0
  24. package/src/domain/shopping/types/mercado-pago-card.type.d.ts +14 -0
  25. package/src/domain/shopping/types/mercado-pago-credentials.type.d.ts +5 -0
  26. package/src/domain/shopping/types/payment-card-info.type.d.ts +3 -0
  27. package/src/infra/firebase/firestore/repositories/catalog/category-brand-firestore.repository.d.ts +7 -0
  28. package/src/infra/firebase/firestore/repositories/catalog/index.d.ts +1 -0
  29. package/src/infra/hasura-graphql/models/index.d.ts +1 -0
  30. package/src/infra/hasura-graphql/models/product-catalog-hasura-graphql.d.ts +16 -0
  31. package/src/infra/hasura-graphql/models/variant-hasura-graphql.d.ts +7 -0
  32. package/src/infra/hasura-graphql/repositories/catalog/index.d.ts +1 -0
  33. package/src/infra/hasura-graphql/repositories/catalog/product-catalog-hasura-graphql.repository.d.ts +22 -0
  34. package/src/infra/hasura-graphql/repositories/catalog/variant-hasura-graphql.repository.d.ts +1 -0
  35. package/src/infra/index.d.ts +1 -0
  36. package/src/infra/mercado-pago/adapters/index.d.ts +3 -0
  37. package/src/infra/mercado-pago/adapters/mercado-pago-boleto-payment-axios.adapter.d.ts +8 -0
  38. package/src/infra/mercado-pago/adapters/mercado-pago-card-payment-axios.adapter.d.ts +20 -0
  39. package/src/infra/mercado-pago/adapters/mercado-pago-pix-payment-axios.adapter.d.ts +7 -0
  40. package/src/infra/mercado-pago/enums/index.d.ts +2 -0
  41. package/src/infra/mercado-pago/enums/mercado-pago-status-detail.enum.d.ts +33 -0
  42. package/src/infra/mercado-pago/enums/mercado-pago-status.enum.d.ts +10 -0
  43. package/src/infra/mercado-pago/helpers/index.d.ts +2 -0
  44. package/src/infra/mercado-pago/helpers/mercado-pago-request.helper.d.ts +60 -0
  45. package/src/infra/mercado-pago/helpers/mercado-pago-response.helper.d.ts +10 -0
  46. package/src/infra/mercado-pago/index.d.ts +4 -0
  47. package/src/infra/mercado-pago/types/index.d.ts +3 -0
  48. package/src/infra/mercado-pago/types/mercado-pago-request.type.d.ts +1 -0
  49. package/src/infra/mercado-pago/types/mercado-pago-response.type.d.ts +188 -0
  50. package/src/infra/mercado-pago/types/mercado-pago-status-detail.type.d.ts +2 -0
  51. package/src/infra/mercado-pago/types/mercado-pago-status.type.d.ts +2 -0
  52. package/src/infra/pagarme/adapters/helpers/pagarme-v5-request.helper.d.ts +1 -0
  53. package/src/infra/pagarme/types/v5/pagarmev5-order-request-payload.type.d.ts +3 -1
package/index.esm.js CHANGED
@@ -38,6 +38,18 @@ var OrderBlockedType;
38
38
  OrderBlockedType["Boleto"] = "Boleto";
39
39
  })(OrderBlockedType || (OrderBlockedType = {}));
40
40
 
41
+ var OrderPaymentStatus;
42
+ (function (OrderPaymentStatus) {
43
+ OrderPaymentStatus["Em processamento"] = "processing";
44
+ OrderPaymentStatus["Autorizada"] = "authorized";
45
+ OrderPaymentStatus["Pago"] = "paid";
46
+ OrderPaymentStatus["Estornada"] = "refunded";
47
+ OrderPaymentStatus["Aguardando pagamento"] = "waiting_payment";
48
+ OrderPaymentStatus["Aguardando estorno"] = "pending_refund";
49
+ OrderPaymentStatus["Recusada/N\u00E3o autorizada"] = "refused";
50
+ OrderPaymentStatus["Chargedback"] = "chargedback";
51
+ })(OrderPaymentStatus || (OrderPaymentStatus = {}));
52
+
41
53
  var PagarmePaymentStatus;
42
54
  (function (PagarmePaymentStatus) {
43
55
  PagarmePaymentStatus["Em processamento"] = "processing";
@@ -90,6 +102,7 @@ var PaymentProviders;
90
102
  PaymentProviders["PAGARME"] = "pagarMe";
91
103
  PaymentProviders["ADYEN"] = "adyen";
92
104
  PaymentProviders["GLAMPOINTS"] = "glampoints";
105
+ PaymentProviders["MERCADOPAGO"] = "mercadoPago";
93
106
  })(PaymentProviders || (PaymentProviders = {}));
94
107
 
95
108
  var TransactionPaymentMethods;
@@ -123,6 +136,9 @@ class AntifraudProviderFactory {
123
136
  class GlampointsPaymentMethodFactory extends BasePaymentMethodFactory {
124
137
  }
125
138
 
139
+ class MercadoPagoPaymentMethodFactory extends BasePaymentMethodFactory {
140
+ }
141
+
126
142
  class PagarmePaymentMethodFactory extends BasePaymentMethodFactory {
127
143
  }
128
144
 
@@ -733,6 +749,30 @@ __decorate([
733
749
  ], Category.prototype, "filters", void 0);
734
750
  registerClass('Category', Category);
735
751
 
752
+ class BrandCategory extends BaseModel {
753
+ get glamImages() {
754
+ return this.images?.[Shops.GLAMSHOP]
755
+ ? this.images[Shops.GLAMSHOP]
756
+ : {
757
+ brandBanner: null,
758
+ brandBannerMobile: null,
759
+ image: null,
760
+ };
761
+ }
762
+ get mensImages() {
763
+ return this.images?.[Shops.MENSMARKET]
764
+ ? this.images[Shops.MENSMARKET]
765
+ : {
766
+ brandBanner: null,
767
+ brandBannerMobile: null,
768
+ image: null,
769
+ };
770
+ }
771
+ static get identifiersFields() {
772
+ return ['id'];
773
+ }
774
+ }
775
+
736
776
  class CategoryCollectionChildren extends BaseModel {
737
777
  static get identifiersFields() {
738
778
  return ['collectionId', 'categoryId'];
@@ -805,7 +845,12 @@ class ProductReview extends BaseModel {
805
845
  static get identifiersFields() {
806
846
  return ['id'];
807
847
  }
808
- }
848
+ }
849
+ __decorate([
850
+ Type(resolveClass('Product')),
851
+ __metadata("design:type", Function)
852
+ ], ProductReview.prototype, "product", void 0);
853
+ registerClass('ProductReview', ProductReview);
809
854
 
810
855
  class ProductBase extends BaseModel {
811
856
  get evaluation() {
@@ -1736,19 +1781,58 @@ class AntifraudCardService {
1736
1781
  constructor(orderRepository, orderBlockedRepository) {
1737
1782
  this.orderRepository = orderRepository;
1738
1783
  this.orderBlockedRepository = orderBlockedRepository;
1739
- this.LIMIT_ORDERS_DAY = 2;
1740
- this.LIMIT_ORDERS_WEEK = 7;
1741
- this.LIMIT_BLOCKED_ORDERS_DAY = 5;
1784
+ this.LIMIT_ORDERS_DAY = null;
1785
+ this.LIMIT_ORDERS_WEEK = null;
1742
1786
  }
1743
1787
  async validate(checkout, card) {
1788
+ this.setLimitsByUserType(checkout.user.isSubscriber);
1744
1789
  await this.validateBlockedOrderAttempts(checkout, card);
1745
1790
  await this.validateDayAndWeekOrderLimits(checkout, card);
1746
1791
  return true;
1747
1792
  }
1793
+ setLimitsByUserType(isSubscriber) {
1794
+ this.LIMIT_ORDERS_DAY = {
1795
+ subscriber: {
1796
+ cpf: 4,
1797
+ email: 4,
1798
+ phone: 4,
1799
+ card: 4,
1800
+ zip: 4,
1801
+ },
1802
+ nonSubscriber: {
1803
+ cpf: 2,
1804
+ email: 2,
1805
+ phone: 2,
1806
+ card: 2,
1807
+ zip: 2,
1808
+ },
1809
+ };
1810
+ this.LIMIT_ORDERS_WEEK = {
1811
+ subscriber: {
1812
+ cpf: 12,
1813
+ email: 12,
1814
+ phone: 12,
1815
+ card: 12,
1816
+ zip: Infinity,
1817
+ },
1818
+ nonSubscriber: {
1819
+ cpf: 7,
1820
+ email: 7,
1821
+ phone: 7,
1822
+ card: 7,
1823
+ zip: Infinity,
1824
+ },
1825
+ };
1826
+ this.LIMIT_BLOCKED_ORDERS_DAY = isSubscriber ? 7 : 5;
1827
+ }
1828
+ getLimitsByUserType(type, isSubscriber) {
1829
+ const limits = type === 'day' ? this.LIMIT_ORDERS_DAY : this.LIMIT_ORDERS_WEEK;
1830
+ return isSubscriber ? limits['subscriber'] : limits['nonSubscriber'];
1831
+ }
1748
1832
  async validateBlockedOrderAttempts(checkout, card) {
1749
1833
  const isValid = await this.verifyBlockedOrderAttempts(checkout, card);
1750
1834
  if (!isValid) {
1751
- throw new FraudValidationError('Cliente com mais de 5 compras negadas/bloqueadas no dia', {
1835
+ throw new FraudValidationError(`Cliente com mais de ${this.LIMIT_BLOCKED_ORDERS_DAY} compras negadas/bloqueadas no dia`, {
1752
1836
  checkoutId: checkout.id,
1753
1837
  userEmail: checkout.user.email,
1754
1838
  info: {
@@ -1762,7 +1846,7 @@ class AntifraudCardService {
1762
1846
  async validateDayAndWeekOrderLimits(checkout, card) {
1763
1847
  const isValid = await this.verifyDayAndWeekOrders(checkout, card);
1764
1848
  if (!isValid) {
1765
- throw new FraudValidationError('Cliente tentando comprar mais de 2 vezes no dia ou 7 vezes na semana', {
1849
+ throw new FraudValidationError('Cliente tentando comprar mais do que o permitido no dia/semana', {
1766
1850
  checkoutId: checkout.id,
1767
1851
  userEmail: checkout.user.email,
1768
1852
  info: {
@@ -1781,7 +1865,7 @@ class AntifraudCardService {
1781
1865
  await this.createBlockedOrderRecord({
1782
1866
  checkout,
1783
1867
  card,
1784
- reason: 'More than 5 attempts have failed',
1868
+ reason: `More than ${this.LIMIT_BLOCKED_ORDERS_DAY} attempts have failed`,
1785
1869
  key: 'Failed attempts',
1786
1870
  period: 'day',
1787
1871
  });
@@ -1902,26 +1986,28 @@ class AntifraudCardService {
1902
1986
  }
1903
1987
  async validateDayOrderLimits(checkout, params) {
1904
1988
  const ordersPerDay = await this.validateOrdersByRange(params, this.getDateRange('day'));
1989
+ const limits = this.getLimitsByUserType('day', checkout.user.isSubscriber);
1905
1990
  return this.checkOrderLimitsAndBlock({
1906
1991
  checkout,
1907
1992
  orderCounts: ordersPerDay,
1908
- limit: this.LIMIT_ORDERS_DAY,
1993
+ limit: limits,
1909
1994
  period: 'day',
1910
1995
  });
1911
1996
  }
1912
1997
  async validateWeekOrderLimits(checkout, params) {
1913
1998
  const ordersPerWeek = await this.validateOrdersByRange(params, this.getDateRange('week'));
1999
+ const limits = this.getLimitsByUserType('week', checkout.user.isSubscriber);
1914
2000
  return this.checkOrderLimitsAndBlock({
1915
2001
  checkout,
1916
2002
  orderCounts: ordersPerWeek,
1917
- limit: this.LIMIT_ORDERS_WEEK,
2003
+ limit: limits,
1918
2004
  period: 'week',
1919
2005
  });
1920
2006
  }
1921
2007
  async checkOrderLimitsAndBlock(params) {
1922
2008
  const { checkout, orderCounts, limit, period } = params;
1923
2009
  for (const key in orderCounts) {
1924
- if (orderCounts[key] >= limit) {
2010
+ if (orderCounts[key] >= limit[key]) {
1925
2011
  await this.createBlockedOrderRecord({
1926
2012
  checkout,
1927
2013
  card: null,
@@ -4739,6 +4825,17 @@ const withCrudFirestore = (MixinBase) => {
4739
4825
  };
4740
4826
  };
4741
4827
 
4828
+ class BrandCategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4829
+ constructor({ firestore, interceptors, }) {
4830
+ super({
4831
+ firestore,
4832
+ collectionName: 'brandsCategory',
4833
+ model: BrandCategory,
4834
+ interceptors,
4835
+ });
4836
+ }
4837
+ }
4838
+
4742
4839
  class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4743
4840
  constructor({ firestore, interceptors }) {
4744
4841
  super({
@@ -5827,6 +5924,9 @@ __decorate([
5827
5924
  __metadata("design:type", Product)
5828
5925
  ], KitProductHasuraGraphQL.prototype, "product", void 0);
5829
5926
 
5927
+ class ProductCatalogHasuraGraphQL extends Product {
5928
+ }
5929
+
5830
5930
  class ProductHasuraGraphQL extends Product {
5831
5931
  }
5832
5932
  __decorate([
@@ -7192,83 +7292,7 @@ class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasu
7192
7292
  }
7193
7293
  }
7194
7294
 
7195
- class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7196
- constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7197
- super({
7198
- tableName: 'product_errors',
7199
- model: ProductErrorsHasuraGraphQL,
7200
- endpoint,
7201
- authOptions,
7202
- interceptors,
7203
- cache,
7204
- fields: [
7205
- {
7206
- productId: {
7207
- columnName: 'product_id',
7208
- to: (value) => +value,
7209
- from: (value) => value.toString(),
7210
- },
7211
- },
7212
- 'source',
7213
- 'error',
7214
- { createdAt: { columnName: 'created_at' } },
7215
- { updatedAt: { columnName: 'updated_at' } },
7216
- {
7217
- product: {
7218
- columnName: 'product',
7219
- foreignKeyColumn: { id: 'productId' },
7220
- fields: [
7221
- { id: { columnName: 'id', from: (value) => value.toString() } },
7222
- { productId: { columnName: 'main_product_id' } },
7223
- 'name',
7224
- 'published',
7225
- 'group',
7226
- 'validity',
7227
- { createdAt: { columnName: 'created_at' } },
7228
- { updatedAt: { columnName: 'updated_at' } },
7229
- ],
7230
- },
7231
- },
7232
- ],
7233
- });
7234
- this.productRepository = productRepository;
7235
- }
7236
- async get(params) {
7237
- const result = await super.get(params);
7238
- if (result instanceof VariantHasuraGraphQL) {
7239
- const product = await this.productRepository.get({ id: result.productId.toString() });
7240
- result.product.name = product.name;
7241
- result.product.group = product.group;
7242
- }
7243
- return result;
7244
- }
7245
- async find(params) {
7246
- const result = await super.find(params);
7247
- const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7248
- (isEmpty(item.product.name) || isEmpty(item.product.group) || isEmpty(item.product)));
7249
- if (variantsWithNoData.length > 0) {
7250
- const { data: products } = await this.productRepository.find({
7251
- filters: {
7252
- id: {
7253
- operator: Where.IN,
7254
- value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7255
- },
7256
- },
7257
- });
7258
- products.forEach((product) => {
7259
- result.data
7260
- .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7261
- .forEach((variant) => {
7262
- variant.product.name = product.name;
7263
- variant.product.group = product.group;
7264
- });
7265
- });
7266
- }
7267
- return result;
7268
- }
7269
- }
7270
-
7271
- const commonFields = [
7295
+ const commonFields$1 = [
7272
7296
  {
7273
7297
  id: {
7274
7298
  columnName: 'id',
@@ -7435,55 +7459,427 @@ const commonFields = [
7435
7459
  { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7436
7460
  { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7437
7461
  { daysOfUse: { columnName: 'days_of_use' } },
7462
+ { showVariants: { columnName: 'show_variants' } },
7463
+ { variantSlug: { columnName: 'variant_slug' } },
7438
7464
  ];
7439
- const fieldsConfiguration$2 = [
7440
- ...commonFields,
7441
- {
7442
- categories: {
7443
- columnName: 'categories',
7444
- fields: ['category_id'],
7445
- bindPersistData: (value) => ({
7446
- categories: { data: value.map((category) => ({ category_id: +category })) },
7447
- }),
7448
- to: (categories) => categories.map((categoryId) => +categoryId),
7449
- from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7450
- },
7451
- },
7452
- {
7453
- kitProducts: {
7454
- columnName: 'kit_products',
7455
- foreignKeyColumn: { productId: 'id' },
7456
- fields: [
7457
- { productId: { columnName: 'product_id' } },
7458
- { kitProductId: { columnName: 'kit_product_id' } },
7459
- 'quantity',
7460
- { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7461
- ],
7462
- },
7463
- },
7464
- {
7465
- reviews: {
7466
- columnName: 'reviews',
7467
- foreignKeyColumn: { product_id: 'id' },
7465
+ class ProductCatalogHasuraGraphQLRepository extends withFindHasuraGraphQL(withHasuraGraphQL(Base)) {
7466
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
7467
+ super({
7468
+ tableName: 'product_catalog',
7469
+ model: ProductCatalogHasuraGraphQL,
7470
+ endpoint,
7471
+ authOptions,
7472
+ interceptors,
7473
+ fields: commonFields$1,
7474
+ cache,
7475
+ });
7476
+ }
7477
+ async get({ id }, options) {
7478
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7479
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7480
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7481
+ if (cachedData) {
7482
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7483
+ return this.model.toInstance(deserialize(cachedData));
7484
+ }
7485
+ }
7486
+ const product = await super
7487
+ .find({
7488
+ filters: {
7489
+ id,
7490
+ },
7491
+ limits: {
7492
+ limit: 1,
7493
+ },
7494
+ })
7495
+ .then((res) => res.data.at(0));
7496
+ if (!product)
7497
+ throw new NotFoundError(`Product not found`);
7498
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7499
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7500
+ await this.cache.cacheAdapter.set({
7501
+ key: cacheKey,
7502
+ data: serialize(product),
7503
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7504
+ });
7505
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7506
+ }
7507
+ return product;
7508
+ }
7509
+ async getByEAN(EAN, options) {
7510
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7511
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7512
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7513
+ if (cachedData) {
7514
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7515
+ return this.model.toInstance(deserialize(cachedData));
7516
+ }
7517
+ }
7518
+ const product = await super
7519
+ .find({
7520
+ filters: {
7521
+ EAN,
7522
+ },
7523
+ limits: {
7524
+ limit: 1,
7525
+ },
7526
+ })
7527
+ .then((res) => res.data.at(0));
7528
+ if (!product)
7529
+ return null;
7530
+ RoundProductPricesHelper.roundProductPrices(product);
7531
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7532
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7533
+ await this.cache.cacheAdapter.set({
7534
+ key: cacheKey,
7535
+ data: serialize(product),
7536
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7537
+ });
7538
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7539
+ }
7540
+ return product;
7541
+ }
7542
+ async find(params, optionsParams) {
7543
+ const { filters, fields, ...options } = params || {};
7544
+ const bindFields = fields ||
7545
+ this.fields
7546
+ .map((field) => (typeof field === 'string' ? field : Object.keys(field).shift()))
7547
+ .filter((field) => field !== 'reviews' && field !== 'categories');
7548
+ if (options.options?.minimal?.includes('price'))
7549
+ options.options?.minimal.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
7550
+ if (options.options?.maximum?.includes('price'))
7551
+ options.options?.maximum.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
7552
+ options.options?.minimal?.splice(options.options?.minimal.indexOf('price'), 1);
7553
+ options.options?.maximum?.splice(options.options?.maximum.indexOf('price'), 1);
7554
+ return super.find({
7555
+ ...options,
7556
+ filters: { ...filters },
7468
7557
  fields: [
7469
- 'id',
7470
- 'shop',
7471
- 'rate',
7472
- 'author',
7473
- 'email',
7474
- 'location',
7475
- 'review',
7476
- 'status',
7477
- 'title',
7478
- { personId: { columnName: 'person_id' } },
7479
- 'points',
7480
- { orderId: { columnName: 'order_id' } },
7481
- { createdAt: { columnName: 'created_at' } },
7482
- { updatedAt: { columnName: 'updated_at' } },
7558
+ ...bindFields,
7559
+ ...(bindFields.includes('price')
7560
+ ? [
7561
+ 'subscriberPrice',
7562
+ 'subscriberDiscountPercentage',
7563
+ 'fullPrice',
7564
+ ]
7565
+ : []),
7483
7566
  ],
7484
- },
7485
- },
7486
- {
7567
+ }, optionsParams);
7568
+ }
7569
+ async findCatalog(params, mainGender, options) {
7570
+ const result = await this.find({
7571
+ ...params,
7572
+ filters: { ...params.filters, published: true },
7573
+ orderBy: {
7574
+ hasStock: 'desc',
7575
+ ...(!mainGender ? {} : { intGender: mainGender === 'female' ? 'desc' : 'asc' }),
7576
+ ...omit(params.orderBy, ['hasStock', 'intGender']),
7577
+ },
7578
+ }, options);
7579
+ return result;
7580
+ }
7581
+ }
7582
+ __decorate([
7583
+ Log(),
7584
+ __metadata("design:type", Function),
7585
+ __metadata("design:paramtypes", [Object, Object, Object]),
7586
+ __metadata("design:returntype", Promise)
7587
+ ], ProductCatalogHasuraGraphQLRepository.prototype, "findCatalog", null);
7588
+
7589
+ class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7590
+ constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7591
+ super({
7592
+ tableName: 'product_errors',
7593
+ model: ProductErrorsHasuraGraphQL,
7594
+ endpoint,
7595
+ authOptions,
7596
+ interceptors,
7597
+ cache,
7598
+ fields: [
7599
+ {
7600
+ productId: {
7601
+ columnName: 'product_id',
7602
+ to: (value) => +value,
7603
+ from: (value) => value.toString(),
7604
+ },
7605
+ },
7606
+ 'source',
7607
+ 'error',
7608
+ { createdAt: { columnName: 'created_at' } },
7609
+ { updatedAt: { columnName: 'updated_at' } },
7610
+ {
7611
+ product: {
7612
+ columnName: 'product',
7613
+ foreignKeyColumn: { id: 'productId' },
7614
+ fields: [
7615
+ { id: { columnName: 'id', from: (value) => value.toString() } },
7616
+ { productId: { columnName: 'main_product_id' } },
7617
+ 'name',
7618
+ 'published',
7619
+ 'group',
7620
+ 'validity',
7621
+ { createdAt: { columnName: 'created_at' } },
7622
+ { updatedAt: { columnName: 'updated_at' } },
7623
+ ],
7624
+ },
7625
+ },
7626
+ ],
7627
+ });
7628
+ this.productRepository = productRepository;
7629
+ }
7630
+ async get(params) {
7631
+ const result = await super.get(params);
7632
+ if (result instanceof VariantHasuraGraphQL) {
7633
+ const product = await this.productRepository.get({ id: result.productId.toString() });
7634
+ result.product.name = product.name;
7635
+ result.product.group = product.group;
7636
+ }
7637
+ return result;
7638
+ }
7639
+ async find(params) {
7640
+ const result = await super.find(params);
7641
+ const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7642
+ (isEmpty(item.product.name) || isEmpty(item.product.group) || isEmpty(item.product)));
7643
+ if (variantsWithNoData.length > 0) {
7644
+ const { data: products } = await this.productRepository.find({
7645
+ filters: {
7646
+ id: {
7647
+ operator: Where.IN,
7648
+ value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7649
+ },
7650
+ },
7651
+ });
7652
+ products.forEach((product) => {
7653
+ result.data
7654
+ .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7655
+ .forEach((variant) => {
7656
+ variant.product.name = product.name;
7657
+ variant.product.group = product.group;
7658
+ });
7659
+ });
7660
+ }
7661
+ return result;
7662
+ }
7663
+ }
7664
+
7665
+ const commonFields = [
7666
+ {
7667
+ id: {
7668
+ columnName: 'id',
7669
+ to: (value) => +value,
7670
+ from: (value) => value.toString(),
7671
+ },
7672
+ },
7673
+ { firestoreId: { columnName: 'firestore_id' } },
7674
+ { productId: { columnName: 'main_product_id' } },
7675
+ { CEST: { columnName: 'cest' } },
7676
+ { EAN: { columnName: 'ean' } },
7677
+ { NCM: { columnName: 'ncm' } },
7678
+ 'brand',
7679
+ { costPrice: { columnName: 'cost_price' } },
7680
+ {
7681
+ description: {
7682
+ columnName: 'description',
7683
+ from: (description, data) => ({
7684
+ description,
7685
+ differentials: data.differentials,
7686
+ whoMustUse: data.who_must_use,
7687
+ howToUse: data.how_to_use,
7688
+ brand: data.brand_description,
7689
+ ingredients: data.ingredients,
7690
+ purpose: data.purpose,
7691
+ }),
7692
+ bindFindFilter: (filters) => {
7693
+ return {
7694
+ ...(filters?.description && { description: filters.description }),
7695
+ ...(filters.differentials && { differentials: filters.differentials }),
7696
+ ...(filters.whoMustUse && {
7697
+ who_must_use: filters.whoMustUse,
7698
+ }),
7699
+ ...(filters.howToUse && {
7700
+ how_to_use: filters.howToUse,
7701
+ }),
7702
+ ...(filters.brand && {
7703
+ brand_description: filters.brand,
7704
+ }),
7705
+ ...(filters.ingredients && {
7706
+ ingredients: filters.ingredients,
7707
+ }),
7708
+ ...(filters.purpose && {
7709
+ purpose: filters.purpose,
7710
+ }),
7711
+ };
7712
+ },
7713
+ bindPersistData: (descriptionData) => ({
7714
+ ...(descriptionData?.description && { description: descriptionData.description }),
7715
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
7716
+ ...(descriptionData.whoMustUse && {
7717
+ who_must_use: descriptionData.whoMustUse,
7718
+ }),
7719
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
7720
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
7721
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
7722
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
7723
+ }),
7724
+ },
7725
+ },
7726
+ { differentials: { columnName: 'differentials' } },
7727
+ { whoMustUse: { columnName: 'who_must_use' } },
7728
+ { howToUse: { columnName: 'how_to_use' } },
7729
+ { brandDescription: { columnName: 'brand_description' } },
7730
+ { ingredients: { columnName: 'ingredients' } },
7731
+ { purpose: { columnName: 'purpose' } },
7732
+ { hasVariants: { columnName: 'has_variants' } },
7733
+ {
7734
+ images: {
7735
+ columnName: 'images',
7736
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7737
+ },
7738
+ },
7739
+ {
7740
+ miniatures: {
7741
+ columnName: 'miniatures',
7742
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7743
+ },
7744
+ },
7745
+ {
7746
+ imagesCard: {
7747
+ columnName: 'images_card',
7748
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7749
+ },
7750
+ },
7751
+ 'name',
7752
+ {
7753
+ price: {
7754
+ columnName: 'price',
7755
+ from: (price, data) => ({
7756
+ price,
7757
+ fullPrice: data.full_price,
7758
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
7759
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
7760
+ subscriberPrice: data.subscriber_price,
7761
+ }),
7762
+ bindFindFilter: (filters) => {
7763
+ return {
7764
+ ...((filters?.price || filters?.price === 0) && { price: filters.price }),
7765
+ ...((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice }),
7766
+ ...((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
7767
+ subscriber_discount_percentage: filters.subscriberDiscountPercentage,
7768
+ }),
7769
+ ...((filters.subscriberPrice || filters.subscriberPrice === 0) && {
7770
+ subscriber_price: filters.subscriberPrice,
7771
+ }),
7772
+ ...((filters.fullPriceDiscountPercentage || filters.fullPriceDiscountPercentage === 0) && {
7773
+ full_price_discount_percentage: filters.fullPriceDiscountPercentage,
7774
+ }),
7775
+ };
7776
+ },
7777
+ bindPersistData: (priceData) => ({
7778
+ ...(priceData?.price >= 0 && { price: priceData.price }),
7779
+ ...(priceData.fullPrice >= 0 && { full_price: priceData.fullPrice }),
7780
+ ...(priceData.subscriberDiscountPercentage >= 0 && {
7781
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
7782
+ }),
7783
+ ...(priceData.subscriberPrice >= 0 && { subscriber_price: priceData.subscriberPrice }),
7784
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
7785
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
7786
+ }),
7787
+ }),
7788
+ },
7789
+ },
7790
+ { fullPrice: { columnName: 'full_price' } },
7791
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
7792
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
7793
+ { subscriberPrice: { columnName: 'subscriber_price' } },
7794
+ 'published',
7795
+ 'outlet',
7796
+ 'label',
7797
+ 'sku',
7798
+ {
7799
+ stock: {
7800
+ columnName: 'stock',
7801
+ from: (quantity) => ({ quantity }),
7802
+ to: (value) => (isNil(value?.quantity) ? value : value?.quantity),
7803
+ },
7804
+ },
7805
+ { hasStock: { columnName: 'has_stock' } },
7806
+ 'slug',
7807
+ 'type',
7808
+ 'video',
7809
+ 'weight',
7810
+ 'gender',
7811
+ { intGender: { columnName: 'int_gender' } },
7812
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7813
+ { isKit: { columnName: 'is_kit' } },
7814
+ { createdAt: { columnName: 'created_at' } },
7815
+ { updatedAt: { columnName: 'updated_at' } },
7816
+ { rate: { columnName: 'rating' } },
7817
+ { reviewsTotal: { columnName: 'reviews_total' } },
7818
+ { shoppingCount: { columnName: 'shopping_count' } },
7819
+ { categoryId: { columnName: 'category_id' } },
7820
+ {
7821
+ category: {
7822
+ columnName: 'category',
7823
+ foreignKeyColumn: { id: 'categoryId' },
7824
+ fields: ['id', 'name', 'reference', 'slug'],
7825
+ },
7826
+ },
7827
+ 'group',
7828
+ 'validity',
7829
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7830
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7831
+ { daysOfUse: { columnName: 'days_of_use' } },
7832
+ { showVariants: { columnName: 'show_variants' } },
7833
+ { variantSlug: { columnName: 'variant_slug' } },
7834
+ ];
7835
+ const fieldsConfiguration$2 = [
7836
+ ...commonFields,
7837
+ {
7838
+ categories: {
7839
+ columnName: 'categories',
7840
+ fields: ['category_id'],
7841
+ bindPersistData: (value) => ({
7842
+ categories: { data: value.map((category) => ({ category_id: +category })) },
7843
+ }),
7844
+ to: (categories) => categories.map((categoryId) => +categoryId),
7845
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7846
+ },
7847
+ },
7848
+ {
7849
+ kitProducts: {
7850
+ columnName: 'kit_products',
7851
+ foreignKeyColumn: { productId: 'id' },
7852
+ fields: [
7853
+ { productId: { columnName: 'product_id' } },
7854
+ { kitProductId: { columnName: 'kit_product_id' } },
7855
+ 'quantity',
7856
+ { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7857
+ ],
7858
+ },
7859
+ },
7860
+ {
7861
+ reviews: {
7862
+ columnName: 'reviews',
7863
+ foreignKeyColumn: { product_id: 'id' },
7864
+ fields: [
7865
+ 'id',
7866
+ 'shop',
7867
+ 'rate',
7868
+ 'author',
7869
+ 'email',
7870
+ 'location',
7871
+ 'review',
7872
+ 'status',
7873
+ 'title',
7874
+ { personId: { columnName: 'person_id' } },
7875
+ 'points',
7876
+ { orderId: { columnName: 'order_id' } },
7877
+ { createdAt: { columnName: 'created_at' } },
7878
+ { updatedAt: { columnName: 'updated_at' } },
7879
+ ],
7880
+ },
7881
+ },
7882
+ {
7487
7883
  metadata: {
7488
7884
  columnName: 'metadata',
7489
7885
  fields: ['title', 'description'],
@@ -7498,9 +7894,61 @@ const fieldsConfiguration$2 = [
7498
7894
  foreignKeyColumn: { product_id: 'id' },
7499
7895
  fields: [
7500
7896
  'id',
7897
+ 'name',
7501
7898
  'ean',
7502
7899
  'sku',
7503
- 'description',
7900
+ {
7901
+ description: {
7902
+ columnName: 'description',
7903
+ from: (description, data) => ({
7904
+ description,
7905
+ differentials: data.differentials,
7906
+ whoMustUse: data.who_must_use,
7907
+ howToUse: data.how_to_use,
7908
+ brand: data.brand_description,
7909
+ ingredients: data.ingredients,
7910
+ purpose: data.purpose,
7911
+ }),
7912
+ bindFindFilter: (filters) => {
7913
+ return {
7914
+ ...(filters?.description && { description: filters.description }),
7915
+ ...(filters.differentials && { differentials: filters.differentials }),
7916
+ ...(filters.whoMustUse && {
7917
+ who_must_use: filters.whoMustUse,
7918
+ }),
7919
+ ...(filters.howToUse && {
7920
+ how_to_use: filters.howToUse,
7921
+ }),
7922
+ ...(filters.brand && {
7923
+ brand_description: filters.brand,
7924
+ }),
7925
+ ...(filters.ingredients && {
7926
+ ingredients: filters.ingredients,
7927
+ }),
7928
+ ...(filters.purpose && {
7929
+ purpose: filters.purpose,
7930
+ }),
7931
+ };
7932
+ },
7933
+ bindPersistData: (descriptionData) => ({
7934
+ ...(descriptionData?.description && { description: descriptionData.description }),
7935
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
7936
+ ...(descriptionData.whoMustUse && {
7937
+ who_must_use: descriptionData.whoMustUse,
7938
+ }),
7939
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
7940
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
7941
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
7942
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
7943
+ }),
7944
+ },
7945
+ },
7946
+ { differentials: { columnName: 'differentials' } },
7947
+ { whoMustUse: { columnName: 'who_must_use' } },
7948
+ { howToUse: { columnName: 'how_to_use' } },
7949
+ { brandDescription: { columnName: 'brand_description' } },
7950
+ { ingredients: { columnName: 'ingredients' } },
7951
+ { purpose: { columnName: 'purpose' } },
7504
7952
  {
7505
7953
  grade: {
7506
7954
  columnName: 'grade',
@@ -7517,22 +7965,6 @@ const fieldsConfiguration$2 = [
7517
7965
  subscriberPrice: data.subscriber_price,
7518
7966
  fullPriceDiscountPercentage: data.full_price_discount_percentage,
7519
7967
  }),
7520
- bindFindFilter: (sentence) => {
7521
- const filters = Object.values(sentence).shift();
7522
- return {
7523
- ...((filters?.price || filters?.price === 0) && { price: filters.price }),
7524
- ...((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice }),
7525
- ...((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
7526
- subscriber_discount_percentage: filters.subscriberDiscountPercentage,
7527
- }),
7528
- ...((filters.subscriberPrice || filters.subscriberPrice === 0) && {
7529
- subscriber_price: filters.subscriberPrice,
7530
- }),
7531
- ...((filters.fullPriceDiscountPercentage || filters.fullPriceDiscountPercentage === 0) && {
7532
- full_price_discount_percentage: filters.fullPriceDiscountPercentage,
7533
- }),
7534
- };
7535
- },
7536
7968
  bindPersistData: (priceData) => ({
7537
7969
  ...((priceData?.price || 0) >= 0 && { price: priceData.price }),
7538
7970
  ...((priceData?.fullPrice || 0) >= 0 && { full_price: priceData.fullPrice }),
@@ -7578,6 +8010,39 @@ const fieldsConfiguration$2 = [
7578
8010
  },
7579
8011
  { tagsProfile: { columnName: 'tags_profile' } },
7580
8012
  { tagsCollection: { columnName: 'tags_collection' } },
8013
+ { variantSlug: { columnName: 'variant_slug' } },
8014
+ {
8015
+ reviews: {
8016
+ columnName: 'reviews',
8017
+ foreignKeyColumn: { product_id: 'id' },
8018
+ fields: [
8019
+ 'id',
8020
+ 'shop',
8021
+ 'rate',
8022
+ 'author',
8023
+ 'email',
8024
+ 'location',
8025
+ 'review',
8026
+ 'status',
8027
+ 'title',
8028
+ { personId: { columnName: 'person_id' } },
8029
+ 'points',
8030
+ { orderId: { columnName: 'order_id' } },
8031
+ { createdAt: { columnName: 'created_at' } },
8032
+ { updatedAt: { columnName: 'updated_at' } },
8033
+ ],
8034
+ },
8035
+ },
8036
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
8037
+ {
8038
+ metadata: {
8039
+ columnName: 'metadata',
8040
+ fields: ['title', 'description'],
8041
+ bindPersistData: (value) => ({
8042
+ metadata: { data: value },
8043
+ }),
8044
+ },
8045
+ },
7581
8046
  ],
7582
8047
  },
7583
8048
  },
@@ -7643,7 +8108,12 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7643
8108
  : await super.get(identifiers, options);
7644
8109
  if (product.productId)
7645
8110
  throw new NotFoundError('Product not found, it is a variant');
7646
- product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, options));
8111
+ product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, false, options));
8112
+ if (!product.variants?.length) {
8113
+ for (const [index, variant] of product.variants.entries()) {
8114
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8115
+ }
8116
+ }
7647
8117
  return product;
7648
8118
  }
7649
8119
  async find(params, optionsParams) {
@@ -7685,6 +8155,9 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7685
8155
  const result = await this.find({
7686
8156
  filters: {
7687
8157
  slug,
8158
+ productId: {
8159
+ operator: Where.ISNULL,
8160
+ },
7688
8161
  },
7689
8162
  fields: this.fields.map((field) => typeof field === 'string' ? field : Object.keys(field).shift()),
7690
8163
  options: {
@@ -7694,6 +8167,11 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7694
8167
  if (!result.data.length)
7695
8168
  return null;
7696
8169
  const product = result?.data?.shift();
8170
+ if (!product.variants?.length) {
8171
+ for (const [index, variant] of product.variants.entries()) {
8172
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8173
+ }
8174
+ }
7697
8175
  RoundProductPricesHelper.roundProductPrices(product);
7698
8176
  if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7699
8177
  const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
@@ -7873,7 +8351,8 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7873
8351
  const plainData = this.paramsToPlain({ metadata });
7874
8352
  if (!plainData.metadata)
7875
8353
  return null;
7876
- await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8354
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8355
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
7877
8356
  pk_columns: {
7878
8357
  value: { product_id: productId },
7879
8358
  type: 'product_metadata_pk_columns_input',
@@ -7885,6 +8364,14 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7885
8364
  required: true,
7886
8365
  },
7887
8366
  });
8367
+ if (!update_product_metadata_by_pk) {
8368
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8369
+ objects: {
8370
+ type: '[product_metadata_insert_input!]!',
8371
+ value: [{ product_id: productId, ...metadata }],
8372
+ },
8373
+ });
8374
+ }
7888
8375
  return plainData.metadata;
7889
8376
  }
7890
8377
  async getId(id) {
@@ -7895,7 +8382,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7895
8382
  return data?.[0]?.id;
7896
8383
  throw new NotFoundError(`Product with id ${id} not found`);
7897
8384
  }
7898
- async findReviewsByProduct(productId, options) {
8385
+ async findReviewsByProduct(productId, onlyApproved, options) {
7899
8386
  if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7900
8387
  const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
7901
8388
  const cachedData = await this.cache.cacheAdapter.get(cacheKey);
@@ -7908,10 +8395,16 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7908
8395
  where: {
7909
8396
  value: {
7910
8397
  product_id: { _eq: productId },
8398
+ ...(onlyApproved && { status: { _eq: true } }),
7911
8399
  },
7912
8400
  type: 'product_review_bool_exp',
7913
8401
  required: true,
7914
8402
  },
8403
+ order_by: {
8404
+ type: '[product_review_order_by]',
8405
+ value: [{ createdAt: 'desc' }],
8406
+ required: true,
8407
+ },
7915
8408
  });
7916
8409
  const reviews = data?.map((review) => this.bindReviewToModel(review));
7917
8410
  if (this.cache?.cacheAdapter && options?.cache?.enabled && reviews) {
@@ -8016,7 +8509,7 @@ __decorate([
8016
8509
  __decorate([
8017
8510
  Log(),
8018
8511
  __metadata("design:type", Function),
8019
- __metadata("design:paramtypes", [Number, Object]),
8512
+ __metadata("design:paramtypes", [Number, Boolean, Object]),
8020
8513
  __metadata("design:returntype", Promise)
8021
8514
  ], ProductHasuraGraphQLRepository.prototype, "findReviewsByProduct", null);
8022
8515
 
@@ -8048,7 +8541,25 @@ class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHas
8048
8541
  product: {
8049
8542
  columnName: 'product',
8050
8543
  foreignKeyColumn: { id: 'productId' },
8051
- fields: ['id', 'ean', 'sku', 'name', 'brand', 'slug', 'images', 'grade', 'gender'],
8544
+ fields: [
8545
+ 'id',
8546
+ {
8547
+ productId: {
8548
+ columnName: 'main_product_id',
8549
+ to: (value) => +value,
8550
+ from: (value) => value?.toString(),
8551
+ },
8552
+ },
8553
+ 'ean',
8554
+ 'sku',
8555
+ 'name',
8556
+ 'brand',
8557
+ 'slug',
8558
+ 'images',
8559
+ 'grade',
8560
+ 'gender',
8561
+ '',
8562
+ ],
8052
8563
  },
8053
8564
  },
8054
8565
  ],
@@ -8241,6 +8752,7 @@ const fieldsConfiguration$1 = [
8241
8752
  },
8242
8753
  },
8243
8754
  'group',
8755
+ 'type',
8244
8756
  'validity',
8245
8757
  'published',
8246
8758
  { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
@@ -8259,11 +8771,129 @@ const fieldsConfiguration$1 = [
8259
8771
  },
8260
8772
  },
8261
8773
  {
8262
- imagesCard: {
8263
- columnName: 'images_card',
8264
- to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8774
+ imagesCard: {
8775
+ columnName: 'images_card',
8776
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8777
+ },
8778
+ },
8779
+ 'slug',
8780
+ 'brand',
8781
+ 'name',
8782
+ 'sku',
8783
+ { NCM: { columnName: 'ncm' } },
8784
+ { CEST: { columnName: 'cest' } },
8785
+ {
8786
+ description: {
8787
+ columnName: 'description',
8788
+ from: (description, data) => ({
8789
+ description,
8790
+ differentials: data.differentials,
8791
+ whoMustUse: data.who_must_use,
8792
+ howToUse: data.how_to_use,
8793
+ brand: data.brand_description,
8794
+ ingredients: data.ingredients,
8795
+ purpose: data.purpose,
8796
+ }),
8797
+ bindFindFilter: (filters) => {
8798
+ return {
8799
+ ...(filters?.description && { description: filters.description }),
8800
+ ...(filters.differentials && { differentials: filters.differentials }),
8801
+ ...(filters.whoMustUse && {
8802
+ who_must_use: filters.whoMustUse,
8803
+ }),
8804
+ ...(filters.howToUse && {
8805
+ how_to_use: filters.howToUse,
8806
+ }),
8807
+ ...(filters.brand && {
8808
+ brand_description: filters.brand,
8809
+ }),
8810
+ ...(filters.ingredients && {
8811
+ ingredients: filters.ingredients,
8812
+ }),
8813
+ ...(filters.purpose && {
8814
+ purpose: filters.purpose,
8815
+ }),
8816
+ };
8817
+ },
8818
+ bindPersistData: (descriptionData) => ({
8819
+ ...(descriptionData?.description && { description: descriptionData.description }),
8820
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
8821
+ ...(descriptionData.whoMustUse && {
8822
+ who_must_use: descriptionData.whoMustUse,
8823
+ }),
8824
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
8825
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
8826
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
8827
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
8828
+ }),
8829
+ },
8830
+ },
8831
+ { differentials: { columnName: 'differentials' } },
8832
+ { whoMustUse: { columnName: 'who_must_use' } },
8833
+ { howToUse: { columnName: 'how_to_use' } },
8834
+ { brandDescription: { columnName: 'brand_description' } },
8835
+ { ingredients: { columnName: 'ingredients' } },
8836
+ { purpose: { columnName: 'purpose' } },
8837
+ 'gender',
8838
+ { intGender: { columnName: 'int_gender' } },
8839
+ 'label',
8840
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
8841
+ { rate: { columnName: 'rating' } },
8842
+ { reviewsTotal: { columnName: 'reviews_total' } },
8843
+ { shoppingCount: { columnName: 'shopping_count' } },
8844
+ { categoryId: { columnName: 'category_id' } },
8845
+ {
8846
+ category: {
8847
+ columnName: 'category',
8848
+ foreignKeyColumn: { id: 'categoryId' },
8849
+ fields: ['id', 'name', 'reference', 'slug'],
8850
+ },
8851
+ },
8852
+ {
8853
+ categories: {
8854
+ columnName: 'categories',
8855
+ fields: ['category_id'],
8856
+ bindPersistData: (value) => ({
8857
+ categories: { data: value.map((category) => ({ category_id: +category })) },
8858
+ }),
8859
+ to: (categories) => categories.map((categoryId) => +categoryId),
8860
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
8861
+ },
8862
+ },
8863
+ {
8864
+ metadata: {
8865
+ columnName: 'metadata',
8866
+ fields: ['title', 'description'],
8867
+ bindPersistData: (value) => ({
8868
+ metadata: { data: value },
8869
+ }),
8870
+ },
8871
+ },
8872
+ {
8873
+ reviews: {
8874
+ columnName: 'reviews',
8875
+ foreignKeyColumn: { product_id: 'id' },
8876
+ fields: [
8877
+ 'id',
8878
+ 'shop',
8879
+ 'rate',
8880
+ 'author',
8881
+ 'email',
8882
+ 'location',
8883
+ 'review',
8884
+ 'status',
8885
+ 'title',
8886
+ { personId: { columnName: 'person_id' } },
8887
+ 'points',
8888
+ { orderId: { columnName: 'order_id' } },
8889
+ { createdAt: { columnName: 'created_at' } },
8890
+ { updatedAt: { columnName: 'updated_at' } },
8891
+ ],
8265
8892
  },
8266
8893
  },
8894
+ { variantSlug: { columnName: 'variant_slug' } },
8895
+ { createdAt: { columnName: 'created_at' } },
8896
+ { updatedAt: { columnName: 'updated_at' } },
8267
8897
  ];
8268
8898
  class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8269
8899
  constructor({ endpoint, authOptions, interceptors, cache, }) {
@@ -8304,18 +8934,46 @@ class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
8304
8934
  return data.at(0);
8305
8935
  }
8306
8936
  async update(params) {
8307
- const { productId, id: checkId, ...data } = params;
8937
+ const { productId, id: checkId, metadata, ...data } = params;
8308
8938
  const dataWithProductId = this.paramsToPlain({ id: checkId, productId });
8309
8939
  if (!dataWithProductId.id) {
8310
8940
  throw new NotFoundError('Variant ID is required for update');
8311
8941
  }
8312
8942
  const id = await this.getId(dataWithProductId.id);
8313
8943
  const product = await super.update({ id, ...data });
8944
+ product.metadata = metadata && (await this.updateMetadata(+id, { metadata }));
8314
8945
  if (dataWithProductId.productId) {
8315
8946
  product.productId = dataWithProductId.productId;
8316
8947
  }
8317
8948
  return product;
8318
8949
  }
8950
+ async updateMetadata(productId, { metadata }) {
8951
+ const plainData = this.paramsToPlain({ metadata });
8952
+ if (!plainData.metadata)
8953
+ return null;
8954
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8955
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8956
+ pk_columns: {
8957
+ value: { product_id: productId },
8958
+ type: 'product_metadata_pk_columns_input',
8959
+ required: true,
8960
+ },
8961
+ _set: {
8962
+ value: omit(metadata, ['product_id']),
8963
+ type: 'product_metadata_set_input',
8964
+ required: true,
8965
+ },
8966
+ });
8967
+ if (!update_product_metadata_by_pk) {
8968
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8969
+ objects: {
8970
+ type: '[product_metadata_insert_input!]!',
8971
+ value: [{ product_id: productId, ...metadata }],
8972
+ },
8973
+ });
8974
+ }
8975
+ return plainData.metadata;
8976
+ }
8319
8977
  async getId(id) {
8320
8978
  if (!Number.isNaN(+id))
8321
8979
  return id;
@@ -8659,6 +9317,438 @@ __decorate([
8659
9317
  __metadata("design:returntype", Promise)
8660
9318
  ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
8661
9319
 
9320
+ class MercadoPagoRequestHelper {
9321
+ static build(data) {
9322
+ const { checkout, method, postback, card } = data;
9323
+ return {
9324
+ transaction_amount: +checkout.totalPrice.toFixed(2),
9325
+ notification_url: postback,
9326
+ metadata: {
9327
+ checkoutId: checkout.id,
9328
+ },
9329
+ payer: this.buildPayer(checkout, card),
9330
+ statement_descriptor: checkout.shop === Shops.GLAMSHOP ? 'Glam' : 'Mens Market',
9331
+ additional_info: {
9332
+ items: this.buildItems(checkout),
9333
+ },
9334
+ ...(method === 'credit_card' && this.buildCardPayment(card)),
9335
+ ...(method === 'pix' && this.buildPixPayment()),
9336
+ ...(method === 'boleto' && this.buildBoletoPayment(checkout)),
9337
+ };
9338
+ }
9339
+ static buildItems(checkout) {
9340
+ return checkout.lineItems
9341
+ .filter((item) => !item.isGift)
9342
+ .map((item) => {
9343
+ return {
9344
+ id: item.EAN,
9345
+ title: item.name,
9346
+ description: item.name,
9347
+ picture_url: item.image ?? null,
9348
+ category_id: item.category?.id ?? null,
9349
+ quantity: item.quantity,
9350
+ unit_price: +item.pricePaid.toFixed(2),
9351
+ };
9352
+ });
9353
+ }
9354
+ static buildPayer(checkout, card) {
9355
+ return {
9356
+ ...(card && { id: card.customerId }),
9357
+ first_name: checkout.user.firstName,
9358
+ last_name: checkout.user.lastName,
9359
+ email: checkout.user.email,
9360
+ identification: {
9361
+ type: 'CPF',
9362
+ number: checkout.user.cpf.replace(/\D/g, ''),
9363
+ },
9364
+ };
9365
+ }
9366
+ static buildFullPayer(checkout) {
9367
+ return {
9368
+ first_name: checkout.user.firstName,
9369
+ last_name: checkout.user.lastName,
9370
+ phone: {
9371
+ area_code: checkout.user.phone.substring(0, 2),
9372
+ number: checkout.user.phone.substring(2),
9373
+ },
9374
+ address: {
9375
+ zip_code: checkout.shippingAddress.zip,
9376
+ street_name: `${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9377
+ street_number: checkout.shippingAddress.number,
9378
+ neighborhood: checkout.shippingAddress.district,
9379
+ city: checkout.shippingAddress.city,
9380
+ federal_unit: checkout.shippingAddress.state,
9381
+ },
9382
+ };
9383
+ }
9384
+ static buildCardPayment(card) {
9385
+ return {
9386
+ installments: card.installments,
9387
+ token: card.cardId,
9388
+ binary_mode: true,
9389
+ capture: true,
9390
+ };
9391
+ }
9392
+ static buildPixPayment() {
9393
+ return {
9394
+ payment_method_id: 'pix',
9395
+ date_of_expiration: format(addDays(new Date(), 1), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
9396
+ };
9397
+ }
9398
+ static buildBoletoPayment(checkout) {
9399
+ return {
9400
+ payment_method_id: 'bolbradesco',
9401
+ date_of_expiration: format(addDays(new Date(), 3), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
9402
+ payer: {
9403
+ first_name: checkout.user.firstName,
9404
+ last_name: checkout.user.lastName,
9405
+ email: checkout.user.email,
9406
+ identification: {
9407
+ type: 'CPF',
9408
+ number: checkout.user.cpf.replace(/\D/g, ''),
9409
+ },
9410
+ phone: {
9411
+ area_code: checkout.user.phone.substring(0, 2),
9412
+ number: checkout.user.phone.substring(2),
9413
+ },
9414
+ address: {
9415
+ zip_code: checkout.shippingAddress.zip.replace(/\D/g, ''),
9416
+ street_name: `${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9417
+ street_number: checkout.shippingAddress.number,
9418
+ neighborhood: checkout.shippingAddress.district,
9419
+ city: checkout.shippingAddress.city,
9420
+ federal_unit: checkout.shippingAddress.state,
9421
+ },
9422
+ },
9423
+ };
9424
+ }
9425
+ }
9426
+
9427
+ class MercadoPagoResponseHelper {
9428
+ static build(method, checkout, response) {
9429
+ return Payment.toInstance({
9430
+ createdAt: new Date(),
9431
+ updatedAt: new Date(),
9432
+ userId: checkout.user.id,
9433
+ checkoutId: checkout.id,
9434
+ totalPrice: checkout.totalPrice,
9435
+ paymentProvider: PaymentProviders.MERCADOPAGO,
9436
+ mercadoPagoId: response.id,
9437
+ transaction: this.buildPaymentTransaction(method, response),
9438
+ });
9439
+ }
9440
+ static buildPaymentTransaction(method, response) {
9441
+ return PaymentTransaction.toInstance({
9442
+ id: response.id.toString(),
9443
+ acquirer_name: PaymentProviders.MERCADOPAGO,
9444
+ amount: response.transaction_amount,
9445
+ status: this.statusMapping(response.status),
9446
+ status_reason: response.status_detail?.toString(),
9447
+ payment_method: method,
9448
+ currency: response.currency_id?.toString(),
9449
+ paid_amount: response.transaction_details?.total_paid_amount ?? null,
9450
+ paid_at: response.date_approved ?? null,
9451
+ charger_id: response.charges_details?.at(0)?.id?.toString() ?? null,
9452
+ ...(method == TransactionPaymentMethods.PIX && this.getPixReponse(response)),
9453
+ ...(method == TransactionPaymentMethods.CARD && this.getCardReponse(response)),
9454
+ ...(method == TransactionPaymentMethods.BANKSLIP && this.getBoletoReponse(response)),
9455
+ });
9456
+ }
9457
+ static getBoletoReponse(response) {
9458
+ return {
9459
+ boleto_url: response.transaction_details?.external_resource_url?.toString(),
9460
+ boleto_barcode: response.transaction_details?.barcode?.content?.toString(),
9461
+ boleto_line: response.transaction_details?.digitable_line?.toString(),
9462
+ boleto_expiration_date: response.date_of_expiration?.toString(),
9463
+ boleto_document_number: response.transaction_details?.verification_code?.toString(),
9464
+ };
9465
+ }
9466
+ static getPixReponse(response) {
9467
+ return {
9468
+ pix_qr_code: response.point_of_interaction?.transaction_data?.qr_code,
9469
+ pix_expiration_date: response.date_of_expiration?.toString(),
9470
+ };
9471
+ }
9472
+ static getCardReponse(response) {
9473
+ return {
9474
+ soft_descriptor: response.statement_descriptor?.toString(),
9475
+ installments: response.installments,
9476
+ card_brand: response.payment_method_id?.toString(),
9477
+ card_first_digits: response.card?.first_six_digits?.toString(),
9478
+ card_last_digits: response.card?.last_four_digits?.toString(),
9479
+ card_id: response.card?.id?.toString(),
9480
+ card_holder_name: response.card?.cardholder?.name?.toString(),
9481
+ card_expiration_month: response.card?.expiration_month?.toString(),
9482
+ card_expiration_year: response.card?.expiration_year?.toString(),
9483
+ capture_method: response.payment_type_id?.toString(),
9484
+ authorization_code: response.authorization_code?.toString(),
9485
+ paid_amount: this.statusMapping(response.status) == 'paid' ? response.transaction_details?.total_paid_amount : null,
9486
+ paid_at: this.statusMapping(response.status) == 'paid' ? response.date_approved : null,
9487
+ };
9488
+ }
9489
+ static statusMapping(status) {
9490
+ const statusMap = {
9491
+ approved: 'paid',
9492
+ pending: 'waiting_payment',
9493
+ in_process: 'processing',
9494
+ rejected: 'refused',
9495
+ cancelled: 'refused',
9496
+ refunded: 'refunded',
9497
+ charged_back: 'chargedback',
9498
+ };
9499
+ return statusMap[status] || status;
9500
+ }
9501
+ }
9502
+
9503
+ class MercadoPagoBankSlipAxiosAdapter {
9504
+ constructor(credentials, paymentRepository) {
9505
+ this.credentials = credentials;
9506
+ this.paymentRepository = paymentRepository;
9507
+ }
9508
+ async pay(checkout) {
9509
+ try {
9510
+ const payload = MercadoPagoRequestHelper.build({
9511
+ checkout,
9512
+ method: 'boleto',
9513
+ postback: this.credentials.postback,
9514
+ });
9515
+ console.warn('[MERCADO PAGO BOLETO DATA TO SEND]', JSON.stringify(payload));
9516
+ const { data } = await axios({
9517
+ method: 'POST',
9518
+ url: `${this.credentials.url}/v1/payments`,
9519
+ headers: {
9520
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
9521
+ Authorization: `Bearer ${this.credentials.api_key}`,
9522
+ 'Content-Type': 'application/json',
9523
+ },
9524
+ data: payload,
9525
+ });
9526
+ console.warn('[MERCADO PAGO RESPONSE BOLETO DATA]', JSON.stringify(data));
9527
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(TransactionPaymentMethods.BANKSLIP, checkout, data));
9528
+ return payment;
9529
+ }
9530
+ catch (error) {
9531
+ if (error instanceof AxiosError) {
9532
+ console.warn(JSON.stringify(error.response.data.message));
9533
+ }
9534
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
9535
+ checkoutId: checkout.id,
9536
+ userEmail: checkout.user.email,
9537
+ info: error.response.data?.message || error.message?.toString(),
9538
+ });
9539
+ }
9540
+ }
9541
+ getBoletoTransaction(paymentId) {
9542
+ throw new Error('Method not implemented.');
9543
+ }
9544
+ }
9545
+
9546
+ class MercadoPagoCardAxiosAdapter {
9547
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
9548
+ this.credentials = credentials;
9549
+ this.paymentRepository = paymentRepository;
9550
+ this.orderBlockedRepository = orderBlockedRepository;
9551
+ }
9552
+ async pay(checkout, card) {
9553
+ try {
9554
+ const payload = await this.getPaymentPayload(checkout, card);
9555
+ console.warn('[MERCADO PAGO CARD DATA TO SEND]', JSON.stringify(payload));
9556
+ const { data } = await axios({
9557
+ method: 'POST',
9558
+ url: `${this.credentials.url}/v1/payments`,
9559
+ headers: {
9560
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
9561
+ Authorization: `Bearer ${this.credentials.api_key}`,
9562
+ 'Content-Type': 'application/json',
9563
+ },
9564
+ data: payload,
9565
+ });
9566
+ console.warn('[MERCADO PAGO RESPONSE CARD DATA]', JSON.stringify(data));
9567
+ if (data.status == MercadoPagoStatusEnum.rejected) {
9568
+ await this.orderBlockedRepository.createBlockedOrderOrPayment({
9569
+ checkout,
9570
+ blockType: 'Card not authorized',
9571
+ type: 'Card',
9572
+ limiteRange: 'day',
9573
+ card,
9574
+ });
9575
+ throw new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', {
9576
+ checkoutId: checkout.id,
9577
+ userEmail: checkout.user.email,
9578
+ info: data,
9579
+ });
9580
+ }
9581
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(TransactionPaymentMethods.CARD, checkout, data));
9582
+ return payment;
9583
+ }
9584
+ catch (error) {
9585
+ if (error instanceof AxiosError) {
9586
+ console.warn(JSON.stringify(error.response.data.message));
9587
+ }
9588
+ throw new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', {
9589
+ checkoutId: checkout.id,
9590
+ userEmail: checkout.user.email,
9591
+ info: error.response.data?.message || error.message?.toString(),
9592
+ });
9593
+ }
9594
+ }
9595
+ async getPaymentPayload(checkout, card) {
9596
+ const cardResponse = await this.getCardByToken(card.customerId, card.cardId, card.cardCvv);
9597
+ const payload = MercadoPagoRequestHelper.build({
9598
+ checkout,
9599
+ method: 'credit_card',
9600
+ postback: this.credentials.postback,
9601
+ card: {
9602
+ ...card,
9603
+ cardId: cardResponse.id,
9604
+ },
9605
+ });
9606
+ return payload;
9607
+ }
9608
+ async addCard(card, customer) {
9609
+ return;
9610
+ }
9611
+ async getCardByToken(customerId, token, cardCvv) {
9612
+ try {
9613
+ const payload = { cardId: token, customerId: customerId, securityCode: cardCvv };
9614
+ console.warn('payload getCardByToken', payload);
9615
+ const { data } = await axios({
9616
+ method: 'POST',
9617
+ url: `${this.credentials.url}/v1/card_tokens`,
9618
+ headers: {
9619
+ Authorization: `Bearer ${this.credentials.api_key}`,
9620
+ 'Content-Type': 'application/json',
9621
+ },
9622
+ data: payload,
9623
+ });
9624
+ return data;
9625
+ }
9626
+ catch (error) {
9627
+ if (error instanceof AxiosError) {
9628
+ console.warn(JSON.stringify(error.response.data.cause));
9629
+ }
9630
+ throw error;
9631
+ }
9632
+ }
9633
+ createCardHash(bu, shop, card) {
9634
+ return;
9635
+ }
9636
+ createTransaction(info) {
9637
+ return;
9638
+ }
9639
+ async createOrUpdateCustomer(customer) {
9640
+ const { data } = await axios({
9641
+ method: 'POST',
9642
+ url: `${this.credentials.url}/v1/customers`,
9643
+ headers: {
9644
+ Authorization: `Bearer ${this.credentials.api_key}`,
9645
+ 'Content-Type': 'application/json',
9646
+ },
9647
+ data: {
9648
+ email: customer.email,
9649
+ first_name: customer.firstName,
9650
+ last_name: customer.lastName,
9651
+ phone: {
9652
+ area_code: customer.phone.substring(0, 2),
9653
+ number: customer.phone.substring(2),
9654
+ },
9655
+ identification: {
9656
+ type: 'CPF',
9657
+ number: customer.cpf.replace(/\D/g, ''),
9658
+ },
9659
+ },
9660
+ });
9661
+ return data;
9662
+ }
9663
+ }
9664
+
9665
+ class MercadoPagoPixAxiosAdapter {
9666
+ constructor(credentials, paymentRepository) {
9667
+ this.credentials = credentials;
9668
+ this.paymentRepository = paymentRepository;
9669
+ }
9670
+ async pay(checkout) {
9671
+ try {
9672
+ const payload = MercadoPagoRequestHelper.build({
9673
+ checkout,
9674
+ method: 'pix',
9675
+ postback: this.credentials.postback,
9676
+ });
9677
+ console.warn('[MERCADO PAGO PIX DATA TO SEND]', JSON.stringify(payload));
9678
+ const { data } = await axios({
9679
+ method: 'POST',
9680
+ url: `${this.credentials.url}/v1/payments`,
9681
+ headers: {
9682
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
9683
+ Authorization: `Bearer ${this.credentials.api_key}`,
9684
+ 'Content-Type': 'application/json',
9685
+ },
9686
+ data: payload,
9687
+ });
9688
+ console.warn('[MERCADO PAGO RESPONSE PIX DATA]', JSON.stringify(data));
9689
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(TransactionPaymentMethods.PIX, checkout, data));
9690
+ return payment;
9691
+ }
9692
+ catch (error) {
9693
+ if (error instanceof AxiosError) {
9694
+ console.warn(JSON.stringify(error.response.data.message));
9695
+ }
9696
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
9697
+ checkoutId: checkout.id,
9698
+ userEmail: checkout.user.email,
9699
+ info: error.response.data?.message || error.message?.toString(),
9700
+ });
9701
+ }
9702
+ }
9703
+ }
9704
+
9705
+ var MercadoPagoStatusDetailEnum;
9706
+ (function (MercadoPagoStatusDetailEnum) {
9707
+ MercadoPagoStatusDetailEnum["accredited"] = "accredited";
9708
+ MercadoPagoStatusDetailEnum["partially_refunded"] = "partially_refunded";
9709
+ MercadoPagoStatusDetailEnum["pending_capture"] = "pending_capture";
9710
+ MercadoPagoStatusDetailEnum["offline_process"] = "offline_process";
9711
+ MercadoPagoStatusDetailEnum["pending_contingency"] = "pending_contingency";
9712
+ MercadoPagoStatusDetailEnum["pending_review_manual"] = "pending_review_manual";
9713
+ MercadoPagoStatusDetailEnum["pending_waiting_transfer"] = "pending_waiting_transfer";
9714
+ MercadoPagoStatusDetailEnum["pending_waiting_payment"] = "pending_waiting_payment";
9715
+ MercadoPagoStatusDetailEnum["pending_challenge"] = "pending_challenge";
9716
+ MercadoPagoStatusDetailEnum["bank_error"] = "bank_error";
9717
+ MercadoPagoStatusDetailEnum["cc_rejected_3ds_mandatory"] = "cc_rejected_3ds_mandatory";
9718
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_card_number"] = "cc_rejected_bad_filled_card_number";
9719
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_date"] = "cc_rejected_bad_filled_date";
9720
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_other"] = "cc_rejected_bad_filled_other";
9721
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_security_code"] = "cc_rejected_bad_filled_security_code";
9722
+ MercadoPagoStatusDetailEnum["cc_rejected_blacklist"] = "cc_rejected_blacklist";
9723
+ MercadoPagoStatusDetailEnum["cc_rejected_call_for_authorize"] = "cc_rejected_call_for_authorize";
9724
+ MercadoPagoStatusDetailEnum["cc_rejected_card_disabled"] = "cc_rejected_card_disabled";
9725
+ MercadoPagoStatusDetailEnum["cc_rejected_card_error"] = "cc_rejected_card_error";
9726
+ MercadoPagoStatusDetailEnum["cc_rejected_duplicated_payment"] = "cc_rejected_duplicated_payment";
9727
+ MercadoPagoStatusDetailEnum["cc_rejected_high_risk"] = "cc_rejected_high_risk";
9728
+ MercadoPagoStatusDetailEnum["cc_rejected_insufficient_amount"] = "cc_rejected_insufficient_amount";
9729
+ MercadoPagoStatusDetailEnum["cc_rejected_invalid_installments"] = "cc_rejected_invalid_installments";
9730
+ MercadoPagoStatusDetailEnum["cc_rejected_max_attempts"] = "cc_rejected_max_attempts";
9731
+ MercadoPagoStatusDetailEnum["cc_rejected_other_reason"] = "cc_rejected_other_reason";
9732
+ MercadoPagoStatusDetailEnum["cc_amount_rate_limit_exceeded"] = "cc_amount_rate_limit_exceeded";
9733
+ MercadoPagoStatusDetailEnum["rejected_insufficient_data"] = "rejected_insufficient_data";
9734
+ MercadoPagoStatusDetailEnum["rejected_by_bank"] = "rejected_by_bank";
9735
+ MercadoPagoStatusDetailEnum["rejected_by_regulations"] = "rejected_by_regulations";
9736
+ MercadoPagoStatusDetailEnum["insufficient_amount"] = "insufficient_amount";
9737
+ MercadoPagoStatusDetailEnum["cc_rejected_card_type_not_allowed"] = "cc_rejected_card_type_not_allowed";
9738
+ })(MercadoPagoStatusDetailEnum || (MercadoPagoStatusDetailEnum = {}));
9739
+
9740
+ var MercadoPagoStatusEnum;
9741
+ (function (MercadoPagoStatusEnum) {
9742
+ MercadoPagoStatusEnum["approved"] = "approved";
9743
+ MercadoPagoStatusEnum["authorized"] = "authorized";
9744
+ MercadoPagoStatusEnum["pending"] = "pending";
9745
+ MercadoPagoStatusEnum["in_process"] = "in_process";
9746
+ MercadoPagoStatusEnum["rejected"] = "rejected";
9747
+ MercadoPagoStatusEnum["cancelled"] = "cancelled";
9748
+ MercadoPagoStatusEnum["refunded"] = "refunded";
9749
+ MercadoPagoStatusEnum["charged_back"] = "charged_back";
9750
+ })(MercadoPagoStatusEnum || (MercadoPagoStatusEnum = {}));
9751
+
8662
9752
  class PagarmeBankSlipAxiosAdapter {
8663
9753
  constructor(credentials, paymentRepository) {
8664
9754
  this.credentials = credentials;
@@ -8806,15 +9896,17 @@ class PagarMeV5RequestHelper {
8806
9896
  customer: this.buildCustomer(checkout),
8807
9897
  shipping: this.buildShipping(checkout),
8808
9898
  payments: this.buildPayment(checkout, method, card),
9899
+ ...this.buildAdditionalInfo(checkout),
8809
9900
  };
8810
9901
  }
8811
9902
  static buildItems(checkout) {
9903
+ const isSubscriber = checkout.user?.isSubscriber ?? false;
8812
9904
  return checkout.lineItems
8813
9905
  .filter((item) => !item.isGift)
8814
9906
  .map((item) => {
8815
9907
  return {
8816
9908
  amount: Math.floor(item.pricePaid * 100),
8817
- description: item.name,
9909
+ description: isSubscriber ? `${item.name} - ASSINANTE` : item.name,
8818
9910
  quantity: item.quantity,
8819
9911
  code: item.EAN,
8820
9912
  };
@@ -8883,12 +9975,12 @@ class PagarMeV5RequestHelper {
8883
9975
  }
8884
9976
  static getPixOrder() {
8885
9977
  return {
8886
- expires_at: format(addDays(new Date(), 1), 'yyyy-MM-dd'),
9978
+ expires_at: format(addDays(new Date(), 1), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
8887
9979
  };
8888
9980
  }
8889
9981
  static getBoletoOrder() {
8890
9982
  return {
8891
- due_at: format(addDays(new Date(), 3), 'yyyy-MM-dd'),
9983
+ due_at: format(addDays(new Date(), 3), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
8892
9984
  instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
8893
9985
  type: 'DM',
8894
9986
  document_number: new Date().getTime().toString(),
@@ -8911,6 +10003,14 @@ class PagarMeV5RequestHelper {
8911
10003
  },
8912
10004
  };
8913
10005
  }
10006
+ static buildAdditionalInfo(checkout) {
10007
+ const isSubscriber = checkout.user?.isSubscriber ?? false;
10008
+ if (isSubscriber)
10009
+ return {
10010
+ antifraude_enabled: false,
10011
+ };
10012
+ return {};
10013
+ }
8914
10014
  }
8915
10015
 
8916
10016
  class PagarMeV5ResponseHelper {
@@ -9643,4 +10743,4 @@ class ProductsVertexSearch {
9643
10743
  }
9644
10744
  }
9645
10745
 
9646
- export { AccessoryImportances, Address, AdyenCardAxiosAdapter, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BrandEquityOptions, BusinessError, BusinessUnitEnum, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, FraudValidationError, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, Group, GroupFirestoreRepository, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, NotFoundError, ObsEmitter, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderBlockedType, OrderFirestoreRepository, OrderStatus, PagarMeV5OrderStatus, PagarMeV5PaymentStatus, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, PagarmeV5BankSlipAxiosAdapter, PagarmeV5CardAxiosAdapter, PagarmeV5PixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductErrors, ProductErrorsHasuraGraphQL, ProductErrorsHasuraGraphQLRepository, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductReview, ProductReviewHasuraGraphQLRepository, ProductSpents, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RestCacheAdapter, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, StockLimitError, StockOutError, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, TransactionPaymentMethods, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, deserialize, getClass, is, isDebuggable, isUUID, parseDateTime, registerClass, resolveClass, serialize, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };
10746
+ export { AccessoryImportances, Address, AdyenCardAxiosAdapter, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BrandCategory, BrandCategoryFirestoreRepository, BrandEquityOptions, BusinessError, BusinessUnitEnum, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, FraudValidationError, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, Group, GroupFirestoreRepository, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, MercadoPagoBankSlipAxiosAdapter, MercadoPagoCardAxiosAdapter, MercadoPagoPaymentMethodFactory, MercadoPagoPixAxiosAdapter, MercadoPagoRequestHelper, MercadoPagoResponseHelper, MercadoPagoStatusDetailEnum, MercadoPagoStatusEnum, NotFoundError, ObsEmitter, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderBlockedType, OrderFirestoreRepository, OrderPaymentStatus, OrderStatus, PagarMeV5OrderStatus, PagarMeV5PaymentStatus, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, PagarmeV5BankSlipAxiosAdapter, PagarmeV5CardAxiosAdapter, PagarmeV5PixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductCatalogHasuraGraphQL, ProductCatalogHasuraGraphQLRepository, ProductErrors, ProductErrorsHasuraGraphQL, ProductErrorsHasuraGraphQLRepository, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductReview, ProductReviewHasuraGraphQLRepository, ProductSpents, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RestCacheAdapter, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, StockLimitError, StockOutError, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, TransactionPaymentMethods, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, deserialize, getClass, is, isDebuggable, isUUID, parseDateTime, registerClass, resolveClass, serialize, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };