@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.cjs.js CHANGED
@@ -62,6 +62,18 @@ exports.OrderBlockedType = void 0;
62
62
  OrderBlockedType["Boleto"] = "Boleto";
63
63
  })(exports.OrderBlockedType || (exports.OrderBlockedType = {}));
64
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
+
65
77
  exports.PagarmePaymentStatus = void 0;
66
78
  (function (PagarmePaymentStatus) {
67
79
  PagarmePaymentStatus["Em processamento"] = "processing";
@@ -114,6 +126,7 @@ exports.PaymentProviders = void 0;
114
126
  PaymentProviders["PAGARME"] = "pagarMe";
115
127
  PaymentProviders["ADYEN"] = "adyen";
116
128
  PaymentProviders["GLAMPOINTS"] = "glampoints";
129
+ PaymentProviders["MERCADOPAGO"] = "mercadoPago";
117
130
  })(exports.PaymentProviders || (exports.PaymentProviders = {}));
118
131
 
119
132
  exports.TransactionPaymentMethods = void 0;
@@ -147,6 +160,9 @@ class AntifraudProviderFactory {
147
160
  class GlampointsPaymentMethodFactory extends BasePaymentMethodFactory {
148
161
  }
149
162
 
163
+ class MercadoPagoPaymentMethodFactory extends BasePaymentMethodFactory {
164
+ }
165
+
150
166
  class PagarmePaymentMethodFactory extends BasePaymentMethodFactory {
151
167
  }
152
168
 
@@ -757,6 +773,30 @@ tslib.__decorate([
757
773
  ], Category.prototype, "filters", void 0);
758
774
  registerClass('Category', Category);
759
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
+
760
800
  class CategoryCollectionChildren extends BaseModel {
761
801
  static get identifiersFields() {
762
802
  return ['collectionId', 'categoryId'];
@@ -829,7 +869,12 @@ class ProductReview extends BaseModel {
829
869
  static get identifiersFields() {
830
870
  return ['id'];
831
871
  }
832
- }
872
+ }
873
+ tslib.__decorate([
874
+ classTransformer.Type(resolveClass('Product')),
875
+ tslib.__metadata("design:type", Function)
876
+ ], ProductReview.prototype, "product", void 0);
877
+ registerClass('ProductReview', ProductReview);
833
878
 
834
879
  class ProductBase extends BaseModel {
835
880
  get evaluation() {
@@ -1760,19 +1805,58 @@ class AntifraudCardService {
1760
1805
  constructor(orderRepository, orderBlockedRepository) {
1761
1806
  this.orderRepository = orderRepository;
1762
1807
  this.orderBlockedRepository = orderBlockedRepository;
1763
- this.LIMIT_ORDERS_DAY = 2;
1764
- this.LIMIT_ORDERS_WEEK = 7;
1765
- this.LIMIT_BLOCKED_ORDERS_DAY = 5;
1808
+ this.LIMIT_ORDERS_DAY = null;
1809
+ this.LIMIT_ORDERS_WEEK = null;
1766
1810
  }
1767
1811
  async validate(checkout, card) {
1812
+ this.setLimitsByUserType(checkout.user.isSubscriber);
1768
1813
  await this.validateBlockedOrderAttempts(checkout, card);
1769
1814
  await this.validateDayAndWeekOrderLimits(checkout, card);
1770
1815
  return true;
1771
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
+ }
1772
1856
  async validateBlockedOrderAttempts(checkout, card) {
1773
1857
  const isValid = await this.verifyBlockedOrderAttempts(checkout, card);
1774
1858
  if (!isValid) {
1775
- 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`, {
1776
1860
  checkoutId: checkout.id,
1777
1861
  userEmail: checkout.user.email,
1778
1862
  info: {
@@ -1786,7 +1870,7 @@ class AntifraudCardService {
1786
1870
  async validateDayAndWeekOrderLimits(checkout, card) {
1787
1871
  const isValid = await this.verifyDayAndWeekOrders(checkout, card);
1788
1872
  if (!isValid) {
1789
- 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', {
1790
1874
  checkoutId: checkout.id,
1791
1875
  userEmail: checkout.user.email,
1792
1876
  info: {
@@ -1805,7 +1889,7 @@ class AntifraudCardService {
1805
1889
  await this.createBlockedOrderRecord({
1806
1890
  checkout,
1807
1891
  card,
1808
- reason: 'More than 5 attempts have failed',
1892
+ reason: `More than ${this.LIMIT_BLOCKED_ORDERS_DAY} attempts have failed`,
1809
1893
  key: 'Failed attempts',
1810
1894
  period: 'day',
1811
1895
  });
@@ -1926,26 +2010,28 @@ class AntifraudCardService {
1926
2010
  }
1927
2011
  async validateDayOrderLimits(checkout, params) {
1928
2012
  const ordersPerDay = await this.validateOrdersByRange(params, this.getDateRange('day'));
2013
+ const limits = this.getLimitsByUserType('day', checkout.user.isSubscriber);
1929
2014
  return this.checkOrderLimitsAndBlock({
1930
2015
  checkout,
1931
2016
  orderCounts: ordersPerDay,
1932
- limit: this.LIMIT_ORDERS_DAY,
2017
+ limit: limits,
1933
2018
  period: 'day',
1934
2019
  });
1935
2020
  }
1936
2021
  async validateWeekOrderLimits(checkout, params) {
1937
2022
  const ordersPerWeek = await this.validateOrdersByRange(params, this.getDateRange('week'));
2023
+ const limits = this.getLimitsByUserType('week', checkout.user.isSubscriber);
1938
2024
  return this.checkOrderLimitsAndBlock({
1939
2025
  checkout,
1940
2026
  orderCounts: ordersPerWeek,
1941
- limit: this.LIMIT_ORDERS_WEEK,
2027
+ limit: limits,
1942
2028
  period: 'week',
1943
2029
  });
1944
2030
  }
1945
2031
  async checkOrderLimitsAndBlock(params) {
1946
2032
  const { checkout, orderCounts, limit, period } = params;
1947
2033
  for (const key in orderCounts) {
1948
- if (orderCounts[key] >= limit) {
2034
+ if (orderCounts[key] >= limit[key]) {
1949
2035
  await this.createBlockedOrderRecord({
1950
2036
  checkout,
1951
2037
  card: null,
@@ -4763,6 +4849,17 @@ const withCrudFirestore = (MixinBase) => {
4763
4849
  };
4764
4850
  };
4765
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
+
4766
4863
  class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4767
4864
  constructor({ firestore, interceptors }) {
4768
4865
  super({
@@ -5851,6 +5948,9 @@ tslib.__decorate([
5851
5948
  tslib.__metadata("design:type", Product)
5852
5949
  ], KitProductHasuraGraphQL.prototype, "product", void 0);
5853
5950
 
5951
+ class ProductCatalogHasuraGraphQL extends Product {
5952
+ }
5953
+
5854
5954
  class ProductHasuraGraphQL extends Product {
5855
5955
  }
5856
5956
  tslib.__decorate([
@@ -7216,83 +7316,7 @@ class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasu
7216
7316
  }
7217
7317
  }
7218
7318
 
7219
- class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7220
- constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7221
- super({
7222
- tableName: 'product_errors',
7223
- model: ProductErrorsHasuraGraphQL,
7224
- endpoint,
7225
- authOptions,
7226
- interceptors,
7227
- cache,
7228
- fields: [
7229
- {
7230
- productId: {
7231
- columnName: 'product_id',
7232
- to: (value) => +value,
7233
- from: (value) => value.toString(),
7234
- },
7235
- },
7236
- 'source',
7237
- 'error',
7238
- { createdAt: { columnName: 'created_at' } },
7239
- { updatedAt: { columnName: 'updated_at' } },
7240
- {
7241
- product: {
7242
- columnName: 'product',
7243
- foreignKeyColumn: { id: 'productId' },
7244
- fields: [
7245
- { id: { columnName: 'id', from: (value) => value.toString() } },
7246
- { productId: { columnName: 'main_product_id' } },
7247
- 'name',
7248
- 'published',
7249
- 'group',
7250
- 'validity',
7251
- { createdAt: { columnName: 'created_at' } },
7252
- { updatedAt: { columnName: 'updated_at' } },
7253
- ],
7254
- },
7255
- },
7256
- ],
7257
- });
7258
- this.productRepository = productRepository;
7259
- }
7260
- async get(params) {
7261
- const result = await super.get(params);
7262
- if (result instanceof VariantHasuraGraphQL) {
7263
- const product = await this.productRepository.get({ id: result.productId.toString() });
7264
- result.product.name = product.name;
7265
- result.product.group = product.group;
7266
- }
7267
- return result;
7268
- }
7269
- async find(params) {
7270
- const result = await super.find(params);
7271
- const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7272
- (lodash.isEmpty(item.product.name) || lodash.isEmpty(item.product.group) || lodash.isEmpty(item.product)));
7273
- if (variantsWithNoData.length > 0) {
7274
- const { data: products } = await this.productRepository.find({
7275
- filters: {
7276
- id: {
7277
- operator: exports.Where.IN,
7278
- value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7279
- },
7280
- },
7281
- });
7282
- products.forEach((product) => {
7283
- result.data
7284
- .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7285
- .forEach((variant) => {
7286
- variant.product.name = product.name;
7287
- variant.product.group = product.group;
7288
- });
7289
- });
7290
- }
7291
- return result;
7292
- }
7293
- }
7294
-
7295
- const commonFields = [
7319
+ const commonFields$1 = [
7296
7320
  {
7297
7321
  id: {
7298
7322
  columnName: 'id',
@@ -7459,55 +7483,427 @@ const commonFields = [
7459
7483
  { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7460
7484
  { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7461
7485
  { daysOfUse: { columnName: 'days_of_use' } },
7486
+ { showVariants: { columnName: 'show_variants' } },
7487
+ { variantSlug: { columnName: 'variant_slug' } },
7462
7488
  ];
7463
- const fieldsConfiguration$2 = [
7464
- ...commonFields,
7465
- {
7466
- categories: {
7467
- columnName: 'categories',
7468
- fields: ['category_id'],
7469
- bindPersistData: (value) => ({
7470
- categories: { data: value.map((category) => ({ category_id: +category })) },
7471
- }),
7472
- to: (categories) => categories.map((categoryId) => +categoryId),
7473
- from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7474
- },
7475
- },
7476
- {
7477
- kitProducts: {
7478
- columnName: 'kit_products',
7479
- foreignKeyColumn: { productId: 'id' },
7480
- fields: [
7481
- { productId: { columnName: 'product_id' } },
7482
- { kitProductId: { columnName: 'kit_product_id' } },
7483
- 'quantity',
7484
- { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7485
- ],
7486
- },
7487
- },
7488
- {
7489
- reviews: {
7490
- columnName: 'reviews',
7491
- foreignKeyColumn: { product_id: 'id' },
7489
+ class ProductCatalogHasuraGraphQLRepository extends withFindHasuraGraphQL(withHasuraGraphQL(Base)) {
7490
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
7491
+ super({
7492
+ tableName: 'product_catalog',
7493
+ model: ProductCatalogHasuraGraphQL,
7494
+ endpoint,
7495
+ authOptions,
7496
+ interceptors,
7497
+ fields: commonFields$1,
7498
+ cache,
7499
+ });
7500
+ }
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
+ }
7509
+ }
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 },
7492
7581
  fields: [
7493
- 'id',
7494
- 'shop',
7495
- 'rate',
7496
- 'author',
7497
- 'email',
7498
- 'location',
7499
- 'review',
7500
- 'status',
7501
- 'title',
7502
- { personId: { columnName: 'person_id' } },
7503
- 'points',
7504
- { orderId: { columnName: 'order_id' } },
7505
- { createdAt: { columnName: 'created_at' } },
7506
- { updatedAt: { columnName: 'updated_at' } },
7582
+ ...bindFields,
7583
+ ...(bindFields.includes('price')
7584
+ ? [
7585
+ 'subscriberPrice',
7586
+ 'subscriberDiscountPercentage',
7587
+ 'fullPrice',
7588
+ ]
7589
+ : []),
7507
7590
  ],
7508
- },
7509
- },
7510
- {
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
+ {
7511
7907
  metadata: {
7512
7908
  columnName: 'metadata',
7513
7909
  fields: ['title', 'description'],
@@ -7522,9 +7918,61 @@ const fieldsConfiguration$2 = [
7522
7918
  foreignKeyColumn: { product_id: 'id' },
7523
7919
  fields: [
7524
7920
  'id',
7921
+ 'name',
7525
7922
  'ean',
7526
7923
  'sku',
7527
- 'description',
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' } },
7528
7976
  {
7529
7977
  grade: {
7530
7978
  columnName: 'grade',
@@ -7541,22 +7989,6 @@ const fieldsConfiguration$2 = [
7541
7989
  subscriberPrice: data.subscriber_price,
7542
7990
  fullPriceDiscountPercentage: data.full_price_discount_percentage,
7543
7991
  }),
7544
- bindFindFilter: (sentence) => {
7545
- const filters = Object.values(sentence).shift();
7546
- return {
7547
- ...((filters?.price || filters?.price === 0) && { price: filters.price }),
7548
- ...((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice }),
7549
- ...((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
7550
- subscriber_discount_percentage: filters.subscriberDiscountPercentage,
7551
- }),
7552
- ...((filters.subscriberPrice || filters.subscriberPrice === 0) && {
7553
- subscriber_price: filters.subscriberPrice,
7554
- }),
7555
- ...((filters.fullPriceDiscountPercentage || filters.fullPriceDiscountPercentage === 0) && {
7556
- full_price_discount_percentage: filters.fullPriceDiscountPercentage,
7557
- }),
7558
- };
7559
- },
7560
7992
  bindPersistData: (priceData) => ({
7561
7993
  ...((priceData?.price || 0) >= 0 && { price: priceData.price }),
7562
7994
  ...((priceData?.fullPrice || 0) >= 0 && { full_price: priceData.fullPrice }),
@@ -7602,6 +8034,39 @@ const fieldsConfiguration$2 = [
7602
8034
  },
7603
8035
  { tagsProfile: { columnName: 'tags_profile' } },
7604
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
+ },
7605
8070
  ],
7606
8071
  },
7607
8072
  },
@@ -7667,7 +8132,12 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7667
8132
  : await super.get(identifiers, options);
7668
8133
  if (product.productId)
7669
8134
  throw new NotFoundError('Product not found, it is a variant');
7670
- product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, options));
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
+ }
7671
8141
  return product;
7672
8142
  }
7673
8143
  async find(params, optionsParams) {
@@ -7709,6 +8179,9 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7709
8179
  const result = await this.find({
7710
8180
  filters: {
7711
8181
  slug,
8182
+ productId: {
8183
+ operator: exports.Where.ISNULL,
8184
+ },
7712
8185
  },
7713
8186
  fields: this.fields.map((field) => typeof field === 'string' ? field : Object.keys(field).shift()),
7714
8187
  options: {
@@ -7718,6 +8191,11 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7718
8191
  if (!result.data.length)
7719
8192
  return null;
7720
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
+ }
7721
8199
  RoundProductPricesHelper.roundProductPrices(product);
7722
8200
  if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7723
8201
  const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
@@ -7897,7 +8375,8 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7897
8375
  const plainData = this.paramsToPlain({ metadata });
7898
8376
  if (!plainData.metadata)
7899
8377
  return null;
7900
- 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'], {
7901
8380
  pk_columns: {
7902
8381
  value: { product_id: productId },
7903
8382
  type: 'product_metadata_pk_columns_input',
@@ -7909,6 +8388,14 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7909
8388
  required: true,
7910
8389
  },
7911
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
+ }
7912
8399
  return plainData.metadata;
7913
8400
  }
7914
8401
  async getId(id) {
@@ -7919,7 +8406,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7919
8406
  return data?.[0]?.id;
7920
8407
  throw new NotFoundError(`Product with id ${id} not found`);
7921
8408
  }
7922
- async findReviewsByProduct(productId, options) {
8409
+ async findReviewsByProduct(productId, onlyApproved, options) {
7923
8410
  if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7924
8411
  const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
7925
8412
  const cachedData = await this.cache.cacheAdapter.get(cacheKey);
@@ -7932,10 +8419,16 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7932
8419
  where: {
7933
8420
  value: {
7934
8421
  product_id: { _eq: productId },
8422
+ ...(onlyApproved && { status: { _eq: true } }),
7935
8423
  },
7936
8424
  type: 'product_review_bool_exp',
7937
8425
  required: true,
7938
8426
  },
8427
+ order_by: {
8428
+ type: '[product_review_order_by]',
8429
+ value: [{ createdAt: 'desc' }],
8430
+ required: true,
8431
+ },
7939
8432
  });
7940
8433
  const reviews = data?.map((review) => this.bindReviewToModel(review));
7941
8434
  if (this.cache?.cacheAdapter && options?.cache?.enabled && reviews) {
@@ -8040,7 +8533,7 @@ tslib.__decorate([
8040
8533
  tslib.__decorate([
8041
8534
  Log(),
8042
8535
  tslib.__metadata("design:type", Function),
8043
- tslib.__metadata("design:paramtypes", [Number, Object]),
8536
+ tslib.__metadata("design:paramtypes", [Number, Boolean, Object]),
8044
8537
  tslib.__metadata("design:returntype", Promise)
8045
8538
  ], ProductHasuraGraphQLRepository.prototype, "findReviewsByProduct", null);
8046
8539
 
@@ -8072,7 +8565,25 @@ class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHas
8072
8565
  product: {
8073
8566
  columnName: 'product',
8074
8567
  foreignKeyColumn: { id: 'productId' },
8075
- 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
+ ],
8076
8587
  },
8077
8588
  },
8078
8589
  ],
@@ -8265,6 +8776,7 @@ const fieldsConfiguration$1 = [
8265
8776
  },
8266
8777
  },
8267
8778
  'group',
8779
+ 'type',
8268
8780
  'validity',
8269
8781
  'published',
8270
8782
  { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
@@ -8283,11 +8795,129 @@ const fieldsConfiguration$1 = [
8283
8795
  },
8284
8796
  },
8285
8797
  {
8286
- imagesCard: {
8287
- columnName: 'images_card',
8288
- to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
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
+ },
8887
+ {
8888
+ metadata: {
8889
+ columnName: 'metadata',
8890
+ fields: ['title', 'description'],
8891
+ bindPersistData: (value) => ({
8892
+ metadata: { data: value },
8893
+ }),
8894
+ },
8895
+ },
8896
+ {
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
+ ],
8289
8916
  },
8290
8917
  },
8918
+ { variantSlug: { columnName: 'variant_slug' } },
8919
+ { createdAt: { columnName: 'created_at' } },
8920
+ { updatedAt: { columnName: 'updated_at' } },
8291
8921
  ];
8292
8922
  class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8293
8923
  constructor({ endpoint, authOptions, interceptors, cache, }) {
@@ -8328,18 +8958,46 @@ class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
8328
8958
  return data.at(0);
8329
8959
  }
8330
8960
  async update(params) {
8331
- const { productId, id: checkId, ...data } = params;
8961
+ const { productId, id: checkId, metadata, ...data } = params;
8332
8962
  const dataWithProductId = this.paramsToPlain({ id: checkId, productId });
8333
8963
  if (!dataWithProductId.id) {
8334
8964
  throw new NotFoundError('Variant ID is required for update');
8335
8965
  }
8336
8966
  const id = await this.getId(dataWithProductId.id);
8337
8967
  const product = await super.update({ id, ...data });
8968
+ product.metadata = metadata && (await this.updateMetadata(+id, { metadata }));
8338
8969
  if (dataWithProductId.productId) {
8339
8970
  product.productId = dataWithProductId.productId;
8340
8971
  }
8341
8972
  return product;
8342
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
+ }
8343
9001
  async getId(id) {
8344
9002
  if (!Number.isNaN(+id))
8345
9003
  return id;
@@ -8683,6 +9341,438 @@ tslib.__decorate([
8683
9341
  tslib.__metadata("design:returntype", Promise)
8684
9342
  ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
8685
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
+
8686
9776
  class PagarmeBankSlipAxiosAdapter {
8687
9777
  constructor(credentials, paymentRepository) {
8688
9778
  this.credentials = credentials;
@@ -8830,15 +9920,17 @@ class PagarMeV5RequestHelper {
8830
9920
  customer: this.buildCustomer(checkout),
8831
9921
  shipping: this.buildShipping(checkout),
8832
9922
  payments: this.buildPayment(checkout, method, card),
9923
+ ...this.buildAdditionalInfo(checkout),
8833
9924
  };
8834
9925
  }
8835
9926
  static buildItems(checkout) {
9927
+ const isSubscriber = checkout.user?.isSubscriber ?? false;
8836
9928
  return checkout.lineItems
8837
9929
  .filter((item) => !item.isGift)
8838
9930
  .map((item) => {
8839
9931
  return {
8840
9932
  amount: Math.floor(item.pricePaid * 100),
8841
- description: item.name,
9933
+ description: isSubscriber ? `${item.name} - ASSINANTE` : item.name,
8842
9934
  quantity: item.quantity,
8843
9935
  code: item.EAN,
8844
9936
  };
@@ -8907,12 +9999,12 @@ class PagarMeV5RequestHelper {
8907
9999
  }
8908
10000
  static getPixOrder() {
8909
10001
  return {
8910
- expires_at: dateFns.format(dateFns.addDays(new Date(), 1), 'yyyy-MM-dd'),
10002
+ expires_at: dateFns.format(dateFns.addDays(new Date(), 1), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
8911
10003
  };
8912
10004
  }
8913
10005
  static getBoletoOrder() {
8914
10006
  return {
8915
- due_at: dateFns.format(dateFns.addDays(new Date(), 3), 'yyyy-MM-dd'),
10007
+ due_at: dateFns.format(dateFns.addDays(new Date(), 3), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
8916
10008
  instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
8917
10009
  type: 'DM',
8918
10010
  document_number: new Date().getTime().toString(),
@@ -8935,6 +10027,14 @@ class PagarMeV5RequestHelper {
8935
10027
  },
8936
10028
  };
8937
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
+ }
8938
10038
  }
8939
10039
 
8940
10040
  class PagarMeV5ResponseHelper {
@@ -9806,6 +10906,8 @@ exports.Base = Base;
9806
10906
  exports.BaseModel = BaseModel;
9807
10907
  exports.BeautyProfile = BeautyProfile;
9808
10908
  exports.BeautyQuestionsHelper = BeautyQuestionsHelper;
10909
+ exports.BrandCategory = BrandCategory;
10910
+ exports.BrandCategoryFirestoreRepository = BrandCategoryFirestoreRepository;
9809
10911
  exports.BusinessError = BusinessError;
9810
10912
  exports.Buy2Win = Buy2Win;
9811
10913
  exports.Buy2WinFirestoreRepository = Buy2WinFirestoreRepository;
@@ -9864,6 +10966,12 @@ exports.Log = Log;
9864
10966
  exports.LogDocument = LogDocument;
9865
10967
  exports.LogFirestoreRepository = LogFirestoreRepository;
9866
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;
9867
10975
  exports.NotFoundError = NotFoundError;
9868
10976
  exports.ObsEmitter = ObsEmitter;
9869
10977
  exports.Order = Order;
@@ -9883,6 +10991,8 @@ exports.PaymentFirestoreRepository = PaymentFirestoreRepository;
9883
10991
  exports.PaymentProviderFactory = PaymentProviderFactory;
9884
10992
  exports.PaymentTransaction = PaymentTransaction;
9885
10993
  exports.Product = Product;
10994
+ exports.ProductCatalogHasuraGraphQL = ProductCatalogHasuraGraphQL;
10995
+ exports.ProductCatalogHasuraGraphQLRepository = ProductCatalogHasuraGraphQLRepository;
9886
10996
  exports.ProductErrors = ProductErrors;
9887
10997
  exports.ProductErrorsHasuraGraphQL = ProductErrorsHasuraGraphQL;
9888
10998
  exports.ProductErrorsHasuraGraphQLRepository = ProductErrorsHasuraGraphQLRepository;