@infrab4a/connect 5.3.0-beta.1 → 5.3.0-beta.11

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 +1490 -208
  2. package/index.esm.js +1484 -210
  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-review.d.ts +2 -0
  6. package/src/domain/catalog/models/product.d.ts +1 -0
  7. package/src/domain/catalog/models/types/brands-shop-menu.type.d.ts +13 -0
  8. package/src/domain/catalog/models/types/index.d.ts +1 -0
  9. package/src/domain/catalog/repositories/category.repository.d.ts +1 -0
  10. package/src/domain/catalog/repositories/index.d.ts +1 -0
  11. package/src/domain/catalog/repositories/product-catalog.repository.d.ts +17 -0
  12. package/src/domain/catalog/repositories/product.repository.d.ts +3 -0
  13. package/src/domain/catalog/repositories/variant.repository.d.ts +1 -0
  14. package/src/domain/shopping/enums/index.d.ts +2 -0
  15. package/src/domain/shopping/enums/pagarme-v5-payment-status.enum.d.ts +24 -0
  16. package/src/domain/shopping/enums/transaction-payment-methods.enum.d.ts +5 -0
  17. package/src/domain/shopping/interfaces/payment-provider-card.interface.d.ts +10 -2
  18. package/src/domain/shopping/models/order.d.ts +7 -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;
@@ -795,6 +830,10 @@ class ProductReview extends BaseModel {
795
830
  return ['id'];
796
831
  }
797
832
  }
833
+ tslib.__decorate([
834
+ classTransformer.Type(() => Product),
835
+ tslib.__metadata("design:type", Array)
836
+ ], ProductReview.prototype, "product", void 0);
798
837
 
799
838
  class ProductBase extends BaseModel {
800
839
  get evaluation() {
@@ -1779,15 +1818,17 @@ class AntifraudCardService {
1779
1818
  return true;
1780
1819
  }
1781
1820
  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 };
1821
+ const timeZone = 'America/Sao_Paulo';
1822
+ const today = dateFnsTz.utcToZonedTime(new Date(), timeZone);
1823
+ const day = dateFns.startOfDay(today);
1824
+ const endOfDay = dateFns.endOfDay(today);
1825
+ return { day: dateFns.addHours(day, 3), endOfDay: dateFns.addHours(endOfDay, 3) };
1785
1826
  }
1786
1827
  async getBlockedOrdersByMultipleCriteria(checkout, dateRange) {
1787
1828
  const { day, endOfDay } = dateRange;
1788
1829
  const dateFilter = [
1789
- { operator: exports.Where.GTE, value: new Date(day) },
1790
- { operator: exports.Where.LTE, value: new Date(endOfDay) },
1830
+ { operator: exports.Where.GTE, value: day },
1831
+ { operator: exports.Where.LTE, value: endOfDay },
1791
1832
  ];
1792
1833
  const [ordersBlockedWithCpf, ordersBlockedWithEmail, ordersBlockedWithCep, ordersBlockedWithPhone] = await Promise.all([
1793
1834
  this.getBlockedOrdersByCpf(checkout.user?.cpf, dateFilter),
@@ -4801,6 +4842,9 @@ class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFire
4801
4842
  isChild(_id, _parentId) {
4802
4843
  return;
4803
4844
  }
4845
+ async getBrandsWithProducts() {
4846
+ return;
4847
+ }
4804
4848
  }
4805
4849
  tslib.__decorate([
4806
4850
  Log(),
@@ -4891,6 +4935,9 @@ class ProductFirestoreRepository extends withCrudFirestore(withHelpers(withFires
4891
4935
  productVariantFullReport() {
4892
4936
  return;
4893
4937
  }
4938
+ getByEAN(EAN, options) {
4939
+ return;
4940
+ }
4894
4941
  }
4895
4942
  tslib.__decorate([
4896
4943
  Log(),
@@ -4916,6 +4963,9 @@ class ProductVariantFirestoreRepository extends withSubCollection(withCrudFirest
4916
4963
  });
4917
4964
  this.parentRepository = parentRepository;
4918
4965
  }
4966
+ getByEAN(EAN) {
4967
+ return;
4968
+ }
4919
4969
  }
4920
4970
 
4921
4971
  class SubscriptionProductFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
@@ -5805,6 +5855,9 @@ tslib.__decorate([
5805
5855
  tslib.__metadata("design:type", Product)
5806
5856
  ], KitProductHasuraGraphQL.prototype, "product", void 0);
5807
5857
 
5858
+ class ProductCatalogHasuraGraphQL extends Product {
5859
+ }
5860
+
5808
5861
  class ProductHasuraGraphQL extends Product {
5809
5862
  }
5810
5863
  tslib.__decorate([
@@ -6152,7 +6205,8 @@ class CategoryProductOperationsHelper {
6152
6205
  'isKit',
6153
6206
  'sku',
6154
6207
  'rate',
6155
- 'tags',
6208
+ 'tagsProfile',
6209
+ 'tagsCollection',
6156
6210
  'type',
6157
6211
  'shoppingCount',
6158
6212
  'gender',
@@ -6892,6 +6946,19 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
6892
6946
  categoryFilterRepository: this.categoryFilterRepository,
6893
6947
  });
6894
6948
  }
6949
+ async getBrandsWithProducts() {
6950
+ const fields = ['id', 'name', 'slug', 'brand_category', 'published', 'images'];
6951
+ const { brands_with_products_query: data, } = await this.query('brands_with_products_query', fields);
6952
+ return data.map((brand) => Category.toInstance({
6953
+ id: brand.id,
6954
+ name: brand.name,
6955
+ slug: brand.slug,
6956
+ brandCategory: brand.brand_category,
6957
+ shops: brand.shops,
6958
+ published: brand.published,
6959
+ images: brand.images,
6960
+ }));
6961
+ }
6895
6962
  }
6896
6963
  tslib.__decorate([
6897
6964
  Log(),
@@ -7156,83 +7223,7 @@ class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasu
7156
7223
  }
7157
7224
  }
7158
7225
 
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 = [
7226
+ const commonFields$1 = [
7236
7227
  {
7237
7228
  id: {
7238
7229
  columnName: 'id',
@@ -7312,6 +7303,12 @@ const commonFields = [
7312
7303
  to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7313
7304
  },
7314
7305
  },
7306
+ {
7307
+ imagesCard: {
7308
+ columnName: 'images_card',
7309
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7310
+ },
7311
+ },
7315
7312
  'name',
7316
7313
  {
7317
7314
  price: {
@@ -7373,7 +7370,6 @@ const commonFields = [
7373
7370
  'weight',
7374
7371
  'gender',
7375
7372
  { intGender: { columnName: 'int_gender' } },
7376
- { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
7377
7373
  { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7378
7374
  { isKit: { columnName: 'is_kit' } },
7379
7375
  { createdAt: { columnName: 'created_at' } },
@@ -7391,126 +7387,87 @@ const commonFields = [
7391
7387
  },
7392
7388
  'group',
7393
7389
  'validity',
7390
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7391
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7392
+ { daysOfUse: { columnName: 'days_of_use' } },
7393
+ { showVariants: { columnName: 'show_variants' } },
7394
+ { variantSlug: { columnName: 'variant_slug' } },
7394
7395
  ];
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
- }
7396
+ class ProductCatalogHasuraGraphQLRepository extends withFindHasuraGraphQL(withHasuraGraphQL(Base)) {
7471
7397
  constructor({ endpoint, authOptions, interceptors, cache, }) {
7472
7398
  super({
7473
- tableName: 'product',
7474
- model: ProductHasuraGraphQL,
7399
+ tableName: 'product_catalog',
7400
+ model: ProductCatalogHasuraGraphQL,
7475
7401
  endpoint,
7476
7402
  authOptions,
7477
7403
  interceptors,
7478
- fields: fieldsConfiguration$2,
7404
+ fields: commonFields$1,
7479
7405
  cache,
7480
7406
  });
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
7407
  }
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));
7408
+ async get({ id }, options) {
7409
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7410
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7411
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7412
+ if (cachedData) {
7413
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7414
+ return this.model.toInstance(deserialize(cachedData));
7415
+ }
7499
7416
  }
7500
- catch (error) {
7501
- await this.delete({ id: product.id });
7502
- throw error;
7417
+ const product = await super
7418
+ .find({
7419
+ filters: {
7420
+ id,
7421
+ },
7422
+ limits: {
7423
+ limit: 1,
7424
+ },
7425
+ })
7426
+ .then((res) => res.data.at(0));
7427
+ if (!product)
7428
+ throw new NotFoundError(`Product not found`);
7429
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7430
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7431
+ await this.cache.cacheAdapter.set({
7432
+ key: cacheKey,
7433
+ data: serialize(product),
7434
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7435
+ });
7436
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7503
7437
  }
7504
7438
  return product;
7505
7439
  }
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));
7440
+ async getByEAN(EAN, options) {
7441
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7442
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7443
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7444
+ if (cachedData) {
7445
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7446
+ return this.model.toInstance(deserialize(cachedData));
7447
+ }
7448
+ }
7449
+ const product = await super
7450
+ .find({
7451
+ filters: {
7452
+ EAN,
7453
+ },
7454
+ limits: {
7455
+ limit: 1,
7456
+ },
7457
+ })
7458
+ .then((res) => res.data.at(0));
7459
+ if (!product)
7460
+ return null;
7461
+ RoundProductPricesHelper.roundProductPrices(product);
7462
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7463
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7464
+ await this.cache.cacheAdapter.set({
7465
+ key: cacheKey,
7466
+ data: serialize(product),
7467
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7468
+ });
7469
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7470
+ }
7514
7471
  return product;
7515
7472
  }
7516
7473
  async find(params, optionsParams) {
@@ -7527,7 +7484,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7527
7484
  options.options?.maximum?.splice(options.options?.maximum.indexOf('price'), 1);
7528
7485
  return super.find({
7529
7486
  ...options,
7530
- filters: { ...filters, productId: { operator: exports.Where.ISNULL } },
7487
+ filters: { ...filters },
7531
7488
  fields: [
7532
7489
  ...bindFields,
7533
7490
  ...(bindFields.includes('price')
@@ -7540,18 +7497,598 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7540
7497
  ],
7541
7498
  }, optionsParams);
7542
7499
  }
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
- }
7500
+ async findCatalog(params, mainGender, options) {
7501
+ const result = await this.find({
7502
+ ...params,
7503
+ filters: { ...params.filters, published: true },
7504
+ orderBy: {
7505
+ hasStock: 'desc',
7506
+ ...(!mainGender ? {} : { intGender: mainGender === 'female' ? 'desc' : 'asc' }),
7507
+ ...lodash.omit(params.orderBy, ['hasStock', 'intGender']),
7508
+ },
7509
+ }, options);
7510
+ return result;
7511
+ }
7512
+ }
7513
+ tslib.__decorate([
7514
+ Log(),
7515
+ tslib.__metadata("design:type", Function),
7516
+ tslib.__metadata("design:paramtypes", [Object, Object, Object]),
7517
+ tslib.__metadata("design:returntype", Promise)
7518
+ ], ProductCatalogHasuraGraphQLRepository.prototype, "findCatalog", null);
7519
+
7520
+ class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7521
+ constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7522
+ super({
7523
+ tableName: 'product_errors',
7524
+ model: ProductErrorsHasuraGraphQL,
7525
+ endpoint,
7526
+ authOptions,
7527
+ interceptors,
7528
+ cache,
7529
+ fields: [
7530
+ {
7531
+ productId: {
7532
+ columnName: 'product_id',
7533
+ to: (value) => +value,
7534
+ from: (value) => value.toString(),
7535
+ },
7536
+ },
7537
+ 'source',
7538
+ 'error',
7539
+ { createdAt: { columnName: 'created_at' } },
7540
+ { updatedAt: { columnName: 'updated_at' } },
7541
+ {
7542
+ product: {
7543
+ columnName: 'product',
7544
+ foreignKeyColumn: { id: 'productId' },
7545
+ fields: [
7546
+ { id: { columnName: 'id', from: (value) => value.toString() } },
7547
+ { productId: { columnName: 'main_product_id' } },
7548
+ 'name',
7549
+ 'published',
7550
+ 'group',
7551
+ 'validity',
7552
+ { createdAt: { columnName: 'created_at' } },
7553
+ { updatedAt: { columnName: 'updated_at' } },
7554
+ ],
7555
+ },
7556
+ },
7557
+ ],
7558
+ });
7559
+ this.productRepository = productRepository;
7560
+ }
7561
+ async get(params) {
7562
+ const result = await super.get(params);
7563
+ if (result instanceof VariantHasuraGraphQL) {
7564
+ const product = await this.productRepository.get({ id: result.productId.toString() });
7565
+ result.product.name = product.name;
7566
+ result.product.group = product.group;
7567
+ }
7568
+ return result;
7569
+ }
7570
+ async find(params) {
7571
+ const result = await super.find(params);
7572
+ const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7573
+ (lodash.isEmpty(item.product.name) || lodash.isEmpty(item.product.group) || lodash.isEmpty(item.product)));
7574
+ if (variantsWithNoData.length > 0) {
7575
+ const { data: products } = await this.productRepository.find({
7576
+ filters: {
7577
+ id: {
7578
+ operator: exports.Where.IN,
7579
+ value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7580
+ },
7581
+ },
7582
+ });
7583
+ products.forEach((product) => {
7584
+ result.data
7585
+ .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7586
+ .forEach((variant) => {
7587
+ variant.product.name = product.name;
7588
+ variant.product.group = product.group;
7589
+ });
7590
+ });
7591
+ }
7592
+ return result;
7593
+ }
7594
+ }
7595
+
7596
+ const commonFields = [
7597
+ {
7598
+ id: {
7599
+ columnName: 'id',
7600
+ to: (value) => +value,
7601
+ from: (value) => value.toString(),
7602
+ },
7603
+ },
7604
+ { firestoreId: { columnName: 'firestore_id' } },
7605
+ { productId: { columnName: 'main_product_id' } },
7606
+ { CEST: { columnName: 'cest' } },
7607
+ { EAN: { columnName: 'ean' } },
7608
+ { NCM: { columnName: 'ncm' } },
7609
+ 'brand',
7610
+ { costPrice: { columnName: 'cost_price' } },
7611
+ {
7612
+ description: {
7613
+ columnName: 'description',
7614
+ from: (description, data) => ({
7615
+ description,
7616
+ differentials: data.differentials,
7617
+ whoMustUse: data.who_must_use,
7618
+ howToUse: data.how_to_use,
7619
+ brand: data.brand_description,
7620
+ ingredients: data.ingredients,
7621
+ purpose: data.purpose,
7622
+ }),
7623
+ bindFindFilter: (filters) => {
7624
+ return {
7625
+ ...(filters?.description && { description: filters.description }),
7626
+ ...(filters.differentials && { differentials: filters.differentials }),
7627
+ ...(filters.whoMustUse && {
7628
+ who_must_use: filters.whoMustUse,
7629
+ }),
7630
+ ...(filters.howToUse && {
7631
+ how_to_use: filters.howToUse,
7632
+ }),
7633
+ ...(filters.brand && {
7634
+ brand_description: filters.brand,
7635
+ }),
7636
+ ...(filters.ingredients && {
7637
+ ingredients: filters.ingredients,
7638
+ }),
7639
+ ...(filters.purpose && {
7640
+ purpose: filters.purpose,
7641
+ }),
7642
+ };
7643
+ },
7644
+ bindPersistData: (descriptionData) => ({
7645
+ ...(descriptionData?.description && { description: descriptionData.description }),
7646
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
7647
+ ...(descriptionData.whoMustUse && {
7648
+ who_must_use: descriptionData.whoMustUse,
7649
+ }),
7650
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
7651
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
7652
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
7653
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
7654
+ }),
7655
+ },
7656
+ },
7657
+ { differentials: { columnName: 'differentials' } },
7658
+ { whoMustUse: { columnName: 'who_must_use' } },
7659
+ { howToUse: { columnName: 'how_to_use' } },
7660
+ { brandDescription: { columnName: 'brand_description' } },
7661
+ { ingredients: { columnName: 'ingredients' } },
7662
+ { purpose: { columnName: 'purpose' } },
7663
+ { hasVariants: { columnName: 'has_variants' } },
7664
+ {
7665
+ images: {
7666
+ columnName: 'images',
7667
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7668
+ },
7669
+ },
7670
+ {
7671
+ miniatures: {
7672
+ columnName: 'miniatures',
7673
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7674
+ },
7675
+ },
7676
+ {
7677
+ imagesCard: {
7678
+ columnName: 'images_card',
7679
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7680
+ },
7681
+ },
7682
+ 'name',
7683
+ {
7684
+ price: {
7685
+ columnName: 'price',
7686
+ from: (price, data) => ({
7687
+ price,
7688
+ fullPrice: data.full_price,
7689
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
7690
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
7691
+ subscriberPrice: data.subscriber_price,
7692
+ }),
7693
+ bindFindFilter: (filters) => {
7694
+ return {
7695
+ ...((filters?.price || filters?.price === 0) && { price: filters.price }),
7696
+ ...((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice }),
7697
+ ...((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
7698
+ subscriber_discount_percentage: filters.subscriberDiscountPercentage,
7699
+ }),
7700
+ ...((filters.subscriberPrice || filters.subscriberPrice === 0) && {
7701
+ subscriber_price: filters.subscriberPrice,
7702
+ }),
7703
+ ...((filters.fullPriceDiscountPercentage || filters.fullPriceDiscountPercentage === 0) && {
7704
+ full_price_discount_percentage: filters.fullPriceDiscountPercentage,
7705
+ }),
7706
+ };
7707
+ },
7708
+ bindPersistData: (priceData) => ({
7709
+ ...(priceData?.price >= 0 && { price: priceData.price }),
7710
+ ...(priceData.fullPrice >= 0 && { full_price: priceData.fullPrice }),
7711
+ ...(priceData.subscriberDiscountPercentage >= 0 && {
7712
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
7713
+ }),
7714
+ ...(priceData.subscriberPrice >= 0 && { subscriber_price: priceData.subscriberPrice }),
7715
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
7716
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
7717
+ }),
7718
+ }),
7719
+ },
7720
+ },
7721
+ { fullPrice: { columnName: 'full_price' } },
7722
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
7723
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
7724
+ { subscriberPrice: { columnName: 'subscriber_price' } },
7725
+ 'published',
7726
+ 'outlet',
7727
+ 'label',
7728
+ 'sku',
7729
+ {
7730
+ stock: {
7731
+ columnName: 'stock',
7732
+ from: (quantity) => ({ quantity }),
7733
+ to: (value) => (lodash.isNil(value?.quantity) ? value : value?.quantity),
7734
+ },
7735
+ },
7736
+ { hasStock: { columnName: 'has_stock' } },
7737
+ 'slug',
7738
+ 'type',
7739
+ 'video',
7740
+ 'weight',
7741
+ 'gender',
7742
+ { intGender: { columnName: 'int_gender' } },
7743
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7744
+ { isKit: { columnName: 'is_kit' } },
7745
+ { createdAt: { columnName: 'created_at' } },
7746
+ { updatedAt: { columnName: 'updated_at' } },
7747
+ { rate: { columnName: 'rating' } },
7748
+ { reviewsTotal: { columnName: 'reviews_total' } },
7749
+ { shoppingCount: { columnName: 'shopping_count' } },
7750
+ { categoryId: { columnName: 'category_id' } },
7751
+ {
7752
+ category: {
7753
+ columnName: 'category',
7754
+ foreignKeyColumn: { id: 'categoryId' },
7755
+ fields: ['id', 'name', 'reference', 'slug'],
7756
+ },
7757
+ },
7758
+ 'group',
7759
+ 'validity',
7760
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7761
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7762
+ { daysOfUse: { columnName: 'days_of_use' } },
7763
+ { showVariants: { columnName: 'show_variants' } },
7764
+ { variantSlug: { columnName: 'variant_slug' } },
7765
+ ];
7766
+ const fieldsConfiguration$2 = [
7767
+ ...commonFields,
7768
+ {
7769
+ categories: {
7770
+ columnName: 'categories',
7771
+ fields: ['category_id'],
7772
+ bindPersistData: (value) => ({
7773
+ categories: { data: value.map((category) => ({ category_id: +category })) },
7774
+ }),
7775
+ to: (categories) => categories.map((categoryId) => +categoryId),
7776
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7777
+ },
7778
+ },
7779
+ {
7780
+ kitProducts: {
7781
+ columnName: 'kit_products',
7782
+ foreignKeyColumn: { productId: 'id' },
7783
+ fields: [
7784
+ { productId: { columnName: 'product_id' } },
7785
+ { kitProductId: { columnName: 'kit_product_id' } },
7786
+ 'quantity',
7787
+ { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7788
+ ],
7789
+ },
7790
+ },
7791
+ {
7792
+ reviews: {
7793
+ columnName: 'reviews',
7794
+ foreignKeyColumn: { product_id: 'id' },
7795
+ fields: [
7796
+ 'id',
7797
+ 'shop',
7798
+ 'rate',
7799
+ 'author',
7800
+ 'email',
7801
+ 'location',
7802
+ 'review',
7803
+ 'status',
7804
+ 'title',
7805
+ { personId: { columnName: 'person_id' } },
7806
+ 'points',
7807
+ { orderId: { columnName: 'order_id' } },
7808
+ { createdAt: { columnName: 'created_at' } },
7809
+ { updatedAt: { columnName: 'updated_at' } },
7810
+ ],
7811
+ },
7812
+ },
7813
+ {
7814
+ metadata: {
7815
+ columnName: 'metadata',
7816
+ fields: ['title', 'description'],
7817
+ bindPersistData: (value) => ({
7818
+ metadata: { data: value },
7819
+ }),
7820
+ },
7821
+ },
7822
+ {
7823
+ variants: {
7824
+ columnName: 'variants',
7825
+ foreignKeyColumn: { product_id: 'id' },
7826
+ fields: [
7827
+ 'id',
7828
+ 'name',
7829
+ 'ean',
7830
+ 'sku',
7831
+ {
7832
+ description: {
7833
+ columnName: 'description',
7834
+ from: (description, data) => ({
7835
+ description,
7836
+ differentials: data.differentials,
7837
+ whoMustUse: data.who_must_use,
7838
+ howToUse: data.how_to_use,
7839
+ brand: data.brand_description,
7840
+ ingredients: data.ingredients,
7841
+ purpose: data.purpose,
7842
+ }),
7843
+ bindFindFilter: (filters) => {
7844
+ return {
7845
+ ...(filters?.description && { description: filters.description }),
7846
+ ...(filters.differentials && { differentials: filters.differentials }),
7847
+ ...(filters.whoMustUse && {
7848
+ who_must_use: filters.whoMustUse,
7849
+ }),
7850
+ ...(filters.howToUse && {
7851
+ how_to_use: filters.howToUse,
7852
+ }),
7853
+ ...(filters.brand && {
7854
+ brand_description: filters.brand,
7855
+ }),
7856
+ ...(filters.ingredients && {
7857
+ ingredients: filters.ingredients,
7858
+ }),
7859
+ ...(filters.purpose && {
7860
+ purpose: filters.purpose,
7861
+ }),
7862
+ };
7863
+ },
7864
+ bindPersistData: (descriptionData) => ({
7865
+ ...(descriptionData?.description && { description: descriptionData.description }),
7866
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
7867
+ ...(descriptionData.whoMustUse && {
7868
+ who_must_use: descriptionData.whoMustUse,
7869
+ }),
7870
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
7871
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
7872
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
7873
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
7874
+ }),
7875
+ },
7876
+ },
7877
+ { differentials: { columnName: 'differentials' } },
7878
+ { whoMustUse: { columnName: 'who_must_use' } },
7879
+ { howToUse: { columnName: 'how_to_use' } },
7880
+ { brandDescription: { columnName: 'brand_description' } },
7881
+ { ingredients: { columnName: 'ingredients' } },
7882
+ { purpose: { columnName: 'purpose' } },
7883
+ {
7884
+ grade: {
7885
+ columnName: 'grade',
7886
+ type: HasuraGraphQLColumnType.Jsonb,
7887
+ },
7888
+ },
7889
+ {
7890
+ price: {
7891
+ columnName: 'price',
7892
+ from: (price, data) => ({
7893
+ price,
7894
+ fullPrice: data.full_price,
7895
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
7896
+ subscriberPrice: data.subscriber_price,
7897
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
7898
+ }),
7899
+ bindPersistData: (priceData) => ({
7900
+ ...((priceData?.price || 0) >= 0 && { price: priceData.price }),
7901
+ ...((priceData?.fullPrice || 0) >= 0 && { full_price: priceData.fullPrice }),
7902
+ ...((priceData?.subscriberDiscountPercentage || 0) >= 0 && {
7903
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
7904
+ }),
7905
+ ...((priceData?.subscriberPrice || 0) >= 0 && { subscriber_price: priceData.subscriberPrice }),
7906
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
7907
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
7908
+ }),
7909
+ }),
7910
+ },
7911
+ },
7912
+ { fullPrice: { columnName: 'full_price' } },
7913
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
7914
+ { subscriberPrice: { columnName: 'subscriber_price' } },
7915
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
7916
+ 'published',
7917
+ {
7918
+ stock: {
7919
+ columnName: 'stock',
7920
+ from: (quantity) => ({ quantity }),
7921
+ to: (value) => (lodash.isNil(value?.quantity) ? value : value?.quantity),
7922
+ },
7923
+ },
7924
+ {
7925
+ images: {
7926
+ columnName: 'images',
7927
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7928
+ },
7929
+ },
7930
+ {
7931
+ miniatures: {
7932
+ columnName: 'miniatures',
7933
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7934
+ },
7935
+ },
7936
+ {
7937
+ imagesCard: {
7938
+ columnName: 'images_card',
7939
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7940
+ },
7941
+ },
7942
+ { tagsProfile: { columnName: 'tags_profile' } },
7943
+ { tagsCollection: { columnName: 'tags_collection' } },
7944
+ { variantSlug: { columnName: 'variant_slug' } },
7945
+ {
7946
+ reviews: {
7947
+ columnName: 'reviews',
7948
+ foreignKeyColumn: { product_id: 'id' },
7949
+ fields: [
7950
+ 'id',
7951
+ 'shop',
7952
+ 'rate',
7953
+ 'author',
7954
+ 'email',
7955
+ 'location',
7956
+ 'review',
7957
+ 'status',
7958
+ 'title',
7959
+ { personId: { columnName: 'person_id' } },
7960
+ 'points',
7961
+ { orderId: { columnName: 'order_id' } },
7962
+ { createdAt: { columnName: 'created_at' } },
7963
+ { updatedAt: { columnName: 'updated_at' } },
7964
+ ],
7965
+ },
7966
+ },
7967
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7968
+ {
7969
+ metadata: {
7970
+ columnName: 'metadata',
7971
+ fields: ['title', 'description'],
7972
+ bindPersistData: (value) => ({
7973
+ metadata: { data: value },
7974
+ }),
7975
+ },
7976
+ },
7977
+ ],
7978
+ },
7979
+ },
7980
+ ];
7981
+ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7982
+ get reviewsFields() {
7983
+ return [
7984
+ 'id',
7985
+ 'shop',
7986
+ 'rate',
7987
+ 'author',
7988
+ 'email',
7989
+ 'location',
7990
+ 'review',
7991
+ 'status',
7992
+ 'title',
7993
+ { personId: { columnName: 'person_id' } },
7994
+ 'points',
7995
+ { orderId: { columnName: 'order_id' } },
7996
+ { createdAt: { columnName: 'created_at' } },
7997
+ { updatedAt: { columnName: 'updated_at' } },
7998
+ ];
7999
+ }
8000
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
8001
+ super({
8002
+ tableName: 'product',
8003
+ model: ProductHasuraGraphQL,
8004
+ endpoint,
8005
+ authOptions,
8006
+ interceptors,
8007
+ fields: fieldsConfiguration$2,
8008
+ cache,
8009
+ });
8010
+ this.bindReviewToModel = (plain) => ProductReview.toInstance({
8011
+ ...is(lodash.omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id'])),
8012
+ createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at,
8013
+ updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at,
8014
+ personId: plain.person_id,
8015
+ orderId: plain.order_id,
8016
+ });
8017
+ this.bindReviewToHasura = (review) => ({
8018
+ ...is(lodash.omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId'])),
8019
+ person_id: review.personId,
8020
+ order_id: review.orderId,
8021
+ });
8022
+ }
8023
+ async create(params) {
8024
+ const { metadata, ...data } = params;
8025
+ const product = await super.create(lodash.omit({ ...data, metadata: metadata || { description: null, title: null } }, ['reviews']));
8026
+ try {
8027
+ product.reviews = data.reviews && (await this.updateReviews(+product.id, data));
8028
+ }
8029
+ catch (error) {
8030
+ await this.delete({ id: product.id });
8031
+ throw error;
8032
+ }
8033
+ return product;
8034
+ }
8035
+ async get(identifiers, options) {
8036
+ const product = Number.isNaN(+identifiers.id)
8037
+ ? (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
8038
+ .data?.[0]
8039
+ : await super.get(identifiers, options);
8040
+ if (product.productId)
8041
+ throw new NotFoundError('Product not found, it is a variant');
8042
+ product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, false, options));
8043
+ if (!product.variants?.length) {
8044
+ for (const [index, variant] of product.variants.entries()) {
8045
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8046
+ }
8047
+ }
8048
+ return product;
8049
+ }
8050
+ async find(params, optionsParams) {
8051
+ const { filters, fields, ...options } = params || {};
8052
+ const bindFields = fields ||
8053
+ this.fields
8054
+ .map((field) => (typeof field === 'string' ? field : Object.keys(field).shift()))
8055
+ .filter((field) => field !== 'reviews' && field !== 'categories');
8056
+ if (options.options?.minimal?.includes('price'))
8057
+ options.options?.minimal.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
8058
+ if (options.options?.maximum?.includes('price'))
8059
+ options.options?.maximum.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
8060
+ options.options?.minimal?.splice(options.options?.minimal.indexOf('price'), 1);
8061
+ options.options?.maximum?.splice(options.options?.maximum.indexOf('price'), 1);
8062
+ return super.find({
8063
+ ...options,
8064
+ filters: { ...filters, productId: { operator: exports.Where.ISNULL } },
8065
+ fields: [
8066
+ ...bindFields,
8067
+ ...(bindFields.includes('price')
8068
+ ? [
8069
+ 'subscriberPrice',
8070
+ 'subscriberDiscountPercentage',
8071
+ 'fullPrice',
8072
+ ]
8073
+ : []),
8074
+ ],
8075
+ }, optionsParams);
8076
+ }
8077
+ async getBySlug(slug, options) {
8078
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
8079
+ const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
8080
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
8081
+ if (cachedData) {
8082
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
8083
+ return this.model.toInstance(deserialize(cachedData));
8084
+ }
7551
8085
  }
7552
8086
  const result = await this.find({
7553
8087
  filters: {
7554
8088
  slug,
8089
+ productId: {
8090
+ operator: exports.Where.ISNULL,
8091
+ },
7555
8092
  },
7556
8093
  fields: this.fields.map((field) => typeof field === 'string' ? field : Object.keys(field).shift()),
7557
8094
  options: {
@@ -7561,6 +8098,11 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7561
8098
  if (!result.data.length)
7562
8099
  return null;
7563
8100
  const product = result?.data?.shift();
8101
+ if (!product.variants?.length) {
8102
+ for (const [index, variant] of product.variants.entries()) {
8103
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8104
+ }
8105
+ }
7564
8106
  RoundProductPricesHelper.roundProductPrices(product);
7565
8107
  if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7566
8108
  const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
@@ -7573,6 +8115,39 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7573
8115
  }
7574
8116
  return product;
7575
8117
  }
8118
+ async getByEAN(EAN, options) {
8119
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
8120
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
8121
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
8122
+ if (cachedData) {
8123
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
8124
+ return this.model.toInstance(deserialize(cachedData));
8125
+ }
8126
+ }
8127
+ const result = await this.find({
8128
+ filters: {
8129
+ EAN,
8130
+ },
8131
+ fields: this.fields.map((field) => typeof field === 'string' ? field : Object.keys(field).shift()),
8132
+ options: {
8133
+ enableCount: false,
8134
+ },
8135
+ });
8136
+ if (!result.data.length)
8137
+ return null;
8138
+ const product = result?.data?.shift();
8139
+ RoundProductPricesHelper.roundProductPrices(product);
8140
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
8141
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
8142
+ await this.cache.cacheAdapter.set({
8143
+ key: cacheKey,
8144
+ data: serialize(product),
8145
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
8146
+ });
8147
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
8148
+ }
8149
+ return product;
8150
+ }
7576
8151
  async update(params) {
7577
8152
  const { kitProducts, reviews, id: checkId, metadata, ...data } = lodash.omit(params, ['categories', 'rate']);
7578
8153
  const plainData = this.paramsToPlain({ id: checkId });
@@ -7707,7 +8282,8 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7707
8282
  const plainData = this.paramsToPlain({ metadata });
7708
8283
  if (!plainData.metadata)
7709
8284
  return null;
7710
- await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8285
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8286
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
7711
8287
  pk_columns: {
7712
8288
  value: { product_id: productId },
7713
8289
  type: 'product_metadata_pk_columns_input',
@@ -7719,6 +8295,14 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7719
8295
  required: true,
7720
8296
  },
7721
8297
  });
8298
+ if (!update_product_metadata_by_pk) {
8299
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8300
+ objects: {
8301
+ type: '[product_metadata_insert_input!]!',
8302
+ value: [{ product_id: productId, ...metadata }],
8303
+ },
8304
+ });
8305
+ }
7722
8306
  return plainData.metadata;
7723
8307
  }
7724
8308
  async getId(id) {
@@ -7729,7 +8313,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7729
8313
  return data?.[0]?.id;
7730
8314
  throw new NotFoundError(`Product with id ${id} not found`);
7731
8315
  }
7732
- async findReviewsByProduct(productId, options) {
8316
+ async findReviewsByProduct(productId, onlyApproved, options) {
7733
8317
  if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7734
8318
  const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
7735
8319
  const cachedData = await this.cache.cacheAdapter.get(cacheKey);
@@ -7742,10 +8326,16 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7742
8326
  where: {
7743
8327
  value: {
7744
8328
  product_id: { _eq: productId },
8329
+ ...(onlyApproved && { status: { _eq: true } }),
7745
8330
  },
7746
8331
  type: 'product_review_bool_exp',
7747
8332
  required: true,
7748
8333
  },
8334
+ order_by: {
8335
+ type: '[product_review_order_by]',
8336
+ value: [{ createdAt: 'desc' }],
8337
+ required: true,
8338
+ },
7749
8339
  });
7750
8340
  const reviews = data?.map((review) => this.bindReviewToModel(review));
7751
8341
  if (this.cache?.cacheAdapter && options?.cache?.enabled && reviews) {
@@ -7817,6 +8407,12 @@ tslib.__decorate([
7817
8407
  tslib.__metadata("design:paramtypes", [String, Object]),
7818
8408
  tslib.__metadata("design:returntype", Promise)
7819
8409
  ], ProductHasuraGraphQLRepository.prototype, "getBySlug", null);
8410
+ tslib.__decorate([
8411
+ Log(),
8412
+ tslib.__metadata("design:type", Function),
8413
+ tslib.__metadata("design:paramtypes", [String, Object]),
8414
+ tslib.__metadata("design:returntype", Promise)
8415
+ ], ProductHasuraGraphQLRepository.prototype, "getByEAN", null);
7820
8416
  tslib.__decorate([
7821
8417
  Log(),
7822
8418
  tslib.__metadata("design:type", Function),
@@ -7844,7 +8440,7 @@ tslib.__decorate([
7844
8440
  tslib.__decorate([
7845
8441
  Log(),
7846
8442
  tslib.__metadata("design:type", Function),
7847
- tslib.__metadata("design:paramtypes", [Number, Object]),
8443
+ tslib.__metadata("design:paramtypes", [Number, Boolean, Object]),
7848
8444
  tslib.__metadata("design:returntype", Promise)
7849
8445
  ], ProductHasuraGraphQLRepository.prototype, "findReviewsByProduct", null);
7850
8446
 
@@ -7872,6 +8468,31 @@ class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHas
7872
8468
  { orderId: { columnName: 'order_id' } },
7873
8469
  { createdAt: { columnName: 'created_at' } },
7874
8470
  { updatedAt: { columnName: 'updated_at' } },
8471
+ {
8472
+ product: {
8473
+ columnName: 'product',
8474
+ foreignKeyColumn: { id: 'productId' },
8475
+ fields: [
8476
+ 'id',
8477
+ {
8478
+ productId: {
8479
+ columnName: 'main_product_id',
8480
+ to: (value) => +value,
8481
+ from: (value) => value?.toString(),
8482
+ },
8483
+ },
8484
+ 'ean',
8485
+ 'sku',
8486
+ 'name',
8487
+ 'brand',
8488
+ 'slug',
8489
+ 'images',
8490
+ 'grade',
8491
+ 'gender',
8492
+ '',
8493
+ ],
8494
+ },
8495
+ },
7875
8496
  ],
7876
8497
  cache,
7877
8498
  });
@@ -8062,9 +8683,148 @@ const fieldsConfiguration$1 = [
8062
8683
  },
8063
8684
  },
8064
8685
  'group',
8686
+ 'type',
8065
8687
  'validity',
8066
- { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
8067
8688
  'published',
8689
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
8690
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
8691
+ { daysOfUse: { columnName: 'days_of_use' } },
8692
+ {
8693
+ images: {
8694
+ columnName: 'images',
8695
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8696
+ },
8697
+ },
8698
+ {
8699
+ miniatures: {
8700
+ columnName: 'miniatures',
8701
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8702
+ },
8703
+ },
8704
+ {
8705
+ imagesCard: {
8706
+ columnName: 'images_card',
8707
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8708
+ },
8709
+ },
8710
+ 'slug',
8711
+ 'brand',
8712
+ 'name',
8713
+ 'sku',
8714
+ { NCM: { columnName: 'ncm' } },
8715
+ { CEST: { columnName: 'cest' } },
8716
+ {
8717
+ description: {
8718
+ columnName: 'description',
8719
+ from: (description, data) => ({
8720
+ description,
8721
+ differentials: data.differentials,
8722
+ whoMustUse: data.who_must_use,
8723
+ howToUse: data.how_to_use,
8724
+ brand: data.brand_description,
8725
+ ingredients: data.ingredients,
8726
+ purpose: data.purpose,
8727
+ }),
8728
+ bindFindFilter: (filters) => {
8729
+ return {
8730
+ ...(filters?.description && { description: filters.description }),
8731
+ ...(filters.differentials && { differentials: filters.differentials }),
8732
+ ...(filters.whoMustUse && {
8733
+ who_must_use: filters.whoMustUse,
8734
+ }),
8735
+ ...(filters.howToUse && {
8736
+ how_to_use: filters.howToUse,
8737
+ }),
8738
+ ...(filters.brand && {
8739
+ brand_description: filters.brand,
8740
+ }),
8741
+ ...(filters.ingredients && {
8742
+ ingredients: filters.ingredients,
8743
+ }),
8744
+ ...(filters.purpose && {
8745
+ purpose: filters.purpose,
8746
+ }),
8747
+ };
8748
+ },
8749
+ bindPersistData: (descriptionData) => ({
8750
+ ...(descriptionData?.description && { description: descriptionData.description }),
8751
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
8752
+ ...(descriptionData.whoMustUse && {
8753
+ who_must_use: descriptionData.whoMustUse,
8754
+ }),
8755
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
8756
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
8757
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
8758
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
8759
+ }),
8760
+ },
8761
+ },
8762
+ { differentials: { columnName: 'differentials' } },
8763
+ { whoMustUse: { columnName: 'who_must_use' } },
8764
+ { howToUse: { columnName: 'how_to_use' } },
8765
+ { brandDescription: { columnName: 'brand_description' } },
8766
+ { ingredients: { columnName: 'ingredients' } },
8767
+ { purpose: { columnName: 'purpose' } },
8768
+ 'gender',
8769
+ { intGender: { columnName: 'int_gender' } },
8770
+ 'label',
8771
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
8772
+ { rate: { columnName: 'rating' } },
8773
+ { reviewsTotal: { columnName: 'reviews_total' } },
8774
+ { shoppingCount: { columnName: 'shopping_count' } },
8775
+ { categoryId: { columnName: 'category_id' } },
8776
+ {
8777
+ category: {
8778
+ columnName: 'category',
8779
+ foreignKeyColumn: { id: 'categoryId' },
8780
+ fields: ['id', 'name', 'reference', 'slug'],
8781
+ },
8782
+ },
8783
+ {
8784
+ categories: {
8785
+ columnName: 'categories',
8786
+ fields: ['category_id'],
8787
+ bindPersistData: (value) => ({
8788
+ categories: { data: value.map((category) => ({ category_id: +category })) },
8789
+ }),
8790
+ to: (categories) => categories.map((categoryId) => +categoryId),
8791
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
8792
+ },
8793
+ },
8794
+ {
8795
+ metadata: {
8796
+ columnName: 'metadata',
8797
+ fields: ['title', 'description'],
8798
+ bindPersistData: (value) => ({
8799
+ metadata: { data: value },
8800
+ }),
8801
+ },
8802
+ },
8803
+ {
8804
+ reviews: {
8805
+ columnName: 'reviews',
8806
+ foreignKeyColumn: { product_id: 'id' },
8807
+ fields: [
8808
+ 'id',
8809
+ 'shop',
8810
+ 'rate',
8811
+ 'author',
8812
+ 'email',
8813
+ 'location',
8814
+ 'review',
8815
+ 'status',
8816
+ 'title',
8817
+ { personId: { columnName: 'person_id' } },
8818
+ 'points',
8819
+ { orderId: { columnName: 'order_id' } },
8820
+ { createdAt: { columnName: 'created_at' } },
8821
+ { updatedAt: { columnName: 'updated_at' } },
8822
+ ],
8823
+ },
8824
+ },
8825
+ { variantSlug: { columnName: 'variant_slug' } },
8826
+ { createdAt: { columnName: 'created_at' } },
8827
+ { updatedAt: { columnName: 'updated_at' } },
8068
8828
  ];
8069
8829
  class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8070
8830
  constructor({ endpoint, authOptions, interceptors, cache, }) {
@@ -8093,18 +8853,57 @@ class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
8093
8853
  const { filters, ...options } = params || {};
8094
8854
  return super.find({ ...options, filters: { productId: { operator: exports.Where.ISNOTNULL }, ...filters } });
8095
8855
  }
8856
+ async getByEAN(EAN) {
8857
+ const { data } = await this.find({
8858
+ filters: {
8859
+ EAN,
8860
+ },
8861
+ options: {
8862
+ enableCount: false,
8863
+ },
8864
+ });
8865
+ return data.at(0);
8866
+ }
8096
8867
  async update(params) {
8097
- const { productId, id: checkId, ...data } = params;
8868
+ const { productId, id: checkId, metadata, ...data } = params;
8098
8869
  const dataWithProductId = this.paramsToPlain({ id: checkId, productId });
8099
8870
  if (!dataWithProductId.id) {
8100
8871
  throw new NotFoundError('Variant ID is required for update');
8101
8872
  }
8102
8873
  const id = await this.getId(dataWithProductId.id);
8103
8874
  const product = await super.update({ id, ...data });
8875
+ product.metadata = metadata && (await this.updateMetadata(+id, { metadata }));
8104
8876
  if (dataWithProductId.productId) {
8105
8877
  product.productId = dataWithProductId.productId;
8106
8878
  }
8107
- return product;
8879
+ return product;
8880
+ }
8881
+ async updateMetadata(productId, { metadata }) {
8882
+ const plainData = this.paramsToPlain({ metadata });
8883
+ if (!plainData.metadata)
8884
+ return null;
8885
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8886
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8887
+ pk_columns: {
8888
+ value: { product_id: productId },
8889
+ type: 'product_metadata_pk_columns_input',
8890
+ required: true,
8891
+ },
8892
+ _set: {
8893
+ value: lodash.omit(metadata, ['product_id']),
8894
+ type: 'product_metadata_set_input',
8895
+ required: true,
8896
+ },
8897
+ });
8898
+ if (!update_product_metadata_by_pk) {
8899
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8900
+ objects: {
8901
+ type: '[product_metadata_insert_input!]!',
8902
+ value: [{ product_id: productId, ...metadata }],
8903
+ },
8904
+ });
8905
+ }
8906
+ return plainData.metadata;
8108
8907
  }
8109
8908
  async getId(id) {
8110
8909
  if (!Number.isNaN(+id))
@@ -8420,6 +9219,9 @@ class WishlistHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
8420
9219
  productId: +productId,
8421
9220
  });
8422
9221
  }
9222
+ async getBrandsWithProducts() {
9223
+ return;
9224
+ }
8423
9225
  }
8424
9226
  tslib.__decorate([
8425
9227
  Log(),
@@ -8586,6 +9388,201 @@ class PagarmePaymentOperationsHelper {
8586
9388
  }
8587
9389
  }
8588
9390
 
9391
+ class PagarMeV5RequestHelper {
9392
+ static build(checkout, method, card) {
9393
+ return {
9394
+ items: this.buildItems(checkout),
9395
+ customer: this.buildCustomer(checkout),
9396
+ shipping: this.buildShipping(checkout),
9397
+ payments: this.buildPayment(checkout, method, card),
9398
+ };
9399
+ }
9400
+ static buildItems(checkout) {
9401
+ return checkout.lineItems
9402
+ .filter((item) => !item.isGift)
9403
+ .map((item) => {
9404
+ return {
9405
+ amount: Math.floor(item.pricePaid * 100),
9406
+ description: item.name,
9407
+ quantity: item.quantity,
9408
+ code: item.EAN,
9409
+ };
9410
+ });
9411
+ }
9412
+ static buildCustomer(checkout) {
9413
+ return {
9414
+ name: checkout.user.displayName,
9415
+ email: checkout.user.email,
9416
+ type: 'individual',
9417
+ document: checkout.user.cpf,
9418
+ phones: {
9419
+ home_phone: {
9420
+ country_code: '55',
9421
+ number: checkout.user.phone.slice(2),
9422
+ area_code: checkout.user.phone.slice(0, 2),
9423
+ },
9424
+ mobile_phone: {
9425
+ country_code: '55',
9426
+ number: checkout.user.phone.slice(2),
9427
+ area_code: checkout.user.phone.slice(0, 2),
9428
+ },
9429
+ },
9430
+ address: {
9431
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
9432
+ line_2: `${checkout.billingAddress.extension}`,
9433
+ zip_code: checkout.shippingAddress.zip,
9434
+ city: checkout.billingAddress.city,
9435
+ state: checkout.billingAddress.state,
9436
+ country: 'BR',
9437
+ },
9438
+ };
9439
+ }
9440
+ static buildShipping(checkout) {
9441
+ return {
9442
+ amount: Math.floor(checkout.shipping.ShippingPrice * 100),
9443
+ description: `${checkout.shipping.ShippingCompanyName} - ${checkout.shipping.description}`,
9444
+ recipient_name: checkout.shippingAddress.recipient,
9445
+ recipient_phone: checkout.user.phone,
9446
+ address: {
9447
+ line_1: `${checkout.shippingAddress.number}, ${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9448
+ line_2: `${checkout.shippingAddress.extension}`,
9449
+ zip_code: checkout.shippingAddress.zip,
9450
+ city: checkout.shippingAddress.city,
9451
+ state: checkout.shippingAddress.state,
9452
+ country: 'BR',
9453
+ },
9454
+ };
9455
+ }
9456
+ static buildPayment(checkout, method, card) {
9457
+ return [
9458
+ {
9459
+ payment_method: method,
9460
+ amount: Math.floor(checkout.totalPrice * 100),
9461
+ ...(method === 'pix' && {
9462
+ pix: this.getPixOrder(),
9463
+ }),
9464
+ ...(method === 'boleto' && {
9465
+ boleto: this.getBoletoOrder(),
9466
+ }),
9467
+ ...(method === 'credit_card' && {
9468
+ credit_card: this.getCardOrder(checkout, card),
9469
+ }),
9470
+ },
9471
+ ];
9472
+ }
9473
+ static getPixOrder() {
9474
+ return {
9475
+ expires_at: dateFns.format(dateFns.addDays(new Date(), 1), 'yyyy-MM-dd'),
9476
+ };
9477
+ }
9478
+ static getBoletoOrder() {
9479
+ return {
9480
+ due_at: dateFns.format(dateFns.addDays(new Date(), 3), 'yyyy-MM-dd'),
9481
+ instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
9482
+ type: 'DM',
9483
+ document_number: new Date().getTime().toString(),
9484
+ };
9485
+ }
9486
+ static getCardOrder(checkout, card) {
9487
+ return {
9488
+ installments: card.installments,
9489
+ statement_descriptor: checkout.shop === exports.Shops.GLAMSHOP ? 'Glam' : 'Mens Market',
9490
+ card_id: card.cardId,
9491
+ card: {
9492
+ cvv: card.cardCvv,
9493
+ billing_address: {
9494
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
9495
+ zip_code: checkout.billingAddress.zip,
9496
+ city: checkout.billingAddress.city,
9497
+ state: checkout.billingAddress.state,
9498
+ country: 'BR',
9499
+ },
9500
+ },
9501
+ };
9502
+ }
9503
+ }
9504
+
9505
+ class PagarMeV5ResponseHelper {
9506
+ static build(method, checkout, response) {
9507
+ return Payment.toInstance({
9508
+ createdAt: new Date(),
9509
+ updatedAt: new Date(),
9510
+ userId: checkout.user.id,
9511
+ checkoutId: checkout.id,
9512
+ totalPrice: checkout.totalPrice,
9513
+ paymentProvider: exports.PaymentProviders.PAGARME,
9514
+ pagarMeOrderId: response.id,
9515
+ transaction: this.buildPaymentTransaction(method, response),
9516
+ });
9517
+ }
9518
+ static buildPaymentTransaction(method, response) {
9519
+ const charger = response.charges.at(0);
9520
+ const transaction = charger.last_transaction;
9521
+ return PaymentTransaction.toInstance({
9522
+ acquirer_name: 'pagar_me',
9523
+ amount: charger.amount,
9524
+ currency: charger.currency,
9525
+ gateway_id: charger.gateway_id,
9526
+ status: this.getPaymentStatus(transaction.status),
9527
+ payment_method: charger.payment_method,
9528
+ date_created: charger.created_at,
9529
+ date_updated: charger.updated_at,
9530
+ paid_amount: charger.paid_amount,
9531
+ paid_at: charger.paid_at,
9532
+ order_id: response.id,
9533
+ charger_id: charger.id,
9534
+ tid: charger.id,
9535
+ id: charger.id,
9536
+ ...(method == exports.TransactionPaymentMethods.BANKSLIP && this.getBoletoReponse(transaction)),
9537
+ ...(method == exports.TransactionPaymentMethods.PIX && this.getPixReponse(transaction)),
9538
+ ...(method == exports.TransactionPaymentMethods.CARD && this.getCardReponse(transaction)),
9539
+ });
9540
+ }
9541
+ static getPaymentStatus(status) {
9542
+ if (status == exports.PagarMeV5PaymentStatus.Gerado)
9543
+ return exports.PagarMeV5PaymentStatus['Aguardando pagamento'];
9544
+ if (status == exports.PagarMeV5PaymentStatus.Capturada)
9545
+ return exports.PagarMeV5PaymentStatus.Pago;
9546
+ return status;
9547
+ }
9548
+ static getBoletoReponse(transaction) {
9549
+ return {
9550
+ boleto_url: transaction.url?.toString(),
9551
+ boleto_barcode: transaction.line?.toString(),
9552
+ boleto_qr_code: transaction.qr_code?.toString(),
9553
+ boleto_expiration_date: transaction.due_at?.toString(),
9554
+ boleto_instructions: transaction.instructions?.toString(),
9555
+ boleto_nosso_numero: transaction.nosso_numero?.toString(),
9556
+ boleto_type: transaction.type?.toString(),
9557
+ boleto_document_number: transaction.document_number?.toString(),
9558
+ };
9559
+ }
9560
+ static getPixReponse(transaction) {
9561
+ return {
9562
+ pix_qr_code: transaction.qr_code?.toString(),
9563
+ pix_qr_code_url: transaction.qr_code_url?.toString(),
9564
+ pix_expiration_date: transaction.expires_at?.toString(),
9565
+ };
9566
+ }
9567
+ static getCardReponse(transaction) {
9568
+ return {
9569
+ soft_descriptor: transaction.statement_descriptor?.toString(),
9570
+ acquirer_name: transaction.acquirer_name?.toString(),
9571
+ acquirer_id: transaction.acquirer_tid?.toString(),
9572
+ acquirer_nsu: transaction.acquirer_nsu?.toString(),
9573
+ acquirer_auth_code: transaction.acquirer_auth_code?.toString(),
9574
+ acquirer_message: transaction.acquirer_message?.toString(),
9575
+ acquirer_return_code: transaction.acquirer_return_code?.toString(),
9576
+ installments: transaction.installments ?? null,
9577
+ card_holder_name: transaction.card?.holder_name?.toString(),
9578
+ card_last_digits: transaction.card?.last_four_digits?.toString(),
9579
+ card_first_digits: transaction.card?.first_six_digits?.toString(),
9580
+ card_brand: transaction.card?.brand?.toString(),
9581
+ card_id: transaction.card?.id?.toString(),
9582
+ };
9583
+ }
9584
+ }
9585
+
8589
9586
  class PagarmeCardAxiosAdapter {
8590
9587
  constructor(credentials, paymentRepository, orderBlockedRepository) {
8591
9588
  this.credentials = credentials;
@@ -8642,8 +9639,9 @@ class PagarmeCardAxiosAdapter {
8642
9639
  });
8643
9640
  }
8644
9641
  }
8645
- async createCardHash(bu) {
8646
- const key = bu === exports.BusinessUnitEnum.SHOP ? this.credentials.SHOP_API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
9642
+ async createCardHash(bu, shop) {
9643
+ const credentials = shop && shop == exports.Shops.MENSMARKET ? this.credentials[exports.Shops.MENSMARKET] : this.credentials[exports.Shops.GLAMSHOP];
9644
+ const key = bu === exports.BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
8647
9645
  try {
8648
9646
  const { data } = await axios__default["default"]({
8649
9647
  method: 'GET',
@@ -8806,6 +9804,281 @@ class PagarmePixAxiosAdapter {
8806
9804
  }
8807
9805
  }
8808
9806
 
9807
+ class PagarmeV5BankSlipAxiosAdapter {
9808
+ constructor(credentials, paymentRepository) {
9809
+ this.credentials = credentials;
9810
+ this.paymentRepository = paymentRepository;
9811
+ }
9812
+ async pay(checkout) {
9813
+ try {
9814
+ const payload = PagarMeV5RequestHelper.build(checkout, 'boleto');
9815
+ console.warn('[PAGARME BOLETO DATA TO SEND]', JSON.stringify(payload));
9816
+ const { data } = await axios__default["default"]({
9817
+ method: 'POST',
9818
+ url: `${this.credentials.URL}/orders`,
9819
+ headers: {
9820
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9821
+ 'Content-Type': 'application/json',
9822
+ },
9823
+ data: payload,
9824
+ });
9825
+ console.warn('[PAGARME RESPONSE BOLETO DATA]', JSON.stringify(data));
9826
+ if (data.status === exports.PagarMeV5OrderStatus.Falha ||
9827
+ data.charges.at(0).status === exports.PagarMeV5OrderStatus.Falha ||
9828
+ (data.charges.at(0).last_transaction.status !== exports.PagarMeV5PaymentStatus.Gerado &&
9829
+ data.charges.at(0).last_transaction.status !== exports.PagarMeV5PaymentStatus['Em processamento'])) {
9830
+ return Promise.reject(new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
9831
+ checkoutId: checkout.id,
9832
+ userEmail: checkout.user.email,
9833
+ info: data.charges.at(0).last_transaction?.gateway_response,
9834
+ }));
9835
+ }
9836
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(exports.TransactionPaymentMethods.BANKSLIP, checkout, data));
9837
+ return payment;
9838
+ }
9839
+ catch (error) {
9840
+ if (error instanceof axios.AxiosError) {
9841
+ console.error('error data: ', JSON.stringify(error.response?.data));
9842
+ }
9843
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
9844
+ checkoutId: checkout.id,
9845
+ userEmail: checkout.user.email,
9846
+ info: error.response?.data,
9847
+ });
9848
+ }
9849
+ }
9850
+ async getBoletoTransaction(paymentId) {
9851
+ try {
9852
+ const { data } = await axios__default["default"]({
9853
+ method: 'GET',
9854
+ url: `${this.credentials.URL}/charges/${paymentId}`,
9855
+ headers: {
9856
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9857
+ 'Content-Type': 'application/json',
9858
+ },
9859
+ });
9860
+ const payment = await this.paymentRepository.get({
9861
+ id: data.id,
9862
+ });
9863
+ return payment.transaction;
9864
+ }
9865
+ catch (error) {
9866
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
9867
+ paymentId,
9868
+ info: error.response.data,
9869
+ });
9870
+ }
9871
+ }
9872
+ }
9873
+
9874
+ class PagarmeV5CardAxiosAdapter {
9875
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
9876
+ this.credentials = credentials;
9877
+ this.paymentRepository = paymentRepository;
9878
+ this.orderBlockedRepository = orderBlockedRepository;
9879
+ }
9880
+ async pay(checkout, card) {
9881
+ try {
9882
+ const payload = PagarMeV5RequestHelper.build(checkout, 'credit_card', card);
9883
+ console.warn('[PAGARME CARD DATA TO SEND]', JSON.stringify(payload));
9884
+ const { data } = await axios__default["default"]({
9885
+ method: 'POST',
9886
+ url: `${this.credentials.URL}/orders`,
9887
+ headers: {
9888
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9889
+ 'Content-Type': 'application/json',
9890
+ },
9891
+ data: payload,
9892
+ });
9893
+ console.warn('[RESPONSE PAGARME CARD DATA]', JSON.stringify(data));
9894
+ if (data.status == exports.PagarMeV5OrderStatus.Falha ||
9895
+ data.charges.at(0).status !== exports.PagarMeV5OrderStatus.Pago ||
9896
+ data.charges.at(0).last_transaction.status !== exports.PagarMeV5PaymentStatus.Capturada) {
9897
+ await PagarmeBlockedOrderHelper.createBlockedOrderForUnauthorizedCard({
9898
+ checkout,
9899
+ card,
9900
+ orderBlockedRepository: this.orderBlockedRepository,
9901
+ });
9902
+ throw PagarmeBlockedOrderHelper.createPaymentError(checkout, data);
9903
+ }
9904
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(exports.TransactionPaymentMethods.CARD, checkout, data));
9905
+ return payment;
9906
+ }
9907
+ catch (error) {
9908
+ if (error instanceof PaymentError) {
9909
+ throw error;
9910
+ }
9911
+ if (error instanceof axios.AxiosError) {
9912
+ console.error('error data: ', JSON.stringify(error.response?.data));
9913
+ }
9914
+ throw PagarmeBlockedOrderHelper.createGenericPaymentError(checkout, error.response?.data);
9915
+ }
9916
+ }
9917
+ async addCard(card, customer) {
9918
+ try {
9919
+ const { id } = await this.createOrUpdateCustomer(customer);
9920
+ const { data } = await axios__default["default"]({
9921
+ method: 'POST',
9922
+ url: `${this.credentials.URL}/customers/${id}/cards`,
9923
+ headers: {
9924
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9925
+ 'Content-Type': 'application/json',
9926
+ },
9927
+ data: {
9928
+ number: card.number,
9929
+ holder_name: card.name,
9930
+ holder_document: card.cpf,
9931
+ exp_month: card.expirationDate.split('/').at(0),
9932
+ exp_year: card.expirationDate.split('/').at(1),
9933
+ cvv: card.cvv,
9934
+ billing_address: {
9935
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
9936
+ line_2: `${customer.billingAddress.extension}`,
9937
+ zip_code: customer.billingAddress.zip,
9938
+ city: customer.billingAddress.city,
9939
+ state: customer.billingAddress.state,
9940
+ country: 'BR',
9941
+ },
9942
+ },
9943
+ });
9944
+ return data;
9945
+ }
9946
+ catch (error) {
9947
+ console.warn(JSON.stringify(error));
9948
+ throw error;
9949
+ }
9950
+ }
9951
+ async createCardHash(bu, shop) {
9952
+ const credentials = shop && shop == exports.Shops.MENSMARKET ? this.credentials[exports.Shops.MENSMARKET] : this.credentials[exports.Shops.GLAMSHOP];
9953
+ const key = bu === exports.BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
9954
+ try {
9955
+ const { data } = await axios__default["default"]({
9956
+ method: 'GET',
9957
+ headers: {
9958
+ 'content-type': 'application/json',
9959
+ },
9960
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
9961
+ data: JSON.stringify({
9962
+ api_key: key,
9963
+ }),
9964
+ });
9965
+ return data;
9966
+ }
9967
+ catch (error) {
9968
+ throw new BusinessError('Houve uma falha gerar o hash', {
9969
+ info: error.response.data,
9970
+ });
9971
+ }
9972
+ }
9973
+ async getCardByToken(customerId, token) {
9974
+ try {
9975
+ const { data } = await axios__default["default"]({
9976
+ method: 'GET',
9977
+ url: `${this.credentials.URL}/cards/${token}`,
9978
+ data: {
9979
+ api_key: this.credentials.API_KEY,
9980
+ },
9981
+ });
9982
+ return data;
9983
+ }
9984
+ catch (error) {
9985
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + token, {
9986
+ info: error.response.data,
9987
+ });
9988
+ }
9989
+ }
9990
+ async createTransaction(info) {
9991
+ return info;
9992
+ }
9993
+ async createOrUpdateCustomer(customer) {
9994
+ try {
9995
+ const { data } = await axios__default["default"]({
9996
+ method: 'POST',
9997
+ url: `${this.credentials.URL}/customers`,
9998
+ headers: {
9999
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10000
+ 'Content-Type': 'application/json',
10001
+ },
10002
+ data: {
10003
+ name: customer.displayName,
10004
+ email: customer.email,
10005
+ document: customer.cpf,
10006
+ type: 'individual',
10007
+ document_type: 'CPF',
10008
+ address: {
10009
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
10010
+ line_2: `${customer.billingAddress.extension}`,
10011
+ zip_code: customer.billingAddress.zip,
10012
+ city: customer.billingAddress.city,
10013
+ state: customer.billingAddress.state,
10014
+ country: 'BR',
10015
+ },
10016
+ birthdate: dateFns.format(new Date(customer.birthday), 'MM/dd/yyyy'),
10017
+ phones: {
10018
+ home_phone: {
10019
+ country_code: '55',
10020
+ number: customer.phone.slice(2),
10021
+ area_code: customer.phone.slice(0, 2),
10022
+ },
10023
+ mobile_phone: {
10024
+ country_code: '55',
10025
+ number: customer.phone.slice(2),
10026
+ area_code: customer.phone.slice(0, 2),
10027
+ },
10028
+ },
10029
+ },
10030
+ });
10031
+ return data;
10032
+ }
10033
+ catch (error) {
10034
+ console.warn(error);
10035
+ throw error;
10036
+ }
10037
+ }
10038
+ }
10039
+
10040
+ class PagarmeV5PixAxiosAdapter {
10041
+ constructor(credentials, paymentRepository) {
10042
+ this.credentials = credentials;
10043
+ this.paymentRepository = paymentRepository;
10044
+ }
10045
+ async pay(checkout) {
10046
+ try {
10047
+ const payload = PagarMeV5RequestHelper.build(checkout, 'pix');
10048
+ console.warn('[PAGARME PIX DATA TO SEND]', JSON.stringify(payload));
10049
+ const { data } = await axios__default["default"]({
10050
+ method: 'POST',
10051
+ url: `${this.credentials.URL}/orders`,
10052
+ headers: {
10053
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
10054
+ 'Content-Type': 'application/json',
10055
+ },
10056
+ data: payload,
10057
+ });
10058
+ console.warn('[RESPONSE PAGARME PIX DATA]', JSON.stringify(data));
10059
+ if (data.status == exports.PagarMeV5OrderStatus.Falha || data.status == exports.PagarMeV5OrderStatus.Cancelado) {
10060
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
10061
+ checkoutId: checkout.id,
10062
+ userEmail: checkout.user.email,
10063
+ info: data.charges.at(0).last_transaction?.gateway_response,
10064
+ });
10065
+ }
10066
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(exports.TransactionPaymentMethods.PIX, checkout, data));
10067
+ return payment;
10068
+ }
10069
+ catch (error) {
10070
+ if (error instanceof axios.AxiosError) {
10071
+ console.error('error data: ', JSON.stringify(error.response?.data));
10072
+ }
10073
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
10074
+ checkoutId: checkout.id,
10075
+ userEmail: checkout.user.email,
10076
+ info: error.response?.data,
10077
+ });
10078
+ }
10079
+ }
10080
+ }
10081
+
8809
10082
  class VertexAxiosAdapter {
8810
10083
  constructor(config) {
8811
10084
  this.config = config;
@@ -9007,6 +10280,10 @@ Object.defineProperty(exports, 'subDays', {
9007
10280
  enumerable: true,
9008
10281
  get: function () { return dateFns.subDays; }
9009
10282
  });
10283
+ Object.defineProperty(exports, 'formatInTimeZone', {
10284
+ enumerable: true,
10285
+ get: function () { return dateFnsTz.formatInTimeZone; }
10286
+ });
9010
10287
  Object.defineProperty(exports, 'chunk', {
9011
10288
  enumerable: true,
9012
10289
  get: function () { return lodash.chunk; }
@@ -9162,12 +10439,17 @@ exports.PagarmeBankSlipAxiosAdapter = PagarmeBankSlipAxiosAdapter;
9162
10439
  exports.PagarmeCardAxiosAdapter = PagarmeCardAxiosAdapter;
9163
10440
  exports.PagarmePaymentMethodFactory = PagarmePaymentMethodFactory;
9164
10441
  exports.PagarmePixAxiosAdapter = PagarmePixAxiosAdapter;
10442
+ exports.PagarmeV5BankSlipAxiosAdapter = PagarmeV5BankSlipAxiosAdapter;
10443
+ exports.PagarmeV5CardAxiosAdapter = PagarmeV5CardAxiosAdapter;
10444
+ exports.PagarmeV5PixAxiosAdapter = PagarmeV5PixAxiosAdapter;
9165
10445
  exports.Payment = Payment;
9166
10446
  exports.PaymentError = PaymentError;
9167
10447
  exports.PaymentFirestoreRepository = PaymentFirestoreRepository;
9168
10448
  exports.PaymentProviderFactory = PaymentProviderFactory;
9169
10449
  exports.PaymentTransaction = PaymentTransaction;
9170
10450
  exports.Product = Product;
10451
+ exports.ProductCatalogHasuraGraphQL = ProductCatalogHasuraGraphQL;
10452
+ exports.ProductCatalogHasuraGraphQLRepository = ProductCatalogHasuraGraphQLRepository;
9171
10453
  exports.ProductErrors = ProductErrors;
9172
10454
  exports.ProductErrorsHasuraGraphQL = ProductErrorsHasuraGraphQL;
9173
10455
  exports.ProductErrorsHasuraGraphQLRepository = ProductErrorsHasuraGraphQLRepository;