@infrab4a/connect 5.3.0-beta.3 → 5.3.0-beta.31

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 (161) hide show
  1. package/index.cjs.js +3018 -435
  2. package/index.esm.js +2980 -419
  3. package/package.json +3 -2
  4. package/src/domain/catalog/models/category-brand.d.ts +17 -0
  5. package/src/domain/catalog/models/category.d.ts +12 -0
  6. package/src/domain/catalog/models/enums/shops.enum.d.ts +2 -0
  7. package/src/domain/catalog/models/index.d.ts +4 -0
  8. package/src/domain/catalog/models/product-base.d.ts +10 -0
  9. package/src/domain/catalog/models/product-group.d.ts +12 -0
  10. package/src/domain/catalog/models/product-price-log.d.ts +25 -0
  11. package/src/domain/catalog/models/product-review.d.ts +2 -0
  12. package/src/domain/catalog/models/product-stock-entry.d.ts +16 -0
  13. package/src/domain/catalog/models/product.d.ts +1 -0
  14. package/src/domain/catalog/models/types/brands-shop-menu.type.d.ts +13 -0
  15. package/src/domain/catalog/models/types/index.d.ts +2 -0
  16. package/src/domain/catalog/models/types/product-competitors-price.d.ts +6 -0
  17. package/src/domain/catalog/repositories/category-brand.repository.d.ts +4 -0
  18. package/src/domain/catalog/repositories/category-product.repository.d.ts +2 -0
  19. package/src/domain/catalog/repositories/category.repository.d.ts +1 -0
  20. package/src/domain/catalog/repositories/index.d.ts +5 -0
  21. package/src/domain/catalog/repositories/product-catalog.repository.d.ts +17 -0
  22. package/src/domain/catalog/repositories/product-group.repository.d.ts +4 -0
  23. package/src/domain/catalog/repositories/product-price-log.repository.d.ts +4 -0
  24. package/src/domain/catalog/repositories/product-stock-entry.repository.d.ts +4 -0
  25. package/src/domain/shop-settings/enums/shop-page-name.enum.d.ts +2 -1
  26. package/src/domain/shop-settings/models/home.d.ts +2 -1
  27. package/src/domain/shop-settings/models/index.d.ts +2 -1
  28. package/src/domain/shop-settings/models/shop-configs.d.ts +18 -0
  29. package/src/domain/shop-settings/models/{shop-settings.d.ts → shop-page-settings.d.ts} +4 -1
  30. package/src/domain/shop-settings/models/types/index.d.ts +3 -0
  31. package/src/domain/shop-settings/models/types/limit-orders.type.d.ts +7 -0
  32. package/src/domain/shop-settings/models/types/shipping-thresholds.type.d.ts +17 -0
  33. package/src/domain/shop-settings/models/types/shop-error-messages.type.d.ts +10 -0
  34. package/src/domain/shop-settings/models/types/shop-page-section.type.d.ts +140 -0
  35. package/src/domain/shop-settings/repositories/index.d.ts +1 -0
  36. package/src/domain/shop-settings/repositories/shop-configs.repository.d.ts +4 -0
  37. package/src/domain/shop-settings/repositories/shop-settings.repository.d.ts +1 -1
  38. package/src/domain/shopping/enums/index.d.ts +3 -0
  39. package/src/domain/shopping/enums/order-payment-status.enum.d.ts +10 -0
  40. package/src/domain/shopping/enums/pagarme-v5-payment-status.enum.d.ts +24 -0
  41. package/src/domain/shopping/enums/payment-providers.enum.d.ts +2 -1
  42. package/src/domain/shopping/enums/transaction-payment-methods.enum.d.ts +5 -0
  43. package/src/domain/shopping/factories/index.d.ts +1 -0
  44. package/src/domain/shopping/factories/mercado-pago-payment-method.factory.d.ts +11 -0
  45. package/src/domain/shopping/factories/payment-provider.factory.d.ts +2 -0
  46. package/src/domain/shopping/interfaces/payment-provider-card.interface.d.ts +10 -2
  47. package/src/domain/shopping/models/checkout.d.ts +2 -0
  48. package/src/domain/shopping/models/enums/index.d.ts +3 -0
  49. package/src/domain/shopping/models/enums/order-status.enum.d.ts +2 -1
  50. package/src/domain/shopping/models/enums/shopping-recurrence-cycle.enum.d.ts +5 -0
  51. package/src/domain/shopping/models/enums/shopping-recurrence-edition-status.enum.d.ts +11 -0
  52. package/src/domain/shopping/models/enums/shopping-recurrence-status.enum.d.ts +7 -0
  53. package/src/domain/shopping/models/index.d.ts +1 -0
  54. package/src/domain/shopping/models/line-item.d.ts +5 -0
  55. package/src/domain/shopping/models/order-blocked.d.ts +5 -0
  56. package/src/domain/shopping/models/order.d.ts +20 -0
  57. package/src/domain/shopping/models/payment-transaction.d.ts +19 -2
  58. package/src/domain/shopping/models/payment.d.ts +3 -1
  59. package/src/domain/shopping/models/recurrence/index.d.ts +3 -0
  60. package/src/domain/shopping/models/recurrence/shopping-recurrence-edition.d.ts +18 -0
  61. package/src/domain/shopping/models/recurrence/shopping-recurrence-error-log.d.ts +9 -0
  62. package/src/domain/shopping/models/recurrence/shopping-recurrence.d.ts +45 -0
  63. package/src/domain/shopping/models/shipping-method.d.ts +2 -0
  64. package/src/domain/shopping/models/types/index.d.ts +1 -0
  65. package/src/domain/shopping/models/types/line-item-recurrence.type.d.ts +2 -0
  66. package/src/domain/shopping/repositories/index.d.ts +1 -0
  67. package/src/domain/shopping/repositories/order-blocked.repository.d.ts +5 -0
  68. package/src/domain/shopping/repositories/recurrence/index.d.ts +3 -0
  69. package/src/domain/shopping/repositories/recurrence/shopping-recurrence-edition.repository.d.ts +4 -0
  70. package/src/domain/shopping/repositories/recurrence/shopping-recurrence-error-log.repository.d.ts +4 -0
  71. package/src/domain/shopping/repositories/recurrence/shopping-recurrence.repository.d.ts +9 -0
  72. package/src/domain/shopping/services/antifraud-card.service.d.ts +2 -0
  73. package/src/domain/shopping/types/card-info.type.d.ts +1 -0
  74. package/src/domain/shopping/types/checkout-paylod-request.type.d.ts +2 -7
  75. package/src/domain/shopping/types/create-recurrency-payload.type.d.ts +6 -0
  76. package/src/domain/shopping/types/index.d.ts +5 -0
  77. package/src/domain/shopping/types/mercado-pago-card.type.d.ts +14 -0
  78. package/src/domain/shopping/types/mercado-pago-credentials.type.d.ts +5 -0
  79. package/src/domain/shopping/types/pagarme-card.type.d.ts +9 -3
  80. package/src/domain/shopping/types/pagarme-credentials-v5.type.d.ts +4 -0
  81. package/src/domain/shopping/types/pagarme-credentials.type.d.ts +9 -3
  82. package/src/domain/shopping/types/payment-card-info.type.d.ts +6 -1
  83. package/src/domain/shopping/types/shopping-recurrence-update-payloads.type.d.ts +35 -0
  84. package/src/domain/users/models/user-payment-method.d.ts +2 -0
  85. package/src/domain/users/models/user.d.ts +1 -0
  86. package/src/errors/enum/error.enum.d.ts +14 -0
  87. package/src/errors/enum/index.d.ts +1 -0
  88. package/src/errors/fraud-validation.error.d.ts +1 -1
  89. package/src/errors/index.d.ts +2 -0
  90. package/src/errors/invalid-checkout.error.d.ts +7 -0
  91. package/src/errors/not-found.error.d.ts +1 -0
  92. package/src/errors/payment.error.d.ts +1 -1
  93. package/src/infra/cache/index.d.ts +1 -0
  94. package/src/infra/cache/resolve-cache-config.d.ts +2 -0
  95. package/src/infra/cache/restcache.adapter.d.ts +3 -0
  96. package/src/infra/firebase/firestore/repositories/catalog/category-brand-firestore.repository.d.ts +7 -0
  97. package/src/infra/firebase/firestore/repositories/catalog/category-firestore.repository.d.ts +1 -0
  98. package/src/infra/firebase/firestore/repositories/catalog/index.d.ts +1 -0
  99. package/src/infra/firebase/firestore/repositories/shop-settings/index.d.ts +1 -0
  100. package/src/infra/firebase/firestore/repositories/shop-settings/shop-configs-firestore.repository.d.ts +7 -0
  101. package/src/infra/firebase/firestore/repositories/shopping/index.d.ts +3 -0
  102. package/src/infra/firebase/firestore/repositories/shopping/order-blocked-firestore.repository.d.ts +1 -0
  103. package/src/infra/firebase/firestore/repositories/shopping/shopping-recurrence-edition-firestore.repository.d.ts +7 -0
  104. package/src/infra/firebase/firestore/repositories/shopping/shopping-recurrence-error-log-firestore.repository.d.ts +7 -0
  105. package/src/infra/firebase/firestore/repositories/shopping/shopping-recurrence-firestore.repository.d.ts +10 -0
  106. package/src/infra/hasura-graphql/models/index.d.ts +2 -0
  107. package/src/infra/hasura-graphql/models/product-catalog-hasura-graphql.d.ts +16 -0
  108. package/src/infra/hasura-graphql/models/product-stock-entry-hasura-graphql.d.ts +3 -0
  109. package/src/infra/hasura-graphql/models/variant-hasura-graphql.d.ts +7 -0
  110. package/src/infra/hasura-graphql/repositories/catalog/category-hasura-graphql.repository.d.ts +1 -0
  111. package/src/infra/hasura-graphql/repositories/catalog/category-product-hasura-graphql.repository.d.ts +2 -0
  112. package/src/infra/hasura-graphql/repositories/catalog/index.d.ts +4 -0
  113. package/src/infra/hasura-graphql/repositories/catalog/product-catalog-hasura-graphql.repository.d.ts +22 -0
  114. package/src/infra/hasura-graphql/repositories/catalog/product-group-hasura-graphql.repository.d.ts +7 -0
  115. package/src/infra/hasura-graphql/repositories/catalog/product-price-log-hasura-graphql.repository.d.ts +7 -0
  116. package/src/infra/hasura-graphql/repositories/catalog/product-stock-entry-hasura-graphql.repository.d.ts +8 -0
  117. package/src/infra/hasura-graphql/repositories/catalog/variant-hasura-graphql.repository.d.ts +1 -0
  118. package/src/infra/hasura-graphql/repositories/catalog/wishlist-hasura-graphql.repository.d.ts +1 -0
  119. package/src/infra/index.d.ts +1 -0
  120. package/src/infra/mercado-pago/adapters/index.d.ts +3 -0
  121. package/src/infra/mercado-pago/adapters/mercado-pago-base-axios.d.ts +11 -0
  122. package/src/infra/mercado-pago/adapters/mercado-pago-boleto-payment-axios.adapter.d.ts +8 -0
  123. package/src/infra/mercado-pago/adapters/mercado-pago-card-payment-axios.adapter.d.ts +22 -0
  124. package/src/infra/mercado-pago/adapters/mercado-pago-pix-payment-axios.adapter.d.ts +8 -0
  125. package/src/infra/mercado-pago/enums/index.d.ts +2 -0
  126. package/src/infra/mercado-pago/enums/mercado-pago-status-detail.enum.d.ts +33 -0
  127. package/src/infra/mercado-pago/enums/mercado-pago-status.enum.d.ts +10 -0
  128. package/src/infra/mercado-pago/helpers/index.d.ts +3 -0
  129. package/src/infra/mercado-pago/helpers/mercado-pago-errors.helper.d.ts +3 -0
  130. package/src/infra/mercado-pago/helpers/mercado-pago-request.helper.d.ts +60 -0
  131. package/src/infra/mercado-pago/helpers/mercado-pago-response.helper.d.ts +10 -0
  132. package/src/infra/mercado-pago/index.d.ts +4 -0
  133. package/src/infra/mercado-pago/types/index.d.ts +3 -0
  134. package/src/infra/mercado-pago/types/mercado-pago-request.type.d.ts +1 -0
  135. package/src/infra/mercado-pago/types/mercado-pago-response.type.d.ts +211 -0
  136. package/src/infra/mercado-pago/types/mercado-pago-status-detail.type.d.ts +2 -0
  137. package/src/infra/mercado-pago/types/mercado-pago-status.type.d.ts +2 -0
  138. package/src/infra/pagarme/adapters/helpers/index.d.ts +3 -0
  139. package/src/infra/pagarme/adapters/helpers/pagarme-blocked-order.helper.d.ts +7 -2
  140. package/src/infra/pagarme/adapters/helpers/pagarme-errors.helper.d.ts +3 -0
  141. package/src/infra/pagarme/adapters/helpers/pagarme-v5-request.helper.d.ts +13 -0
  142. package/src/infra/pagarme/adapters/helpers/pagarme-v5-response.helper.d.ts +10 -0
  143. package/src/infra/pagarme/adapters/index.d.ts +2 -3
  144. package/src/infra/pagarme/adapters/v4/index.d.ts +3 -0
  145. package/src/infra/pagarme/adapters/{pagarme-bank-slip-payment-axios.adapter.d.ts → v4/pagarme-bank-slip-payment-axios.adapter.d.ts} +4 -4
  146. package/src/infra/pagarme/adapters/{pagarme-card-payment-axios.adapter.d.ts → v4/pagarme-card-payment-axios.adapter.d.ts} +7 -6
  147. package/src/infra/pagarme/adapters/{pagarme-pix-payment-axios.adapter.d.ts → v4/pagarme-pix-payment-axios.adapter.d.ts} +4 -4
  148. package/src/infra/pagarme/adapters/v5/index.d.ts +4 -0
  149. package/src/infra/pagarme/adapters/v5/pagarmev5-bank-slip-payment-axios.adapter.d.ts +11 -0
  150. package/src/infra/pagarme/adapters/v5/pagarmev5-base-axios.d.ts +11 -0
  151. package/src/infra/pagarme/adapters/v5/pagarmev5-card-payment-axios.adapter.d.ts +25 -0
  152. package/src/infra/pagarme/adapters/v5/pagarmev5-pix-payment-axios.adapter.d.ts +11 -0
  153. package/src/infra/pagarme/index.d.ts +1 -0
  154. package/src/infra/pagarme/types/index.d.ts +1 -0
  155. package/src/infra/pagarme/types/v5/index.d.ts +4 -0
  156. package/src/infra/pagarme/types/v5/pagarmev5-customer.type.d.ts +19 -0
  157. package/src/infra/pagarme/types/v5/pagarmev5-order-request-payload.type.d.ts +91 -0
  158. package/src/infra/pagarme/types/v5/pagarmev5-order-response.type.d.ts +241 -0
  159. package/src/infra/pagarme/types/v5/pagarmev5-postback-response.type.d.ts +11 -0
  160. package/src/utils/index.d.ts +4 -2
  161. package/src/utils/to-cents.d.ts +5 -0
package/index.esm.js CHANGED
@@ -1,12 +1,14 @@
1
1
  import 'reflect-metadata';
2
2
  import { __decorate, __metadata } from 'tslib';
3
3
  import { plainToInstance, instanceToPlain, Type } from 'class-transformer';
4
- import { parseISO, format, startOfDay, endOfDay, subDays, addDays } from 'date-fns';
5
- export { add, addBusinessDays, addDays, addMonths, addYears, endOfDay, format, formatISO9075, parseISO, startOfDay, sub, subDays } from 'date-fns';
4
+ import { parseISO, startOfDay, endOfDay, addHours, subDays, format, addDays } from 'date-fns';
5
+ export { add, addBusinessDays, addDays, addHours, addMonths, addYears, endOfDay, format, formatISO9075, parseISO, startOfDay, sub, subDays } from 'date-fns';
6
+ import { utcToZonedTime } from 'date-fns-tz';
7
+ export { formatInTimeZone } from 'date-fns-tz';
6
8
  import { compact, get, isNil, isArray, first, last, flatten, isString, omit, each, unset, isObject, isEmpty, isDate, isBoolean, isInteger, isNumber, isNaN as isNaN$1, set, chunk, sortBy } from 'lodash';
7
9
  export { chunk, each, get, isBoolean, isDate, isEmpty, isInteger, isNaN, isNil, isNumber, isObject, isString, now, omit, pick, set, sortBy, unset } from 'lodash';
8
10
  import { debug } from 'debug';
9
- import * as serializeJavascript from 'serialize-javascript';
11
+ import serializeJavascript from 'serialize-javascript';
10
12
  import { CustomError } from 'ts-custom-error';
11
13
  import axios, { AxiosError } from 'axios';
12
14
  import { signInWithEmailAndPassword, signInWithPopup, GoogleAuthProvider, browserPopupRedirectResolver, signInAnonymously, sendPasswordResetEmail, createUserWithEmailAndPassword, sendEmailVerification } from 'firebase/auth';
@@ -36,6 +38,18 @@ var OrderBlockedType;
36
38
  OrderBlockedType["Boleto"] = "Boleto";
37
39
  })(OrderBlockedType || (OrderBlockedType = {}));
38
40
 
41
+ var OrderPaymentStatus;
42
+ (function (OrderPaymentStatus) {
43
+ OrderPaymentStatus["Em processamento"] = "processing";
44
+ OrderPaymentStatus["Autorizada"] = "authorized";
45
+ OrderPaymentStatus["Pago"] = "paid";
46
+ OrderPaymentStatus["Estornada"] = "refunded";
47
+ OrderPaymentStatus["Aguardando pagamento"] = "waiting_payment";
48
+ OrderPaymentStatus["Aguardando estorno"] = "pending_refund";
49
+ OrderPaymentStatus["Recusada/N\u00E3o autorizada"] = "refused";
50
+ OrderPaymentStatus["Chargedback"] = "chargedback";
51
+ })(OrderPaymentStatus || (OrderPaymentStatus = {}));
52
+
39
53
  var PagarmePaymentStatus;
40
54
  (function (PagarmePaymentStatus) {
41
55
  PagarmePaymentStatus["Em processamento"] = "processing";
@@ -48,6 +62,33 @@ var PagarmePaymentStatus;
48
62
  PagarmePaymentStatus["Chargedback"] = "chargedback";
49
63
  })(PagarmePaymentStatus || (PagarmePaymentStatus = {}));
50
64
 
65
+ var PagarMeV5PaymentStatus;
66
+ (function (PagarMeV5PaymentStatus) {
67
+ PagarMeV5PaymentStatus["Em processamento"] = "processing";
68
+ PagarMeV5PaymentStatus["Gerado"] = "generated";
69
+ PagarMeV5PaymentStatus["Visualizado"] = "viewed";
70
+ PagarMeV5PaymentStatus["Pago a menor"] = "underpaid";
71
+ PagarMeV5PaymentStatus["Pago a maior"] = "overpaid";
72
+ PagarMeV5PaymentStatus["Aguardando pagamento"] = "waiting_payment";
73
+ PagarMeV5PaymentStatus["Pago"] = "paid";
74
+ PagarMeV5PaymentStatus["Aguardando estorno"] = "pending_refund";
75
+ PagarMeV5PaymentStatus["Autorizada pendente de captura"] = "authorized_pending_capture";
76
+ PagarMeV5PaymentStatus["N\u00E3o autorizada"] = "not_authorized";
77
+ PagarMeV5PaymentStatus["Capturada"] = "captured";
78
+ PagarMeV5PaymentStatus["Aguardando captura"] = "waiting_capture";
79
+ PagarMeV5PaymentStatus["Com erro"] = "with_error";
80
+ PagarMeV5PaymentStatus["Estornado"] = "refunded";
81
+ PagarMeV5PaymentStatus["Cancelado"] = "voided";
82
+ PagarMeV5PaymentStatus["Falha"] = "failed";
83
+ })(PagarMeV5PaymentStatus || (PagarMeV5PaymentStatus = {}));
84
+ var PagarMeV5OrderStatus;
85
+ (function (PagarMeV5OrderStatus) {
86
+ PagarMeV5OrderStatus["Pendente"] = "pending";
87
+ PagarMeV5OrderStatus["Pago"] = "paid";
88
+ PagarMeV5OrderStatus["Cancelado"] = "canceled";
89
+ PagarMeV5OrderStatus["Falha"] = "failed";
90
+ })(PagarMeV5OrderStatus || (PagarMeV5OrderStatus = {}));
91
+
51
92
  var PaymentMethods;
52
93
  (function (PaymentMethods) {
53
94
  PaymentMethods["CARD"] = "card";
@@ -61,8 +102,16 @@ var PaymentProviders;
61
102
  PaymentProviders["PAGARME"] = "pagarMe";
62
103
  PaymentProviders["ADYEN"] = "adyen";
63
104
  PaymentProviders["GLAMPOINTS"] = "glampoints";
105
+ PaymentProviders["MERCADOPAGO"] = "mercadoPago";
64
106
  })(PaymentProviders || (PaymentProviders = {}));
65
107
 
108
+ var TransactionPaymentMethods;
109
+ (function (TransactionPaymentMethods) {
110
+ TransactionPaymentMethods["CARD"] = "credit_card";
111
+ TransactionPaymentMethods["BANKSLIP"] = "boleto";
112
+ TransactionPaymentMethods["PIX"] = "pix";
113
+ })(TransactionPaymentMethods || (TransactionPaymentMethods = {}));
114
+
66
115
  class BasePaymentMethodFactory {
67
116
  constructor(methods) {
68
117
  this.methods = methods;
@@ -87,6 +136,9 @@ class AntifraudProviderFactory {
87
136
  class GlampointsPaymentMethodFactory extends BasePaymentMethodFactory {
88
137
  }
89
138
 
139
+ class MercadoPagoPaymentMethodFactory extends BasePaymentMethodFactory {
140
+ }
141
+
90
142
  class PagarmePaymentMethodFactory extends BasePaymentMethodFactory {
91
143
  }
92
144
 
@@ -587,6 +639,19 @@ const serialize = (data) => {
587
639
  return serializeJavascript(data);
588
640
  };
589
641
 
642
+ /**
643
+ * Converts a BRL major-unit amount (e.g. 10.5) to integer cents (1050).
644
+ * Uses fixed 2-decimal normalization to avoid IEEE-754 artifacts like 19.99 * 100.
645
+ */
646
+ function toCents(amount) {
647
+ if (!Number.isFinite(amount)) {
648
+ throw new Error(`Invalid amount: ${amount}`);
649
+ }
650
+ const sign = amount < 0 ? -1 : 1;
651
+ const [whole, fraction = '0'] = Math.abs(amount).toFixed(2).split('.');
652
+ return sign * (Number(whole) * 100 + Number(fraction));
653
+ }
654
+
590
655
  class BaseModel {
591
656
  get identifier() {
592
657
  const fields = this.constructor.identifiersFields.filter((field) => field !== 'identifier');
@@ -639,6 +704,8 @@ var Shops;
639
704
  Shops["MENSMARKET"] = "mensmarket";
640
705
  Shops["GLAMSHOP"] = "Glamshop";
641
706
  Shops["GLAMPOINTS"] = "Glampoints";
707
+ Shops["GLAMBEAUTY"] = "Glambeauty";
708
+ Shops["ELLA"] = "ella";
642
709
  Shops["ALL"] = "ALL";
643
710
  })(Shops || (Shops = {}));
644
711
 
@@ -673,12 +740,36 @@ class Category extends BaseModel {
673
740
  image: null,
674
741
  };
675
742
  }
743
+ get glamBeautyImages() {
744
+ return this.images?.[Shops.GLAMBEAUTY]
745
+ ? this.images[Shops.GLAMBEAUTY]
746
+ : {
747
+ brandBanner: null,
748
+ brandBannerMobile: null,
749
+ image: null,
750
+ };
751
+ }
752
+ get ellaImages() {
753
+ return this.images?.[Shops.ELLA]
754
+ ? this.images[Shops.ELLA]
755
+ : {
756
+ brandBanner: null,
757
+ brandBannerMobile: null,
758
+ image: null,
759
+ };
760
+ }
676
761
  get glamMetadata() {
677
762
  return this.metadatas.find((metadata) => metadata.shop === Shops.GLAMSHOP);
678
763
  }
679
764
  get mensMetadata() {
680
765
  return this.metadatas.find((metadata) => metadata.shop === Shops.MENSMARKET);
681
766
  }
767
+ get glamBeautyMetadata() {
768
+ return this.metadatas.find((metadata) => metadata.shop === Shops.GLAMBEAUTY);
769
+ }
770
+ get ellaMetadata() {
771
+ return this.metadatas.find((metadata) => metadata.shop === Shops.ELLA);
772
+ }
682
773
  getMostRelevantByShop(shop) {
683
774
  return this.mostRelevants?.[shop] || [];
684
775
  }
@@ -697,6 +788,30 @@ __decorate([
697
788
  ], Category.prototype, "filters", void 0);
698
789
  registerClass('Category', Category);
699
790
 
791
+ class BrandCategory extends BaseModel {
792
+ get glamImages() {
793
+ return this.images?.[Shops.GLAMSHOP]
794
+ ? this.images[Shops.GLAMSHOP]
795
+ : {
796
+ brandBanner: null,
797
+ brandBannerMobile: null,
798
+ image: null,
799
+ };
800
+ }
801
+ get mensImages() {
802
+ return this.images?.[Shops.MENSMARKET]
803
+ ? this.images[Shops.MENSMARKET]
804
+ : {
805
+ brandBanner: null,
806
+ brandBannerMobile: null,
807
+ image: null,
808
+ };
809
+ }
810
+ static get identifiersFields() {
811
+ return ['id'];
812
+ }
813
+ }
814
+
700
815
  class CategoryCollectionChildren extends BaseModel {
701
816
  static get identifiersFields() {
702
817
  return ['collectionId', 'categoryId'];
@@ -770,6 +885,11 @@ class ProductReview extends BaseModel {
770
885
  return ['id'];
771
886
  }
772
887
  }
888
+ __decorate([
889
+ Type(resolveClass('Product')),
890
+ __metadata("design:type", Function)
891
+ ], ProductReview.prototype, "product", void 0);
892
+ registerClass('ProductReview', ProductReview);
773
893
 
774
894
  class ProductBase extends BaseModel {
775
895
  get evaluation() {
@@ -834,28 +954,6 @@ __decorate([
834
954
  __metadata("design:type", Object)
835
955
  ], ProductErrors.prototype, "product", void 0);
836
956
 
837
- class ProductStockNotification extends BaseModel {
838
- static get identifiersFields() {
839
- return ['id'];
840
- }
841
- }
842
-
843
- class Wishlist extends Category {
844
- static get identifiersFields() {
845
- return ['id'];
846
- }
847
- }
848
-
849
- class Buy2Win extends BaseModel {
850
- static get identifiersFields() {
851
- return ['id'];
852
- }
853
- }
854
- __decorate([
855
- Type(() => Category),
856
- __metadata("design:type", Array)
857
- ], Buy2Win.prototype, "categories", void 0);
858
-
859
957
  var Where;
860
958
  (function (Where) {
861
959
  Where["EQUALS"] = "==";
@@ -882,6 +980,46 @@ var UpdateOptionActions;
882
980
  UpdateOptionActions["NULL"] = "null";
883
981
  })(UpdateOptionActions || (UpdateOptionActions = {}));
884
982
 
983
+ class ProductGroup extends BaseModel {
984
+ static get identifiersFields() {
985
+ return ['id'];
986
+ }
987
+ }
988
+
989
+ class ProductPriceLog extends BaseModel {
990
+ static get identifiersFields() {
991
+ return ['id'];
992
+ }
993
+ }
994
+
995
+ class ProductStockEntry extends BaseModel {
996
+ static get identifiersFields() {
997
+ return ['id'];
998
+ }
999
+ }
1000
+
1001
+ class ProductStockNotification extends BaseModel {
1002
+ static get identifiersFields() {
1003
+ return ['id'];
1004
+ }
1005
+ }
1006
+
1007
+ class Wishlist extends Category {
1008
+ static get identifiersFields() {
1009
+ return ['id'];
1010
+ }
1011
+ }
1012
+
1013
+ class Buy2Win extends BaseModel {
1014
+ static get identifiersFields() {
1015
+ return ['id'];
1016
+ }
1017
+ }
1018
+ __decorate([
1019
+ Type(() => Category),
1020
+ __metadata("design:type", Array)
1021
+ ], Buy2Win.prototype, "categories", void 0);
1022
+
885
1023
  class CampaignDashboard extends BaseModel {
886
1024
  static get identifiersFields() {
887
1025
  return ['id'];
@@ -1568,8 +1706,38 @@ var OrderStatus;
1568
1706
  OrderStatus["ENTREGUE"] = "Entregue";
1569
1707
  OrderStatus["CANCELADO"] = "Cancelado";
1570
1708
  OrderStatus["PENDENTE_REENVIO"] = "Pendente reenvio";
1709
+ OrderStatus["AGUARDANDO_STOCK_REENVIO"] = "Aguardando stock para reenvio";
1571
1710
  })(OrderStatus || (OrderStatus = {}));
1572
1711
 
1712
+ var ShoppingRecurrenceCycle;
1713
+ (function (ShoppingRecurrenceCycle) {
1714
+ ShoppingRecurrenceCycle[ShoppingRecurrenceCycle["MONTHLY"] = 1] = "MONTHLY";
1715
+ ShoppingRecurrenceCycle[ShoppingRecurrenceCycle["BIMONTHLY"] = 2] = "BIMONTHLY";
1716
+ ShoppingRecurrenceCycle[ShoppingRecurrenceCycle["QUARTERLY"] = 3] = "QUARTERLY";
1717
+ })(ShoppingRecurrenceCycle || (ShoppingRecurrenceCycle = {}));
1718
+
1719
+ var ShoppingRecurrenceEditionStatus;
1720
+ (function (ShoppingRecurrenceEditionStatus) {
1721
+ ShoppingRecurrenceEditionStatus["SCHEDULED"] = "scheduled";
1722
+ ShoppingRecurrenceEditionStatus["PAUSED"] = "paused";
1723
+ ShoppingRecurrenceEditionStatus["SKIPPED"] = "skipped";
1724
+ ShoppingRecurrenceEditionStatus["PROCESSING"] = "processing";
1725
+ ShoppingRecurrenceEditionStatus["FINISHED"] = "finished";
1726
+ ShoppingRecurrenceEditionStatus["PAYMENT_FAIL"] = "payment_fail";
1727
+ ShoppingRecurrenceEditionStatus["AWAITING_PAYMENT"] = "awaiting_payment";
1728
+ ShoppingRecurrenceEditionStatus["STOCK_VALIDATION"] = "stock_validation";
1729
+ ShoppingRecurrenceEditionStatus["CANCELLED"] = "cancelled";
1730
+ })(ShoppingRecurrenceEditionStatus || (ShoppingRecurrenceEditionStatus = {}));
1731
+
1732
+ var ShoppingRecurrenceStatus;
1733
+ (function (ShoppingRecurrenceStatus) {
1734
+ ShoppingRecurrenceStatus["ACTIVE"] = "active";
1735
+ ShoppingRecurrenceStatus["PAUSED"] = "paused";
1736
+ ShoppingRecurrenceStatus["CANCELLED"] = "cancelled";
1737
+ ShoppingRecurrenceStatus["PAYMENT_FAILED"] = "payment_failed";
1738
+ ShoppingRecurrenceStatus["WAITING_STOCK"] = "waiting_stock";
1739
+ })(ShoppingRecurrenceStatus || (ShoppingRecurrenceStatus = {}));
1740
+
1573
1741
  class Order extends Checkout {
1574
1742
  }
1575
1743
  __decorate([
@@ -1583,6 +1751,44 @@ class OrderBlocked extends BaseModel {
1583
1751
  }
1584
1752
  }
1585
1753
 
1754
+ class ShoppingRecurrence extends BaseModel {
1755
+ static get identifiersFields() {
1756
+ return ['id'];
1757
+ }
1758
+ }
1759
+ __decorate([
1760
+ Type(() => User),
1761
+ __metadata("design:type", User)
1762
+ ], ShoppingRecurrence.prototype, "user", void 0);
1763
+ __decorate([
1764
+ Type(() => UserAddress),
1765
+ __metadata("design:type", UserAddress)
1766
+ ], ShoppingRecurrence.prototype, "shippingAddress", void 0);
1767
+ __decorate([
1768
+ Type(() => UserAddress),
1769
+ __metadata("design:type", UserAddress)
1770
+ ], ShoppingRecurrence.prototype, "billingAddress", void 0);
1771
+ __decorate([
1772
+ Type(() => ShippingMethod),
1773
+ __metadata("design:type", ShippingMethod)
1774
+ ], ShoppingRecurrence.prototype, "shipping", void 0);
1775
+ __decorate([
1776
+ Type(() => Coupon),
1777
+ __metadata("design:type", Coupon)
1778
+ ], ShoppingRecurrence.prototype, "coupon", void 0);
1779
+
1780
+ class ShoppingRecurrenceEdition extends BaseModel {
1781
+ static get identifiersFields() {
1782
+ return ['id'];
1783
+ }
1784
+ }
1785
+
1786
+ class ShoppingRecurrenceErrorLog extends BaseModel {
1787
+ static get identifiersFields() {
1788
+ return ['id'];
1789
+ }
1790
+ }
1791
+
1586
1792
  class CheckoutSubscription extends BaseModel {
1587
1793
  static get identifiersFields() {
1588
1794
  return ['id'];
@@ -1605,11 +1811,27 @@ __decorate([
1605
1811
  __metadata("design:type", Coupon)
1606
1812
  ], CheckoutSubscription.prototype, "coupon", void 0);
1607
1813
 
1814
+ var ErrorsCode;
1815
+ (function (ErrorsCode) {
1816
+ ErrorsCode["genericError"] = "generic-error";
1817
+ ErrorsCode["businessError"] = "business-error";
1818
+ ErrorsCode["invalidCheckoutError"] = "invalid-checkout";
1819
+ ErrorsCode["stockLimit"] = "stock-limit";
1820
+ ErrorsCode["stockOut"] = "stock-out";
1821
+ ErrorsCode["notFound"] = "not-found";
1822
+ ErrorsCode["fraudPreventionInternal"] = "fraud-prevention-internal";
1823
+ ErrorsCode["fraudPreventionExternal"] = "fraud-prevention-external";
1824
+ ErrorsCode["invalidCardError"] = "invalid-card-error";
1825
+ ErrorsCode["insufficientFundsError"] = "insufficient-funds-error";
1826
+ ErrorsCode["paymentNotAuthorizedError"] = "payment-not-authorized-error";
1827
+ ErrorsCode["paymentError"] = "payment-error";
1828
+ })(ErrorsCode || (ErrorsCode = {}));
1829
+
1608
1830
  class BusinessError extends CustomError {
1609
- constructor(message, additionalData, type = '') {
1831
+ constructor(message, additionalData, type) {
1610
1832
  super(message);
1611
1833
  this.additionalData = additionalData;
1612
- this.type = type;
1834
+ this.type = type || ErrorsCode.businessError;
1613
1835
  }
1614
1836
  }
1615
1837
 
@@ -1620,10 +1842,10 @@ class DuplicatedResultsError extends CustomError {
1620
1842
  }
1621
1843
 
1622
1844
  class FraudValidationError extends CustomError {
1623
- constructor(message, additionalData) {
1845
+ constructor(message, type, additionalData) {
1624
1846
  super(message);
1625
1847
  this.additionalData = additionalData;
1626
- this.type = 'antifraud';
1848
+ this.type = type;
1627
1849
  }
1628
1850
  }
1629
1851
 
@@ -1633,17 +1855,26 @@ class InvalidArgumentError extends CustomError {
1633
1855
  }
1634
1856
  }
1635
1857
 
1858
+ class InvalidCheckoutError extends CustomError {
1859
+ constructor(message, additionalData) {
1860
+ super(message);
1861
+ this.additionalData = additionalData;
1862
+ this.type = ErrorsCode.invalidCheckoutError;
1863
+ }
1864
+ }
1865
+
1636
1866
  class NotFoundError extends CustomError {
1637
1867
  constructor(message) {
1638
1868
  super(message);
1869
+ this.type = ErrorsCode.notFound;
1639
1870
  }
1640
1871
  }
1641
1872
 
1642
1873
  class PaymentError extends CustomError {
1643
- constructor(message, additionalData) {
1874
+ constructor(message, type, additionalData) {
1644
1875
  super(message);
1645
1876
  this.additionalData = additionalData;
1646
- this.type = 'payment';
1877
+ this.type = type;
1647
1878
  }
1648
1879
  }
1649
1880
 
@@ -1658,14 +1889,14 @@ class RequiredArgumentError extends CustomError {
1658
1889
  class StockLimitError extends BusinessError {
1659
1890
  constructor(message, additionalData) {
1660
1891
  super(message, additionalData);
1661
- this.type = 'stock-limit';
1892
+ this.type = ErrorsCode.stockLimit;
1662
1893
  }
1663
1894
  }
1664
1895
 
1665
1896
  class StockOutError extends BusinessError {
1666
1897
  constructor(message, additionalData) {
1667
1898
  super(message, additionalData);
1668
- this.type = 'stock-out';
1899
+ this.type = ErrorsCode.stockOut;
1669
1900
  }
1670
1901
  }
1671
1902
 
@@ -1682,7 +1913,7 @@ class AntifraudBankSlipService {
1682
1913
  type: 'Boleto',
1683
1914
  limiteRange: 'day',
1684
1915
  });
1685
- throw new FraudValidationError('Boleto não autorizado para cliente não assinante', {
1916
+ throw new FraudValidationError('Boleto não autorizado para cliente não assinante', ErrorsCode.fraudPreventionInternal, {
1686
1917
  checkoutId: checkout.id,
1687
1918
  userEmail: checkout.user.email,
1688
1919
  info: {
@@ -1700,19 +1931,58 @@ class AntifraudCardService {
1700
1931
  constructor(orderRepository, orderBlockedRepository) {
1701
1932
  this.orderRepository = orderRepository;
1702
1933
  this.orderBlockedRepository = orderBlockedRepository;
1703
- this.LIMIT_ORDERS_DAY = 2;
1704
- this.LIMIT_ORDERS_WEEK = 7;
1705
- this.LIMIT_BLOCKED_ORDERS_DAY = 5;
1934
+ this.LIMIT_ORDERS_DAY = null;
1935
+ this.LIMIT_ORDERS_WEEK = null;
1706
1936
  }
1707
1937
  async validate(checkout, card) {
1938
+ this.setLimitsByUserType(checkout.user.isSubscriber);
1708
1939
  await this.validateBlockedOrderAttempts(checkout, card);
1709
1940
  await this.validateDayAndWeekOrderLimits(checkout, card);
1710
1941
  return true;
1711
1942
  }
1943
+ setLimitsByUserType(isSubscriber) {
1944
+ this.LIMIT_ORDERS_DAY = {
1945
+ subscriber: {
1946
+ cpf: 4,
1947
+ email: 4,
1948
+ phone: 4,
1949
+ card: 4,
1950
+ zip: 4,
1951
+ },
1952
+ nonSubscriber: {
1953
+ cpf: 2,
1954
+ email: 2,
1955
+ phone: 2,
1956
+ card: 2,
1957
+ zip: 2,
1958
+ },
1959
+ };
1960
+ this.LIMIT_ORDERS_WEEK = {
1961
+ subscriber: {
1962
+ cpf: 12,
1963
+ email: 12,
1964
+ phone: 12,
1965
+ card: 12,
1966
+ zip: Infinity,
1967
+ },
1968
+ nonSubscriber: {
1969
+ cpf: 7,
1970
+ email: 7,
1971
+ phone: 7,
1972
+ card: 7,
1973
+ zip: Infinity,
1974
+ },
1975
+ };
1976
+ this.LIMIT_BLOCKED_ORDERS_DAY = isSubscriber ? 7 : 5;
1977
+ }
1978
+ getLimitsByUserType(type, isSubscriber) {
1979
+ const limits = type === 'day' ? this.LIMIT_ORDERS_DAY : this.LIMIT_ORDERS_WEEK;
1980
+ return isSubscriber ? limits['subscriber'] : limits['nonSubscriber'];
1981
+ }
1712
1982
  async validateBlockedOrderAttempts(checkout, card) {
1713
1983
  const isValid = await this.verifyBlockedOrderAttempts(checkout, card);
1714
1984
  if (!isValid) {
1715
- throw new FraudValidationError('Cliente com mais de 5 compras negadas/bloqueadas no dia', {
1985
+ throw new FraudValidationError(`Cliente com mais de ${this.LIMIT_BLOCKED_ORDERS_DAY} compras negadas/bloqueadas no dia`, ErrorsCode.fraudPreventionInternal, {
1716
1986
  checkoutId: checkout.id,
1717
1987
  userEmail: checkout.user.email,
1718
1988
  info: {
@@ -1726,7 +1996,7 @@ class AntifraudCardService {
1726
1996
  async validateDayAndWeekOrderLimits(checkout, card) {
1727
1997
  const isValid = await this.verifyDayAndWeekOrders(checkout, card);
1728
1998
  if (!isValid) {
1729
- throw new FraudValidationError('Cliente tentando comprar mais de 2 vezes no dia ou 7 vezes na semana', {
1999
+ throw new FraudValidationError('Cliente tentando comprar mais do que o permitido no dia/semana', ErrorsCode.fraudPreventionInternal, {
1730
2000
  checkoutId: checkout.id,
1731
2001
  userEmail: checkout.user.email,
1732
2002
  info: {
@@ -1745,7 +2015,7 @@ class AntifraudCardService {
1745
2015
  await this.createBlockedOrderRecord({
1746
2016
  checkout,
1747
2017
  card,
1748
- reason: 'More than 5 attempts have failed',
2018
+ reason: `More than ${this.LIMIT_BLOCKED_ORDERS_DAY} attempts have failed`,
1749
2019
  key: 'Failed attempts',
1750
2020
  period: 'day',
1751
2021
  });
@@ -1754,15 +2024,17 @@ class AntifraudCardService {
1754
2024
  return true;
1755
2025
  }
1756
2026
  getTodayDateRange() {
1757
- const day = `${format(new Date(), 'yyyy-MM-dd')}T00:00:00`;
1758
- const endOfDay = `${format(new Date(), 'yyyy-MM-dd')}T23:59:59`;
1759
- return { day, endOfDay };
2027
+ const timeZone = 'America/Sao_Paulo';
2028
+ const today = utcToZonedTime(new Date(), timeZone);
2029
+ const day = startOfDay(today);
2030
+ const endOfDay$1 = endOfDay(today);
2031
+ return { day: addHours(day, 3), endOfDay: addHours(endOfDay$1, 3) };
1760
2032
  }
1761
2033
  async getBlockedOrdersByMultipleCriteria(checkout, dateRange) {
1762
2034
  const { day, endOfDay } = dateRange;
1763
2035
  const dateFilter = [
1764
- { operator: Where.GTE, value: new Date(day) },
1765
- { operator: Where.LTE, value: new Date(endOfDay) },
2036
+ { operator: Where.GTE, value: day },
2037
+ { operator: Where.LTE, value: endOfDay },
1766
2038
  ];
1767
2039
  const [ordersBlockedWithCpf, ordersBlockedWithEmail, ordersBlockedWithCep, ordersBlockedWithPhone] = await Promise.all([
1768
2040
  this.getBlockedOrdersByCpf(checkout.user?.cpf, dateFilter),
@@ -1864,26 +2136,28 @@ class AntifraudCardService {
1864
2136
  }
1865
2137
  async validateDayOrderLimits(checkout, params) {
1866
2138
  const ordersPerDay = await this.validateOrdersByRange(params, this.getDateRange('day'));
2139
+ const limits = this.getLimitsByUserType('day', checkout.user.isSubscriber);
1867
2140
  return this.checkOrderLimitsAndBlock({
1868
2141
  checkout,
1869
2142
  orderCounts: ordersPerDay,
1870
- limit: this.LIMIT_ORDERS_DAY,
2143
+ limit: limits,
1871
2144
  period: 'day',
1872
2145
  });
1873
2146
  }
1874
2147
  async validateWeekOrderLimits(checkout, params) {
1875
2148
  const ordersPerWeek = await this.validateOrdersByRange(params, this.getDateRange('week'));
2149
+ const limits = this.getLimitsByUserType('week', checkout.user.isSubscriber);
1876
2150
  return this.checkOrderLimitsAndBlock({
1877
2151
  checkout,
1878
2152
  orderCounts: ordersPerWeek,
1879
- limit: this.LIMIT_ORDERS_WEEK,
2153
+ limit: limits,
1880
2154
  period: 'week',
1881
2155
  });
1882
2156
  }
1883
2157
  async checkOrderLimitsAndBlock(params) {
1884
2158
  const { checkout, orderCounts, limit, period } = params;
1885
2159
  for (const key in orderCounts) {
1886
- if (orderCounts[key] >= limit) {
2160
+ if (orderCounts[key] >= limit[key]) {
1887
2161
  await this.createBlockedOrderRecord({
1888
2162
  checkout,
1889
2163
  card: null,
@@ -2149,6 +2423,7 @@ var ShopPageName;
2149
2423
  ShopPageName["LP_GLAMQUEENS"] = "LP_GLAMQUEENS";
2150
2424
  ShopPageName["LP_INVITE"] = "LP_INVITE";
2151
2425
  ShopPageName["LP_LIVELO"] = "LP_LIVELO";
2426
+ ShopPageName["GLAM_NEW_HOME"] = "GLAM_NEW_HOME";
2152
2427
  })(ShopPageName || (ShopPageName = {}));
2153
2428
 
2154
2429
  class BeautyQuestionsHelper {
@@ -2214,16 +2489,100 @@ class Home extends BaseModel {
2214
2489
  }
2215
2490
  }
2216
2491
 
2492
+ class ShopConfigs extends BaseModel {
2493
+ static get identifiersFields() {
2494
+ return ['id'];
2495
+ }
2496
+ }
2497
+
2217
2498
  class ShopMenu extends BaseModel {
2218
2499
  static get identifiersFields() {
2219
2500
  return ['id'];
2220
2501
  }
2221
2502
  }
2222
2503
 
2504
+ var ShopPageSectionType;
2505
+ (function (ShopPageSectionType) {
2506
+ ShopPageSectionType["LIVE"] = "LIVE";
2507
+ ShopPageSectionType["CAROUSEL"] = "CAROUSEL";
2508
+ ShopPageSectionType["BANNER"] = "BANNER";
2509
+ ShopPageSectionType["INFOBARS"] = "INFOBARS";
2510
+ ShopPageSectionType["HIGHLIGHTS"] = "HIGHLIGHTS";
2511
+ ShopPageSectionType["SUBSCRIBER_INFO"] = "SUBSCRIBER_INFO";
2512
+ ShopPageSectionType["COLLECTION"] = "COLLECTION";
2513
+ ShopPageSectionType["BEAUTY_PROFILE_COLLECTION"] = "BEAUTY_PROFILE_COLLECTION";
2514
+ ShopPageSectionType["PLANS"] = "PLANS";
2515
+ ShopPageSectionType["SINGLE_PLAN"] = "SINGLE_PLAN";
2516
+ ShopPageSectionType["BRANDS"] = "BRANDS";
2517
+ ShopPageSectionType["NEWSLETTER"] = "NEWSLETTER";
2518
+ })(ShopPageSectionType || (ShopPageSectionType = {}));
2519
+
2520
+ /* eslint-disable max-lines-per-function */
2223
2521
  class ShopSettings extends BaseModel {
2224
2522
  static get identifiersFields() {
2225
2523
  return ['id'];
2226
2524
  }
2525
+ getPageSections(displayRules) {
2526
+ const now = new Date();
2527
+ return (Array.isArray(this.sections) ? this.sections : [])
2528
+ .map((section) => {
2529
+ // Filtra banners dentro de carrousel
2530
+ if (section.type === ShopPageSectionType.CAROUSEL && Array.isArray(section.banners)) {
2531
+ const filteredBanners = section.banners.filter((banner) => {
2532
+ // Filtra por displayRules
2533
+ const rulesMatch = banner.displayRules.length
2534
+ ? banner.displayRules.some((rule) => Object.keys(rule).every((key) => rule[key] === displayRules[key]))
2535
+ : true;
2536
+ // Filtra por publishDate e expirationDate
2537
+ const publishOk = !banner.publishDate || now >= new Date(banner.publishDate);
2538
+ const expireOk = !banner.expirationDate || now <= new Date(banner.expirationDate);
2539
+ return rulesMatch && publishOk && expireOk;
2540
+ });
2541
+ return { ...section, banners: filteredBanners };
2542
+ }
2543
+ // Filtra highlights
2544
+ if (section.type === ShopPageSectionType.HIGHLIGHTS && Array.isArray(section.highlights)) {
2545
+ const filteredHighlights = section.highlights.filter((highlight) => {
2546
+ // Filtra por displayRules
2547
+ const rulesMatch = highlight.displayRules.length
2548
+ ? highlight.displayRules.some((rule) => Object.keys(rule).every((key) => rule[key] === displayRules[key]))
2549
+ : true;
2550
+ return rulesMatch;
2551
+ });
2552
+ const sortedHighlights = !displayRules.beautyProfile
2553
+ ? filteredHighlights.sort((a, b) => (a.starred === b.starred ? 0 : a.starred ? -1 : 1))
2554
+ : filteredHighlights;
2555
+ return { ...section, highlights: sortedHighlights };
2556
+ }
2557
+ // Filtra collections
2558
+ if (section.type === ShopPageSectionType.COLLECTION) {
2559
+ const rulesMatch = section.displayRules.length
2560
+ ? section.displayRules.some((rule) => Object.keys(rule).every((key) => rule[key] === displayRules[key]))
2561
+ : true;
2562
+ const publishOk = !section.publishDate || now >= new Date(section.publishDate);
2563
+ const expireOk = !section.expirationDate || now <= new Date(section.expirationDate);
2564
+ return rulesMatch && publishOk && expireOk ? section : null;
2565
+ }
2566
+ // Filtra banners
2567
+ if (section.type === ShopPageSectionType.BANNER) {
2568
+ const rulesMatch = section.displayRules.length
2569
+ ? section.displayRules.some((rule) => Object.keys(rule).every((key) => rule[key] === displayRules[key]))
2570
+ : true;
2571
+ const publishOk = !section.publishDate || now >= new Date(section.publishDate);
2572
+ const expireOk = !section.expirationDate || now <= new Date(section.expirationDate);
2573
+ return rulesMatch && publishOk && expireOk ? section : null;
2574
+ }
2575
+ if (section.type === ShopPageSectionType.LIVE) {
2576
+ return section.active ? section : null;
2577
+ }
2578
+ if (section.type === ShopPageSectionType.PLANS || section.type === ShopPageSectionType.SINGLE_PLAN) {
2579
+ return displayRules.notSubscriber ? section : null;
2580
+ }
2581
+ // Demais seções retornam normalmente
2582
+ return section;
2583
+ })
2584
+ .filter(Boolean);
2585
+ }
2227
2586
  }
2228
2587
 
2229
2588
  class AdyenBlockedOrderHelper {
@@ -2235,14 +2594,14 @@ class AdyenBlockedOrderHelper {
2235
2594
  limiteRange: 'day',
2236
2595
  card: params.card,
2237
2596
  });
2238
- throw new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', {
2597
+ throw new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', ErrorsCode.paymentError, {
2239
2598
  checkoutId: params.checkout.id,
2240
2599
  userEmail: params.checkout.user.email,
2241
2600
  info: params.adyenResponse,
2242
2601
  });
2243
2602
  }
2244
2603
  static createPaymentError(checkout, errorInfo) {
2245
- return new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', {
2604
+ return new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', ErrorsCode.paymentError, {
2246
2605
  checkoutId: checkout.id,
2247
2606
  userEmail: checkout.user.email,
2248
2607
  info: errorInfo,
@@ -2350,11 +2709,39 @@ class AdyenCardAxiosAdapter {
2350
2709
  }
2351
2710
  }
2352
2711
 
2712
+ function resolveCacheConfig(cache) {
2713
+ if (isNil(cache) || typeof cache !== 'object')
2714
+ return undefined;
2715
+ const candidate = cache;
2716
+ const cacheAdapter = candidate.cacheAdapter;
2717
+ if (!cacheAdapter)
2718
+ return undefined;
2719
+ if (!isCacheAdapter(cacheAdapter))
2720
+ return undefined;
2721
+ if (typeof cacheAdapter.isConfigured === 'function' && !cacheAdapter.isConfigured()) {
2722
+ return undefined;
2723
+ }
2724
+ return {
2725
+ cacheAdapter,
2726
+ ttlDefault: candidate.ttlDefault,
2727
+ };
2728
+ }
2729
+ function isCacheAdapter(adapter) {
2730
+ return (typeof adapter.get === 'function' &&
2731
+ typeof adapter.set === 'function' &&
2732
+ typeof adapter.remove === 'function' &&
2733
+ typeof adapter.clear === 'function');
2734
+ }
2735
+
2353
2736
  class RestCacheAdapter {
2354
2737
  constructor(config) {
2738
+ this.client = null;
2355
2739
  this.logger = new DebugHelper('RestCacheAdapter');
2740
+ this.configured = this.isValidBaseURL(config.baseURL);
2741
+ if (!this.configured)
2742
+ return;
2356
2743
  this.client = axios.create({
2357
- baseURL: config.baseURL,
2744
+ baseURL: config.baseURL.trim(),
2358
2745
  headers: {
2359
2746
  'Content-Type': 'application/json',
2360
2747
  ...(isNil(config.authToken) ? {} : { Authorization: `Bearer ${config.authToken}` }),
@@ -2362,7 +2749,12 @@ class RestCacheAdapter {
2362
2749
  },
2363
2750
  });
2364
2751
  }
2752
+ isConfigured() {
2753
+ return this.configured;
2754
+ }
2365
2755
  async set(options) {
2756
+ if (!this.client)
2757
+ return false;
2366
2758
  try {
2367
2759
  const response = await this.client.post('/redis/set', {
2368
2760
  key: options.key,
@@ -2378,6 +2770,8 @@ class RestCacheAdapter {
2378
2770
  }
2379
2771
  }
2380
2772
  async get(key) {
2773
+ if (!this.client)
2774
+ return null;
2381
2775
  try {
2382
2776
  const response = await this.client.post('/redis/get', {
2383
2777
  key,
@@ -2394,6 +2788,8 @@ class RestCacheAdapter {
2394
2788
  }
2395
2789
  }
2396
2790
  async remove(key) {
2791
+ if (!this.client)
2792
+ return false;
2397
2793
  try {
2398
2794
  const response = await this.client.post('/redis/del', {
2399
2795
  key,
@@ -2407,6 +2803,8 @@ class RestCacheAdapter {
2407
2803
  }
2408
2804
  }
2409
2805
  async clear() {
2806
+ if (!this.client)
2807
+ return false;
2410
2808
  try {
2411
2809
  const response = await this.client.post('/redis/flushdb', {});
2412
2810
  return response.data.success;
@@ -2417,6 +2815,9 @@ class RestCacheAdapter {
2417
2815
  return false;
2418
2816
  }
2419
2817
  }
2818
+ isValidBaseURL(baseURL) {
2819
+ return isString(baseURL) && baseURL.trim().length > 0;
2820
+ }
2420
2821
  }
2421
2822
 
2422
2823
  class AxiosAdapter {
@@ -4701,6 +5102,17 @@ const withCrudFirestore = (MixinBase) => {
4701
5102
  };
4702
5103
  };
4703
5104
 
5105
+ class BrandCategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
5106
+ constructor({ firestore, interceptors, }) {
5107
+ super({
5108
+ firestore,
5109
+ collectionName: 'brandsCategory',
5110
+ model: BrandCategory,
5111
+ interceptors,
5112
+ });
5113
+ }
5114
+ }
5115
+
4704
5116
  class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4705
5117
  constructor({ firestore, interceptors }) {
4706
5118
  super({
@@ -4776,6 +5188,9 @@ class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFire
4776
5188
  isChild(_id, _parentId) {
4777
5189
  return;
4778
5190
  }
5191
+ async getBrandsWithProducts() {
5192
+ return;
5193
+ }
4779
5194
  }
4780
5195
  __decorate([
4781
5196
  Log(),
@@ -4989,6 +5404,18 @@ class HomeFirestoreRepository extends withCrudFirestore(withHelpers(withFirestor
4989
5404
  }
4990
5405
  }
4991
5406
 
5407
+ class ShopConfigsFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
5408
+ constructor({ firestore, interceptors, cache, }) {
5409
+ super({
5410
+ firestore,
5411
+ collectionName: 'shopConfigs',
5412
+ model: ShopConfigs,
5413
+ interceptors,
5414
+ cache,
5415
+ });
5416
+ }
5417
+ }
5418
+
4992
5419
  class ShopMenuFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4993
5420
  constructor({ firestore, interceptors, cache, }) {
4994
5421
  super({
@@ -5182,6 +5609,7 @@ class OrderBlockedFirestoreRepository extends withCrudFirestore(withHelpers(with
5182
5609
  card,
5183
5610
  checkout,
5184
5611
  date: new Date(),
5612
+ gatewayInfo: params.gatewayInfo || {},
5185
5613
  }));
5186
5614
  }
5187
5615
  formatZip(zip) {
@@ -5203,6 +5631,74 @@ class PaymentFirestoreRepository extends withCrudFirestore(withHelpers(withFires
5203
5631
  }
5204
5632
  }
5205
5633
 
5634
+ class ShoppingRecurrenceEditionFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
5635
+ constructor({ firestore, interceptors, cache, }) {
5636
+ super({
5637
+ firestore,
5638
+ collectionName: 'shoppingRecurrenceEditions',
5639
+ model: ShoppingRecurrenceEdition,
5640
+ interceptors,
5641
+ cache,
5642
+ });
5643
+ }
5644
+ }
5645
+
5646
+ class ShoppingRecurrenceErrorLogFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
5647
+ constructor({ firestore, interceptors, cache, }) {
5648
+ super({
5649
+ firestore,
5650
+ collectionName: 'shoppingRecurrenceErrorLogs',
5651
+ model: ShoppingRecurrenceErrorLog,
5652
+ interceptors,
5653
+ cache,
5654
+ });
5655
+ }
5656
+ }
5657
+
5658
+ class ShoppingRecurrenceFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
5659
+ constructor({ firestore, interceptors, cache, }) {
5660
+ super({
5661
+ firestore,
5662
+ collectionName: 'shoppingRecurrences',
5663
+ model: ShoppingRecurrence,
5664
+ interceptors,
5665
+ cache,
5666
+ });
5667
+ }
5668
+ async findByUserId(userId) {
5669
+ const result = await this.find({
5670
+ filters: {
5671
+ user: {
5672
+ id: userId,
5673
+ },
5674
+ },
5675
+ });
5676
+ return result.data;
5677
+ }
5678
+ async findByUserIdAndStatus(userId, status) {
5679
+ const result = await this.find({
5680
+ filters: {
5681
+ user: {
5682
+ id: userId,
5683
+ },
5684
+ status,
5685
+ },
5686
+ });
5687
+ return result.data;
5688
+ }
5689
+ async findByUserAndShop(userId, shop) {
5690
+ const result = await this.find({
5691
+ filters: {
5692
+ user: {
5693
+ id: userId,
5694
+ },
5695
+ shop,
5696
+ },
5697
+ });
5698
+ return result.data;
5699
+ }
5700
+ }
5701
+
5206
5702
  class SubscriptionPlanFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
5207
5703
  constructor({ firestore, interceptors, cache, }) {
5208
5704
  super({
@@ -5668,7 +6164,7 @@ function createHasuraGraphQLClass(MixinBase) {
5668
6164
  this.model = options.model;
5669
6165
  this.fields = options.fields || this.model.identifiersFields;
5670
6166
  this.logger = DebugHelper.from(this);
5671
- this.cache = options.cache;
6167
+ this.cache = resolveCacheConfig(options.cache);
5672
6168
  }
5673
6169
  get headers() {
5674
6170
  return HasuraAuthHelper.buildHeaders(this.authOptions);
@@ -5786,7 +6282,10 @@ __decorate([
5786
6282
  __metadata("design:type", Product)
5787
6283
  ], KitProductHasuraGraphQL.prototype, "product", void 0);
5788
6284
 
5789
- class ProductHasuraGraphQL extends Product {
6285
+ class ProductCatalogHasuraGraphQL extends Product {
6286
+ }
6287
+
6288
+ class ProductHasuraGraphQL extends Product {
5790
6289
  }
5791
6290
  __decorate([
5792
6291
  Type(() => KitProductHasuraGraphQL),
@@ -5803,6 +6302,9 @@ __decorate([
5803
6302
  __metadata("design:type", Object)
5804
6303
  ], ProductErrorsHasuraGraphQL.prototype, "product", void 0);
5805
6304
 
6305
+ class ProductStockEntryHasuraGraphQL extends ProductStockEntry {
6306
+ }
6307
+
5806
6308
  class CategoryCollectionChildrenHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5807
6309
  constructor({ endpoint, authOptions, interceptors, cache, }) {
5808
6310
  super({
@@ -6689,6 +7191,8 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
6689
7191
  mostRelevants: mostRelevants || {
6690
7192
  [Shops.GLAMSHOP]: null,
6691
7193
  [Shops.MENSMARKET]: null,
7194
+ [Shops.GLAMBEAUTY]: null,
7195
+ [Shops.ELLA]: null,
6692
7196
  },
6693
7197
  images: images || {
6694
7198
  [Shops.GLAMSHOP]: {
@@ -6701,6 +7205,16 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
6701
7205
  brandBannerMobile: null,
6702
7206
  image: null,
6703
7207
  },
7208
+ [Shops.GLAMBEAUTY]: {
7209
+ brandBanner: null,
7210
+ brandBannerMobile: null,
7211
+ image: null,
7212
+ },
7213
+ [Shops.ELLA]: {
7214
+ brandBanner: null,
7215
+ brandBannerMobile: null,
7216
+ image: null,
7217
+ },
6704
7218
  },
6705
7219
  });
6706
7220
  }
@@ -6874,6 +7388,19 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
6874
7388
  categoryFilterRepository: this.categoryFilterRepository,
6875
7389
  });
6876
7390
  }
7391
+ async getBrandsWithProducts() {
7392
+ const fields = ['id', 'name', 'slug', 'brand_category', 'published', 'images'];
7393
+ const { brands_with_products_query: data, } = await this.query('brands_with_products_query', fields);
7394
+ return data.map((brand) => Category.toInstance({
7395
+ id: brand.id,
7396
+ name: brand.name,
7397
+ slug: brand.slug,
7398
+ brandCategory: brand.brand_category,
7399
+ shops: brand.shops,
7400
+ published: brand.published,
7401
+ images: brand.images,
7402
+ }));
7403
+ }
6877
7404
  }
6878
7405
  __decorate([
6879
7406
  Log(),
@@ -6988,6 +7515,26 @@ class CategoryProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withH
6988
7515
  },
6989
7516
  });
6990
7517
  }
7518
+ async removeProductFromAllCategories(productId) {
7519
+ this.logger = DebugHelper.from(this, 'removeProductFromAllCategories');
7520
+ await this.mutation('delete_category_product', ['affected_rows'], {
7521
+ where: {
7522
+ type: 'category_product_bool_exp',
7523
+ required: true,
7524
+ value: { product_id: { _eq: productId } },
7525
+ },
7526
+ });
7527
+ }
7528
+ async removeCategoryFromAllProducts(categoryId) {
7529
+ this.logger = DebugHelper.from(this, 'removeCategoryFromAllProducts');
7530
+ await this.mutation('delete_category_product', ['affected_rows'], {
7531
+ where: {
7532
+ type: 'category_product_bool_exp',
7533
+ required: true,
7534
+ value: { category_id: { _eq: categoryId } },
7535
+ },
7536
+ });
7537
+ }
6991
7538
  }
6992
7539
 
6993
7540
  const fieldsConfiguration$3 = [
@@ -7138,83 +7685,7 @@ class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasu
7138
7685
  }
7139
7686
  }
7140
7687
 
7141
- class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7142
- constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7143
- super({
7144
- tableName: 'product_errors',
7145
- model: ProductErrorsHasuraGraphQL,
7146
- endpoint,
7147
- authOptions,
7148
- interceptors,
7149
- cache,
7150
- fields: [
7151
- {
7152
- productId: {
7153
- columnName: 'product_id',
7154
- to: (value) => +value,
7155
- from: (value) => value.toString(),
7156
- },
7157
- },
7158
- 'source',
7159
- 'error',
7160
- { createdAt: { columnName: 'created_at' } },
7161
- { updatedAt: { columnName: 'updated_at' } },
7162
- {
7163
- product: {
7164
- columnName: 'product',
7165
- foreignKeyColumn: { id: 'productId' },
7166
- fields: [
7167
- { id: { columnName: 'id', from: (value) => value.toString() } },
7168
- { productId: { columnName: 'main_product_id' } },
7169
- 'name',
7170
- 'published',
7171
- 'group',
7172
- 'validity',
7173
- { createdAt: { columnName: 'created_at' } },
7174
- { updatedAt: { columnName: 'updated_at' } },
7175
- ],
7176
- },
7177
- },
7178
- ],
7179
- });
7180
- this.productRepository = productRepository;
7181
- }
7182
- async get(params) {
7183
- const result = await super.get(params);
7184
- if (result instanceof VariantHasuraGraphQL) {
7185
- const product = await this.productRepository.get({ id: result.productId.toString() });
7186
- result.product.name = product.name;
7187
- result.product.group = product.group;
7188
- }
7189
- return result;
7190
- }
7191
- async find(params) {
7192
- const result = await super.find(params);
7193
- const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
7194
- (isEmpty(item.product.name) || isEmpty(item.product.group) || isEmpty(item.product)));
7195
- if (variantsWithNoData.length > 0) {
7196
- const { data: products } = await this.productRepository.find({
7197
- filters: {
7198
- id: {
7199
- operator: Where.IN,
7200
- value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
7201
- },
7202
- },
7203
- });
7204
- products.forEach((product) => {
7205
- result.data
7206
- .filter((variant) => variant.product.productId?.toString() === product.id.toString())
7207
- .forEach((variant) => {
7208
- variant.product.name = product.name;
7209
- variant.product.group = product.group;
7210
- });
7211
- });
7212
- }
7213
- return result;
7214
- }
7215
- }
7216
-
7217
- const commonFields = [
7688
+ const commonFields$1 = [
7218
7689
  {
7219
7690
  id: {
7220
7691
  columnName: 'id',
@@ -7294,6 +7765,12 @@ const commonFields = [
7294
7765
  to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7295
7766
  },
7296
7767
  },
7768
+ {
7769
+ imagesCard: {
7770
+ columnName: 'images_card',
7771
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7772
+ },
7773
+ },
7297
7774
  'name',
7298
7775
  {
7299
7776
  price: {
@@ -7355,7 +7832,6 @@ const commonFields = [
7355
7832
  'weight',
7356
7833
  'gender',
7357
7834
  { intGender: { columnName: 'int_gender' } },
7358
- // { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
7359
7835
  { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
7360
7836
  { isKit: { columnName: 'is_kit' } },
7361
7837
  { createdAt: { columnName: 'created_at' } },
@@ -7372,151 +7848,707 @@ const commonFields = [
7372
7848
  },
7373
7849
  },
7374
7850
  'group',
7851
+ { groupId: { columnName: 'group_id' } },
7375
7852
  'validity',
7376
7853
  { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
7377
7854
  { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
7378
7855
  { daysOfUse: { columnName: 'days_of_use' } },
7856
+ { showVariants: { columnName: 'show_variants' } },
7857
+ { variantSlug: { columnName: 'variant_slug' } },
7379
7858
  ];
7380
- const fieldsConfiguration$2 = [
7381
- ...commonFields,
7382
- {
7383
- categories: {
7384
- columnName: 'categories',
7385
- fields: ['category_id'],
7386
- bindPersistData: (value) => ({
7387
- categories: { data: value.map((category) => ({ category_id: +category })) },
7388
- }),
7389
- to: (categories) => categories.map((categoryId) => +categoryId),
7390
- from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
7391
- },
7392
- },
7393
- {
7394
- kitProducts: {
7395
- columnName: 'kit_products',
7396
- foreignKeyColumn: { productId: 'id' },
7397
- fields: [
7398
- { productId: { columnName: 'product_id' } },
7399
- { kitProductId: { columnName: 'kit_product_id' } },
7400
- 'quantity',
7401
- { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
7402
- ],
7403
- },
7404
- },
7405
- {
7406
- reviews: {
7407
- columnName: 'reviews',
7408
- foreignKeyColumn: { product_id: 'id' },
7409
- fields: [
7410
- 'id',
7411
- 'shop',
7412
- 'rate',
7413
- 'author',
7414
- 'email',
7415
- 'location',
7416
- 'review',
7417
- 'status',
7418
- 'title',
7419
- { personId: { columnName: 'person_id' } },
7420
- 'points',
7421
- { orderId: { columnName: 'order_id' } },
7422
- { createdAt: { columnName: 'created_at' } },
7423
- { updatedAt: { columnName: 'updated_at' } },
7424
- ],
7425
- },
7426
- },
7427
- {
7428
- metadata: {
7429
- columnName: 'metadata',
7430
- fields: ['title', 'description'],
7431
- bindPersistData: (value) => ({
7432
- metadata: { data: value },
7433
- }),
7434
- },
7435
- },
7436
- {
7437
- variants: {
7438
- columnName: 'variants',
7439
- foreignKeyColumn: { product_id: 'id' },
7440
- fields: [
7441
- 'id',
7442
- 'ean',
7443
- 'grade',
7444
- 'price',
7445
- 'published',
7446
- 'stock',
7447
- { tagsCollection: { columnName: 'tags_collection' } },
7448
- { tagsProfile: { columnName: 'tags_profile' } },
7449
- ],
7450
- },
7451
- },
7452
- ];
7453
- class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7454
- get reviewsFields() {
7455
- return [
7456
- 'id',
7457
- 'shop',
7458
- 'rate',
7459
- 'author',
7460
- 'email',
7461
- 'location',
7462
- 'review',
7463
- 'status',
7464
- 'title',
7465
- { personId: { columnName: 'person_id' } },
7466
- 'points',
7467
- { orderId: { columnName: 'order_id' } },
7468
- { createdAt: { columnName: 'created_at' } },
7469
- { updatedAt: { columnName: 'updated_at' } },
7470
- ];
7471
- }
7859
+ class ProductCatalogHasuraGraphQLRepository extends withFindHasuraGraphQL(withHasuraGraphQL(Base)) {
7472
7860
  constructor({ endpoint, authOptions, interceptors, cache, }) {
7473
7861
  super({
7474
- tableName: 'product',
7475
- model: ProductHasuraGraphQL,
7862
+ tableName: 'product_catalog',
7863
+ model: ProductCatalogHasuraGraphQL,
7476
7864
  endpoint,
7477
7865
  authOptions,
7478
7866
  interceptors,
7479
- fields: fieldsConfiguration$2,
7867
+ fields: commonFields$1,
7480
7868
  cache,
7481
7869
  });
7482
- this.bindReviewToModel = (plain) => ProductReview.toInstance({
7483
- ...is(omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id'])),
7484
- createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at,
7485
- updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at,
7486
- personId: plain.person_id,
7487
- orderId: plain.order_id,
7488
- });
7489
- this.bindReviewToHasura = (review) => ({
7490
- ...is(omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId'])),
7491
- person_id: review.personId,
7492
- order_id: review.orderId,
7493
- });
7494
7870
  }
7495
- async create(params) {
7496
- const { metadata, ...data } = params;
7497
- const product = await super.create(omit({ ...data, metadata: metadata || { description: null, title: null } }, ['reviews']));
7498
- try {
7499
- product.reviews = data.reviews && (await this.updateReviews(+product.id, data));
7871
+ async get({ id }, options) {
7872
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7873
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7874
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7875
+ if (cachedData) {
7876
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7877
+ return this.model.toInstance(deserialize(cachedData));
7878
+ }
7500
7879
  }
7501
- catch (error) {
7502
- await this.delete({ id: product.id });
7503
- throw error;
7880
+ const product = await super
7881
+ .find({
7882
+ filters: {
7883
+ id,
7884
+ },
7885
+ limits: {
7886
+ limit: 1,
7887
+ },
7888
+ })
7889
+ .then((res) => res.data.at(0));
7890
+ if (!product)
7891
+ throw new NotFoundError(`Product not found`);
7892
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7893
+ const cacheKey = `${this.model.name.toLowerCase()}:id:${id}`;
7894
+ await this.cache.cacheAdapter.set({
7895
+ key: cacheKey,
7896
+ data: serialize(product),
7897
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7898
+ });
7899
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7504
7900
  }
7505
7901
  return product;
7506
7902
  }
7507
- async get(identifiers, options) {
7508
- const product = Number.isNaN(+identifiers.id)
7509
- ? (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
7510
- .data?.[0]
7511
- : await super.get(identifiers, options);
7512
- if (product.productId)
7513
- throw new NotFoundError('Product not found, it is a variant');
7514
- product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, options));
7515
- return product;
7516
- }
7517
- async find(params, optionsParams) {
7518
- const { filters, fields, ...options } = params || {};
7519
- const bindFields = fields ||
7903
+ async getByEAN(EAN, options) {
7904
+ if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7905
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7906
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
7907
+ if (cachedData) {
7908
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
7909
+ return this.model.toInstance(deserialize(cachedData));
7910
+ }
7911
+ }
7912
+ const product = await super
7913
+ .find({
7914
+ filters: {
7915
+ EAN,
7916
+ },
7917
+ limits: {
7918
+ limit: 1,
7919
+ },
7920
+ })
7921
+ .then((res) => res.data.at(0));
7922
+ if (!product)
7923
+ return null;
7924
+ RoundProductPricesHelper.roundProductPrices(product);
7925
+ if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7926
+ const cacheKey = `${this.model.name.toLowerCase()}:EAN:${EAN}`;
7927
+ await this.cache.cacheAdapter.set({
7928
+ key: cacheKey,
7929
+ data: serialize(product),
7930
+ expirationInSeconds: options?.cache?.ttl || this.cache.ttlDefault,
7931
+ });
7932
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
7933
+ }
7934
+ return product;
7935
+ }
7936
+ async find(params, optionsParams) {
7937
+ const { filters, fields, ...options } = params || {};
7938
+ const bindFields = fields ||
7939
+ this.fields
7940
+ .map((field) => (typeof field === 'string' ? field : Object.keys(field).shift()))
7941
+ .filter((field) => field !== 'reviews' && field !== 'categories');
7942
+ if (options.options?.minimal?.includes('price'))
7943
+ options.options?.minimal.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
7944
+ if (options.options?.maximum?.includes('price'))
7945
+ options.options?.maximum.push('price.price', 'price.fullPrice', 'price.subscriberPrice');
7946
+ options.options?.minimal?.splice(options.options?.minimal.indexOf('price'), 1);
7947
+ options.options?.maximum?.splice(options.options?.maximum.indexOf('price'), 1);
7948
+ return super.find({
7949
+ ...options,
7950
+ filters: { ...filters },
7951
+ fields: [
7952
+ ...bindFields,
7953
+ ...(bindFields.includes('price')
7954
+ ? [
7955
+ 'subscriberPrice',
7956
+ 'subscriberDiscountPercentage',
7957
+ 'fullPrice',
7958
+ ]
7959
+ : []),
7960
+ ],
7961
+ }, optionsParams);
7962
+ }
7963
+ async findCatalog(params, mainGender, options) {
7964
+ const result = await this.find({
7965
+ ...params,
7966
+ filters: { ...params.filters, published: true },
7967
+ orderBy: {
7968
+ hasStock: 'desc',
7969
+ ...(!mainGender ? {} : { intGender: mainGender === 'female' ? 'desc' : 'asc' }),
7970
+ ...omit(params.orderBy, ['hasStock', 'intGender']),
7971
+ },
7972
+ }, options);
7973
+ return result;
7974
+ }
7975
+ }
7976
+ __decorate([
7977
+ Log(),
7978
+ __metadata("design:type", Function),
7979
+ __metadata("design:paramtypes", [Object, Object, Object]),
7980
+ __metadata("design:returntype", Promise)
7981
+ ], ProductCatalogHasuraGraphQLRepository.prototype, "findCatalog", null);
7982
+
7983
+ class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7984
+ constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
7985
+ super({
7986
+ tableName: 'product_errors',
7987
+ model: ProductErrorsHasuraGraphQL,
7988
+ endpoint,
7989
+ authOptions,
7990
+ interceptors,
7991
+ cache,
7992
+ fields: [
7993
+ {
7994
+ productId: {
7995
+ columnName: 'product_id',
7996
+ to: (value) => +value,
7997
+ from: (value) => value.toString(),
7998
+ },
7999
+ },
8000
+ 'source',
8001
+ 'error',
8002
+ { createdAt: { columnName: 'created_at' } },
8003
+ { updatedAt: { columnName: 'updated_at' } },
8004
+ {
8005
+ product: {
8006
+ columnName: 'product',
8007
+ foreignKeyColumn: { id: 'productId' },
8008
+ fields: [
8009
+ { id: { columnName: 'id', from: (value) => value.toString() } },
8010
+ { productId: { columnName: 'main_product_id' } },
8011
+ 'name',
8012
+ 'published',
8013
+ 'group',
8014
+ 'validity',
8015
+ { createdAt: { columnName: 'created_at' } },
8016
+ { updatedAt: { columnName: 'updated_at' } },
8017
+ ],
8018
+ },
8019
+ },
8020
+ ],
8021
+ });
8022
+ this.productRepository = productRepository;
8023
+ }
8024
+ async get(params) {
8025
+ const result = await super.get(params);
8026
+ if (result instanceof VariantHasuraGraphQL) {
8027
+ const product = await this.productRepository.get({ id: result.productId.toString() });
8028
+ result.product.name = product.name;
8029
+ result.product.group = product.group;
8030
+ }
8031
+ return result;
8032
+ }
8033
+ async find(params) {
8034
+ const result = await super.find(params);
8035
+ const variantsWithNoData = result.data.filter((item) => item.product instanceof VariantHasuraGraphQL &&
8036
+ (isEmpty(item.product.name) || isEmpty(item.product.group) || isEmpty(item.product)));
8037
+ if (variantsWithNoData.length > 0) {
8038
+ const { data: products } = await this.productRepository.find({
8039
+ filters: {
8040
+ id: {
8041
+ operator: Where.IN,
8042
+ value: Array.from(new Set(variantsWithNoData.map((item) => item.product.productId?.toString()))),
8043
+ },
8044
+ },
8045
+ });
8046
+ products.forEach((product) => {
8047
+ result.data
8048
+ .filter((variant) => variant.product.productId?.toString() === product.id.toString())
8049
+ .forEach((variant) => {
8050
+ variant.product.name = product.name;
8051
+ variant.product.group = product.group;
8052
+ });
8053
+ });
8054
+ }
8055
+ return result;
8056
+ }
8057
+ }
8058
+
8059
+ class ProductGroupHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8060
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
8061
+ super({
8062
+ tableName: 'group',
8063
+ model: ProductGroup,
8064
+ endpoint,
8065
+ authOptions,
8066
+ interceptors,
8067
+ fields: [
8068
+ {
8069
+ id: {
8070
+ columnName: 'id',
8071
+ to: (value) => +value,
8072
+ from: (value) => value.toString(),
8073
+ },
8074
+ },
8075
+ 'name',
8076
+ 'description',
8077
+ { markupMin: { columnName: 'markup_min' } },
8078
+ { markupWithoutCompetitor: { columnName: 'markup_without_competitor' } },
8079
+ { discountCompetitor: { columnName: 'discount_competitor' } },
8080
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
8081
+ { dynamicPrecification: { columnName: 'dynamic_precification' } },
8082
+ { createdAt: { columnName: 'created_at' } },
8083
+ { updatedAt: { columnName: 'updated_at' } },
8084
+ ],
8085
+ cache,
8086
+ });
8087
+ }
8088
+ }
8089
+
8090
+ const commonFields = [
8091
+ {
8092
+ id: {
8093
+ columnName: 'id',
8094
+ to: (value) => +value,
8095
+ from: (value) => value.toString(),
8096
+ },
8097
+ },
8098
+ { firestoreId: { columnName: 'firestore_id' } },
8099
+ { productId: { columnName: 'main_product_id' } },
8100
+ { CEST: { columnName: 'cest' } },
8101
+ { EAN: { columnName: 'ean' } },
8102
+ { NCM: { columnName: 'ncm' } },
8103
+ 'brand',
8104
+ { costPrice: { columnName: 'cost_price' } },
8105
+ {
8106
+ description: {
8107
+ columnName: 'description',
8108
+ from: (description, data) => ({
8109
+ description,
8110
+ differentials: data.differentials,
8111
+ whoMustUse: data.who_must_use,
8112
+ howToUse: data.how_to_use,
8113
+ brand: data.brand_description,
8114
+ ingredients: data.ingredients,
8115
+ purpose: data.purpose,
8116
+ }),
8117
+ bindFindFilter: (filters) => {
8118
+ return {
8119
+ ...(filters?.description && { description: filters.description }),
8120
+ ...(filters.differentials && { differentials: filters.differentials }),
8121
+ ...(filters.whoMustUse && {
8122
+ who_must_use: filters.whoMustUse,
8123
+ }),
8124
+ ...(filters.howToUse && {
8125
+ how_to_use: filters.howToUse,
8126
+ }),
8127
+ ...(filters.brand && {
8128
+ brand_description: filters.brand,
8129
+ }),
8130
+ ...(filters.ingredients && {
8131
+ ingredients: filters.ingredients,
8132
+ }),
8133
+ ...(filters.purpose && {
8134
+ purpose: filters.purpose,
8135
+ }),
8136
+ };
8137
+ },
8138
+ bindPersistData: (descriptionData) => ({
8139
+ ...(descriptionData?.description && { description: descriptionData.description }),
8140
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
8141
+ ...(descriptionData.whoMustUse && {
8142
+ who_must_use: descriptionData.whoMustUse,
8143
+ }),
8144
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
8145
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
8146
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
8147
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
8148
+ }),
8149
+ },
8150
+ },
8151
+ { differentials: { columnName: 'differentials' } },
8152
+ { whoMustUse: { columnName: 'who_must_use' } },
8153
+ { howToUse: { columnName: 'how_to_use' } },
8154
+ { brandDescription: { columnName: 'brand_description' } },
8155
+ { ingredients: { columnName: 'ingredients' } },
8156
+ { purpose: { columnName: 'purpose' } },
8157
+ { hasVariants: { columnName: 'has_variants' } },
8158
+ {
8159
+ images: {
8160
+ columnName: 'images',
8161
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8162
+ },
8163
+ },
8164
+ {
8165
+ miniatures: {
8166
+ columnName: 'miniatures',
8167
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8168
+ },
8169
+ },
8170
+ {
8171
+ imagesCard: {
8172
+ columnName: 'images_card',
8173
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8174
+ },
8175
+ },
8176
+ 'name',
8177
+ {
8178
+ price: {
8179
+ columnName: 'price',
8180
+ from: (price, data) => ({
8181
+ price,
8182
+ fullPrice: data.full_price,
8183
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
8184
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
8185
+ subscriberPrice: data.subscriber_price,
8186
+ }),
8187
+ bindFindFilter: (filters) => {
8188
+ return {
8189
+ ...((filters?.price || filters?.price === 0) && { price: filters.price }),
8190
+ ...((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice }),
8191
+ ...((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
8192
+ subscriber_discount_percentage: filters.subscriberDiscountPercentage,
8193
+ }),
8194
+ ...((filters.subscriberPrice || filters.subscriberPrice === 0) && {
8195
+ subscriber_price: filters.subscriberPrice,
8196
+ }),
8197
+ ...((filters.fullPriceDiscountPercentage || filters.fullPriceDiscountPercentage === 0) && {
8198
+ full_price_discount_percentage: filters.fullPriceDiscountPercentage,
8199
+ }),
8200
+ };
8201
+ },
8202
+ bindPersistData: (priceData) => ({
8203
+ ...(priceData?.price >= 0 && { price: priceData.price }),
8204
+ ...(priceData.fullPrice >= 0 && { full_price: priceData.fullPrice }),
8205
+ ...(priceData.subscriberDiscountPercentage >= 0 && {
8206
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
8207
+ }),
8208
+ ...(priceData.subscriberPrice >= 0 && { subscriber_price: priceData.subscriberPrice }),
8209
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
8210
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
8211
+ }),
8212
+ }),
8213
+ },
8214
+ },
8215
+ { fullPrice: { columnName: 'full_price' } },
8216
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
8217
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
8218
+ { subscriberPrice: { columnName: 'subscriber_price' } },
8219
+ 'published',
8220
+ 'outlet',
8221
+ 'label',
8222
+ 'sku',
8223
+ {
8224
+ stock: {
8225
+ columnName: 'stock',
8226
+ from: (quantity) => ({ quantity }),
8227
+ to: (value) => (isNil(value?.quantity) ? value : value?.quantity),
8228
+ },
8229
+ },
8230
+ { hasStock: { columnName: 'has_stock' } },
8231
+ 'slug',
8232
+ 'type',
8233
+ 'video',
8234
+ 'weight',
8235
+ 'gender',
8236
+ { intGender: { columnName: 'int_gender' } },
8237
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
8238
+ { isKit: { columnName: 'is_kit' } },
8239
+ { createdAt: { columnName: 'created_at' } },
8240
+ { updatedAt: { columnName: 'updated_at' } },
8241
+ { rate: { columnName: 'rating' } },
8242
+ { reviewsTotal: { columnName: 'reviews_total' } },
8243
+ { shoppingCount: { columnName: 'shopping_count' } },
8244
+ { categoryId: { columnName: 'category_id' } },
8245
+ {
8246
+ category: {
8247
+ columnName: 'category',
8248
+ foreignKeyColumn: { id: 'categoryId' },
8249
+ fields: ['id', 'name', 'reference', 'slug'],
8250
+ },
8251
+ },
8252
+ 'group',
8253
+ { groupId: { columnName: 'group_id' } },
8254
+ 'validity',
8255
+ { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
8256
+ { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
8257
+ { tagsSupply: { columnName: 'tags_supply', type: HasuraGraphQLColumnType.Jsonb } },
8258
+ { daysOfUse: { columnName: 'days_of_use' } },
8259
+ { showVariants: { columnName: 'show_variants' } },
8260
+ { variantSlug: { columnName: 'variant_slug' } },
8261
+ { caixariaMinima: { columnName: 'caixaria_minima', type: HasuraGraphQLColumnType.Jsonb } },
8262
+ 'suppliers',
8263
+ 'curve',
8264
+ ];
8265
+ const fieldsConfiguration$2 = [
8266
+ ...commonFields,
8267
+ {
8268
+ categories: {
8269
+ columnName: 'categories',
8270
+ fields: ['category_id'],
8271
+ bindPersistData: (value) => ({
8272
+ categories: { data: value.map((category) => ({ category_id: +category })) },
8273
+ }),
8274
+ to: (categories) => categories.map((categoryId) => +categoryId),
8275
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
8276
+ },
8277
+ },
8278
+ {
8279
+ kitProducts: {
8280
+ columnName: 'kit_products',
8281
+ foreignKeyColumn: { productId: 'id' },
8282
+ fields: [
8283
+ { productId: { columnName: 'product_id' } },
8284
+ { kitProductId: { columnName: 'kit_product_id' } },
8285
+ 'quantity',
8286
+ { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
8287
+ ],
8288
+ },
8289
+ },
8290
+ {
8291
+ reviews: {
8292
+ columnName: 'reviews',
8293
+ foreignKeyColumn: { product_id: 'id' },
8294
+ fields: [
8295
+ 'id',
8296
+ 'shop',
8297
+ 'rate',
8298
+ 'author',
8299
+ 'email',
8300
+ 'location',
8301
+ 'review',
8302
+ 'status',
8303
+ 'title',
8304
+ { personId: { columnName: 'person_id' } },
8305
+ 'points',
8306
+ { orderId: { columnName: 'order_id' } },
8307
+ { createdAt: { columnName: 'created_at' } },
8308
+ { updatedAt: { columnName: 'updated_at' } },
8309
+ ],
8310
+ },
8311
+ },
8312
+ {
8313
+ metadata: {
8314
+ columnName: 'metadata',
8315
+ fields: ['title', 'description'],
8316
+ bindPersistData: (value) => ({
8317
+ metadata: { data: value },
8318
+ }),
8319
+ },
8320
+ },
8321
+ {
8322
+ variants: {
8323
+ columnName: 'variants',
8324
+ foreignKeyColumn: { product_id: 'id' },
8325
+ fields: [
8326
+ 'id',
8327
+ 'name',
8328
+ 'ean',
8329
+ 'sku',
8330
+ {
8331
+ description: {
8332
+ columnName: 'description',
8333
+ from: (description, data) => ({
8334
+ description,
8335
+ differentials: data.differentials,
8336
+ whoMustUse: data.who_must_use,
8337
+ howToUse: data.how_to_use,
8338
+ brand: data.brand_description,
8339
+ ingredients: data.ingredients,
8340
+ purpose: data.purpose,
8341
+ }),
8342
+ bindFindFilter: (filters) => {
8343
+ return {
8344
+ ...(filters?.description && { description: filters.description }),
8345
+ ...(filters.differentials && { differentials: filters.differentials }),
8346
+ ...(filters.whoMustUse && {
8347
+ who_must_use: filters.whoMustUse,
8348
+ }),
8349
+ ...(filters.howToUse && {
8350
+ how_to_use: filters.howToUse,
8351
+ }),
8352
+ ...(filters.brand && {
8353
+ brand_description: filters.brand,
8354
+ }),
8355
+ ...(filters.ingredients && {
8356
+ ingredients: filters.ingredients,
8357
+ }),
8358
+ ...(filters.purpose && {
8359
+ purpose: filters.purpose,
8360
+ }),
8361
+ };
8362
+ },
8363
+ bindPersistData: (descriptionData) => ({
8364
+ ...(descriptionData?.description && { description: descriptionData.description }),
8365
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
8366
+ ...(descriptionData.whoMustUse && {
8367
+ who_must_use: descriptionData.whoMustUse,
8368
+ }),
8369
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
8370
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
8371
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
8372
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
8373
+ }),
8374
+ },
8375
+ },
8376
+ { differentials: { columnName: 'differentials' } },
8377
+ { whoMustUse: { columnName: 'who_must_use' } },
8378
+ { howToUse: { columnName: 'how_to_use' } },
8379
+ { brandDescription: { columnName: 'brand_description' } },
8380
+ { ingredients: { columnName: 'ingredients' } },
8381
+ { purpose: { columnName: 'purpose' } },
8382
+ {
8383
+ grade: {
8384
+ columnName: 'grade',
8385
+ type: HasuraGraphQLColumnType.Jsonb,
8386
+ },
8387
+ },
8388
+ {
8389
+ price: {
8390
+ columnName: 'price',
8391
+ from: (price, data) => ({
8392
+ price,
8393
+ fullPrice: data.full_price,
8394
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
8395
+ subscriberPrice: data.subscriber_price,
8396
+ fullPriceDiscountPercentage: data.full_price_discount_percentage,
8397
+ }),
8398
+ bindPersistData: (priceData) => ({
8399
+ ...((priceData?.price || 0) >= 0 && { price: priceData.price }),
8400
+ ...((priceData?.fullPrice || 0) >= 0 && { full_price: priceData.fullPrice }),
8401
+ ...((priceData?.subscriberDiscountPercentage || 0) >= 0 && {
8402
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
8403
+ }),
8404
+ ...((priceData?.subscriberPrice || 0) >= 0 && { subscriber_price: priceData.subscriberPrice }),
8405
+ ...(priceData.fullPriceDiscountPercentage >= 0 && {
8406
+ full_price_discount_percentage: priceData.fullPriceDiscountPercentage,
8407
+ }),
8408
+ }),
8409
+ },
8410
+ },
8411
+ { fullPrice: { columnName: 'full_price' } },
8412
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
8413
+ { subscriberPrice: { columnName: 'subscriber_price' } },
8414
+ { fullPriceDiscountPercentage: { columnName: 'full_price_discount_percentage' } },
8415
+ 'published',
8416
+ {
8417
+ stock: {
8418
+ columnName: 'stock',
8419
+ from: (quantity) => ({ quantity }),
8420
+ to: (value) => (isNil(value?.quantity) ? value : value?.quantity),
8421
+ },
8422
+ },
8423
+ {
8424
+ images: {
8425
+ columnName: 'images',
8426
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8427
+ },
8428
+ },
8429
+ {
8430
+ miniatures: {
8431
+ columnName: 'miniatures',
8432
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8433
+ },
8434
+ },
8435
+ {
8436
+ imagesCard: {
8437
+ columnName: 'images_card',
8438
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8439
+ },
8440
+ },
8441
+ { tagsProfile: { columnName: 'tags_profile' } },
8442
+ { tagsCollection: { columnName: 'tags_collection' } },
8443
+ { variantSlug: { columnName: 'variant_slug' } },
8444
+ {
8445
+ reviews: {
8446
+ columnName: 'reviews',
8447
+ foreignKeyColumn: { product_id: 'id' },
8448
+ fields: [
8449
+ 'id',
8450
+ 'shop',
8451
+ 'rate',
8452
+ 'author',
8453
+ 'email',
8454
+ 'location',
8455
+ 'review',
8456
+ 'status',
8457
+ 'title',
8458
+ { personId: { columnName: 'person_id' } },
8459
+ 'points',
8460
+ { orderId: { columnName: 'order_id' } },
8461
+ { createdAt: { columnName: 'created_at' } },
8462
+ { updatedAt: { columnName: 'updated_at' } },
8463
+ ],
8464
+ },
8465
+ },
8466
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
8467
+ {
8468
+ metadata: {
8469
+ columnName: 'metadata',
8470
+ fields: ['title', 'description'],
8471
+ bindPersistData: (value) => ({
8472
+ metadata: { data: value },
8473
+ }),
8474
+ },
8475
+ },
8476
+ ],
8477
+ },
8478
+ },
8479
+ ];
8480
+ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8481
+ get reviewsFields() {
8482
+ return [
8483
+ 'id',
8484
+ 'shop',
8485
+ 'rate',
8486
+ 'author',
8487
+ 'email',
8488
+ 'location',
8489
+ 'review',
8490
+ 'status',
8491
+ 'title',
8492
+ { personId: { columnName: 'person_id' } },
8493
+ 'points',
8494
+ { orderId: { columnName: 'order_id' } },
8495
+ { createdAt: { columnName: 'created_at' } },
8496
+ { updatedAt: { columnName: 'updated_at' } },
8497
+ ];
8498
+ }
8499
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
8500
+ super({
8501
+ tableName: 'product',
8502
+ model: ProductHasuraGraphQL,
8503
+ endpoint,
8504
+ authOptions,
8505
+ interceptors,
8506
+ fields: fieldsConfiguration$2,
8507
+ cache,
8508
+ });
8509
+ this.bindReviewToModel = (plain) => ProductReview.toInstance({
8510
+ ...is(omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id'])),
8511
+ createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at,
8512
+ updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at,
8513
+ personId: plain.person_id,
8514
+ orderId: plain.order_id,
8515
+ });
8516
+ this.bindReviewToHasura = (review) => ({
8517
+ ...is(omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId'])),
8518
+ person_id: review.personId,
8519
+ order_id: review.orderId,
8520
+ });
8521
+ }
8522
+ async create(params) {
8523
+ const { metadata, ...data } = params;
8524
+ const product = await super.create(omit({ ...data, metadata: metadata || { description: null, title: null } }, ['reviews']));
8525
+ try {
8526
+ product.reviews = data.reviews && (await this.updateReviews(+product.id, data));
8527
+ }
8528
+ catch (error) {
8529
+ await this.delete({ id: product.id });
8530
+ throw error;
8531
+ }
8532
+ return product;
8533
+ }
8534
+ async get(identifiers, options) {
8535
+ const product = Number.isNaN(+identifiers.id)
8536
+ ? (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
8537
+ .data?.[0]
8538
+ : await super.get(identifiers, options);
8539
+ if (product.productId)
8540
+ throw new NotFoundError('Product not found, it is a variant');
8541
+ product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, false, options));
8542
+ if (!product.variants?.length) {
8543
+ for (const [index, variant] of product.variants.entries()) {
8544
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8545
+ }
8546
+ }
8547
+ return product;
8548
+ }
8549
+ async find(params, optionsParams) {
8550
+ const { filters, fields, ...options } = params || {};
8551
+ const bindFields = fields ||
7520
8552
  this.fields
7521
8553
  .map((field) => (typeof field === 'string' ? field : Object.keys(field).shift()))
7522
8554
  .filter((field) => field !== 'reviews' && field !== 'categories');
@@ -7553,6 +8585,9 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7553
8585
  const result = await this.find({
7554
8586
  filters: {
7555
8587
  slug,
8588
+ productId: {
8589
+ operator: Where.ISNULL,
8590
+ },
7556
8591
  },
7557
8592
  fields: this.fields.map((field) => typeof field === 'string' ? field : Object.keys(field).shift()),
7558
8593
  options: {
@@ -7562,6 +8597,11 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7562
8597
  if (!result.data.length)
7563
8598
  return null;
7564
8599
  const product = result?.data?.shift();
8600
+ if (!product.variants?.length) {
8601
+ for (const [index, variant] of product.variants.entries()) {
8602
+ product.variants[index].reviews = await this.findReviewsByProduct(+variant.id, true);
8603
+ }
8604
+ }
7565
8605
  RoundProductPricesHelper.roundProductPrices(product);
7566
8606
  if (this.cache?.cacheAdapter && options?.cache?.enabled && product) {
7567
8607
  const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
@@ -7741,7 +8781,8 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7741
8781
  const plainData = this.paramsToPlain({ metadata });
7742
8782
  if (!plainData.metadata)
7743
8783
  return null;
7744
- await this.mutation('update_product_metadata_by_pk', ['product_id'], {
8784
+ // eslint-disable-next-line @typescript-eslint/naming-convention
8785
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
7745
8786
  pk_columns: {
7746
8787
  value: { product_id: productId },
7747
8788
  type: 'product_metadata_pk_columns_input',
@@ -7753,6 +8794,14 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7753
8794
  required: true,
7754
8795
  },
7755
8796
  });
8797
+ if (!update_product_metadata_by_pk) {
8798
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
8799
+ objects: {
8800
+ type: '[product_metadata_insert_input!]!',
8801
+ value: [{ product_id: productId, ...metadata }],
8802
+ },
8803
+ });
8804
+ }
7756
8805
  return plainData.metadata;
7757
8806
  }
7758
8807
  async getId(id) {
@@ -7763,7 +8812,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7763
8812
  return data?.[0]?.id;
7764
8813
  throw new NotFoundError(`Product with id ${id} not found`);
7765
8814
  }
7766
- async findReviewsByProduct(productId, options) {
8815
+ async findReviewsByProduct(productId, onlyApproved, options) {
7767
8816
  if (this.cache?.cacheAdapter && options?.cache?.enabled) {
7768
8817
  const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
7769
8818
  const cachedData = await this.cache.cacheAdapter.get(cacheKey);
@@ -7776,10 +8825,16 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
7776
8825
  where: {
7777
8826
  value: {
7778
8827
  product_id: { _eq: productId },
8828
+ ...(onlyApproved && { status: { _eq: true } }),
7779
8829
  },
7780
8830
  type: 'product_review_bool_exp',
7781
8831
  required: true,
7782
8832
  },
8833
+ order_by: {
8834
+ type: '[product_review_order_by]',
8835
+ value: [{ createdAt: 'desc' }],
8836
+ required: true,
8837
+ },
7783
8838
  });
7784
8839
  const reviews = data?.map((review) => this.bindReviewToModel(review));
7785
8840
  if (this.cache?.cacheAdapter && options?.cache?.enabled && reviews) {
@@ -7884,10 +8939,53 @@ __decorate([
7884
8939
  __decorate([
7885
8940
  Log(),
7886
8941
  __metadata("design:type", Function),
7887
- __metadata("design:paramtypes", [Number, Object]),
8942
+ __metadata("design:paramtypes", [Number, Boolean, Object]),
7888
8943
  __metadata("design:returntype", Promise)
7889
8944
  ], ProductHasuraGraphQLRepository.prototype, "findReviewsByProduct", null);
7890
8945
 
8946
+ class ProductPriceLogHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8947
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
8948
+ super({
8949
+ tableName: 'product_price_log',
8950
+ model: ProductPriceLog,
8951
+ endpoint,
8952
+ authOptions,
8953
+ interceptors,
8954
+ fields: [
8955
+ {
8956
+ id: {
8957
+ columnName: 'id',
8958
+ to: (value) => +value,
8959
+ from: (value) => value.toString(),
8960
+ },
8961
+ },
8962
+ { productId: { columnName: 'product_id' } },
8963
+ { productEAN: { columnName: 'product_ean' } },
8964
+ { productSKU: { columnName: 'product_sku' } },
8965
+ { productName: { columnName: 'product_name' } },
8966
+ { productCostPrice: { columnName: 'product_cost_price' } },
8967
+ { productPrice: { columnName: 'product_price' } },
8968
+ { productSubscriberPrice: { columnName: 'product_subscriber_price' } },
8969
+ { productSubscriberDiscountPercentage: { columnName: 'product_subscriber_discount_percentage' } },
8970
+ { markupMin: { columnName: 'markup_min' } },
8971
+ { markupWithoutCompetitor: { columnName: 'markup_without_competitor' } },
8972
+ { discountCompetitor: { columnName: 'discount_competitor' } },
8973
+ { minViablePrice: { columnName: 'min_viable_price' } },
8974
+ { targetPrice: { columnName: 'target_price' } },
8975
+ { groupId: { columnName: 'group_id' } },
8976
+ { competitorsAndPrices: { columnName: 'competitors_and_prices', type: HasuraGraphQLColumnType.Jsonb } },
8977
+ { competitorsPrices: { columnName: 'competitors_prices', type: HasuraGraphQLColumnType.Jsonb } },
8978
+ { competitorsMinPrice: { columnName: 'competitors_min_price' } },
8979
+ { competitorsSellerMinPrice: { columnName: 'competitors_seller_min_price' } },
8980
+ { statusPrecificacao: { columnName: 'status_precificacao' } },
8981
+ { createdAt: { columnName: 'created_at' } },
8982
+ { updatedAt: { columnName: 'updated_at' } },
8983
+ ],
8984
+ cache,
8985
+ });
8986
+ }
8987
+ }
8988
+
7891
8989
  class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7892
8990
  constructor({ endpoint, authOptions, interceptors, cache, }) {
7893
8991
  super({
@@ -7916,7 +9014,25 @@ class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHas
7916
9014
  product: {
7917
9015
  columnName: 'product',
7918
9016
  foreignKeyColumn: { id: 'productId' },
7919
- fields: ['id', 'ean', 'sku', 'name', 'brand', 'slug', 'images', 'grade', 'gender'],
9017
+ fields: [
9018
+ 'id',
9019
+ {
9020
+ productId: {
9021
+ columnName: 'main_product_id',
9022
+ to: (value) => +value,
9023
+ from: (value) => value?.toString(),
9024
+ },
9025
+ },
9026
+ 'ean',
9027
+ 'sku',
9028
+ 'name',
9029
+ 'brand',
9030
+ 'slug',
9031
+ 'images',
9032
+ 'grade',
9033
+ 'gender',
9034
+ '',
9035
+ ],
7920
9036
  },
7921
9037
  },
7922
9038
  ],
@@ -7961,6 +9077,33 @@ __decorate([
7961
9077
  __metadata("design:returntype", void 0)
7962
9078
  ], ProductReviewHasuraGraphQLRepository.prototype, "disaproveReview", null);
7963
9079
 
9080
+ class ProductStockEntryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
9081
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
9082
+ super({
9083
+ tableName: 'product_millenium_stock_entry',
9084
+ model: ProductStockEntry,
9085
+ endpoint,
9086
+ authOptions,
9087
+ interceptors,
9088
+ cache,
9089
+ fields: [
9090
+ 'id',
9091
+ { productId: { columnName: 'product_id' } },
9092
+ { codProduct: { columnName: 'cod_product' } },
9093
+ { productDescription: { columnName: 'product_description' } },
9094
+ { eventDescription: { columnName: 'event_description' } },
9095
+ { invoiceValue: { columnName: 'invoice_value' } },
9096
+ 'price',
9097
+ 'quantity',
9098
+ { invoiceId: { columnName: 'invoice_id' } },
9099
+ { nfeKey: { columnName: 'nfe_key' } },
9100
+ 'batch',
9101
+ { createdAt: { columnName: 'created_at' } },
9102
+ ],
9103
+ });
9104
+ }
9105
+ }
9106
+
7964
9107
  class ProductStockNotificationHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
7965
9108
  constructor({ endpoint, authOptions, interceptors, cache, }) {
7966
9109
  super({
@@ -8109,12 +9252,153 @@ const fieldsConfiguration$1 = [
8109
9252
  },
8110
9253
  },
8111
9254
  'group',
9255
+ { groupId: { columnName: 'group_id' } },
9256
+ 'type',
8112
9257
  'validity',
8113
- // { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
8114
9258
  'published',
8115
9259
  { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
8116
9260
  { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
9261
+ { tagsSupply: { columnName: 'tags_supply', type: HasuraGraphQLColumnType.Jsonb } },
8117
9262
  { daysOfUse: { columnName: 'days_of_use' } },
9263
+ {
9264
+ images: {
9265
+ columnName: 'images',
9266
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
9267
+ },
9268
+ },
9269
+ {
9270
+ miniatures: {
9271
+ columnName: 'miniatures',
9272
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
9273
+ },
9274
+ },
9275
+ {
9276
+ imagesCard: {
9277
+ columnName: 'images_card',
9278
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
9279
+ },
9280
+ },
9281
+ 'slug',
9282
+ 'brand',
9283
+ 'name',
9284
+ 'sku',
9285
+ { NCM: { columnName: 'ncm' } },
9286
+ { CEST: { columnName: 'cest' } },
9287
+ {
9288
+ description: {
9289
+ columnName: 'description',
9290
+ from: (description, data) => ({
9291
+ description,
9292
+ differentials: data.differentials,
9293
+ whoMustUse: data.who_must_use,
9294
+ howToUse: data.how_to_use,
9295
+ brand: data.brand_description,
9296
+ ingredients: data.ingredients,
9297
+ purpose: data.purpose,
9298
+ }),
9299
+ bindFindFilter: (filters) => {
9300
+ return {
9301
+ ...(filters?.description && { description: filters.description }),
9302
+ ...(filters.differentials && { differentials: filters.differentials }),
9303
+ ...(filters.whoMustUse && {
9304
+ who_must_use: filters.whoMustUse,
9305
+ }),
9306
+ ...(filters.howToUse && {
9307
+ how_to_use: filters.howToUse,
9308
+ }),
9309
+ ...(filters.brand && {
9310
+ brand_description: filters.brand,
9311
+ }),
9312
+ ...(filters.ingredients && {
9313
+ ingredients: filters.ingredients,
9314
+ }),
9315
+ ...(filters.purpose && {
9316
+ purpose: filters.purpose,
9317
+ }),
9318
+ };
9319
+ },
9320
+ bindPersistData: (descriptionData) => ({
9321
+ ...(descriptionData?.description && { description: descriptionData.description }),
9322
+ ...(descriptionData.differentials && { differentials: descriptionData.differentials }),
9323
+ ...(descriptionData.whoMustUse && {
9324
+ who_must_use: descriptionData.whoMustUse,
9325
+ }),
9326
+ ...(descriptionData.howToUse && { how_to_use: descriptionData.howToUse }),
9327
+ ...(descriptionData.brand && { brand_description: descriptionData.brand }),
9328
+ ...(descriptionData.ingredients && { ingredients: descriptionData.ingredients }),
9329
+ ...(descriptionData.purpose && { purpose: descriptionData.purpose }),
9330
+ }),
9331
+ },
9332
+ },
9333
+ { differentials: { columnName: 'differentials' } },
9334
+ { whoMustUse: { columnName: 'who_must_use' } },
9335
+ { howToUse: { columnName: 'how_to_use' } },
9336
+ { brandDescription: { columnName: 'brand_description' } },
9337
+ { ingredients: { columnName: 'ingredients' } },
9338
+ { purpose: { columnName: 'purpose' } },
9339
+ 'gender',
9340
+ { intGender: { columnName: 'int_gender' } },
9341
+ 'label',
9342
+ { filters: { columnName: 'filters', type: HasuraGraphQLColumnType.Jsonb } },
9343
+ { rate: { columnName: 'rating' } },
9344
+ { reviewsTotal: { columnName: 'reviews_total' } },
9345
+ { shoppingCount: { columnName: 'shopping_count' } },
9346
+ { categoryId: { columnName: 'category_id' } },
9347
+ {
9348
+ category: {
9349
+ columnName: 'category',
9350
+ foreignKeyColumn: { id: 'categoryId' },
9351
+ fields: ['id', 'name', 'reference', 'slug'],
9352
+ },
9353
+ },
9354
+ {
9355
+ categories: {
9356
+ columnName: 'categories',
9357
+ fields: ['category_id'],
9358
+ bindPersistData: (value) => ({
9359
+ categories: { data: value.map((category) => ({ category_id: +category })) },
9360
+ }),
9361
+ to: (categories) => categories.map((categoryId) => +categoryId),
9362
+ from: (categories) => categories?.map((category) => category?.category_id?.toString()) || [],
9363
+ },
9364
+ },
9365
+ {
9366
+ metadata: {
9367
+ columnName: 'metadata',
9368
+ fields: ['title', 'description'],
9369
+ bindPersistData: (value) => ({
9370
+ metadata: { data: value },
9371
+ }),
9372
+ },
9373
+ },
9374
+ {
9375
+ reviews: {
9376
+ columnName: 'reviews',
9377
+ foreignKeyColumn: { product_id: 'id' },
9378
+ fields: [
9379
+ 'id',
9380
+ 'shop',
9381
+ 'rate',
9382
+ 'author',
9383
+ 'email',
9384
+ 'location',
9385
+ 'review',
9386
+ 'status',
9387
+ 'title',
9388
+ { personId: { columnName: 'person_id' } },
9389
+ 'points',
9390
+ { orderId: { columnName: 'order_id' } },
9391
+ { createdAt: { columnName: 'created_at' } },
9392
+ { updatedAt: { columnName: 'updated_at' } },
9393
+ ],
9394
+ },
9395
+ },
9396
+ { variantSlug: { columnName: 'variant_slug' } },
9397
+ { caixariaMinima: { columnName: 'caixaria_minima', type: HasuraGraphQLColumnType.Jsonb } },
9398
+ 'suppliers',
9399
+ 'curve',
9400
+ { createdAt: { columnName: 'created_at' } },
9401
+ { updatedAt: { columnName: 'updated_at' } },
8118
9402
  ];
8119
9403
  class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8120
9404
  constructor({ endpoint, authOptions, interceptors, cache, }) {
@@ -8155,17 +9439,45 @@ class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
8155
9439
  return data.at(0);
8156
9440
  }
8157
9441
  async update(params) {
8158
- const { productId, id: checkId, ...data } = params;
9442
+ const { productId, id: checkId, metadata, ...data } = params;
8159
9443
  const dataWithProductId = this.paramsToPlain({ id: checkId, productId });
8160
9444
  if (!dataWithProductId.id) {
8161
9445
  throw new NotFoundError('Variant ID is required for update');
8162
9446
  }
8163
9447
  const id = await this.getId(dataWithProductId.id);
8164
9448
  const product = await super.update({ id, ...data });
9449
+ product.metadata = metadata && (await this.updateMetadata(+id, { metadata }));
8165
9450
  if (dataWithProductId.productId) {
8166
9451
  product.productId = dataWithProductId.productId;
8167
9452
  }
8168
- return product;
9453
+ return product;
9454
+ }
9455
+ async updateMetadata(productId, { metadata }) {
9456
+ const plainData = this.paramsToPlain({ metadata });
9457
+ if (!plainData.metadata)
9458
+ return null;
9459
+ // eslint-disable-next-line @typescript-eslint/naming-convention
9460
+ const { update_product_metadata_by_pk } = await this.mutation('update_product_metadata_by_pk', ['product_id'], {
9461
+ pk_columns: {
9462
+ value: { product_id: productId },
9463
+ type: 'product_metadata_pk_columns_input',
9464
+ required: true,
9465
+ },
9466
+ _set: {
9467
+ value: omit(metadata, ['product_id']),
9468
+ type: 'product_metadata_set_input',
9469
+ required: true,
9470
+ },
9471
+ });
9472
+ if (!update_product_metadata_by_pk) {
9473
+ await this.mutation('insert_product_metadata', ['affected_rows'], {
9474
+ objects: {
9475
+ type: '[product_metadata_insert_input!]!',
9476
+ value: [{ product_id: productId, ...metadata }],
9477
+ },
9478
+ });
9479
+ }
9480
+ return plainData.metadata;
8169
9481
  }
8170
9482
  async getId(id) {
8171
9483
  if (!Number.isNaN(+id))
@@ -8388,124 +9700,670 @@ class WishlistHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
8388
9700
  async getCategoryBySlug(slug, _shop) {
8389
9701
  return this.getWishlistBySlug(slug);
8390
9702
  }
8391
- async getCategoryByShop(shop) {
8392
- if (!shop)
8393
- return;
8394
- const { data } = await this.find({
8395
- filters: {
8396
- shops: { operator: Where.IN, value: [shop] },
8397
- published: { operator: Where.EQUALS, value: true },
8398
- isWishlist: { operator: Where.EQUALS, value: true },
8399
- },
8400
- options: {
8401
- enableCount: false,
9703
+ async getCategoryByShop(shop) {
9704
+ if (!shop)
9705
+ return;
9706
+ const { data } = await this.find({
9707
+ filters: {
9708
+ shops: { operator: Where.IN, value: [shop] },
9709
+ published: { operator: Where.EQUALS, value: true },
9710
+ isWishlist: { operator: Where.EQUALS, value: true },
9711
+ },
9712
+ options: {
9713
+ enableCount: false,
9714
+ },
9715
+ });
9716
+ return data;
9717
+ }
9718
+ async findBfluOrGlamgirlWishlists(params, shops) {
9719
+ return this.find({
9720
+ ...params,
9721
+ filters: {
9722
+ ...params.filters,
9723
+ published: true,
9724
+ shops: { operator: Where.LIKE, value: shops },
9725
+ personType: params.filters?.personType ?? {
9726
+ operator: Where.IN,
9727
+ value: [PersonTypes.BFLU, PersonTypes.GLAMGIRL],
9728
+ },
9729
+ },
9730
+ orderBy: {
9731
+ personHasPhoto: 'desc',
9732
+ ...omit(params.orderBy, ['personHasPhoto']),
9733
+ },
9734
+ });
9735
+ }
9736
+ getCategoriesForHome() {
9737
+ return;
9738
+ }
9739
+ mountCategory() {
9740
+ return;
9741
+ }
9742
+ getChildren(_parentId) {
9743
+ return;
9744
+ }
9745
+ isChild(_id, _parentId) {
9746
+ return;
9747
+ }
9748
+ async updateMetadata(categoryId, { metadatas }) {
9749
+ if (Array.isArray(metadatas) && !metadatas.length)
9750
+ return [];
9751
+ if (Array.isArray(metadatas) && metadatas.length) {
9752
+ const metadataUpdated = [];
9753
+ for (const data of metadatas) {
9754
+ const update = await this.mutation('update_category_metadata_by_pk', ['category_id', 'shop'], {
9755
+ pk_columns: {
9756
+ value: { category_id: categoryId, shop: data.shop },
9757
+ type: 'category_metadata_pk_columns_input',
9758
+ required: true,
9759
+ },
9760
+ _set: {
9761
+ value: omit(data, ['category_id', 'shop']),
9762
+ type: 'category_metadata_set_input',
9763
+ required: true,
9764
+ },
9765
+ });
9766
+ metadataUpdated.push(update);
9767
+ }
9768
+ return metadataUpdated;
9769
+ }
9770
+ if ('action' in metadatas && metadatas.action === 'remove' && metadatas.value.length) {
9771
+ for (let i = 0; i < metadatas.value.length; i++) {
9772
+ await this.mutation('delete_category_metadata', ['affected_rows'], {
9773
+ where: {
9774
+ type: 'category_metadata_bool_exp',
9775
+ required: true,
9776
+ value: { category_id: { _eq: categoryId }, shop: metadatas.value[i].shop },
9777
+ },
9778
+ });
9779
+ }
9780
+ return [];
9781
+ }
9782
+ }
9783
+ async addProduct(wishlistId, productId) {
9784
+ await this.categoryProductRepository.create({
9785
+ categoryId: +wishlistId,
9786
+ productId: +productId,
9787
+ order: 0,
9788
+ });
9789
+ }
9790
+ async removeProduct(wishlistId, productId) {
9791
+ return this.categoryProductRepository.delete({
9792
+ categoryId: +wishlistId,
9793
+ productId: +productId,
9794
+ });
9795
+ }
9796
+ async getBrandsWithProducts() {
9797
+ return;
9798
+ }
9799
+ }
9800
+ __decorate([
9801
+ Log(),
9802
+ __metadata("design:type", Function),
9803
+ __metadata("design:paramtypes", [String]),
9804
+ __metadata("design:returntype", Promise)
9805
+ ], WishlistHasuraGraphQLRepository.prototype, "getWishlistBySlug", null);
9806
+ __decorate([
9807
+ Log(),
9808
+ __metadata("design:type", Function),
9809
+ __metadata("design:paramtypes", [String]),
9810
+ __metadata("design:returntype", Promise)
9811
+ ], WishlistHasuraGraphQLRepository.prototype, "getWishlistByPerson", null);
9812
+ __decorate([
9813
+ Log(),
9814
+ __metadata("design:type", Function),
9815
+ __metadata("design:paramtypes", [String]),
9816
+ __metadata("design:returntype", Promise)
9817
+ ], WishlistHasuraGraphQLRepository.prototype, "getCategoryByShop", null);
9818
+ __decorate([
9819
+ Log(),
9820
+ __metadata("design:type", Function),
9821
+ __metadata("design:paramtypes", [Object, Array]),
9822
+ __metadata("design:returntype", Promise)
9823
+ ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
9824
+
9825
+ class MercadoPagoErrorHelper {
9826
+ static getErrorTypeFromResponse(errorCode) {
9827
+ switch (errorCode) {
9828
+ case 'bad_filled_card_data':
9829
+ case 'invalid_card_token':
9830
+ case 'card_disabled':
9831
+ case 'cc_rejected_card_disabled':
9832
+ case 'cc_rejected_bad_filled_card_number':
9833
+ case 'cc_rejected_bad_filled_date':
9834
+ case 'cc_rejected_bad_filled_other':
9835
+ case 'cc_rejected_bad_filled_security_code':
9836
+ return ErrorsCode.invalidCardError;
9837
+ case 'high_risk':
9838
+ case 'rejected_high_risk':
9839
+ case 'cc_rejected_blacklist':
9840
+ case 'cc_rejected_call_for_authorize':
9841
+ case 'cc_rejected_high_risk':
9842
+ return ErrorsCode.fraudPreventionExternal;
9843
+ case 'rejected_by_issuer':
9844
+ case 'rejected_by_bank':
9845
+ case 'cc_rejected_max_attempts':
9846
+ case 'required_call_for_authorize':
9847
+ case 'max_attempts_exceeded':
9848
+ return ErrorsCode.paymentNotAuthorizedError;
9849
+ case 'insufficient_amount':
9850
+ case 'amount_limit_exceeded':
9851
+ case 'cc_rejected_insufficient_amount':
9852
+ return ErrorsCode.insufficientFundsError;
9853
+ case 'processing_error':
9854
+ return ErrorsCode.paymentError;
9855
+ case 'invalid_installments':
9856
+ case 'cc_rejected_invalid_installments':
9857
+ case 'cc_rejected_other_reason':
9858
+ case 'rejected_insufficient_data':
9859
+ return ErrorsCode.businessError;
9860
+ default:
9861
+ return ErrorsCode.paymentError;
9862
+ }
9863
+ }
9864
+ }
9865
+
9866
+ class MercadoPagoRequestHelper {
9867
+ static build(data) {
9868
+ const { checkout, method, postback, card } = data;
9869
+ return {
9870
+ transaction_amount: +checkout.totalPrice.toFixed(2),
9871
+ notification_url: postback,
9872
+ metadata: {
9873
+ checkoutId: checkout.id,
9874
+ },
9875
+ payer: this.buildPayer(checkout, card),
9876
+ statement_descriptor: checkout.shop === Shops.GLAMSHOP ? 'loja glam' : 'mens market',
9877
+ additional_info: {
9878
+ items: this.buildItems(checkout),
9879
+ },
9880
+ ...(method === 'credit_card' && this.buildCardPayment(card)),
9881
+ ...(method === 'pix' && this.buildPixPayment()),
9882
+ ...(method === 'boleto' && this.buildBoletoPayment(checkout)),
9883
+ };
9884
+ }
9885
+ static buildItems(checkout) {
9886
+ return checkout.lineItems
9887
+ .filter((item) => !item.isGift)
9888
+ .map((item) => {
9889
+ return {
9890
+ id: item.EAN,
9891
+ title: item.name,
9892
+ description: item.name,
9893
+ picture_url: item.image ?? null,
9894
+ category_id: item.category?.id ?? null,
9895
+ quantity: item.quantity,
9896
+ unit_price: +item.pricePaid.toFixed(2),
9897
+ };
9898
+ });
9899
+ }
9900
+ static buildPayer(checkout, card) {
9901
+ return {
9902
+ ...(card && { id: card.customerId }),
9903
+ first_name: checkout.user.firstName,
9904
+ last_name: checkout.user.lastName,
9905
+ email: checkout.user.email,
9906
+ identification: {
9907
+ type: 'CPF',
9908
+ number: checkout.user.cpf.replace(/\D/g, ''),
9909
+ },
9910
+ };
9911
+ }
9912
+ static buildFullPayer(checkout) {
9913
+ return {
9914
+ first_name: checkout.user.firstName,
9915
+ last_name: checkout.user.lastName,
9916
+ phone: {
9917
+ area_code: checkout.user.phone.substring(0, 2),
9918
+ number: checkout.user.phone.substring(2),
9919
+ },
9920
+ address: {
9921
+ zip_code: checkout.shippingAddress.zip,
9922
+ street_name: `${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9923
+ street_number: checkout.shippingAddress.number,
9924
+ neighborhood: checkout.shippingAddress.district,
9925
+ city: checkout.shippingAddress.city,
9926
+ federal_unit: checkout.shippingAddress.state,
9927
+ },
9928
+ };
9929
+ }
9930
+ static buildCardPayment(card) {
9931
+ return {
9932
+ installments: card.installments,
9933
+ token: card.cardId,
9934
+ binary_mode: true,
9935
+ capture: true,
9936
+ };
9937
+ }
9938
+ static buildPixPayment() {
9939
+ return {
9940
+ payment_method_id: 'pix',
9941
+ date_of_expiration: format(addHours(new Date(), 24), "yyyy-MM-dd'T'HH:mm:ss.SSSxxx"),
9942
+ };
9943
+ }
9944
+ static buildBoletoPayment(checkout) {
9945
+ return {
9946
+ payment_method_id: 'bolbradesco',
9947
+ date_of_expiration: format(addDays(new Date(), 3), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
9948
+ payer: {
9949
+ first_name: checkout.user.firstName,
9950
+ last_name: checkout.user.lastName,
9951
+ email: checkout.user.email,
9952
+ identification: {
9953
+ type: 'CPF',
9954
+ number: checkout.user.cpf.replace(/\D/g, ''),
9955
+ },
9956
+ phone: {
9957
+ area_code: checkout.user.phone.substring(0, 2),
9958
+ number: checkout.user.phone.substring(2),
9959
+ },
9960
+ address: {
9961
+ zip_code: checkout.shippingAddress.zip.replace(/\D/g, ''),
9962
+ street_name: `${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
9963
+ street_number: checkout.shippingAddress.number,
9964
+ neighborhood: checkout.shippingAddress.district,
9965
+ city: checkout.shippingAddress.city,
9966
+ federal_unit: checkout.shippingAddress.state,
9967
+ },
9968
+ },
9969
+ };
9970
+ }
9971
+ }
9972
+
9973
+ class MercadoPagoResponseHelper {
9974
+ static build(method, checkout, response) {
9975
+ return Payment.toInstance({
9976
+ createdAt: new Date(),
9977
+ updatedAt: new Date(),
9978
+ userId: checkout.user.id,
9979
+ checkoutId: checkout.id,
9980
+ totalPrice: checkout.totalPrice,
9981
+ paymentProvider: PaymentProviders.MERCADOPAGO,
9982
+ mercadoPagoId: response.id,
9983
+ transaction: this.buildPaymentTransaction(method, response),
9984
+ });
9985
+ }
9986
+ static buildPaymentTransaction(method, response) {
9987
+ return PaymentTransaction.toInstance({
9988
+ id: response.id.toString(),
9989
+ acquirer_name: PaymentProviders.MERCADOPAGO,
9990
+ amount: response.transaction_amount,
9991
+ status: this.statusMapping(response.status),
9992
+ status_reason: response.status_detail?.toString(),
9993
+ payment_method: method,
9994
+ currency: response.currency_id?.toString(),
9995
+ paid_amount: response.transaction_details?.total_paid_amount ?? null,
9996
+ paid_at: response.date_approved ?? null,
9997
+ charger_id: response.charges_details?.at(0)?.id?.toString() ?? null,
9998
+ ...(method == TransactionPaymentMethods.PIX && this.getPixReponse(response)),
9999
+ ...(method == TransactionPaymentMethods.CARD && this.getCardReponse(response)),
10000
+ ...(method == TransactionPaymentMethods.BANKSLIP && this.getBoletoReponse(response)),
10001
+ });
10002
+ }
10003
+ static getBoletoReponse(response) {
10004
+ return {
10005
+ boleto_url: response.transaction_details?.external_resource_url?.toString(),
10006
+ boleto_barcode: response.transaction_details?.barcode?.content?.toString(),
10007
+ boleto_line: response.transaction_details?.digitable_line?.toString(),
10008
+ boleto_expiration_date: response.date_of_expiration?.toString(),
10009
+ boleto_document_number: response.transaction_details?.verification_code?.toString(),
10010
+ };
10011
+ }
10012
+ static getPixReponse(response) {
10013
+ return {
10014
+ pix_qr_code: response.point_of_interaction?.transaction_data?.qr_code,
10015
+ pix_expiration_date: response.date_of_expiration?.toString(),
10016
+ };
10017
+ }
10018
+ static getCardReponse(response) {
10019
+ return {
10020
+ soft_descriptor: response.statement_descriptor?.toString(),
10021
+ installments: response.installments,
10022
+ card_brand: response.payment_method_id?.toString(),
10023
+ card_first_digits: response.card?.first_six_digits?.toString(),
10024
+ card_last_digits: response.card?.last_four_digits?.toString(),
10025
+ card_id: response.card?.id?.toString(),
10026
+ card_holder_name: response.card?.cardholder?.name?.toString(),
10027
+ card_expiration_month: response.card?.expiration_month?.toString(),
10028
+ card_expiration_year: response.card?.expiration_year?.toString(),
10029
+ capture_method: response.payment_type_id?.toString(),
10030
+ authorization_code: response.authorization_code?.toString(),
10031
+ paid_amount: this.statusMapping(response.status) == 'paid' ? response.transaction_details?.total_paid_amount : null,
10032
+ paid_at: this.statusMapping(response.status) == 'paid' ? response.date_approved : null,
10033
+ };
10034
+ }
10035
+ static statusMapping(status) {
10036
+ const statusMap = {
10037
+ approved: 'paid',
10038
+ pending: 'waiting_payment',
10039
+ in_process: 'processing',
10040
+ rejected: 'refused',
10041
+ cancelled: 'refused',
10042
+ refunded: 'refunded',
10043
+ charged_back: 'chargedback',
10044
+ };
10045
+ return statusMap[status] || status;
10046
+ }
10047
+ }
10048
+
10049
+ class MercadoPagoBankSlipAxiosAdapter {
10050
+ constructor(credentials, paymentRepository) {
10051
+ this.credentials = credentials;
10052
+ this.paymentRepository = paymentRepository;
10053
+ }
10054
+ async pay(checkout) {
10055
+ try {
10056
+ const payload = MercadoPagoRequestHelper.build({
10057
+ checkout,
10058
+ method: 'boleto',
10059
+ postback: this.credentials.postback,
10060
+ });
10061
+ console.warn('[MERCADO PAGO BOLETO DATA TO SEND]', JSON.stringify(payload));
10062
+ const { data } = await axios({
10063
+ method: 'POST',
10064
+ url: `${this.credentials.url}/v1/payments`,
10065
+ headers: {
10066
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
10067
+ Authorization: `Bearer ${this.credentials.api_key}`,
10068
+ 'Content-Type': 'application/json',
10069
+ },
10070
+ data: payload,
10071
+ });
10072
+ console.warn('[MERCADO PAGO RESPONSE BOLETO DATA]', JSON.stringify(data));
10073
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(TransactionPaymentMethods.BANKSLIP, checkout, data));
10074
+ return payment;
10075
+ }
10076
+ catch (error) {
10077
+ if (error instanceof AxiosError) {
10078
+ console.warn(JSON.stringify(error.response.data.message));
10079
+ }
10080
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', ErrorsCode.paymentError, {
10081
+ checkoutId: checkout.id,
10082
+ userEmail: checkout.user.email,
10083
+ info: error.response.data?.message || error.message?.toString(),
10084
+ });
10085
+ }
10086
+ }
10087
+ getBoletoTransaction(paymentId) {
10088
+ throw new Error('Method not implemented.');
10089
+ }
10090
+ }
10091
+
10092
+ var MercadoPagoStatusDetailEnum;
10093
+ (function (MercadoPagoStatusDetailEnum) {
10094
+ MercadoPagoStatusDetailEnum["accredited"] = "accredited";
10095
+ MercadoPagoStatusDetailEnum["partially_refunded"] = "partially_refunded";
10096
+ MercadoPagoStatusDetailEnum["pending_capture"] = "pending_capture";
10097
+ MercadoPagoStatusDetailEnum["offline_process"] = "offline_process";
10098
+ MercadoPagoStatusDetailEnum["pending_contingency"] = "pending_contingency";
10099
+ MercadoPagoStatusDetailEnum["pending_review_manual"] = "pending_review_manual";
10100
+ MercadoPagoStatusDetailEnum["pending_waiting_transfer"] = "pending_waiting_transfer";
10101
+ MercadoPagoStatusDetailEnum["pending_waiting_payment"] = "pending_waiting_payment";
10102
+ MercadoPagoStatusDetailEnum["pending_challenge"] = "pending_challenge";
10103
+ MercadoPagoStatusDetailEnum["bank_error"] = "bank_error";
10104
+ MercadoPagoStatusDetailEnum["cc_rejected_3ds_mandatory"] = "cc_rejected_3ds_mandatory";
10105
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_card_number"] = "cc_rejected_bad_filled_card_number";
10106
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_date"] = "cc_rejected_bad_filled_date";
10107
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_other"] = "cc_rejected_bad_filled_other";
10108
+ MercadoPagoStatusDetailEnum["cc_rejected_bad_filled_security_code"] = "cc_rejected_bad_filled_security_code";
10109
+ MercadoPagoStatusDetailEnum["cc_rejected_blacklist"] = "cc_rejected_blacklist";
10110
+ MercadoPagoStatusDetailEnum["cc_rejected_call_for_authorize"] = "cc_rejected_call_for_authorize";
10111
+ MercadoPagoStatusDetailEnum["cc_rejected_card_disabled"] = "cc_rejected_card_disabled";
10112
+ MercadoPagoStatusDetailEnum["cc_rejected_card_error"] = "cc_rejected_card_error";
10113
+ MercadoPagoStatusDetailEnum["cc_rejected_duplicated_payment"] = "cc_rejected_duplicated_payment";
10114
+ MercadoPagoStatusDetailEnum["cc_rejected_high_risk"] = "cc_rejected_high_risk";
10115
+ MercadoPagoStatusDetailEnum["cc_rejected_insufficient_amount"] = "cc_rejected_insufficient_amount";
10116
+ MercadoPagoStatusDetailEnum["cc_rejected_invalid_installments"] = "cc_rejected_invalid_installments";
10117
+ MercadoPagoStatusDetailEnum["cc_rejected_max_attempts"] = "cc_rejected_max_attempts";
10118
+ MercadoPagoStatusDetailEnum["cc_rejected_other_reason"] = "cc_rejected_other_reason";
10119
+ MercadoPagoStatusDetailEnum["cc_amount_rate_limit_exceeded"] = "cc_amount_rate_limit_exceeded";
10120
+ MercadoPagoStatusDetailEnum["rejected_insufficient_data"] = "rejected_insufficient_data";
10121
+ MercadoPagoStatusDetailEnum["rejected_by_bank"] = "rejected_by_bank";
10122
+ MercadoPagoStatusDetailEnum["rejected_by_regulations"] = "rejected_by_regulations";
10123
+ MercadoPagoStatusDetailEnum["insufficient_amount"] = "insufficient_amount";
10124
+ MercadoPagoStatusDetailEnum["cc_rejected_card_type_not_allowed"] = "cc_rejected_card_type_not_allowed";
10125
+ })(MercadoPagoStatusDetailEnum || (MercadoPagoStatusDetailEnum = {}));
10126
+
10127
+ var MercadoPagoStatusEnum;
10128
+ (function (MercadoPagoStatusEnum) {
10129
+ MercadoPagoStatusEnum["approved"] = "approved";
10130
+ MercadoPagoStatusEnum["authorized"] = "authorized";
10131
+ MercadoPagoStatusEnum["pending"] = "pending";
10132
+ MercadoPagoStatusEnum["in_process"] = "in_process";
10133
+ MercadoPagoStatusEnum["rejected"] = "rejected";
10134
+ MercadoPagoStatusEnum["cancelled"] = "cancelled";
10135
+ MercadoPagoStatusEnum["refunded"] = "refunded";
10136
+ MercadoPagoStatusEnum["charged_back"] = "charged_back";
10137
+ })(MercadoPagoStatusEnum || (MercadoPagoStatusEnum = {}));
10138
+
10139
+ class MercadoPagoBaseAxiosAdapter {
10140
+ constructor(credentials, paymentRepository) {
10141
+ this.credentials = credentials;
10142
+ this.paymentRepository = paymentRepository;
10143
+ }
10144
+ async refund(order, amount) {
10145
+ const { data } = await axios({
10146
+ method: 'POST',
10147
+ url: `${this.credentials.url}/v1/payments/${order.payment.id}/refunds`,
10148
+ headers: {
10149
+ 'X-Idempotency-Key': `${order.payment.charger_id}-${new Date().getTime()}`,
10150
+ Authorization: `Bearer ${this.credentials.api_key}`,
10151
+ 'Content-Type': 'application/json',
10152
+ },
10153
+ data: {
10154
+ amount: +amount.toFixed(2),
10155
+ },
10156
+ });
10157
+ await this.paymentRepository.create({
10158
+ createdAt: new Date(),
10159
+ updatedAt: new Date(),
10160
+ userId: order.user.id,
10161
+ orderId: order.id,
10162
+ totalPrice: amount,
10163
+ paymentProvider: PaymentProviders.MERCADOPAGO,
10164
+ mercadoPagoId: data.id,
10165
+ transaction: data,
10166
+ });
10167
+ console.warn('[RESPONSE MERCADO PAGO REFUND]', JSON.stringify(data));
10168
+ return {
10169
+ status: this.getRefundStatus(data.status),
10170
+ success: [
10171
+ MercadoPagoStatusEnum.approved,
10172
+ MercadoPagoStatusEnum.refunded,
10173
+ MercadoPagoStatusEnum.cancelled,
10174
+ MercadoPagoStatusEnum.authorized,
10175
+ ].includes(data.status)
10176
+ ? true
10177
+ : false,
10178
+ };
10179
+ }
10180
+ getRefundStatus(status) {
10181
+ if ([MercadoPagoStatusEnum.in_process, MercadoPagoStatusEnum.pending].includes(status)) {
10182
+ return 'processing';
10183
+ }
10184
+ if ([
10185
+ MercadoPagoStatusEnum.approved,
10186
+ MercadoPagoStatusEnum.refunded,
10187
+ MercadoPagoStatusEnum.cancelled,
10188
+ MercadoPagoStatusEnum.authorized,
10189
+ ].includes(status)) {
10190
+ return 'success';
10191
+ }
10192
+ return 'unknown';
10193
+ }
10194
+ }
10195
+
10196
+ class MercadoPagoCardAxiosAdapter extends MercadoPagoBaseAxiosAdapter {
10197
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
10198
+ super(credentials, paymentRepository);
10199
+ this.credentials = credentials;
10200
+ this.paymentRepository = paymentRepository;
10201
+ this.orderBlockedRepository = orderBlockedRepository;
10202
+ }
10203
+ async pay(checkout, card) {
10204
+ try {
10205
+ const payload = await this.getPaymentPayload(checkout, card);
10206
+ console.warn('[MERCADO PAGO CARD DATA TO SEND]', JSON.stringify(payload));
10207
+ const data = await this.requestPayment(checkout, payload);
10208
+ console.warn('[MERCADO PAGO RESPONSE CARD DATA]', JSON.stringify(data));
10209
+ if (data.status == MercadoPagoStatusEnum.rejected) {
10210
+ await this.orderBlockedRepository.createBlockedOrderOrPayment({
10211
+ checkout,
10212
+ blockType: 'Card not authorized',
10213
+ type: 'Card',
10214
+ limiteRange: 'day',
10215
+ card,
10216
+ gatewayInfo: {
10217
+ gateway: PaymentProviders.MERCADOPAGO,
10218
+ status: data.status,
10219
+ statusDetail: data.status_detail,
10220
+ },
10221
+ });
10222
+ const errorCode = MercadoPagoErrorHelper.getErrorTypeFromResponse(data.status_detail);
10223
+ throw new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', errorCode, {
10224
+ checkoutId: checkout.id,
10225
+ userEmail: checkout.user.email,
10226
+ info: data,
10227
+ });
10228
+ }
10229
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(TransactionPaymentMethods.CARD, checkout, data));
10230
+ return payment;
10231
+ }
10232
+ catch (error) {
10233
+ if (error instanceof AxiosError) {
10234
+ console.warn(JSON.stringify(error.response?.data?.message));
10235
+ throw new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', ErrorsCode.paymentError, {
10236
+ checkoutId: checkout.id,
10237
+ userEmail: checkout.user.email,
10238
+ info: error.response?.data?.message || error.message?.toString(),
10239
+ });
10240
+ }
10241
+ throw error;
10242
+ }
10243
+ }
10244
+ async requestPayment(checkout, payload) {
10245
+ const { data } = await axios({
10246
+ method: 'POST',
10247
+ url: `${this.credentials.url}/v1/payments`,
10248
+ headers: {
10249
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
10250
+ Authorization: `Bearer ${this.credentials.api_key}`,
10251
+ 'Content-Type': 'application/json',
8402
10252
  },
10253
+ data: payload,
8403
10254
  });
8404
10255
  return data;
8405
10256
  }
8406
- async findBfluOrGlamgirlWishlists(params, shops) {
8407
- return this.find({
8408
- ...params,
8409
- filters: {
8410
- ...params.filters,
8411
- published: true,
8412
- shops: { operator: Where.LIKE, value: shops },
8413
- personType: params.filters?.personType ?? {
8414
- operator: Where.IN,
8415
- value: [PersonTypes.BFLU, PersonTypes.GLAMGIRL],
8416
- },
8417
- },
8418
- orderBy: {
8419
- personHasPhoto: 'desc',
8420
- ...omit(params.orderBy, ['personHasPhoto']),
10257
+ async getPaymentPayload(checkout, card) {
10258
+ const cardResponse = await this.getCardByToken(card.customerId, card.cardId, card.cardCvv);
10259
+ const payload = MercadoPagoRequestHelper.build({
10260
+ checkout,
10261
+ method: 'credit_card',
10262
+ postback: this.credentials.postback,
10263
+ card: {
10264
+ ...card,
10265
+ cardId: cardResponse.id,
8421
10266
  },
8422
10267
  });
10268
+ return payload;
8423
10269
  }
8424
- getCategoriesForHome() {
10270
+ async addCard(card, customer) {
8425
10271
  return;
8426
10272
  }
8427
- mountCategory() {
8428
- return;
10273
+ async getCardByToken(customerId, token, cardCvv) {
10274
+ try {
10275
+ const payload = { cardId: token, customerId: customerId, securityCode: cardCvv };
10276
+ console.warn('payload getCardByToken', payload);
10277
+ const { data } = await axios({
10278
+ method: 'POST',
10279
+ url: `${this.credentials.url}/v1/card_tokens`,
10280
+ headers: {
10281
+ Authorization: `Bearer ${this.credentials.api_key}`,
10282
+ 'Content-Type': 'application/json',
10283
+ },
10284
+ data: payload,
10285
+ });
10286
+ return data;
10287
+ }
10288
+ catch (error) {
10289
+ if (error instanceof AxiosError) {
10290
+ console.warn(JSON.stringify(error.response.data.cause));
10291
+ }
10292
+ throw error;
10293
+ }
8429
10294
  }
8430
- getChildren(_parentId) {
10295
+ createCardHash(bu, shop, card) {
8431
10296
  return;
8432
10297
  }
8433
- isChild(_id, _parentId) {
10298
+ createTransaction(info) {
8434
10299
  return;
8435
10300
  }
8436
- async updateMetadata(categoryId, { metadatas }) {
8437
- if (Array.isArray(metadatas) && !metadatas.length)
8438
- return [];
8439
- if (Array.isArray(metadatas) && metadatas.length) {
8440
- const metadataUpdated = [];
8441
- for (const data of metadatas) {
8442
- const update = await this.mutation('update_category_metadata_by_pk', ['category_id', 'shop'], {
8443
- pk_columns: {
8444
- value: { category_id: categoryId, shop: data.shop },
8445
- type: 'category_metadata_pk_columns_input',
8446
- required: true,
8447
- },
8448
- _set: {
8449
- value: omit(data, ['category_id', 'shop']),
8450
- type: 'category_metadata_set_input',
8451
- required: true,
8452
- },
8453
- });
8454
- metadataUpdated.push(update);
8455
- }
8456
- return metadataUpdated;
10301
+ async createOrUpdateCustomer(customer) {
10302
+ const { data } = await axios({
10303
+ method: 'POST',
10304
+ url: `${this.credentials.url}/v1/customers`,
10305
+ headers: {
10306
+ Authorization: `Bearer ${this.credentials.api_key}`,
10307
+ 'Content-Type': 'application/json',
10308
+ },
10309
+ data: {
10310
+ email: customer.email,
10311
+ first_name: customer.firstName,
10312
+ last_name: customer.lastName,
10313
+ phone: {
10314
+ area_code: customer.phone.substring(0, 2),
10315
+ number: customer.phone.substring(2),
10316
+ },
10317
+ identification: {
10318
+ type: 'CPF',
10319
+ number: customer.cpf.replace(/\D/g, ''),
10320
+ },
10321
+ },
10322
+ });
10323
+ return data;
10324
+ }
10325
+ }
10326
+
10327
+ class MercadoPagoPixAxiosAdapter extends MercadoPagoBaseAxiosAdapter {
10328
+ constructor(credentials, paymentRepository) {
10329
+ super(credentials, paymentRepository);
10330
+ this.credentials = credentials;
10331
+ this.paymentRepository = paymentRepository;
10332
+ }
10333
+ async pay(checkout) {
10334
+ try {
10335
+ const payload = MercadoPagoRequestHelper.build({
10336
+ checkout,
10337
+ method: 'pix',
10338
+ postback: this.credentials.postback,
10339
+ });
10340
+ console.warn('[MERCADO PAGO PIX DATA TO SEND]', JSON.stringify(payload));
10341
+ const { data } = await axios({
10342
+ method: 'POST',
10343
+ url: `${this.credentials.url}/v1/payments`,
10344
+ headers: {
10345
+ 'X-Idempotency-Key': `${checkout.id}-${new Date().getTime()}`,
10346
+ Authorization: `Bearer ${this.credentials.api_key}`,
10347
+ 'Content-Type': 'application/json',
10348
+ },
10349
+ data: payload,
10350
+ });
10351
+ console.warn('[MERCADO PAGO RESPONSE PIX DATA]', JSON.stringify(data));
10352
+ const payment = await this.paymentRepository.create(MercadoPagoResponseHelper.build(TransactionPaymentMethods.PIX, checkout, data));
10353
+ return payment;
8457
10354
  }
8458
- if ('action' in metadatas && metadatas.action === 'remove' && metadatas.value.length) {
8459
- for (let i = 0; i < metadatas.value.length; i++) {
8460
- await this.mutation('delete_category_metadata', ['affected_rows'], {
8461
- where: {
8462
- type: 'category_metadata_bool_exp',
8463
- required: true,
8464
- value: { category_id: { _eq: categoryId }, shop: metadatas.value[i].shop },
8465
- },
8466
- });
10355
+ catch (error) {
10356
+ if (error instanceof AxiosError) {
10357
+ console.warn(JSON.stringify(error.response.data.message));
8467
10358
  }
8468
- return [];
10359
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', ErrorsCode.paymentError, {
10360
+ checkoutId: checkout.id,
10361
+ userEmail: checkout.user.email,
10362
+ info: error.response.data?.message || error.message?.toString(),
10363
+ });
8469
10364
  }
8470
10365
  }
8471
- async addProduct(wishlistId, productId) {
8472
- await this.categoryProductRepository.create({
8473
- categoryId: +wishlistId,
8474
- productId: +productId,
8475
- order: 0,
8476
- });
8477
- }
8478
- async removeProduct(wishlistId, productId) {
8479
- return this.categoryProductRepository.delete({
8480
- categoryId: +wishlistId,
8481
- productId: +productId,
8482
- });
8483
- }
8484
10366
  }
8485
- __decorate([
8486
- Log(),
8487
- __metadata("design:type", Function),
8488
- __metadata("design:paramtypes", [String]),
8489
- __metadata("design:returntype", Promise)
8490
- ], WishlistHasuraGraphQLRepository.prototype, "getWishlistBySlug", null);
8491
- __decorate([
8492
- Log(),
8493
- __metadata("design:type", Function),
8494
- __metadata("design:paramtypes", [String]),
8495
- __metadata("design:returntype", Promise)
8496
- ], WishlistHasuraGraphQLRepository.prototype, "getWishlistByPerson", null);
8497
- __decorate([
8498
- Log(),
8499
- __metadata("design:type", Function),
8500
- __metadata("design:paramtypes", [String]),
8501
- __metadata("design:returntype", Promise)
8502
- ], WishlistHasuraGraphQLRepository.prototype, "getCategoryByShop", null);
8503
- __decorate([
8504
- Log(),
8505
- __metadata("design:type", Function),
8506
- __metadata("design:paramtypes", [Object, Array]),
8507
- __metadata("design:returntype", Promise)
8508
- ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
8509
10367
 
8510
10368
  class PagarmeBankSlipAxiosAdapter {
8511
10369
  constructor(credentials, paymentRepository) {
@@ -8522,7 +10380,7 @@ class PagarmeBankSlipAxiosAdapter {
8522
10380
  });
8523
10381
  console.warn('[PAGARME BOLETO DATA TO SEND]', payload);
8524
10382
  if (result.data.status !== PagarmePaymentStatus['Em processamento']) {
8525
- return Promise.reject(new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
10383
+ return Promise.reject(new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', ErrorsCode.paymentError, {
8526
10384
  checkoutId: checkout.id,
8527
10385
  userEmail: checkout.user.email,
8528
10386
  info: result.data,
@@ -8540,7 +10398,7 @@ class PagarmeBankSlipAxiosAdapter {
8540
10398
  return payment;
8541
10399
  }
8542
10400
  catch (error) {
8543
- throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
10401
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', ErrorsCode.paymentError, {
8544
10402
  checkoutId: checkout.id,
8545
10403
  userEmail: checkout.user.email,
8546
10404
  info: error.response.data,
@@ -8588,62 +10446,423 @@ class PagarmeBankSlipAxiosAdapter {
8588
10446
  },
8589
10447
  };
8590
10448
  }
8591
- }
8592
-
8593
- class PagarmeBlockedOrderHelper {
8594
- static async createBlockedOrderForUnauthorizedCard(params) {
8595
- const { checkout, card, orderBlockedRepository } = params;
8596
- await orderBlockedRepository.createBlockedOrderOrPayment({
8597
- checkout,
8598
- blockType: 'Card not authorized',
8599
- type: 'Card',
8600
- limiteRange: 'day',
8601
- card,
8602
- });
8603
- }
8604
- static createPaymentError(checkout, resultData) {
8605
- return new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', {
8606
- checkoutId: checkout.id,
8607
- userEmail: checkout.user.email,
8608
- info: resultData,
8609
- });
8610
- }
8611
- static createGenericPaymentError(checkout, errorResponseData) {
8612
- return new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', {
8613
- checkoutId: checkout.id,
8614
- userEmail: checkout.user.email,
8615
- info: errorResponseData,
8616
- });
10449
+ }
10450
+
10451
+ class PagarmeBlockedOrderHelper {
10452
+ static async createBlockedOrderForUnauthorizedCard(params) {
10453
+ const { checkout, card, orderBlockedRepository, gatewayInfo } = params;
10454
+ await orderBlockedRepository.createBlockedOrderOrPayment({
10455
+ checkout,
10456
+ blockType: 'Card not authorized',
10457
+ type: 'Card',
10458
+ limiteRange: 'day',
10459
+ card,
10460
+ gatewayInfo,
10461
+ });
10462
+ }
10463
+ static createPaymentError(checkout, errorType, resultData) {
10464
+ return new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', errorType, {
10465
+ checkoutId: checkout.id,
10466
+ userEmail: checkout.user.email,
10467
+ info: resultData,
10468
+ });
10469
+ }
10470
+ static createGenericPaymentError(checkout, errorType, errorResponseData) {
10471
+ return new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', errorType, {
10472
+ checkoutId: checkout.id,
10473
+ userEmail: checkout.user.email,
10474
+ info: errorResponseData,
10475
+ });
10476
+ }
10477
+ }
10478
+
10479
+ /* eslint-disable complexity */
10480
+ class PagarMeErrorHelper {
10481
+ static getErrorTypeFromResponse(errorCode) {
10482
+ switch (errorCode) {
10483
+ // Cartão inválido, vencido, bloqueado
10484
+ case '1000':
10485
+ case '1001':
10486
+ case '1011':
10487
+ case '1025':
10488
+ case '1032':
10489
+ case '1045':
10490
+ case '1068':
10491
+ case '1069':
10492
+ case '1070':
10493
+ case '2001':
10494
+ case '2004':
10495
+ case '5025':
10496
+ case '9124':
10497
+ return ErrorsCode.invalidCardError;
10498
+ // Dados obrigatórios ausentes
10499
+ case '1044':
10500
+ case '5034':
10501
+ case '5047':
10502
+ case '5061':
10503
+ return ErrorsCode.invalidCardError;
10504
+ // Suspeita de fraude, prevenção do banco
10505
+ case '1002':
10506
+ case '1004':
10507
+ case '1019':
10508
+ case '2002':
10509
+ case '2005':
10510
+ case '2007':
10511
+ case '2008':
10512
+ case '2009':
10513
+ case '2010':
10514
+ case '9201':
10515
+ return ErrorsCode.fraudPreventionExternal;
10516
+ // Recusado pelo banco/emissor
10517
+ case '1007':
10518
+ case '1008':
10519
+ case '2000':
10520
+ case '5093':
10521
+ return ErrorsCode.paymentNotAuthorizedError;
10522
+ // Saldo/limite insuficiente ou excedido
10523
+ case '1016':
10524
+ case '1021':
10525
+ case '1023':
10526
+ case '2011':
10527
+ case '2012':
10528
+ case '5051':
10529
+ case '5087':
10530
+ return ErrorsCode.insufficientFundsError;
10531
+ // Valor solicitado inválido
10532
+ case '5094':
10533
+ case '5016':
10534
+ case '5092':
10535
+ return ErrorsCode.paymentError;
10536
+ // Erros internos ou genéricos
10537
+ case '5000':
10538
+ case '5001':
10539
+ case '5003':
10540
+ case '5004':
10541
+ case '5006':
10542
+ case '5008':
10543
+ case '5009':
10544
+ case '5010':
10545
+ case '5011':
10546
+ case '5012':
10547
+ case '5013':
10548
+ case '5014':
10549
+ case '5015':
10550
+ case '5017':
10551
+ case '5018':
10552
+ case '5019':
10553
+ case '5020':
10554
+ case '5021':
10555
+ case '5022':
10556
+ case '5023':
10557
+ case '5024':
10558
+ case '5026':
10559
+ case '5027':
10560
+ case '5028':
10561
+ case '5029':
10562
+ case '5030':
10563
+ case '5031':
10564
+ case '5032':
10565
+ case '5033':
10566
+ case '5035':
10567
+ case '5036':
10568
+ case '5037':
10569
+ case '5038':
10570
+ case '5039':
10571
+ case '5040':
10572
+ case '5041':
10573
+ case '5042':
10574
+ case '5043':
10575
+ case '5044':
10576
+ case '5045':
10577
+ case '5049':
10578
+ case '5050':
10579
+ case '5052':
10580
+ case '5053':
10581
+ case '5054':
10582
+ case '5055':
10583
+ case '5056':
10584
+ case '5057':
10585
+ case '5058':
10586
+ case '5059':
10587
+ case '5060':
10588
+ case '5062':
10589
+ case '5063':
10590
+ case '5064':
10591
+ case '5065':
10592
+ case '5066':
10593
+ case '5067':
10594
+ case '5068':
10595
+ case '5069':
10596
+ case '5070':
10597
+ case '5071':
10598
+ case '5072':
10599
+ case '5073':
10600
+ case '5074':
10601
+ case '5075':
10602
+ case '5076':
10603
+ case '5077':
10604
+ case '5078':
10605
+ case '5079':
10606
+ case '5080':
10607
+ case '5081':
10608
+ case '5082':
10609
+ case '5083':
10610
+ case '5084':
10611
+ case '5085':
10612
+ case '5089':
10613
+ case '5090':
10614
+ case '5095':
10615
+ case '5096':
10616
+ case '5097':
10617
+ return ErrorsCode.paymentError;
10618
+ // Banco/emissor inválido ou não operante
10619
+ case '1049':
10620
+ case '1050':
10621
+ return ErrorsCode.paymentError;
10622
+ // Transação não suportada para o banco/emissor
10623
+ case '1061':
10624
+ return ErrorsCode.paymentError;
10625
+ case '1010':
10626
+ case '1046':
10627
+ return ErrorsCode.invalidCheckoutError;
10628
+ default:
10629
+ return ErrorsCode.paymentError;
10630
+ }
10631
+ }
10632
+ }
10633
+
10634
+ class PagarmePaymentFactoryHelper {
10635
+ static async createSuccessfulPayment(params) {
10636
+ const { checkout, resultData, paymentRepository } = params;
10637
+ const payment = await paymentRepository.create({
10638
+ createdAt: new Date(),
10639
+ updatedAt: new Date(),
10640
+ userId: checkout.user.id,
10641
+ checkoutId: checkout.id,
10642
+ totalPrice: checkout.totalPrice,
10643
+ paymentProvider: PaymentProviders.PAGARME,
10644
+ transaction: { ...resultData, paidAt: new Date() },
10645
+ });
10646
+ return payment;
10647
+ }
10648
+ }
10649
+
10650
+ class PagarmePaymentOperationsHelper {
10651
+ static async executePaymentRequest(params) {
10652
+ const { checkout, card, credentials, createPayloadFunction } = params;
10653
+ const payload = createPayloadFunction(checkout, card);
10654
+ console.warn('[PAGARME CARD DATA TO SEND]', payload);
10655
+ const result = await axios({
10656
+ method: 'POST',
10657
+ url: `${credentials.URL}/transactions`,
10658
+ data: payload,
10659
+ });
10660
+ return result;
10661
+ }
10662
+ }
10663
+
10664
+ class PagarMeV5RequestHelper {
10665
+ static build(checkout, method, card) {
10666
+ return {
10667
+ items: this.buildItems(checkout),
10668
+ customer: this.buildCustomer(checkout),
10669
+ shipping: this.buildShipping(checkout),
10670
+ payments: this.buildPayment(checkout, method, card),
10671
+ ...this.buildAdditionalInfo(checkout),
10672
+ };
10673
+ }
10674
+ static buildItems(checkout) {
10675
+ const isSubscriber = checkout.user?.isSubscriber ?? false;
10676
+ return checkout.lineItems
10677
+ .filter((item) => !item.isGift)
10678
+ .map((item) => {
10679
+ return {
10680
+ amount: Math.floor(item.pricePaid * 100),
10681
+ description: isSubscriber ? `${item.name} - ASSINANTE` : item.name,
10682
+ quantity: item.quantity,
10683
+ code: item.EAN,
10684
+ };
10685
+ });
10686
+ }
10687
+ static buildCustomer(checkout) {
10688
+ return {
10689
+ name: checkout.user.displayName,
10690
+ email: checkout.user.email,
10691
+ type: 'individual',
10692
+ document: checkout.user.cpf,
10693
+ phones: {
10694
+ home_phone: {
10695
+ country_code: '55',
10696
+ number: checkout.user.phone.slice(2),
10697
+ area_code: checkout.user.phone.slice(0, 2),
10698
+ },
10699
+ mobile_phone: {
10700
+ country_code: '55',
10701
+ number: checkout.user.phone.slice(2),
10702
+ area_code: checkout.user.phone.slice(0, 2),
10703
+ },
10704
+ },
10705
+ address: {
10706
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
10707
+ line_2: `${checkout.billingAddress.extension}`,
10708
+ zip_code: checkout.shippingAddress.zip,
10709
+ city: checkout.billingAddress.city,
10710
+ state: checkout.billingAddress.state,
10711
+ country: 'BR',
10712
+ },
10713
+ };
10714
+ }
10715
+ static buildShipping(checkout) {
10716
+ return {
10717
+ amount: Math.floor(checkout.shipping.ShippingPrice * 100),
10718
+ description: `${checkout.shipping.ShippingCompanyName} - ${checkout.shipping.description}`,
10719
+ recipient_name: checkout.shippingAddress.recipient,
10720
+ recipient_phone: checkout.user.phone,
10721
+ address: {
10722
+ line_1: `${checkout.shippingAddress.number}, ${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
10723
+ line_2: `${checkout.shippingAddress.extension}`,
10724
+ zip_code: checkout.shippingAddress.zip,
10725
+ city: checkout.shippingAddress.city,
10726
+ state: checkout.shippingAddress.state,
10727
+ country: 'BR',
10728
+ },
10729
+ };
10730
+ }
10731
+ static buildPayment(checkout, method, card) {
10732
+ return [
10733
+ {
10734
+ payment_method: method,
10735
+ amount: Math.floor(checkout.totalPrice * 100),
10736
+ ...(method === 'pix' && {
10737
+ pix: this.getPixOrder(),
10738
+ }),
10739
+ ...(method === 'boleto' && {
10740
+ boleto: this.getBoletoOrder(),
10741
+ }),
10742
+ ...(method === 'credit_card' && {
10743
+ credit_card: this.getCardOrder(checkout, card),
10744
+ }),
10745
+ },
10746
+ ];
10747
+ }
10748
+ static getPixOrder() {
10749
+ return {
10750
+ expires_at: format(addHours(new Date(), 24), "yyyy-MM-dd'T'HH:mm:ss.SSSxxx"),
10751
+ };
10752
+ }
10753
+ static getBoletoOrder() {
10754
+ return {
10755
+ due_at: format(addDays(new Date(), 3), 'yyyy-MM-dd') + 'T23:59:59.999-03:00',
10756
+ instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
10757
+ type: 'DM',
10758
+ document_number: new Date().getTime().toString(),
10759
+ };
10760
+ }
10761
+ static getCardOrder(checkout, card) {
10762
+ return {
10763
+ installments: card.installments,
10764
+ statement_descriptor: checkout.shop === Shops.GLAMSHOP ? 'loja glam' : 'mens market',
10765
+ card_id: card.cardId,
10766
+ card: {
10767
+ cvv: card.cardCvv,
10768
+ billing_address: {
10769
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
10770
+ zip_code: checkout.billingAddress.zip,
10771
+ city: checkout.billingAddress.city,
10772
+ state: checkout.billingAddress.state,
10773
+ country: 'BR',
10774
+ },
10775
+ },
10776
+ };
10777
+ }
10778
+ static buildAdditionalInfo(checkout) {
10779
+ const isSubscriber = checkout.user?.isSubscriber ?? false;
10780
+ if (isSubscriber)
10781
+ return {
10782
+ antifraude_enabled: false,
10783
+ };
10784
+ return {};
8617
10785
  }
8618
10786
  }
8619
10787
 
8620
- class PagarmePaymentFactoryHelper {
8621
- static async createSuccessfulPayment(params) {
8622
- const { checkout, resultData, paymentRepository } = params;
8623
- const payment = await paymentRepository.create({
10788
+ class PagarMeV5ResponseHelper {
10789
+ static build(method, checkout, response) {
10790
+ return Payment.toInstance({
8624
10791
  createdAt: new Date(),
8625
10792
  updatedAt: new Date(),
8626
10793
  userId: checkout.user.id,
8627
10794
  checkoutId: checkout.id,
8628
10795
  totalPrice: checkout.totalPrice,
8629
10796
  paymentProvider: PaymentProviders.PAGARME,
8630
- transaction: { ...resultData, paidAt: new Date() },
8631
- });
8632
- return payment;
10797
+ pagarMeOrderId: response.id,
10798
+ transaction: this.buildPaymentTransaction(method, response),
10799
+ });
10800
+ }
10801
+ static buildPaymentTransaction(method, response) {
10802
+ const charger = response.charges.at(0);
10803
+ const transaction = charger.last_transaction;
10804
+ return PaymentTransaction.toInstance({
10805
+ acquirer_name: PaymentProviders.PAGARME,
10806
+ amount: charger.amount,
10807
+ currency: charger.currency,
10808
+ gateway_id: charger.gateway_id,
10809
+ status: this.getPaymentStatus(transaction.status),
10810
+ payment_method: charger.payment_method,
10811
+ date_created: charger.created_at,
10812
+ date_updated: charger.updated_at,
10813
+ paid_amount: charger.paid_amount,
10814
+ paid_at: charger.paid_at,
10815
+ order_id: response.id,
10816
+ charger_id: charger.id,
10817
+ tid: charger.id,
10818
+ id: charger.id,
10819
+ ...(method == TransactionPaymentMethods.BANKSLIP && this.getBoletoReponse(transaction)),
10820
+ ...(method == TransactionPaymentMethods.PIX && this.getPixReponse(transaction)),
10821
+ ...(method == TransactionPaymentMethods.CARD && this.getCardReponse(transaction)),
10822
+ });
10823
+ }
10824
+ static getPaymentStatus(status) {
10825
+ if (status == PagarMeV5PaymentStatus.Gerado)
10826
+ return PagarMeV5PaymentStatus['Aguardando pagamento'];
10827
+ if (status == PagarMeV5PaymentStatus.Capturada)
10828
+ return PagarMeV5PaymentStatus.Pago;
10829
+ return status;
10830
+ }
10831
+ static getBoletoReponse(transaction) {
10832
+ return {
10833
+ boleto_url: transaction.url?.toString(),
10834
+ boleto_barcode: transaction.line?.toString(),
10835
+ boleto_qr_code: transaction.qr_code?.toString(),
10836
+ boleto_expiration_date: transaction.due_at?.toString(),
10837
+ boleto_instructions: transaction.instructions?.toString(),
10838
+ boleto_nosso_numero: transaction.nosso_numero?.toString(),
10839
+ boleto_type: transaction.type?.toString(),
10840
+ boleto_document_number: transaction.document_number?.toString(),
10841
+ };
8633
10842
  }
8634
- }
8635
-
8636
- class PagarmePaymentOperationsHelper {
8637
- static async executePaymentRequest(params) {
8638
- const { checkout, card, credentials, createPayloadFunction } = params;
8639
- const payload = createPayloadFunction(checkout, card);
8640
- console.warn('[PAGARME CARD DATA TO SEND]', payload);
8641
- const result = await axios({
8642
- method: 'POST',
8643
- url: `${credentials.URL}/transactions`,
8644
- data: payload,
8645
- });
8646
- return result;
10843
+ static getPixReponse(transaction) {
10844
+ return {
10845
+ pix_qr_code: transaction.qr_code?.toString(),
10846
+ pix_qr_code_url: transaction.qr_code_url?.toString(),
10847
+ pix_expiration_date: transaction.expires_at?.toString(),
10848
+ };
10849
+ }
10850
+ static getCardReponse(transaction) {
10851
+ return {
10852
+ soft_descriptor: transaction.statement_descriptor?.toString(),
10853
+ acquirer_name: transaction.acquirer_name?.toString(),
10854
+ acquirer_id: transaction.acquirer_tid?.toString(),
10855
+ acquirer_nsu: transaction.acquirer_nsu?.toString(),
10856
+ acquirer_auth_code: transaction.acquirer_auth_code?.toString(),
10857
+ acquirer_message: transaction.acquirer_message?.toString(),
10858
+ acquirer_return_code: transaction.acquirer_return_code?.toString(),
10859
+ installments: transaction.installments ?? null,
10860
+ card_holder_name: transaction.card?.holder_name?.toString(),
10861
+ card_last_digits: transaction.card?.last_four_digits?.toString(),
10862
+ card_first_digits: transaction.card?.first_six_digits?.toString(),
10863
+ card_brand: transaction.card?.brand?.toString(),
10864
+ card_id: transaction.card?.id?.toString(),
10865
+ };
8647
10866
  }
8648
10867
  }
8649
10868
 
@@ -8667,7 +10886,7 @@ class PagarmeCardAxiosAdapter {
8667
10886
  card,
8668
10887
  orderBlockedRepository: this.orderBlockedRepository,
8669
10888
  });
8670
- throw PagarmeBlockedOrderHelper.createPaymentError(checkout, result.data);
10889
+ throw PagarmeBlockedOrderHelper.createPaymentError(checkout, ErrorsCode.paymentError, result.data);
8671
10890
  }
8672
10891
  return PagarmePaymentFactoryHelper.createSuccessfulPayment({
8673
10892
  checkout,
@@ -8679,7 +10898,7 @@ class PagarmeCardAxiosAdapter {
8679
10898
  if (error instanceof PaymentError) {
8680
10899
  throw error;
8681
10900
  }
8682
- throw PagarmeBlockedOrderHelper.createGenericPaymentError(checkout, error.response?.data);
10901
+ throw PagarmeBlockedOrderHelper.createGenericPaymentError(checkout, ErrorsCode.paymentError, error.response?.data);
8683
10902
  }
8684
10903
  }
8685
10904
  async addCard(card) {
@@ -8703,8 +10922,9 @@ class PagarmeCardAxiosAdapter {
8703
10922
  });
8704
10923
  }
8705
10924
  }
8706
- async createCardHash(bu) {
8707
- const key = bu === BusinessUnitEnum.SHOP ? this.credentials.SHOP_API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
10925
+ async createCardHash(bu, shop) {
10926
+ const credentials = shop && shop == Shops.MENSMARKET ? this.credentials[Shops.MENSMARKET] : this.credentials[Shops.GLAMSHOP];
10927
+ const key = bu === BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
8708
10928
  try {
8709
10929
  const { data } = await axios({
8710
10930
  method: 'GET',
@@ -8835,7 +11055,7 @@ class PagarmePixAxiosAdapter {
8835
11055
  return payment;
8836
11056
  }
8837
11057
  catch (error) {
8838
- throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
11058
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', ErrorsCode.paymentError, {
8839
11059
  checkoutId: checkout.id,
8840
11060
  userEmail: checkout.user.email,
8841
11061
  info: error.response?.data,
@@ -8867,6 +11087,347 @@ class PagarmePixAxiosAdapter {
8867
11087
  }
8868
11088
  }
8869
11089
 
11090
+ class PagarmeV5BankSlipAxiosAdapter {
11091
+ constructor(credentials, paymentRepository) {
11092
+ this.credentials = credentials;
11093
+ this.paymentRepository = paymentRepository;
11094
+ }
11095
+ async pay(checkout) {
11096
+ try {
11097
+ const payload = PagarMeV5RequestHelper.build(checkout, 'boleto');
11098
+ console.warn('[PAGARME BOLETO DATA TO SEND]', JSON.stringify(payload));
11099
+ const { data } = await axios({
11100
+ method: 'POST',
11101
+ url: `${this.credentials.URL}/orders`,
11102
+ headers: {
11103
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
11104
+ 'Content-Type': 'application/json',
11105
+ },
11106
+ data: payload,
11107
+ });
11108
+ console.warn('[PAGARME RESPONSE BOLETO DATA]', JSON.stringify(data));
11109
+ if (data.status === PagarMeV5OrderStatus.Falha ||
11110
+ data.charges.at(0).status === PagarMeV5OrderStatus.Falha ||
11111
+ (data.charges.at(0).last_transaction.status !== PagarMeV5PaymentStatus.Gerado &&
11112
+ data.charges.at(0).last_transaction.status !== PagarMeV5PaymentStatus['Em processamento'])) {
11113
+ return Promise.reject(new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', ErrorsCode.paymentError, {
11114
+ checkoutId: checkout.id,
11115
+ userEmail: checkout.user.email,
11116
+ info: data.charges.at(0).last_transaction?.gateway_response,
11117
+ }));
11118
+ }
11119
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(TransactionPaymentMethods.BANKSLIP, checkout, data));
11120
+ return payment;
11121
+ }
11122
+ catch (error) {
11123
+ if (error instanceof AxiosError) {
11124
+ console.error('error data: ', JSON.stringify(error.response?.data));
11125
+ }
11126
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', ErrorsCode.paymentError, {
11127
+ checkoutId: checkout.id,
11128
+ userEmail: checkout.user.email,
11129
+ info: error.response?.data,
11130
+ });
11131
+ }
11132
+ }
11133
+ async getBoletoTransaction(paymentId) {
11134
+ try {
11135
+ const { data } = await axios({
11136
+ method: 'GET',
11137
+ url: `${this.credentials.URL}/charges/${paymentId}`,
11138
+ headers: {
11139
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
11140
+ 'Content-Type': 'application/json',
11141
+ },
11142
+ });
11143
+ const payment = await this.paymentRepository.get({
11144
+ id: data.id,
11145
+ });
11146
+ return payment.transaction;
11147
+ }
11148
+ catch (error) {
11149
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
11150
+ paymentId,
11151
+ info: error.response.data,
11152
+ });
11153
+ }
11154
+ }
11155
+ }
11156
+
11157
+ class PagarmeV5BaseAxiosAdapter {
11158
+ constructor(credentials, paymentRepository) {
11159
+ this.credentials = credentials;
11160
+ this.paymentRepository = paymentRepository;
11161
+ }
11162
+ async refund(order, amount) {
11163
+ try {
11164
+ console.warn('[PAGARME REFUND] Starting refund process for order', order.id, order.payment.payment_method, order.payment.amount, 'to refund with amount', amount);
11165
+ const amountInCents = toCents(amount);
11166
+ console.warn('[PAGARME REFUND] Amount to send in cents', amountInCents);
11167
+ const { data } = await axios({
11168
+ method: 'DELETE',
11169
+ url: `${this.credentials.URL}/charges/${order.payment.charger_id}`,
11170
+ headers: {
11171
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
11172
+ 'Content-Type': 'application/json',
11173
+ },
11174
+ data: {
11175
+ amount: amountInCents,
11176
+ },
11177
+ });
11178
+ console.warn('[RESPONSE PAGARME REFUND]', JSON.stringify(data));
11179
+ await this.paymentRepository.create({
11180
+ createdAt: new Date(),
11181
+ updatedAt: new Date(),
11182
+ userId: order.user.id,
11183
+ orderId: order.id,
11184
+ totalPrice: amount,
11185
+ paymentProvider: PaymentProviders.PAGARME,
11186
+ pagarMeOrderId: data.id,
11187
+ transaction: data,
11188
+ });
11189
+ return {
11190
+ status: this.getRefundStatus(data.status),
11191
+ success: [
11192
+ PagarMeV5OrderStatus.Pago,
11193
+ PagarMeV5OrderStatus.Cancelado,
11194
+ PagarMeV5PaymentStatus['Em processamento'],
11195
+ ].includes(data.status)
11196
+ ? true
11197
+ : false,
11198
+ };
11199
+ }
11200
+ catch (error) {
11201
+ console.error('Error during refund process for order', order.id, 'with error', error);
11202
+ throw error;
11203
+ }
11204
+ }
11205
+ getRefundStatus(status) {
11206
+ if ([PagarMeV5PaymentStatus['Em processamento']].includes(status)) {
11207
+ return 'processing';
11208
+ }
11209
+ if ([PagarMeV5OrderStatus.Pago, PagarMeV5OrderStatus.Cancelado].includes(status)) {
11210
+ return 'success';
11211
+ }
11212
+ return 'unknown';
11213
+ }
11214
+ }
11215
+
11216
+ class PagarmeV5CardAxiosAdapter extends PagarmeV5BaseAxiosAdapter {
11217
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
11218
+ super(credentials, paymentRepository);
11219
+ this.credentials = credentials;
11220
+ this.paymentRepository = paymentRepository;
11221
+ this.orderBlockedRepository = orderBlockedRepository;
11222
+ }
11223
+ async pay(checkout, card) {
11224
+ try {
11225
+ const payload = PagarMeV5RequestHelper.build(checkout, 'credit_card', card);
11226
+ console.warn('[PAGARME CARD DATA TO SEND]', JSON.stringify(payload));
11227
+ const { data } = await axios({
11228
+ method: 'POST',
11229
+ url: `${this.credentials.URL}/orders`,
11230
+ headers: {
11231
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
11232
+ 'Content-Type': 'application/json',
11233
+ },
11234
+ data: payload,
11235
+ });
11236
+ console.warn('[RESPONSE PAGARME CARD DATA]', JSON.stringify(data));
11237
+ const charge = data.charges.at(0);
11238
+ if (data.status == PagarMeV5OrderStatus.Falha ||
11239
+ charge.status !== PagarMeV5OrderStatus.Pago ||
11240
+ charge.last_transaction.status !== PagarMeV5PaymentStatus.Capturada) {
11241
+ await PagarmeBlockedOrderHelper.createBlockedOrderForUnauthorizedCard({
11242
+ checkout,
11243
+ card,
11244
+ orderBlockedRepository: this.orderBlockedRepository,
11245
+ gatewayInfo: {
11246
+ gateway: PaymentProviders.PAGARME,
11247
+ status: charge.status,
11248
+ statusDetail: charge.last_transaction?.status,
11249
+ },
11250
+ });
11251
+ const errorCode = PagarMeErrorHelper.getErrorTypeFromResponse(charge.last_transaction.acquirer_return_code);
11252
+ throw PagarmeBlockedOrderHelper.createPaymentError(checkout, errorCode, data);
11253
+ }
11254
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(TransactionPaymentMethods.CARD, checkout, data));
11255
+ return payment;
11256
+ }
11257
+ catch (error) {
11258
+ if (error instanceof AxiosError) {
11259
+ console.error('error data: ', JSON.stringify(error.response?.data));
11260
+ throw PagarmeBlockedOrderHelper.createGenericPaymentError(checkout, ErrorsCode.paymentError, error.response?.data);
11261
+ }
11262
+ throw error;
11263
+ }
11264
+ }
11265
+ async addCard(card, customer) {
11266
+ try {
11267
+ const { id } = await this.createOrUpdateCustomer(customer);
11268
+ const { data } = await axios({
11269
+ method: 'POST',
11270
+ url: `${this.credentials.URL}/customers/${id}/cards`,
11271
+ headers: {
11272
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
11273
+ 'Content-Type': 'application/json',
11274
+ },
11275
+ data: {
11276
+ number: card.number,
11277
+ holder_name: card.name,
11278
+ holder_document: card.cpf,
11279
+ exp_month: card.expirationDate.split('/').at(0),
11280
+ exp_year: card.expirationDate.split('/').at(1),
11281
+ cvv: card.cvv,
11282
+ billing_address: {
11283
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
11284
+ line_2: `${customer.billingAddress.extension}`,
11285
+ zip_code: customer.billingAddress.zip,
11286
+ city: customer.billingAddress.city,
11287
+ state: customer.billingAddress.state,
11288
+ country: 'BR',
11289
+ },
11290
+ },
11291
+ });
11292
+ return data;
11293
+ }
11294
+ catch (error) {
11295
+ console.warn(JSON.stringify(error));
11296
+ throw error;
11297
+ }
11298
+ }
11299
+ async createCardHash(bu, shop) {
11300
+ const credentials = shop && shop == Shops.MENSMARKET ? this.credentials[Shops.MENSMARKET] : this.credentials[Shops.GLAMSHOP];
11301
+ const key = bu === BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
11302
+ try {
11303
+ const { data } = await axios({
11304
+ method: 'GET',
11305
+ headers: {
11306
+ 'content-type': 'application/json',
11307
+ },
11308
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
11309
+ data: JSON.stringify({
11310
+ api_key: key,
11311
+ }),
11312
+ });
11313
+ return data;
11314
+ }
11315
+ catch (error) {
11316
+ throw new BusinessError('Houve uma falha gerar o hash', {
11317
+ info: error.response.data,
11318
+ });
11319
+ }
11320
+ }
11321
+ async getCardByToken(customerId, token) {
11322
+ try {
11323
+ const { data } = await axios({
11324
+ method: 'GET',
11325
+ url: `${this.credentials.URL}/cards/${token}`,
11326
+ data: {
11327
+ api_key: this.credentials.API_KEY,
11328
+ },
11329
+ });
11330
+ return data;
11331
+ }
11332
+ catch (error) {
11333
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + token, {
11334
+ info: error.response.data,
11335
+ });
11336
+ }
11337
+ }
11338
+ async createTransaction(info) {
11339
+ return info;
11340
+ }
11341
+ async createOrUpdateCustomer(customer) {
11342
+ try {
11343
+ const { data } = await axios({
11344
+ method: 'POST',
11345
+ url: `${this.credentials.URL}/customers`,
11346
+ headers: {
11347
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
11348
+ 'Content-Type': 'application/json',
11349
+ },
11350
+ data: {
11351
+ name: customer.displayName,
11352
+ email: customer.email,
11353
+ document: customer.cpf,
11354
+ type: 'individual',
11355
+ document_type: 'CPF',
11356
+ address: {
11357
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
11358
+ line_2: `${customer.billingAddress.extension}`,
11359
+ zip_code: customer.billingAddress.zip,
11360
+ city: customer.billingAddress.city,
11361
+ state: customer.billingAddress.state,
11362
+ country: 'BR',
11363
+ },
11364
+ birthdate: format(new Date(customer.birthday), 'MM/dd/yyyy'),
11365
+ phones: {
11366
+ home_phone: {
11367
+ country_code: '55',
11368
+ number: customer.phone.slice(2),
11369
+ area_code: customer.phone.slice(0, 2),
11370
+ },
11371
+ mobile_phone: {
11372
+ country_code: '55',
11373
+ number: customer.phone.slice(2),
11374
+ area_code: customer.phone.slice(0, 2),
11375
+ },
11376
+ },
11377
+ },
11378
+ });
11379
+ return data;
11380
+ }
11381
+ catch (error) {
11382
+ console.warn(error);
11383
+ throw error;
11384
+ }
11385
+ }
11386
+ }
11387
+
11388
+ class PagarmeV5PixAxiosAdapter extends PagarmeV5BaseAxiosAdapter {
11389
+ constructor(credentials, paymentRepository) {
11390
+ super(credentials, paymentRepository);
11391
+ this.credentials = credentials;
11392
+ this.paymentRepository = paymentRepository;
11393
+ }
11394
+ async pay(checkout) {
11395
+ try {
11396
+ const payload = PagarMeV5RequestHelper.build(checkout, 'pix');
11397
+ console.warn('[PAGARME PIX DATA TO SEND]', JSON.stringify(payload));
11398
+ const { data } = await axios({
11399
+ method: 'POST',
11400
+ url: `${this.credentials.URL}/orders`,
11401
+ headers: {
11402
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
11403
+ 'Content-Type': 'application/json',
11404
+ },
11405
+ data: payload,
11406
+ });
11407
+ console.warn('[RESPONSE PAGARME PIX DATA]', JSON.stringify(data));
11408
+ if (data.status == PagarMeV5OrderStatus.Falha || data.status == PagarMeV5OrderStatus.Cancelado) {
11409
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', ErrorsCode.paymentError, {
11410
+ checkoutId: checkout.id,
11411
+ userEmail: checkout.user.email,
11412
+ info: data.charges.at(0).last_transaction?.gateway_response,
11413
+ });
11414
+ }
11415
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(TransactionPaymentMethods.PIX, checkout, data));
11416
+ return payment;
11417
+ }
11418
+ catch (error) {
11419
+ if (error instanceof AxiosError) {
11420
+ console.error('error data: ', JSON.stringify(error.response?.data));
11421
+ }
11422
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', ErrorsCode.paymentError, {
11423
+ checkoutId: checkout.id,
11424
+ userEmail: checkout.user.email,
11425
+ info: error.response?.data,
11426
+ });
11427
+ }
11428
+ }
11429
+ }
11430
+
8870
11431
  class VertexAxiosAdapter {
8871
11432
  constructor(config) {
8872
11433
  this.config = config;
@@ -9020,4 +11581,4 @@ class ProductsVertexSearch {
9020
11581
  }
9021
11582
  }
9022
11583
 
9023
- export { AccessoryImportances, Address, AdyenCardAxiosAdapter, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BrandEquityOptions, BusinessError, BusinessUnitEnum, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, FraudValidationError, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, Group, GroupFirestoreRepository, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, NotFoundError, ObsEmitter, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderBlockedType, OrderFirestoreRepository, OrderStatus, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductErrors, ProductErrorsHasuraGraphQL, ProductErrorsHasuraGraphQLRepository, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductReview, ProductReviewHasuraGraphQLRepository, ProductSpents, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RestCacheAdapter, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, StockLimitError, StockOutError, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, deserialize, getClass, is, isDebuggable, isUUID, parseDateTime, registerClass, resolveClass, serialize, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };
11584
+ export { AccessoryImportances, Address, AdyenCardAxiosAdapter, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BrandCategory, BrandCategoryFirestoreRepository, BrandEquityOptions, BusinessError, BusinessUnitEnum, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, ErrorsCode, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, FraudValidationError, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, Group, GroupFirestoreRepository, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, InvalidCheckoutError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, MercadoPagoBankSlipAxiosAdapter, MercadoPagoCardAxiosAdapter, MercadoPagoErrorHelper, MercadoPagoPaymentMethodFactory, MercadoPagoPixAxiosAdapter, MercadoPagoRequestHelper, MercadoPagoResponseHelper, MercadoPagoStatusDetailEnum, MercadoPagoStatusEnum, NotFoundError, ObsEmitter, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderBlockedType, OrderFirestoreRepository, OrderPaymentStatus, OrderStatus, PagarMeV5OrderStatus, PagarMeV5PaymentStatus, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, PagarmeV5BankSlipAxiosAdapter, PagarmeV5BaseAxiosAdapter, PagarmeV5CardAxiosAdapter, PagarmeV5PixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductCatalogHasuraGraphQL, ProductCatalogHasuraGraphQLRepository, ProductErrors, ProductErrorsHasuraGraphQL, ProductErrorsHasuraGraphQLRepository, ProductFirestoreRepository, ProductGroup, ProductGroupHasuraGraphQLRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductPriceLog, ProductPriceLogHasuraGraphQLRepository, ProductReview, ProductReviewHasuraGraphQLRepository, ProductSpents, ProductStockEntry, ProductStockEntryHasuraGraphQL, ProductStockEntryHasuraGraphQLRepository, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RestCacheAdapter, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopConfigs, ShopConfigsFirestoreRepository, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, ShoppingRecurrence, ShoppingRecurrenceCycle, ShoppingRecurrenceEdition, ShoppingRecurrenceEditionFirestoreRepository, ShoppingRecurrenceEditionStatus, ShoppingRecurrenceErrorLog, ShoppingRecurrenceErrorLogFirestoreRepository, ShoppingRecurrenceFirestoreRepository, ShoppingRecurrenceStatus, Shops, SignInMethods, SignOut, Status, StockLimitError, StockOutError, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, TransactionPaymentMethods, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, deserialize, getClass, is, isDebuggable, isUUID, parseDateTime, registerClass, resolveCacheConfig, resolveClass, serialize, toCents, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };