@infrab4a/connect 5.3.0-beta.0 → 5.3.0-beta.10

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 (58) hide show
  1. package/index.cjs.js +1475 -211
  2. package/index.esm.js +1469 -213
  3. package/package.json +3 -2
  4. package/src/domain/catalog/models/product-base.d.ts +5 -1
  5. package/src/domain/catalog/models/product.d.ts +1 -0
  6. package/src/domain/catalog/models/types/brands-shop-menu.type.d.ts +13 -0
  7. package/src/domain/catalog/models/types/index.d.ts +1 -0
  8. package/src/domain/catalog/repositories/category.repository.d.ts +1 -0
  9. package/src/domain/catalog/repositories/index.d.ts +1 -0
  10. package/src/domain/catalog/repositories/product-catalog.repository.d.ts +17 -0
  11. package/src/domain/catalog/repositories/product.repository.d.ts +3 -0
  12. package/src/domain/catalog/repositories/variant.repository.d.ts +1 -0
  13. package/src/domain/shopping/enums/index.d.ts +2 -0
  14. package/src/domain/shopping/enums/pagarme-v5-payment-status.enum.d.ts +24 -0
  15. package/src/domain/shopping/enums/transaction-payment-methods.enum.d.ts +5 -0
  16. package/src/domain/shopping/interfaces/payment-provider-card.interface.d.ts +10 -2
  17. package/src/domain/shopping/models/enums/order-status.enum.d.ts +1 -1
  18. package/src/domain/shopping/models/order.d.ts +4 -0
  19. package/src/domain/shopping/models/payment-transaction.d.ts +17 -2
  20. package/src/domain/shopping/models/payment.d.ts +2 -1
  21. package/src/domain/shopping/types/card-info.type.d.ts +1 -0
  22. package/src/domain/shopping/types/index.d.ts +1 -0
  23. package/src/domain/shopping/types/pagarme-card.type.d.ts +9 -3
  24. package/src/domain/shopping/types/pagarme-credentials-v5.type.d.ts +4 -0
  25. package/src/domain/shopping/types/pagarme-credentials.type.d.ts +9 -3
  26. package/src/domain/users/models/user-payment-method.d.ts +2 -0
  27. package/src/infra/firebase/firestore/repositories/catalog/category-firestore.repository.d.ts +1 -0
  28. package/src/infra/firebase/firestore/repositories/catalog/product-firestore.repository.d.ts +4 -1
  29. package/src/infra/firebase/firestore/repositories/catalog/product-variant-firestore.repository.d.ts +1 -0
  30. package/src/infra/hasura-graphql/models/index.d.ts +1 -0
  31. package/src/infra/hasura-graphql/models/product-catalog-hasura-graphql.d.ts +16 -0
  32. package/src/infra/hasura-graphql/models/variant-hasura-graphql.d.ts +7 -0
  33. package/src/infra/hasura-graphql/repositories/catalog/category-hasura-graphql.repository.d.ts +1 -0
  34. package/src/infra/hasura-graphql/repositories/catalog/index.d.ts +1 -0
  35. package/src/infra/hasura-graphql/repositories/catalog/product-catalog-hasura-graphql.repository.d.ts +22 -0
  36. package/src/infra/hasura-graphql/repositories/catalog/product-hasura-graphql.repository.d.ts +3 -0
  37. package/src/infra/hasura-graphql/repositories/catalog/variant-hasura-graphql.repository.d.ts +2 -0
  38. package/src/infra/hasura-graphql/repositories/catalog/wishlist-hasura-graphql.repository.d.ts +1 -0
  39. package/src/infra/pagarme/adapters/helpers/index.d.ts +2 -0
  40. package/src/infra/pagarme/adapters/helpers/pagarme-v5-request.helper.d.ts +12 -0
  41. package/src/infra/pagarme/adapters/helpers/pagarme-v5-response.helper.d.ts +10 -0
  42. package/src/infra/pagarme/adapters/index.d.ts +2 -3
  43. package/src/infra/pagarme/adapters/v4/index.d.ts +3 -0
  44. package/src/infra/pagarme/adapters/{pagarme-bank-slip-payment-axios.adapter.d.ts → v4/pagarme-bank-slip-payment-axios.adapter.d.ts} +4 -4
  45. package/src/infra/pagarme/adapters/{pagarme-card-payment-axios.adapter.d.ts → v4/pagarme-card-payment-axios.adapter.d.ts} +7 -6
  46. package/src/infra/pagarme/adapters/{pagarme-pix-payment-axios.adapter.d.ts → v4/pagarme-pix-payment-axios.adapter.d.ts} +4 -4
  47. package/src/infra/pagarme/adapters/v5/index.d.ts +3 -0
  48. package/src/infra/pagarme/adapters/v5/pagarmev5-bank-slip-payment-axios.adapter.d.ts +11 -0
  49. package/src/infra/pagarme/adapters/v5/pagarmev5-card-payment-axios.adapter.d.ts +24 -0
  50. package/src/infra/pagarme/adapters/v5/pagarmev5-pix-payment-axios.adapter.d.ts +10 -0
  51. package/src/infra/pagarme/index.d.ts +1 -0
  52. package/src/infra/pagarme/types/index.d.ts +1 -0
  53. package/src/infra/pagarme/types/v5/index.d.ts +4 -0
  54. package/src/infra/pagarme/types/v5/pagarmev5-customer.type.d.ts +19 -0
  55. package/src/infra/pagarme/types/v5/pagarmev5-order-request-payload.type.d.ts +89 -0
  56. package/src/infra/pagarme/types/v5/pagarmev5-order-response.type.d.ts +126 -0
  57. package/src/infra/pagarme/types/v5/pagarmev5-postback-response.type.d.ts +11 -0
  58. package/src/utils/index.d.ts +2 -1
package/index.cjs.js CHANGED
@@ -6,6 +6,7 @@ require('reflect-metadata');
6
6
  var tslib = require('tslib');
7
7
  var classTransformer = require('class-transformer');
8
8
  var dateFns = require('date-fns');
9
+ var dateFnsTz = require('date-fns-tz');
9
10
  var lodash = require('lodash');
10
11
  var debug = require('debug');
11
12
  var serializeJavascript = require('serialize-javascript');
@@ -73,6 +74,33 @@ exports.PagarmePaymentStatus = void 0;
73
74
  PagarmePaymentStatus["Chargedback"] = "chargedback";
74
75
  })(exports.PagarmePaymentStatus || (exports.PagarmePaymentStatus = {}));
75
76
 
77
+ exports.PagarMeV5PaymentStatus = void 0;
78
+ (function (PagarMeV5PaymentStatus) {
79
+ PagarMeV5PaymentStatus["Em processamento"] = "processing";
80
+ PagarMeV5PaymentStatus["Gerado"] = "generated";
81
+ PagarMeV5PaymentStatus["Visualizado"] = "viewed";
82
+ PagarMeV5PaymentStatus["Pago a menor"] = "underpaid";
83
+ PagarMeV5PaymentStatus["Pago a maior"] = "overpaid";
84
+ PagarMeV5PaymentStatus["Aguardando pagamento"] = "waiting_payment";
85
+ PagarMeV5PaymentStatus["Pago"] = "paid";
86
+ PagarMeV5PaymentStatus["Aguardando estorno"] = "pending_refund";
87
+ PagarMeV5PaymentStatus["Autorizada pendente de captura"] = "authorized_pending_capture";
88
+ PagarMeV5PaymentStatus["N\u00E3o autorizada"] = "not_authorized";
89
+ PagarMeV5PaymentStatus["Capturada"] = "captured";
90
+ PagarMeV5PaymentStatus["Aguardando captura"] = "waiting_capture";
91
+ PagarMeV5PaymentStatus["Com erro"] = "with_error";
92
+ PagarMeV5PaymentStatus["Estornado"] = "refunded";
93
+ PagarMeV5PaymentStatus["Cancelado"] = "voided";
94
+ PagarMeV5PaymentStatus["Falha"] = "failed";
95
+ })(exports.PagarMeV5PaymentStatus || (exports.PagarMeV5PaymentStatus = {}));
96
+ exports.PagarMeV5OrderStatus = void 0;
97
+ (function (PagarMeV5OrderStatus) {
98
+ PagarMeV5OrderStatus["Pendente"] = "pending";
99
+ PagarMeV5OrderStatus["Pago"] = "paid";
100
+ PagarMeV5OrderStatus["Cancelado"] = "canceled";
101
+ PagarMeV5OrderStatus["Falha"] = "failed";
102
+ })(exports.PagarMeV5OrderStatus || (exports.PagarMeV5OrderStatus = {}));
103
+
76
104
  exports.PaymentMethods = void 0;
77
105
  (function (PaymentMethods) {
78
106
  PaymentMethods["CARD"] = "card";
@@ -88,6 +116,13 @@ exports.PaymentProviders = void 0;
88
116
  PaymentProviders["GLAMPOINTS"] = "glampoints";
89
117
  })(exports.PaymentProviders || (exports.PaymentProviders = {}));
90
118
 
119
+ exports.TransactionPaymentMethods = void 0;
120
+ (function (TransactionPaymentMethods) {
121
+ TransactionPaymentMethods["CARD"] = "credit_card";
122
+ TransactionPaymentMethods["BANKSLIP"] = "boleto";
123
+ TransactionPaymentMethods["PIX"] = "pix";
124
+ })(exports.TransactionPaymentMethods || (exports.TransactionPaymentMethods = {}));
125
+
91
126
  class BasePaymentMethodFactory {
92
127
  constructor(methods) {
93
128
  this.methods = methods;
@@ -1592,7 +1627,7 @@ exports.OrderStatus = void 0;
1592
1627
  OrderStatus["ENVIADO"] = "Enviado";
1593
1628
  OrderStatus["ENTREGUE"] = "Entregue";
1594
1629
  OrderStatus["CANCELADO"] = "Cancelado";
1595
- OrderStatus["CREDIT_CARD"] = "credit_card";
1630
+ OrderStatus["PENDENTE_REENVIO"] = "Pendente reenvio";
1596
1631
  })(exports.OrderStatus || (exports.OrderStatus = {}));
1597
1632
 
1598
1633
  class Order extends Checkout {
@@ -1779,15 +1814,17 @@ class AntifraudCardService {
1779
1814
  return true;
1780
1815
  }
1781
1816
  getTodayDateRange() {
1782
- const day = `${dateFns.format(new Date(), 'yyyy-MM-dd')}T00:00:00`;
1783
- const endOfDay = `${dateFns.format(new Date(), 'yyyy-MM-dd')}T23:59:59`;
1784
- return { day, endOfDay };
1817
+ const timeZone = 'America/Sao_Paulo';
1818
+ const today = dateFnsTz.utcToZonedTime(new Date(), timeZone);
1819
+ const day = dateFns.startOfDay(today);
1820
+ const endOfDay = dateFns.endOfDay(today);
1821
+ return { day: dateFns.addHours(day, 3), endOfDay: dateFns.addHours(endOfDay, 3) };
1785
1822
  }
1786
1823
  async getBlockedOrdersByMultipleCriteria(checkout, dateRange) {
1787
1824
  const { day, endOfDay } = dateRange;
1788
1825
  const dateFilter = [
1789
- { operator: exports.Where.GTE, value: new Date(day) },
1790
- { operator: exports.Where.LTE, value: new Date(endOfDay) },
1826
+ { operator: exports.Where.GTE, value: day },
1827
+ { operator: exports.Where.LTE, value: endOfDay },
1791
1828
  ];
1792
1829
  const [ordersBlockedWithCpf, ordersBlockedWithEmail, ordersBlockedWithCep, ordersBlockedWithPhone] = await Promise.all([
1793
1830
  this.getBlockedOrdersByCpf(checkout.user?.cpf, dateFilter),
@@ -4801,6 +4838,9 @@ class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFire
4801
4838
  isChild(_id, _parentId) {
4802
4839
  return;
4803
4840
  }
4841
+ async getBrandsWithProducts() {
4842
+ return;
4843
+ }
4804
4844
  }
4805
4845
  tslib.__decorate([
4806
4846
  Log(),
@@ -4891,6 +4931,9 @@ class ProductFirestoreRepository extends withCrudFirestore(withHelpers(withFires
4891
4931
  productVariantFullReport() {
4892
4932
  return;
4893
4933
  }
4934
+ getByEAN(EAN, options) {
4935
+ return;
4936
+ }
4894
4937
  }
4895
4938
  tslib.__decorate([
4896
4939
  Log(),
@@ -4916,6 +4959,9 @@ class ProductVariantFirestoreRepository extends withSubCollection(withCrudFirest
4916
4959
  });
4917
4960
  this.parentRepository = parentRepository;
4918
4961
  }
4962
+ getByEAN(EAN) {
4963
+ return;
4964
+ }
4919
4965
  }
4920
4966
 
4921
4967
  class SubscriptionProductFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
@@ -5805,6 +5851,9 @@ tslib.__decorate([
5805
5851
  tslib.__metadata("design:type", Product)
5806
5852
  ], KitProductHasuraGraphQL.prototype, "product", void 0);
5807
5853
 
5854
+ class ProductCatalogHasuraGraphQL extends Product {
5855
+ }
5856
+
5808
5857
  class ProductHasuraGraphQL extends Product {
5809
5858
  }
5810
5859
  tslib.__decorate([
@@ -6152,7 +6201,8 @@ class CategoryProductOperationsHelper {
6152
6201
  'isKit',
6153
6202
  'sku',
6154
6203
  'rate',
6155
- 'tags',
6204
+ 'tagsProfile',
6205
+ 'tagsCollection',
6156
6206
  'type',
6157
6207
  'shoppingCount',
6158
6208
  'gender',
@@ -6892,6 +6942,19 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
6892
6942
  categoryFilterRepository: this.categoryFilterRepository,
6893
6943
  });
6894
6944
  }
6945
+ async getBrandsWithProducts() {
6946
+ const fields = ['id', 'name', 'slug', 'brand_category', 'published', 'images'];
6947
+ const { brands_with_products_query: data, } = await this.query('brands_with_products_query', fields);
6948
+ return data.map((brand) => Category.toInstance({
6949
+ id: brand.id,
6950
+ name: brand.name,
6951
+ slug: brand.slug,
6952
+ brandCategory: brand.brand_category,
6953
+ shops: brand.shops,
6954
+ published: brand.published,
6955
+ images: brand.images,
6956
+ }));
6957
+ }
6895
6958
  }
6896
6959
  tslib.__decorate([
6897
6960
  Log(),
@@ -7156,83 +7219,7 @@ class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasu
7156
7219
  }
7157
7220
  }
7158
7221
 
7159
- class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7160
- constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7161
- super({
7162
- tableName: 'product_errors',
7163
- model: ProductErrorsHasuraGraphQL,
7164
- endpoint,
7165
- authOptions,
7166
- interceptors,
7167
- cache,
7168
- fields: [
7169
- {
7170
- productId: {
7171
- columnName: 'product_id',
7172
- to: (value) => +value,
7173
- from: (value) => value.toString(),
7174
- },
7175
- },
7176
- 'source',
7177
- 'error',
7178
- { createdAt: { columnName: 'created_at' } },
7179
- { updatedAt: { columnName: 'updated_at' } },
7180
- {
7181
- product: {
7182
- columnName: 'product',
7183
- foreignKeyColumn: { id: 'productId' },
7184
- fields: [
7185
- { id: { columnName: 'id', from: (value) => value.toString() } },
7186
- { productId: { columnName: 'main_product_id' } },
7187
- 'name',
7188
- 'published',
7189
- 'group',
7190
- 'validity',
7191
- { createdAt: { columnName: 'created_at' } },
7192
- { updatedAt: { columnName: 'updated_at' } },
7193
- ],
7194
- },
7195
- },
7196
- ],
7197
- });
7198
- this.productRepository = productRepository;
7199
- }
7200
- async get(params) {
7201
- const result = await super.get(params);
7202
- if (result instanceof VariantHasuraGraphQL) {
7203
- const product = await this.productRepository.get({ id: result.productId.toString() });
7204
- result.product.name = product.name;
7205
- result.product.group = product.group;
7206
- }
7207
- return result;
7208
- }
7209
- async find(params) {
7210
- const result = await super.find(params);
7211
- const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7212
- (lodash.isEmpty(item.product.name) || lodash.isEmpty(item.product.group) || lodash.isEmpty(item.product)));
7213
- if (variantsWithNoData.length > 0) {
7214
- const { data: products } = await this.productRepository.find({
7215
- filters: {
7216
- id: {
7217
- operator: exports.Where.IN,
7218
- value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7219
- },
7220
- },
7221
- });
7222
- products.forEach((product) => {
7223
- result.data
7224
- .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7225
- .forEach((variant) => {
7226
- variant.product.name = product.name;
7227
- variant.product.group = product.group;
7228
- });
7229
- });
7230
- }
7231
- return result;
7232
- }
7233
- }
7234
-
7235
- const commonFields = [
7222
+ const commonFields$1 = [
7236
7223
  {
7237
7224
  id: {
7238
7225
  columnName: 'id',
@@ -7312,6 +7299,12 @@ const commonFields = [
7312
7299
  to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7313
7300
  },
7314
7301
  },
7302
+ {
7303
+ imagesCard: {
7304
+ columnName: 'images_card',
7305
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7306
+ },
7307
+ },
7315
7308
  'name',
7316
7309
  {
7317
7310
  price: {
@@ -7373,7 +7366,6 @@ const commonFields = [
7373
7366
  'weight',
7374
7367
  'gender',
7375
7368
  { intGender: { columnName: 'int_gender' } },
7376
- { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
7377
7369
  { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7378
7370
  { isKit: { columnName: 'is_kit' } },
7379
7371
  { createdAt: { columnName: 'created_at' } },
@@ -7391,126 +7383,87 @@ const commonFields = [
7391
7383
  },
7392
7384
  'group',
7393
7385
  'validity',
7386
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7387
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7388
+ { daysOfUse: { columnName: 'days_of_use' } },
7389
+ { showVariants: { columnName: 'show_variants' } },
7390
+ { variantSlug: { columnName: 'variant_slug' } },
7394
7391
  ];
7395
- const fieldsConfiguration$2 = [
7396
- ...commonFields,
7397
- {
7398
- categories: {
7399
- columnName: 'categories',
7400
- fields: ['category_id'],
7401
- bindPersistData: (value) => ({
7402
- categories: { data: value.map((category) => ({ category_id: +category })) },
7403
- }),
7404
- to: (categories) => categories.map((categoryId) => +categoryId),
7405
- from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7406
- },
7407
- },
7408
- {
7409
- kitProducts: {
7410
- columnName: 'kit_products',
7411
- foreignKeyColumn: { productId: 'id' },
7412
- fields: [
7413
- { productId: { columnName: 'product_id' } },
7414
- { kitProductId: { columnName: 'kit_product_id' } },
7415
- 'quantity',
7416
- { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7417
- ],
7418
- },
7419
- },
7420
- {
7421
- reviews: {
7422
- columnName: 'reviews',
7423
- foreignKeyColumn: { product_id: 'id' },
7424
- fields: [
7425
- 'id',
7426
- 'shop',
7427
- 'rate',
7428
- 'author',
7429
- 'email',
7430
- 'location',
7431
- 'review',
7432
- 'status',
7433
- 'title',
7434
- { personId: { columnName: 'person_id' } },
7435
- 'points',
7436
- { orderId: { columnName: 'order_id' } },
7437
- { createdAt: { columnName: 'created_at' } },
7438
- { updatedAt: { columnName: 'updated_at' } },
7439
- ],
7440
- },
7441
- },
7442
- {
7443
- metadata: {
7444
- columnName: 'metadata',
7445
- fields: ['title', 'description'],
7446
- bindPersistData: (value) => ({
7447
- metadata: { data: value },
7448
- }),
7449
- },
7450
- },
7451
- ];
7452
- class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7453
- get reviewsFields() {
7454
- return [
7455
- 'id',
7456
- 'shop',
7457
- 'rate',
7458
- 'author',
7459
- 'email',
7460
- 'location',
7461
- 'review',
7462
- 'status',
7463
- 'title',
7464
- { personId: { columnName: 'person_id' } },
7465
- 'points',
7466
- { orderId: { columnName: 'order_id' } },
7467
- { createdAt: { columnName: 'created_at' } },
7468
- { updatedAt: { columnName: 'updated_at' } },
7469
- ];
7470
- }
7392
+ class ProductCatalogHasuraGraphQLRepository extends withFindHasuraGraphQL(withHasuraGraphQL(Base)) {
7471
7393
  constructor({ endpoint, authOptions, interceptors, cache, }) {
7472
7394
  super({
7473
- tableName: 'product',
7474
- model: ProductHasuraGraphQL,
7395
+ tableName: 'product_catalog',
7396
+ model: ProductCatalogHasuraGraphQL,
7475
7397
  endpoint,
7476
7398
  authOptions,
7477
7399
  interceptors,
7478
- fields: fieldsConfiguration$2,
7400
+ fields: commonFields$1,
7479
7401
  cache,
7480
7402
  });
7481
- this.bindReviewToModel = (plain) => ProductReview.toInstance({
7482
- ...is(lodash.omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id'])),
7483
- createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at,
7484
- updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at,
7485
- personId: plain.person_id,
7486
- orderId: plain.order_id,
7487
- });
7488
- this.bindReviewToHasura = (review) => ({
7489
- ...is(lodash.omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId'])),
7490
- person_id: review.personId,
7491
- order_id: review.orderId,
7492
- });
7493
7403
  }
7494
- async create(params) {
7495
- const { metadata, ...data } = params;
7496
- const product = await super.create(lodash.omit({ ...data, metadata: metadata || { description: null, title: null } }, ['reviews']));
7497
- try {
7498
- product.reviews = data.reviews && (await this.updateReviews(+product.id, data));
7404
+ async get({ id }, options) {
7405
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7406
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7407
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7408
+ if (cachedData) {
7409
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7410
+ return this.model.toInstance(deserialize(cachedData));
7411
+ }
7499
7412
  }
7500
- catch (error) {
7501
- await this.delete({ id: product.id });
7502
- throw error;
7413
+ const product = await super
7414
+ .find({
7415
+ filters: {
7416
+ id,
7417
+ },
7418
+ limits: {
7419
+ limit: 1,
7420
+ },
7421
+ })
7422
+ .then((res) => res.data.at(0));
7423
+ if (!product)
7424
+ throw new NotFoundError(`Product not found`);
7425
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7426
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7427
+ await this.cache.cacheAdapter.set({
7428
+ key: cacheKey,
7429
+ data: serialize(product),
7430
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7431
+ });
7432
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7503
7433
  }
7504
7434
  return product;
7505
7435
  }
7506
- async get(identifiers, options) {
7507
- const product = Number.isNaN(+identifiers.id)
7508
- ? (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
7509
- .data?.[0]
7510
- : await super.get(identifiers, options);
7511
- if (product.productId)
7512
- throw new NotFoundError('Product not found, it is a variant');
7513
- product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, options));
7436
+ async getByEAN(EAN, options) {
7437
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7438
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7439
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7440
+ if (cachedData) {
7441
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7442
+ return this.model.toInstance(deserialize(cachedData));
7443
+ }
7444
+ }
7445
+ const product = await super
7446
+ .find({
7447
+ filters: {
7448
+ EAN,
7449
+ },
7450
+ limits: {
7451
+ limit: 1,
7452
+ },
7453
+ })
7454
+ .then((res) => res.data.at(0));
7455
+ if (!product)
7456
+ return null;
7457
+ RoundProductPricesHelper.roundProductPrices(product);
7458
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7459
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7460
+ await this.cache.cacheAdapter.set({
7461
+ key: cacheKey,
7462
+ data: serialize(product),
7463
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7464
+ });
7465
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7466
+ }
7514
7467
  return product;
7515
7468
  }
7516
7469
  async find(params, optionsParams) {
@@ -7527,7 +7480,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7527
7480
  options.options?.maximum?.splice(options.options?.maximum.indexOf('price'), 1);
7528
7481
  return super.find({
7529
7482
  ...options,
7530
- filters: { ...filters, productId: { operator: exports.Where.ISNULL } },
7483
+ filters: { ...filters },
7531
7484
  fields: [
7532
7485
  ...bindFields,
7533
7486
  ...(bindFields.includes('price')
@@ -7540,18 +7493,614 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7540
7493
  ],
7541
7494
  }, optionsParams);
7542
7495
  }
7543
- async getBySlug(slug, options) {
7544
- if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7545
- const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
7546
- const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7547
- if (cachedData) {
7548
- this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7549
- return this.model.toInstance(deserialize(cachedData));
7550
- }
7551
- }
7496
+ async findCatalog(params, mainGender, options) {
7552
7497
  const result = await this.find({
7553
- filters: {
7498
+ ...params,
7499
+ filters: { ...params.filters, published: true },
7500
+ orderBy: {
7501
+ hasStock: 'desc',
7502
+ ...(!mainGender ? {} : { intGender: mainGender === 'female' ? 'desc' : 'asc' }),
7503
+ ...lodash.omit(params.orderBy, ['hasStock', 'intGender']),
7504
+ },
7505
+ }, options);
7506
+ return result;
7507
+ }
7508
+ }
7509
+ tslib.__decorate([
7510
+ Log(),
7511
+ tslib.__metadata("design:type", Function),
7512
+ tslib.__metadata("design:paramtypes", [Object, Object, Object]),
7513
+ tslib.__metadata("design:returntype", Promise)
7514
+ ], ProductCatalogHasuraGraphQLRepository.prototype, "findCatalog", null);
7515
+
7516
+ class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7517
+ constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7518
+ super({
7519
+ tableName: 'product_errors',
7520
+ model: ProductErrorsHasuraGraphQL,
7521
+ endpoint,
7522
+ authOptions,
7523
+ interceptors,
7524
+ cache,
7525
+ fields: [
7526
+ {
7527
+ productId: {
7528
+ columnName: 'product_id',
7529
+ to: (value) => +value,
7530
+ from: (value) => value.toString(),
7531
+ },
7532
+ },
7533
+ 'source',
7534
+ 'error',
7535
+ { createdAt: { columnName: 'created_at' } },
7536
+ { updatedAt: { columnName: 'updated_at' } },
7537
+ {
7538
+ product: {
7539
+ columnName: 'product',
7540
+ foreignKeyColumn: { id: 'productId' },
7541
+ fields: [
7542
+ { id: { columnName: 'id', from: (value) => value.toString() } },
7543
+ { productId: { columnName: 'main_product_id' } },
7544
+ 'name',
7545
+ 'published',
7546
+ 'group',
7547
+ 'validity',
7548
+ { createdAt: { columnName: 'created_at' } },
7549
+ { updatedAt: { columnName: 'updated_at' } },
7550
+ ],
7551
+ },
7552
+ },
7553
+ ],
7554
+ });
7555
+ this.productRepository = productRepository;
7556
+ }
7557
+ async get(params) {
7558
+ const result = await super.get(params);
7559
+ if (result instanceof VariantHasuraGraphQL) {
7560
+ const product = await this.productRepository.get({ id: result.productId.toString() });
7561
+ result.product.name = product.name;
7562
+ result.product.group = product.group;
7563
+ }
7564
+ return result;
7565
+ }
7566
+ async find(params) {
7567
+ const result = await super.find(params);
7568
+ const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7569
+ (lodash.isEmpty(item.product.name) || lodash.isEmpty(item.product.group) || lodash.isEmpty(item.product)));
7570
+ if (variantsWithNoData.length > 0) {
7571
+ const { data: products } = await this.productRepository.find({
7572
+ filters: {
7573
+ id: {
7574
+ operator: exports.Where.IN,
7575
+ value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7576
+ },
7577
+ },
7578
+ });
7579
+ products.forEach((product) => {
7580
+ result.data
7581
+ .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7582
+ .forEach((variant) => {
7583
+ variant.product.name = product.name;
7584
+ variant.product.group = product.group;
7585
+ });
7586
+ });
7587
+ }
7588
+ return result;
7589
+ }
7590
+ }
7591
+
7592
+ const commonFields = [
7593
+ {
7594
+ id: {
7595
+ columnName: 'id',
7596
+ to: (value) => +value,
7597
+ from: (value) => value.toString(),
7598
+ },
7599
+ },
7600
+ { firestoreId: { columnName: 'firestore_id' } },
7601
+ { productId: { columnName: 'main_product_id' } },
7602
+ { CEST: { columnName: 'cest' } },
7603
+ { EAN: { columnName: 'ean' } },
7604
+ { NCM: { columnName: 'ncm' } },
7605
+ 'brand',
7606
+ { costPrice: { columnName: 'cost_price' } },
7607
+ {
7608
+ description: {
7609
+ columnName: 'description',
7610
+ from: (description, data) => ({
7611
+ description,
7612
+ differentials: data.differentials,
7613
+ whoMustUse: data.who_must_use,
7614
+ howToUse: data.how_to_use,
7615
+ brand: data.brand_description,
7616
+ ingredients: data.ingredients,
7617
+ purpose: data.purpose,
7618
+ }),
7619
+ bindFindFilter: (filters) => {
7620
+ return {
7621
+ ...(filters?.description && { description: filters.description }),
7622
+ ...(filters.differentials && { differentials: filters.differentials }),
7623
+ ...(filters.whoMustUse && {
7624
+ who_must_use: filters.whoMustUse,
7625
+ }),
7626
+ ...(filters.howToUse && {
7627
+ how_to_use: filters.howToUse,
7628
+ }),
7629
+ ...(filters.brand && {
7630
+ brand_description: filters.brand,
7631
+ }),
7632
+ ...(filters.ingredients && {
7633
+ ingredients: filters.ingredients,
7634
+ }),
7635
+ ...(filters.purpose && {
7636
+ purpose: filters.purpose,
7637
+ }),
7638
+ };
7639
+ },
7640
+ bindPersistData: (descriptionData) => ({
7641
+ ...(descriptionData?.description && { description: descriptionData.description }),
7642
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
7643
+ ...(descriptionData.whoMustUse && {
7644
+ who_must_use: descriptionData.whoMustUse,
7645
+ }),
7646
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
7647
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
7648
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
7649
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
7650
+ }),
7651
+ },
7652
+ },
7653
+ { differentials: { columnName: 'differentials' } },
7654
+ { whoMustUse: { columnName: 'who_must_use' } },
7655
+ { howToUse: { columnName: 'how_to_use' } },
7656
+ { brandDescription: { columnName: 'brand_description' } },
7657
+ { ingredients: { columnName: 'ingredients' } },
7658
+ { purpose: { columnName: 'purpose' } },
7659
+ { hasVariants: { columnName: 'has_variants' } },
7660
+ {
7661
+ images: {
7662
+ columnName: 'images',
7663
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7664
+ },
7665
+ },
7666
+ {
7667
+ miniatures: {
7668
+ columnName: 'miniatures',
7669
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7670
+ },
7671
+ },
7672
+ {
7673
+ imagesCard: {
7674
+ columnName: 'images_card',
7675
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7676
+ },
7677
+ },
7678
+ 'name',
7679
+ {
7680
+ price: {
7681
+ columnName: 'price',
7682
+ from: (price, data) => ({
7683
+ price,
7684
+ fullPrice: data.full_price,
7685
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
7686
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
7687
+ subscriberPrice: data.subscriber_price,
7688
+ }),
7689
+ bindFindFilter: (filters) => {
7690
+ return {
7691
+ ...((filters?.price || filters?.price === 0) && { price: filters.price }),
7692
+ ...((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice }),
7693
+ ...((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
7694
+ subscriber_discount_percentage: filters.subscriberDiscountPercentage,
7695
+ }),
7696
+ ...((filters.subscriberPrice || filters.subscriberPrice === 0) && {
7697
+ subscriber_price: filters.subscriberPrice,
7698
+ }),
7699
+ ...((filters.fullPriceDiscountPercentage || filters.fullPriceDiscountPercentage === 0) && {
7700
+ full_price_discount_percentage: filters.fullPriceDiscountPercentage,
7701
+ }),
7702
+ };
7703
+ },
7704
+ bindPersistData: (priceData) => ({
7705
+ ...(priceData?.price >= 0 && { price: priceData.price }),
7706
+ ...(priceData.fullPrice >= 0 && { full_price: priceData.fullPrice }),
7707
+ ...(priceData.subscriberDiscountPercentage >= 0 && {
7708
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
7709
+ }),
7710
+ ...(priceData.subscriberPrice >= 0 && { subscriber_price: priceData.subscriberPrice }),
7711
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
7712
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
7713
+ }),
7714
+ }),
7715
+ },
7716
+ },
7717
+ { fullPrice: { columnName: 'full_price' } },
7718
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
7719
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
7720
+ { subscriberPrice: { columnName: 'subscriber_price' } },
7721
+ 'published',
7722
+ 'outlet',
7723
+ 'label',
7724
+ 'sku',
7725
+ {
7726
+ stock: {
7727
+ columnName: 'stock',
7728
+ from: (quantity) => ({ quantity }),
7729
+ to: (value) => (lodash.isNil(value?.quantity) ? value : value?.quantity),
7730
+ },
7731
+ },
7732
+ { hasStock: { columnName: 'has_stock' } },
7733
+ 'slug',
7734
+ 'type',
7735
+ 'video',
7736
+ 'weight',
7737
+ 'gender',
7738
+ { intGender: { columnName: 'int_gender' } },
7739
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7740
+ { isKit: { columnName: 'is_kit' } },
7741
+ { createdAt: { columnName: 'created_at' } },
7742
+ { updatedAt: { columnName: 'updated_at' } },
7743
+ { rate: { columnName: 'rating' } },
7744
+ { reviewsTotal: { columnName: 'reviews_total' } },
7745
+ { shoppingCount: { columnName: 'shopping_count' } },
7746
+ { categoryId: { columnName: 'category_id' } },
7747
+ {
7748
+ category: {
7749
+ columnName: 'category',
7750
+ foreignKeyColumn: { id: 'categoryId' },
7751
+ fields: ['id', 'name', 'reference', 'slug'],
7752
+ },
7753
+ },
7754
+ 'group',
7755
+ 'validity',
7756
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7757
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7758
+ { daysOfUse: { columnName: 'days_of_use' } },
7759
+ { showVariants: { columnName: 'show_variants' } },
7760
+ { variantSlug: { columnName: 'variant_slug' } },
7761
+ ];
7762
+ const fieldsConfiguration$2 = [
7763
+ ...commonFields,
7764
+ {
7765
+ categories: {
7766
+ columnName: 'categories',
7767
+ fields: ['category_id'],
7768
+ bindPersistData: (value) => ({
7769
+ categories: { data: value.map((category) => ({ category_id: +category })) },
7770
+ }),
7771
+ to: (categories) => categories.map((categoryId) => +categoryId),
7772
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7773
+ },
7774
+ },
7775
+ {
7776
+ kitProducts: {
7777
+ columnName: 'kit_products',
7778
+ foreignKeyColumn: { productId: 'id' },
7779
+ fields: [
7780
+ { productId: { columnName: 'product_id' } },
7781
+ { kitProductId: { columnName: 'kit_product_id' } },
7782
+ 'quantity',
7783
+ { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7784
+ ],
7785
+ },
7786
+ },
7787
+ {
7788
+ reviews: {
7789
+ columnName: 'reviews',
7790
+ foreignKeyColumn: { product_id: 'id' },
7791
+ fields: [
7792
+ 'id',
7793
+ 'shop',
7794
+ 'rate',
7795
+ 'author',
7796
+ 'email',
7797
+ 'location',
7798
+ 'review',
7799
+ 'status',
7800
+ 'title',
7801
+ { personId: { columnName: 'person_id' } },
7802
+ 'points',
7803
+ { orderId: { columnName: 'order_id' } },
7804
+ { createdAt: { columnName: 'created_at' } },
7805
+ { updatedAt: { columnName: 'updated_at' } },
7806
+ ],
7807
+ },
7808
+ },
7809
+ {
7810
+ metadata: {
7811
+ columnName: 'metadata',
7812
+ fields: ['title', 'description'],
7813
+ bindPersistData: (value) => ({
7814
+ metadata: { data: value },
7815
+ }),
7816
+ },
7817
+ },
7818
+ {
7819
+ variants: {
7820
+ columnName: 'variants',
7821
+ foreignKeyColumn: { product_id: 'id' },
7822
+ fields: [
7823
+ 'id',
7824
+ 'name',
7825
+ 'ean',
7826
+ 'sku',
7827
+ {
7828
+ description: {
7829
+ columnName: 'description',
7830
+ from: (description, data) => ({
7831
+ description,
7832
+ differentials: data.differentials,
7833
+ whoMustUse: data.who_must_use,
7834
+ howToUse: data.how_to_use,
7835
+ brand: data.brand_description,
7836
+ ingredients: data.ingredients,
7837
+ purpose: data.purpose,
7838
+ }),
7839
+ bindFindFilter: (filters) => {
7840
+ return {
7841
+ ...(filters?.description && { description: filters.description }),
7842
+ ...(filters.differentials && { differentials: filters.differentials }),
7843
+ ...(filters.whoMustUse && {
7844
+ who_must_use: filters.whoMustUse,
7845
+ }),
7846
+ ...(filters.howToUse && {
7847
+ how_to_use: filters.howToUse,
7848
+ }),
7849
+ ...(filters.brand && {
7850
+ brand_description: filters.brand,
7851
+ }),
7852
+ ...(filters.ingredients && {
7853
+ ingredients: filters.ingredients,
7854
+ }),
7855
+ ...(filters.purpose && {
7856
+ purpose: filters.purpose,
7857
+ }),
7858
+ };
7859
+ },
7860
+ bindPersistData: (descriptionData) => ({
7861
+ ...(descriptionData?.description && { description: descriptionData.description }),
7862
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
7863
+ ...(descriptionData.whoMustUse && {
7864
+ who_must_use: descriptionData.whoMustUse,
7865
+ }),
7866
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
7867
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
7868
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
7869
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
7870
+ }),
7871
+ },
7872
+ },
7873
+ { differentials: { columnName: 'differentials' } },
7874
+ { whoMustUse: { columnName: 'who_must_use' } },
7875
+ { howToUse: { columnName: 'how_to_use' } },
7876
+ { brandDescription: { columnName: 'brand_description' } },
7877
+ { ingredients: { columnName: 'ingredients' } },
7878
+ { purpose: { columnName: 'purpose' } },
7879
+ {
7880
+ grade: {
7881
+ columnName: 'grade',
7882
+ type: HasuraGraphQLColumnType.Jsonb,
7883
+ },
7884
+ },
7885
+ {
7886
+ price: {
7887
+ columnName: 'price',
7888
+ from: (price, data) => ({
7889
+ price,
7890
+ fullPrice: data.full_price,
7891
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
7892
+ subscriberPrice: data.subscriber_price,
7893
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
7894
+ }),
7895
+ bindFindFilter: (sentence) => {
7896
+ const filters = Object.values(sentence).shift();
7897
+ return {
7898
+ ...((filters?.price || filters?.price === 0) && { price: filters.price }),
7899
+ ...((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice }),
7900
+ ...((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
7901
+ subscriber_discount_percentage: filters.subscriberDiscountPercentage,
7902
+ }),
7903
+ ...((filters.subscriberPrice || filters.subscriberPrice === 0) && {
7904
+ subscriber_price: filters.subscriberPrice,
7905
+ }),
7906
+ ...((filters.fullPriceDiscountPercentage || filters.fullPriceDiscountPercentage === 0) && {
7907
+ full_price_discount_percentage: filters.fullPriceDiscountPercentage,
7908
+ }),
7909
+ };
7910
+ },
7911
+ bindPersistData: (priceData) => ({
7912
+ ...((priceData?.price || 0) >= 0 && { price: priceData.price }),
7913
+ ...((priceData?.fullPrice || 0) >= 0 && { full_price: priceData.fullPrice }),
7914
+ ...((priceData?.subscriberDiscountPercentage || 0) >= 0 && {
7915
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
7916
+ }),
7917
+ ...((priceData?.subscriberPrice || 0) >= 0 && { subscriber_price: priceData.subscriberPrice }),
7918
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
7919
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
7920
+ }),
7921
+ }),
7922
+ },
7923
+ },
7924
+ { fullPrice: { columnName: 'full_price' } },
7925
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
7926
+ { subscriberPrice: { columnName: 'subscriber_price' } },
7927
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
7928
+ 'published',
7929
+ {
7930
+ stock: {
7931
+ columnName: 'stock',
7932
+ from: (quantity) => ({ quantity }),
7933
+ to: (value) => (lodash.isNil(value?.quantity) ? value : value?.quantity),
7934
+ },
7935
+ },
7936
+ {
7937
+ images: {
7938
+ columnName: 'images',
7939
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7940
+ },
7941
+ },
7942
+ {
7943
+ miniatures: {
7944
+ columnName: 'miniatures',
7945
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7946
+ },
7947
+ },
7948
+ {
7949
+ imagesCard: {
7950
+ columnName: 'images_card',
7951
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7952
+ },
7953
+ },
7954
+ { tagsProfile: { columnName: 'tags_profile' } },
7955
+ { tagsCollection: { columnName: 'tags_collection' } },
7956
+ { variantSlug: { columnName: 'variant_slug' } },
7957
+ {
7958
+ reviews: {
7959
+ columnName: 'reviews',
7960
+ foreignKeyColumn: { product_id: 'id' },
7961
+ fields: [
7962
+ 'id',
7963
+ 'shop',
7964
+ 'rate',
7965
+ 'author',
7966
+ 'email',
7967
+ 'location',
7968
+ 'review',
7969
+ 'status',
7970
+ 'title',
7971
+ { personId: { columnName: 'person_id' } },
7972
+ 'points',
7973
+ { orderId: { columnName: 'order_id' } },
7974
+ { createdAt: { columnName: 'created_at' } },
7975
+ { updatedAt: { columnName: 'updated_at' } },
7976
+ ],
7977
+ },
7978
+ },
7979
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7980
+ {
7981
+ metadata: {
7982
+ columnName: 'metadata',
7983
+ fields: ['title', 'description'],
7984
+ bindPersistData: (value) => ({
7985
+ metadata: { data: value },
7986
+ }),
7987
+ },
7988
+ },
7989
+ ],
7990
+ },
7991
+ },
7992
+ ];
7993
+ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7994
+ get reviewsFields() {
7995
+ return [
7996
+ 'id',
7997
+ 'shop',
7998
+ 'rate',
7999
+ 'author',
8000
+ 'email',
8001
+ 'location',
8002
+ 'review',
8003
+ 'status',
8004
+ 'title',
8005
+ { personId: { columnName: 'person_id' } },
8006
+ 'points',
8007
+ { orderId: { columnName: 'order_id' } },
8008
+ { createdAt: { columnName: 'created_at' } },
8009
+ { updatedAt: { columnName: 'updated_at' } },
8010
+ ];
8011
+ }
8012
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
8013
+ super({
8014
+ tableName: 'product',
8015
+ model: ProductHasuraGraphQL,
8016
+ endpoint,
8017
+ authOptions,
8018
+ interceptors,
8019
+ fields: fieldsConfiguration$2,
8020
+ cache,
8021
+ });
8022
+ this.bindReviewToModel = (plain) => ProductReview.toInstance({
8023
+ ...is(lodash.omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id'])),
8024
+ createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at,
8025
+ updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at,
8026
+ personId: plain.person_id,
8027
+ orderId: plain.order_id,
8028
+ });
8029
+ this.bindReviewToHasura = (review) => ({
8030
+ ...is(lodash.omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId'])),
8031
+ person_id: review.personId,
8032
+ order_id: review.orderId,
8033
+ });
8034
+ }
8035
+ async create(params) {
8036
+ const { metadata, ...data } = params;
8037
+ const product = await super.create(lodash.omit({ ...data, metadata: metadata || { description: null, title: null } }, ['reviews']));
8038
+ try {
8039
+ product.reviews = data.reviews && (await this.updateReviews(+product.id, data));
8040
+ }
8041
+ catch (error) {
8042
+ await this.delete({ id: product.id });
8043
+ throw error;
8044
+ }
8045
+ return product;
8046
+ }
8047
+ async get(identifiers, options) {
8048
+ const product = Number.isNaN(+identifiers.id)
8049
+ ? (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
8050
+ .data?.[0]
8051
+ : await super.get(identifiers, options);
8052
+ if (product.productId)
8053
+ throw new NotFoundError('Product not found, it is a variant');
8054
+ product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, false, options));
8055
+ if (!product.variants?.length) {
8056
+ for (const [index, variant] of product.variants.entries()) {
8057
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8058
+ }
8059
+ }
8060
+ return product;
8061
+ }
8062
+ async find(params, optionsParams) {
8063
+ const { filters, fields, ...options } = params || {};
8064
+ const bindFields = fields ||
8065
+ this.fields
8066
+ .map((field) => (typeof field === 'string' ? field : Object.keys(field).shift()))
8067
+ .filter((field) => field !== 'reviews' && field !== 'categories');
8068
+ if (options.options?.minimal?.includes('price'))
8069
+ options.options?.minimal.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
8070
+ if (options.options?.maximum?.includes('price'))
8071
+ options.options?.maximum.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
8072
+ options.options?.minimal?.splice(options.options?.minimal.indexOf('price'), 1);
8073
+ options.options?.maximum?.splice(options.options?.maximum.indexOf('price'), 1);
8074
+ return super.find({
8075
+ ...options,
8076
+ filters: { ...filters, productId: { operator: exports.Where.ISNULL } },
8077
+ fields: [
8078
+ ...bindFields,
8079
+ ...(bindFields.includes('price')
8080
+ ? [
8081
+ 'subscriberPrice',
8082
+ 'subscriberDiscountPercentage',
8083
+ 'fullPrice',
8084
+ ]
8085
+ : []),
8086
+ ],
8087
+ }, optionsParams);
8088
+ }
8089
+ async getBySlug(slug, options) {
8090
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
8091
+ const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
8092
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
8093
+ if (cachedData) {
8094
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
8095
+ return this.model.toInstance(deserialize(cachedData));
8096
+ }
8097
+ }
8098
+ const result = await this.find({
8099
+ filters: {
7554
8100
  slug,
8101
+ productId: {
8102
+ operator: exports.Where.ISNULL,
8103
+ },
7555
8104
  },
7556
8105
  fields: this.fields.map((field) => typeof field === 'string' ? field : Object.keys(field).shift()),
7557
8106
  options: {
@@ -7561,6 +8110,11 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7561
8110
  if (!result.data.length)
7562
8111
  return null;
7563
8112
  const product = result?.data?.shift();
8113
+ if (!product.variants?.length) {
8114
+ for (const [index, variant] of product.variants.entries()) {
8115
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8116
+ }
8117
+ }
7564
8118
  RoundProductPricesHelper.roundProductPrices(product);
7565
8119
  if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7566
8120
  const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
@@ -7573,6 +8127,39 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7573
8127
  }
7574
8128
  return product;
7575
8129
  }
8130
+ async getByEAN(EAN, options) {
8131
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
8132
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
8133
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
8134
+ if (cachedData) {
8135
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
8136
+ return this.model.toInstance(deserialize(cachedData));
8137
+ }
8138
+ }
8139
+ const result = await this.find({
8140
+ filters: {
8141
+ EAN,
8142
+ },
8143
+ fields: this.fields.map((field) => typeof field === 'string' ? field : Object.keys(field).shift()),
8144
+ options: {
8145
+ enableCount: false,
8146
+ },
8147
+ });
8148
+ if (!result.data.length)
8149
+ return null;
8150
+ const product = result?.data?.shift();
8151
+ RoundProductPricesHelper.roundProductPrices(product);
8152
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
8153
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
8154
+ await this.cache.cacheAdapter.set({
8155
+ key: cacheKey,
8156
+ data: serialize(product),
8157
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
8158
+ });
8159
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
8160
+ }
8161
+ return product;
8162
+ }
7576
8163
  async update(params) {
7577
8164
  const { kitProducts, reviews, id: checkId, metadata, ...data } = lodash.omit(params, ['categories', 'rate']);
7578
8165
  const plainData = this.paramsToPlain({ id: checkId });
@@ -7707,7 +8294,8 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7707
8294
  const plainData = this.paramsToPlain({ metadata });
7708
8295
  if (!plainData.metadata)
7709
8296
  return null;
7710
- await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8297
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8298
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
7711
8299
  pk_columns: {
7712
8300
  value: { product_id: productId },
7713
8301
  type: 'product_metadata_pk_columns_input',
@@ -7719,6 +8307,14 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7719
8307
  required: true,
7720
8308
  },
7721
8309
  });
8310
+ if (!update_product_metadata_by_pk) {
8311
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8312
+ objects: {
8313
+ type: '[product_metadata_insert_input!]!',
8314
+ value: [{ product_id: productId, ...metadata }],
8315
+ },
8316
+ });
8317
+ }
7722
8318
  return plainData.metadata;
7723
8319
  }
7724
8320
  async getId(id) {
@@ -7729,7 +8325,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7729
8325
  return data?.[0]?.id;
7730
8326
  throw new NotFoundError(`Product with id ${id} not found`);
7731
8327
  }
7732
- async findReviewsByProduct(productId, options) {
8328
+ async findReviewsByProduct(productId, onlyApproved, options) {
7733
8329
  if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7734
8330
  const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
7735
8331
  const cachedData = await this.cache.cacheAdapter.get(cacheKey);
@@ -7742,10 +8338,16 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7742
8338
  where: {
7743
8339
  value: {
7744
8340
  product_id: { _eq: productId },
8341
+ ...(onlyApproved && { status: { _eq: true } }),
7745
8342
  },
7746
8343
  type: 'product_review_bool_exp',
7747
8344
  required: true,
7748
8345
  },
8346
+ order_by: {
8347
+ type: '[product_review_order_by]',
8348
+ value: [{ createdAt: 'desc' }],
8349
+ required: true,
8350
+ },
7749
8351
  });
7750
8352
  const reviews = data?.map((review) => this.bindReviewToModel(review));
7751
8353
  if (this.cache?.cacheAdapter && options?.cache?.enabled && reviews) {
@@ -7817,6 +8419,12 @@ tslib.__decorate([
7817
8419
  tslib.__metadata("design:paramtypes", [String, Object]),
7818
8420
  tslib.__metadata("design:returntype", Promise)
7819
8421
  ], ProductHasuraGraphQLRepository.prototype, "getBySlug", null);
8422
+ tslib.__decorate([
8423
+ Log(),
8424
+ tslib.__metadata("design:type", Function),
8425
+ tslib.__metadata("design:paramtypes", [String, Object]),
8426
+ tslib.__metadata("design:returntype", Promise)
8427
+ ], ProductHasuraGraphQLRepository.prototype, "getByEAN", null);
7820
8428
  tslib.__decorate([
7821
8429
  Log(),
7822
8430
  tslib.__metadata("design:type", Function),
@@ -7844,7 +8452,7 @@ tslib.__decorate([
7844
8452
  tslib.__decorate([
7845
8453
  Log(),
7846
8454
  tslib.__metadata("design:type", Function),
7847
- tslib.__metadata("design:paramtypes", [Number, Object]),
8455
+ tslib.__metadata("design:paramtypes", [Number, Boolean, Object]),
7848
8456
  tslib.__metadata("design:returntype", Promise)
7849
8457
  ], ProductHasuraGraphQLRepository.prototype, "findReviewsByProduct", null);
7850
8458
 
@@ -7872,6 +8480,13 @@ class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHas
7872
8480
  { orderId: { columnName: 'order_id' } },
7873
8481
  { createdAt: { columnName: 'created_at' } },
7874
8482
  { updatedAt: { columnName: 'updated_at' } },
8483
+ {
8484
+ product: {
8485
+ columnName: 'product',
8486
+ foreignKeyColumn: { id: 'productId' },
8487
+ fields: ['id', 'ean', 'sku', 'name', 'brand', 'slug', 'images', 'grade', 'gender'],
8488
+ },
8489
+ },
7875
8490
  ],
7876
8491
  cache,
7877
8492
  });
@@ -8063,8 +8678,135 @@ const fieldsConfiguration$1 = [
8063
8678
  },
8064
8679
  'group',
8065
8680
  'validity',
8066
- { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
8067
8681
  'published',
8682
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
8683
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
8684
+ { daysOfUse: { columnName: 'days_of_use' } },
8685
+ {
8686
+ images: {
8687
+ columnName: 'images',
8688
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8689
+ },
8690
+ },
8691
+ {
8692
+ miniatures: {
8693
+ columnName: 'miniatures',
8694
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8695
+ },
8696
+ },
8697
+ {
8698
+ imagesCard: {
8699
+ columnName: 'images_card',
8700
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8701
+ },
8702
+ },
8703
+ 'slug',
8704
+ 'brand',
8705
+ 'name',
8706
+ 'sku',
8707
+ { NCM: { columnName: 'ncm' } },
8708
+ { CEST: { columnName: 'cest' } },
8709
+ {
8710
+ description: {
8711
+ columnName: 'description',
8712
+ from: (description, data) => ({
8713
+ description,
8714
+ differentials: data.differentials,
8715
+ whoMustUse: data.who_must_use,
8716
+ howToUse: data.how_to_use,
8717
+ brand: data.brand_description,
8718
+ ingredients: data.ingredients,
8719
+ purpose: data.purpose,
8720
+ }),
8721
+ bindFindFilter: (filters) => {
8722
+ return {
8723
+ ...(filters?.description && { description: filters.description }),
8724
+ ...(filters.differentials && { differentials: filters.differentials }),
8725
+ ...(filters.whoMustUse && {
8726
+ who_must_use: filters.whoMustUse,
8727
+ }),
8728
+ ...(filters.howToUse && {
8729
+ how_to_use: filters.howToUse,
8730
+ }),
8731
+ ...(filters.brand && {
8732
+ brand_description: filters.brand,
8733
+ }),
8734
+ ...(filters.ingredients && {
8735
+ ingredients: filters.ingredients,
8736
+ }),
8737
+ ...(filters.purpose && {
8738
+ purpose: filters.purpose,
8739
+ }),
8740
+ };
8741
+ },
8742
+ bindPersistData: (descriptionData) => ({
8743
+ ...(descriptionData?.description && { description: descriptionData.description }),
8744
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
8745
+ ...(descriptionData.whoMustUse && {
8746
+ who_must_use: descriptionData.whoMustUse,
8747
+ }),
8748
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
8749
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
8750
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
8751
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
8752
+ }),
8753
+ },
8754
+ },
8755
+ { differentials: { columnName: 'differentials' } },
8756
+ { whoMustUse: { columnName: 'who_must_use' } },
8757
+ { howToUse: { columnName: 'how_to_use' } },
8758
+ { brandDescription: { columnName: 'brand_description' } },
8759
+ { ingredients: { columnName: 'ingredients' } },
8760
+ { purpose: { columnName: 'purpose' } },
8761
+ 'gender',
8762
+ { intGender: { columnName: 'int_gender' } },
8763
+ 'label',
8764
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
8765
+ { rate: { columnName: 'rating' } },
8766
+ { reviewsTotal: { columnName: 'reviews_total' } },
8767
+ { shoppingCount: { columnName: 'shopping_count' } },
8768
+ { categoryId: { columnName: 'category_id' } },
8769
+ {
8770
+ category: {
8771
+ columnName: 'category',
8772
+ foreignKeyColumn: { id: 'categoryId' },
8773
+ fields: ['id', 'name', 'reference', 'slug'],
8774
+ },
8775
+ },
8776
+ {
8777
+ metadata: {
8778
+ columnName: 'metadata',
8779
+ fields: ['title', 'description'],
8780
+ bindPersistData: (value) => ({
8781
+ metadata: { data: value },
8782
+ }),
8783
+ },
8784
+ },
8785
+ {
8786
+ reviews: {
8787
+ columnName: 'reviews',
8788
+ foreignKeyColumn: { product_id: 'id' },
8789
+ fields: [
8790
+ 'id',
8791
+ 'shop',
8792
+ 'rate',
8793
+ 'author',
8794
+ 'email',
8795
+ 'location',
8796
+ 'review',
8797
+ 'status',
8798
+ 'title',
8799
+ { personId: { columnName: 'person_id' } },
8800
+ 'points',
8801
+ { orderId: { columnName: 'order_id' } },
8802
+ { createdAt: { columnName: 'created_at' } },
8803
+ { updatedAt: { columnName: 'updated_at' } },
8804
+ ],
8805
+ },
8806
+ },
8807
+ { variantSlug: { columnName: 'variant_slug' } },
8808
+ { createdAt: { columnName: 'created_at' } },
8809
+ { updatedAt: { columnName: 'updated_at' } },
8068
8810
  ];
8069
8811
  class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8070
8812
  constructor({ endpoint, authOptions, interceptors, cache, }) {
@@ -8093,18 +8835,57 @@ class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
8093
8835
  const { filters, ...options } = params || {};
8094
8836
  return super.find({ ...options, filters: { productId: { operator: exports.Where.ISNOTNULL }, ...filters } });
8095
8837
  }
8838
+ async getByEAN(EAN) {
8839
+ const { data } = await this.find({
8840
+ filters: {
8841
+ EAN,
8842
+ },
8843
+ options: {
8844
+ enableCount: false,
8845
+ },
8846
+ });
8847
+ return data.at(0);
8848
+ }
8096
8849
  async update(params) {
8097
- const { productId, id: checkId, ...data } = params;
8850
+ const { productId, id: checkId, metadata, ...data } = params;
8098
8851
  const dataWithProductId = this.paramsToPlain({ id: checkId, productId });
8099
8852
  if (!dataWithProductId.id) {
8100
8853
  throw new NotFoundError('Variant ID is required for update');
8101
8854
  }
8102
8855
  const id = await this.getId(dataWithProductId.id);
8103
8856
  const product = await super.update({ id, ...data });
8857
+ product.metadata = metadata && (await this.updateMetadata(+id, { metadata }));
8104
8858
  if (dataWithProductId.productId) {
8105
8859
  product.productId = dataWithProductId.productId;
8106
8860
  }
8107
- return product;
8861
+ return product;
8862
+ }
8863
+ async updateMetadata(productId, { metadata }) {
8864
+ const plainData = this.paramsToPlain({ metadata });
8865
+ if (!plainData.metadata)
8866
+ return null;
8867
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8868
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8869
+ pk_columns: {
8870
+ value: { product_id: productId },
8871
+ type: 'product_metadata_pk_columns_input',
8872
+ required: true,
8873
+ },
8874
+ _set: {
8875
+ value: lodash.omit(metadata, ['product_id']),
8876
+ type: 'product_metadata_set_input',
8877
+ required: true,
8878
+ },
8879
+ });
8880
+ if (!update_product_metadata_by_pk) {
8881
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8882
+ objects: {
8883
+ type: '[product_metadata_insert_input!]!',
8884
+ value: [{ product_id: productId, ...metadata }],
8885
+ },
8886
+ });
8887
+ }
8888
+ return plainData.metadata;
8108
8889
  }
8109
8890
  async getId(id) {
8110
8891
  if (!Number.isNaN(+id))
@@ -8420,6 +9201,9 @@ class WishlistHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
8420
9201
  productId: +productId,
8421
9202
  });
8422
9203
  }
9204
+ async getBrandsWithProducts() {
9205
+ return;
9206
+ }
8423
9207
  }
8424
9208
  tslib.__decorate([
8425
9209
  Log(),
@@ -8586,6 +9370,201 @@ class PagarmePaymentOperationsHelper {
8586
9370
  }
8587
9371
  }
8588
9372
 
9373
+ class PagarMeV5RequestHelper {
9374
+ static build(checkout, method, card) {
9375
+ return {
9376
+ items: this.buildItems(checkout),
9377
+ customer: this.buildCustomer(checkout),
9378
+ shipping: this.buildShipping(checkout),
9379
+ payments: this.buildPayment(checkout, method, card),
9380
+ };
9381
+ }
9382
+ static buildItems(checkout) {
9383
+ return checkout.lineItems
9384
+ .filter((item) => !item.isGift)
9385
+ .map((item) => {
9386
+ return {
9387
+ amount: Math.floor(item.pricePaid * 100),
9388
+ description: item.name,
9389
+ quantity: item.quantity,
9390
+ code: item.EAN,
9391
+ };
9392
+ });
9393
+ }
9394
+ static buildCustomer(checkout) {
9395
+ return {
9396
+ name: checkout.user.displayName,
9397
+ email: checkout.user.email,
9398
+ type: 'individual',
9399
+ document: checkout.user.cpf,
9400
+ phones: {
9401
+ home_phone: {
9402
+ country_code: '55',
9403
+ number: checkout.user.phone.slice(2),
9404
+ area_code: checkout.user.phone.slice(0, 2),
9405
+ },
9406
+ mobile_phone: {
9407
+ country_code: '55',
9408
+ number: checkout.user.phone.slice(2),
9409
+ area_code: checkout.user.phone.slice(0, 2),
9410
+ },
9411
+ },
9412
+ address: {
9413
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
9414
+ line_2: `${checkout.billingAddress.extension}`,
9415
+ zip_code: checkout.shippingAddress.zip,
9416
+ city: checkout.billingAddress.city,
9417
+ state: checkout.billingAddress.state,
9418
+ country: 'BR',
9419
+ },
9420
+ };
9421
+ }
9422
+ static buildShipping(checkout) {
9423
+ return {
9424
+ amount: Math.floor(checkout.shipping.ShippingPrice * 100),
9425
+ description: `${checkout.shipping.ShippingCompanyName} - ${checkout.shipping.description}`,
9426
+ recipient_name: checkout.shippingAddress.recipient,
9427
+ recipient_phone: checkout.user.phone,
9428
+ address: {
9429
+ line_1: `${checkout.shippingAddress.number}, ${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9430
+ line_2: `${checkout.shippingAddress.extension}`,
9431
+ zip_code: checkout.shippingAddress.zip,
9432
+ city: checkout.shippingAddress.city,
9433
+ state: checkout.shippingAddress.state,
9434
+ country: 'BR',
9435
+ },
9436
+ };
9437
+ }
9438
+ static buildPayment(checkout, method, card) {
9439
+ return [
9440
+ {
9441
+ payment_method: method,
9442
+ amount: Math.floor(checkout.totalPrice * 100),
9443
+ ...(method === 'pix' && {
9444
+ pix: this.getPixOrder(),
9445
+ }),
9446
+ ...(method === 'boleto' && {
9447
+ boleto: this.getBoletoOrder(),
9448
+ }),
9449
+ ...(method === 'credit_card' && {
9450
+ credit_card: this.getCardOrder(checkout, card),
9451
+ }),
9452
+ },
9453
+ ];
9454
+ }
9455
+ static getPixOrder() {
9456
+ return {
9457
+ expires_at: dateFns.format(dateFns.addDays(new Date(), 1), 'yyyy-MM-dd'),
9458
+ };
9459
+ }
9460
+ static getBoletoOrder() {
9461
+ return {
9462
+ due_at: dateFns.format(dateFns.addDays(new Date(), 3), 'yyyy-MM-dd'),
9463
+ instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
9464
+ type: 'DM',
9465
+ document_number: new Date().getTime().toString(),
9466
+ };
9467
+ }
9468
+ static getCardOrder(checkout, card) {
9469
+ return {
9470
+ installments: card.installments,
9471
+ statement_descriptor: checkout.shop === exports.Shops.GLAMSHOP ? 'Glam' : 'Mens Market',
9472
+ card_id: card.cardId,
9473
+ card: {
9474
+ cvv: card.cardCvv,
9475
+ billing_address: {
9476
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
9477
+ zip_code: checkout.billingAddress.zip,
9478
+ city: checkout.billingAddress.city,
9479
+ state: checkout.billingAddress.state,
9480
+ country: 'BR',
9481
+ },
9482
+ },
9483
+ };
9484
+ }
9485
+ }
9486
+
9487
+ class PagarMeV5ResponseHelper {
9488
+ static build(method, checkout, response) {
9489
+ return Payment.toInstance({
9490
+ createdAt: new Date(),
9491
+ updatedAt: new Date(),
9492
+ userId: checkout.user.id,
9493
+ checkoutId: checkout.id,
9494
+ totalPrice: checkout.totalPrice,
9495
+ paymentProvider: exports.PaymentProviders.PAGARME,
9496
+ pagarMeOrderId: response.id,
9497
+ transaction: this.buildPaymentTransaction(method, response),
9498
+ });
9499
+ }
9500
+ static buildPaymentTransaction(method, response) {
9501
+ const charger = response.charges.at(0);
9502
+ const transaction = charger.last_transaction;
9503
+ return PaymentTransaction.toInstance({
9504
+ acquirer_name: 'pagar_me',
9505
+ amount: charger.amount,
9506
+ currency: charger.currency,
9507
+ gateway_id: charger.gateway_id,
9508
+ status: this.getPaymentStatus(transaction.status),
9509
+ payment_method: charger.payment_method,
9510
+ date_created: charger.created_at,
9511
+ date_updated: charger.updated_at,
9512
+ paid_amount: charger.paid_amount,
9513
+ paid_at: charger.paid_at,
9514
+ order_id: response.id,
9515
+ charger_id: charger.id,
9516
+ tid: charger.id,
9517
+ id: charger.id,
9518
+ ...(method == exports.TransactionPaymentMethods.BANKSLIP && this.getBoletoReponse(transaction)),
9519
+ ...(method == exports.TransactionPaymentMethods.PIX && this.getPixReponse(transaction)),
9520
+ ...(method == exports.TransactionPaymentMethods.CARD && this.getCardReponse(transaction)),
9521
+ });
9522
+ }
9523
+ static getPaymentStatus(status) {
9524
+ if (status == exports.PagarMeV5PaymentStatus.Gerado)
9525
+ return exports.PagarMeV5PaymentStatus['Aguardando pagamento'];
9526
+ if (status == exports.PagarMeV5PaymentStatus.Capturada)
9527
+ return exports.PagarMeV5PaymentStatus.Pago;
9528
+ return status;
9529
+ }
9530
+ static getBoletoReponse(transaction) {
9531
+ return {
9532
+ boleto_url: transaction.url?.toString(),
9533
+ boleto_barcode: transaction.line?.toString(),
9534
+ boleto_qr_code: transaction.qr_code?.toString(),
9535
+ boleto_expiration_date: transaction.due_at?.toString(),
9536
+ boleto_instructions: transaction.instructions?.toString(),
9537
+ boleto_nosso_numero: transaction.nosso_numero?.toString(),
9538
+ boleto_type: transaction.type?.toString(),
9539
+ boleto_document_number: transaction.document_number?.toString(),
9540
+ };
9541
+ }
9542
+ static getPixReponse(transaction) {
9543
+ return {
9544
+ pix_qr_code: transaction.qr_code?.toString(),
9545
+ pix_qr_code_url: transaction.qr_code_url?.toString(),
9546
+ pix_expiration_date: transaction.expires_at?.toString(),
9547
+ };
9548
+ }
9549
+ static getCardReponse(transaction) {
9550
+ return {
9551
+ soft_descriptor: transaction.statement_descriptor?.toString(),
9552
+ acquirer_name: transaction.acquirer_name?.toString(),
9553
+ acquirer_id: transaction.acquirer_tid?.toString(),
9554
+ acquirer_nsu: transaction.acquirer_nsu?.toString(),
9555
+ acquirer_auth_code: transaction.acquirer_auth_code?.toString(),
9556
+ acquirer_message: transaction.acquirer_message?.toString(),
9557
+ acquirer_return_code: transaction.acquirer_return_code?.toString(),
9558
+ installments: transaction.installments ?? null,
9559
+ card_holder_name: transaction.card?.holder_name?.toString(),
9560
+ card_last_digits: transaction.card?.last_four_digits?.toString(),
9561
+ card_first_digits: transaction.card?.first_six_digits?.toString(),
9562
+ card_brand: transaction.card?.brand?.toString(),
9563
+ card_id: transaction.card?.id?.toString(),
9564
+ };
9565
+ }
9566
+ }
9567
+
8589
9568
  class PagarmeCardAxiosAdapter {
8590
9569
  constructor(credentials, paymentRepository, orderBlockedRepository) {
8591
9570
  this.credentials = credentials;
@@ -8642,8 +9621,9 @@ class PagarmeCardAxiosAdapter {
8642
9621
  });
8643
9622
  }
8644
9623
  }
8645
- async createCardHash(bu) {
8646
- const key = bu === exports.BusinessUnitEnum.SHOP ? this.credentials.SHOP_API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
9624
+ async createCardHash(bu, shop) {
9625
+ const credentials = shop && shop == exports.Shops.MENSMARKET ? this.credentials[exports.Shops.MENSMARKET] : this.credentials[exports.Shops.GLAMSHOP];
9626
+ const key = bu === exports.BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
8647
9627
  try {
8648
9628
  const { data } = await axios__default["default"]({
8649
9629
  method: 'GET',
@@ -8806,6 +9786,281 @@ class PagarmePixAxiosAdapter {
8806
9786
  }
8807
9787
  }
8808
9788
 
9789
+ class PagarmeV5BankSlipAxiosAdapter {
9790
+ constructor(credentials, paymentRepository) {
9791
+ this.credentials = credentials;
9792
+ this.paymentRepository = paymentRepository;
9793
+ }
9794
+ async pay(checkout) {
9795
+ try {
9796
+ const payload = PagarMeV5RequestHelper.build(checkout, 'boleto');
9797
+ console.warn('[PAGARME BOLETO DATA TO SEND]', JSON.stringify(payload));
9798
+ const { data } = await axios__default["default"]({
9799
+ method: 'POST',
9800
+ url: `${this.credentials.URL}/orders`,
9801
+ headers: {
9802
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9803
+ 'Content-Type': 'application/json',
9804
+ },
9805
+ data: payload,
9806
+ });
9807
+ console.warn('[PAGARME RESPONSE BOLETO DATA]', JSON.stringify(data));
9808
+ if (data.status === exports.PagarMeV5OrderStatus.Falha ||
9809
+ data.charges.at(0).status === exports.PagarMeV5OrderStatus.Falha ||
9810
+ (data.charges.at(0).last_transaction.status !== exports.PagarMeV5PaymentStatus.Gerado &&
9811
+ data.charges.at(0).last_transaction.status !== exports.PagarMeV5PaymentStatus['Em processamento'])) {
9812
+ return Promise.reject(new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
9813
+ checkoutId: checkout.id,
9814
+ userEmail: checkout.user.email,
9815
+ info: data.charges.at(0).last_transaction?.gateway_response,
9816
+ }));
9817
+ }
9818
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(exports.TransactionPaymentMethods.BANKSLIP, checkout, data));
9819
+ return payment;
9820
+ }
9821
+ catch (error) {
9822
+ if (error instanceof axios.AxiosError) {
9823
+ console.error('error data: ', JSON.stringify(error.response?.data));
9824
+ }
9825
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
9826
+ checkoutId: checkout.id,
9827
+ userEmail: checkout.user.email,
9828
+ info: error.response?.data,
9829
+ });
9830
+ }
9831
+ }
9832
+ async getBoletoTransaction(paymentId) {
9833
+ try {
9834
+ const { data } = await axios__default["default"]({
9835
+ method: 'GET',
9836
+ url: `${this.credentials.URL}/charges/${paymentId}`,
9837
+ headers: {
9838
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9839
+ 'Content-Type': 'application/json',
9840
+ },
9841
+ });
9842
+ const payment = await this.paymentRepository.get({
9843
+ id: data.id,
9844
+ });
9845
+ return payment.transaction;
9846
+ }
9847
+ catch (error) {
9848
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
9849
+ paymentId,
9850
+ info: error.response.data,
9851
+ });
9852
+ }
9853
+ }
9854
+ }
9855
+
9856
+ class PagarmeV5CardAxiosAdapter {
9857
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
9858
+ this.credentials = credentials;
9859
+ this.paymentRepository = paymentRepository;
9860
+ this.orderBlockedRepository = orderBlockedRepository;
9861
+ }
9862
+ async pay(checkout, card) {
9863
+ try {
9864
+ const payload = PagarMeV5RequestHelper.build(checkout, 'credit_card', card);
9865
+ console.warn('[PAGARME CARD DATA TO SEND]', JSON.stringify(payload));
9866
+ const { data } = await axios__default["default"]({
9867
+ method: 'POST',
9868
+ url: `${this.credentials.URL}/orders`,
9869
+ headers: {
9870
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9871
+ 'Content-Type': 'application/json',
9872
+ },
9873
+ data: payload,
9874
+ });
9875
+ console.warn('[RESPONSE PAGARME CARD DATA]', JSON.stringify(data));
9876
+ if (data.status == exports.PagarMeV5OrderStatus.Falha ||
9877
+ data.charges.at(0).status !== exports.PagarMeV5OrderStatus.Pago ||
9878
+ data.charges.at(0).last_transaction.status !== exports.PagarMeV5PaymentStatus.Capturada) {
9879
+ await PagarmeBlockedOrderHelper.createBlockedOrderForUnauthorizedCard({
9880
+ checkout,
9881
+ card,
9882
+ orderBlockedRepository: this.orderBlockedRepository,
9883
+ });
9884
+ throw PagarmeBlockedOrderHelper.createPaymentError(checkout, data);
9885
+ }
9886
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(exports.TransactionPaymentMethods.CARD, checkout, data));
9887
+ return payment;
9888
+ }
9889
+ catch (error) {
9890
+ if (error instanceof PaymentError) {
9891
+ throw error;
9892
+ }
9893
+ if (error instanceof axios.AxiosError) {
9894
+ console.error('error data: ', JSON.stringify(error.response?.data));
9895
+ }
9896
+ throw PagarmeBlockedOrderHelper.createGenericPaymentError(checkout, error.response?.data);
9897
+ }
9898
+ }
9899
+ async addCard(card, customer) {
9900
+ try {
9901
+ const { id } = await this.createOrUpdateCustomer(customer);
9902
+ const { data } = await axios__default["default"]({
9903
+ method: 'POST',
9904
+ url: `${this.credentials.URL}/customers/${id}/cards`,
9905
+ headers: {
9906
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9907
+ 'Content-Type': 'application/json',
9908
+ },
9909
+ data: {
9910
+ number: card.number,
9911
+ holder_name: card.name,
9912
+ holder_document: card.cpf,
9913
+ exp_month: card.expirationDate.split('/').at(0),
9914
+ exp_year: card.expirationDate.split('/').at(1),
9915
+ cvv: card.cvv,
9916
+ billing_address: {
9917
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
9918
+ line_2: `${customer.billingAddress.extension}`,
9919
+ zip_code: customer.billingAddress.zip,
9920
+ city: customer.billingAddress.city,
9921
+ state: customer.billingAddress.state,
9922
+ country: 'BR',
9923
+ },
9924
+ },
9925
+ });
9926
+ return data;
9927
+ }
9928
+ catch (error) {
9929
+ console.warn(JSON.stringify(error));
9930
+ throw error;
9931
+ }
9932
+ }
9933
+ async createCardHash(bu, shop) {
9934
+ const credentials = shop && shop == exports.Shops.MENSMARKET ? this.credentials[exports.Shops.MENSMARKET] : this.credentials[exports.Shops.GLAMSHOP];
9935
+ const key = bu === exports.BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
9936
+ try {
9937
+ const { data } = await axios__default["default"]({
9938
+ method: 'GET',
9939
+ headers: {
9940
+ 'content-type': 'application/json',
9941
+ },
9942
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
9943
+ data: JSON.stringify({
9944
+ api_key: key,
9945
+ }),
9946
+ });
9947
+ return data;
9948
+ }
9949
+ catch (error) {
9950
+ throw new BusinessError('Houve uma falha gerar o hash', {
9951
+ info: error.response.data,
9952
+ });
9953
+ }
9954
+ }
9955
+ async getCardByToken(customerId, token) {
9956
+ try {
9957
+ const { data } = await axios__default["default"]({
9958
+ method: 'GET',
9959
+ url: `${this.credentials.URL}/cards/${token}`,
9960
+ data: {
9961
+ api_key: this.credentials.API_KEY,
9962
+ },
9963
+ });
9964
+ return data;
9965
+ }
9966
+ catch (error) {
9967
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + token, {
9968
+ info: error.response.data,
9969
+ });
9970
+ }
9971
+ }
9972
+ async createTransaction(info) {
9973
+ return info;
9974
+ }
9975
+ async createOrUpdateCustomer(customer) {
9976
+ try {
9977
+ const { data } = await axios__default["default"]({
9978
+ method: 'POST',
9979
+ url: `${this.credentials.URL}/customers`,
9980
+ headers: {
9981
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9982
+ 'Content-Type': 'application/json',
9983
+ },
9984
+ data: {
9985
+ name: customer.displayName,
9986
+ email: customer.email,
9987
+ document: customer.cpf,
9988
+ type: 'individual',
9989
+ document_type: 'CPF',
9990
+ address: {
9991
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
9992
+ line_2: `${customer.billingAddress.extension}`,
9993
+ zip_code: customer.billingAddress.zip,
9994
+ city: customer.billingAddress.city,
9995
+ state: customer.billingAddress.state,
9996
+ country: 'BR',
9997
+ },
9998
+ birthdate: dateFns.format(new Date(customer.birthday), 'MM/dd/yyyy'),
9999
+ phones: {
10000
+ home_phone: {
10001
+ country_code: '55',
10002
+ number: customer.phone.slice(2),
10003
+ area_code: customer.phone.slice(0, 2),
10004
+ },
10005
+ mobile_phone: {
10006
+ country_code: '55',
10007
+ number: customer.phone.slice(2),
10008
+ area_code: customer.phone.slice(0, 2),
10009
+ },
10010
+ },
10011
+ },
10012
+ });
10013
+ return data;
10014
+ }
10015
+ catch (error) {
10016
+ console.warn(error);
10017
+ throw error;
10018
+ }
10019
+ }
10020
+ }
10021
+
10022
+ class PagarmeV5PixAxiosAdapter {
10023
+ constructor(credentials, paymentRepository) {
10024
+ this.credentials = credentials;
10025
+ this.paymentRepository = paymentRepository;
10026
+ }
10027
+ async pay(checkout) {
10028
+ try {
10029
+ const payload = PagarMeV5RequestHelper.build(checkout, 'pix');
10030
+ console.warn('[PAGARME PIX DATA TO SEND]', JSON.stringify(payload));
10031
+ const { data } = await axios__default["default"]({
10032
+ method: 'POST',
10033
+ url: `${this.credentials.URL}/orders`,
10034
+ headers: {
10035
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10036
+ 'Content-Type': 'application/json',
10037
+ },
10038
+ data: payload,
10039
+ });
10040
+ console.warn('[RESPONSE PAGARME PIX DATA]', JSON.stringify(data));
10041
+ if (data.status == exports.PagarMeV5OrderStatus.Falha || data.status == exports.PagarMeV5OrderStatus.Cancelado) {
10042
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
10043
+ checkoutId: checkout.id,
10044
+ userEmail: checkout.user.email,
10045
+ info: data.charges.at(0).last_transaction?.gateway_response,
10046
+ });
10047
+ }
10048
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(exports.TransactionPaymentMethods.PIX, checkout, data));
10049
+ return payment;
10050
+ }
10051
+ catch (error) {
10052
+ if (error instanceof axios.AxiosError) {
10053
+ console.error('error data: ', JSON.stringify(error.response?.data));
10054
+ }
10055
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
10056
+ checkoutId: checkout.id,
10057
+ userEmail: checkout.user.email,
10058
+ info: error.response?.data,
10059
+ });
10060
+ }
10061
+ }
10062
+ }
10063
+
8809
10064
  class VertexAxiosAdapter {
8810
10065
  constructor(config) {
8811
10066
  this.config = config;
@@ -9007,6 +10262,10 @@ Object.defineProperty(exports, 'subDays', {
9007
10262
  enumerable: true,
9008
10263
  get: function () { return dateFns.subDays; }
9009
10264
  });
10265
+ Object.defineProperty(exports, 'formatInTimeZone', {
10266
+ enumerable: true,
10267
+ get: function () { return dateFnsTz.formatInTimeZone; }
10268
+ });
9010
10269
  Object.defineProperty(exports, 'chunk', {
9011
10270
  enumerable: true,
9012
10271
  get: function () { return lodash.chunk; }
@@ -9162,12 +10421,17 @@ exports.PagarmeBankSlipAxiosAdapter = PagarmeBankSlipAxiosAdapter;
9162
10421
  exports.PagarmeCardAxiosAdapter = PagarmeCardAxiosAdapter;
9163
10422
  exports.PagarmePaymentMethodFactory = PagarmePaymentMethodFactory;
9164
10423
  exports.PagarmePixAxiosAdapter = PagarmePixAxiosAdapter;
10424
+ exports.PagarmeV5BankSlipAxiosAdapter = PagarmeV5BankSlipAxiosAdapter;
10425
+ exports.PagarmeV5CardAxiosAdapter = PagarmeV5CardAxiosAdapter;
10426
+ exports.PagarmeV5PixAxiosAdapter = PagarmeV5PixAxiosAdapter;
9165
10427
  exports.Payment = Payment;
9166
10428
  exports.PaymentError = PaymentError;
9167
10429
  exports.PaymentFirestoreRepository = PaymentFirestoreRepository;
9168
10430
  exports.PaymentProviderFactory = PaymentProviderFactory;
9169
10431
  exports.PaymentTransaction = PaymentTransaction;
9170
10432
  exports.Product = Product;
10433
+ exports.ProductCatalogHasuraGraphQL = ProductCatalogHasuraGraphQL;
10434
+ exports.ProductCatalogHasuraGraphQLRepository = ProductCatalogHasuraGraphQLRepository;
9171
10435
  exports.ProductErrors = ProductErrors;
9172
10436
  exports.ProductErrorsHasuraGraphQL = ProductErrorsHasuraGraphQL;
9173
10437
  exports.ProductErrorsHasuraGraphQLRepository = ProductErrorsHasuraGraphQLRepository;