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

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 (35) hide show
  1. package/index.cjs.js +534 -5
  2. package/index.esm.js +532 -6
  3. package/package.json +1 -1
  4. package/src/domain/catalog/models/product-base.d.ts +1 -0
  5. package/src/domain/shopping/enums/index.d.ts +2 -0
  6. package/src/domain/shopping/enums/pagarme-v5-payment-status.enum.d.ts +24 -0
  7. package/src/domain/shopping/enums/transaction-payment-methods.enum.d.ts +5 -0
  8. package/src/domain/shopping/interfaces/payment-provider-card.interface.d.ts +10 -2
  9. package/src/domain/shopping/models/payment-transaction.d.ts +17 -2
  10. package/src/domain/shopping/models/payment.d.ts +2 -1
  11. package/src/domain/shopping/types/card-info.type.d.ts +1 -0
  12. package/src/domain/shopping/types/index.d.ts +1 -0
  13. package/src/domain/shopping/types/pagarme-card.type.d.ts +9 -3
  14. package/src/domain/shopping/types/pagarme-credentials-v5.type.d.ts +4 -0
  15. package/src/domain/shopping/types/pagarme-credentials.type.d.ts +9 -3
  16. package/src/domain/users/models/user-payment-method.d.ts +2 -0
  17. package/src/infra/pagarme/adapters/helpers/index.d.ts +2 -0
  18. package/src/infra/pagarme/adapters/helpers/pagarme-v5-request.helper.d.ts +12 -0
  19. package/src/infra/pagarme/adapters/helpers/pagarme-v5-response.helper.d.ts +10 -0
  20. package/src/infra/pagarme/adapters/index.d.ts +2 -3
  21. package/src/infra/pagarme/adapters/v4/index.d.ts +3 -0
  22. package/src/infra/pagarme/adapters/{pagarme-bank-slip-payment-axios.adapter.d.ts → v4/pagarme-bank-slip-payment-axios.adapter.d.ts} +4 -4
  23. package/src/infra/pagarme/adapters/{pagarme-card-payment-axios.adapter.d.ts → v4/pagarme-card-payment-axios.adapter.d.ts} +7 -6
  24. package/src/infra/pagarme/adapters/{pagarme-pix-payment-axios.adapter.d.ts → v4/pagarme-pix-payment-axios.adapter.d.ts} +4 -4
  25. package/src/infra/pagarme/adapters/v5/index.d.ts +3 -0
  26. package/src/infra/pagarme/adapters/v5/pagarmev5-bank-slip-payment-axios.adapter.d.ts +11 -0
  27. package/src/infra/pagarme/adapters/v5/pagarmev5-card-payment-axios.adapter.d.ts +24 -0
  28. package/src/infra/pagarme/adapters/v5/pagarmev5-pix-payment-axios.adapter.d.ts +10 -0
  29. package/src/infra/pagarme/index.d.ts +1 -0
  30. package/src/infra/pagarme/types/index.d.ts +1 -0
  31. package/src/infra/pagarme/types/v5/index.d.ts +4 -0
  32. package/src/infra/pagarme/types/v5/pagarmev5-customer.type.d.ts +19 -0
  33. package/src/infra/pagarme/types/v5/pagarmev5-order-request-payload.type.d.ts +89 -0
  34. package/src/infra/pagarme/types/v5/pagarmev5-order-response.type.d.ts +126 -0
  35. package/src/infra/pagarme/types/v5/pagarmev5-postback-response.type.d.ts +11 -0
package/index.esm.js CHANGED
@@ -48,6 +48,33 @@ var PagarmePaymentStatus;
48
48
  PagarmePaymentStatus["Chargedback"] = "chargedback";
49
49
  })(PagarmePaymentStatus || (PagarmePaymentStatus = {}));
50
50
 
51
+ var PagarMeV5PaymentStatus;
52
+ (function (PagarMeV5PaymentStatus) {
53
+ PagarMeV5PaymentStatus["Em processamento"] = "processing";
54
+ PagarMeV5PaymentStatus["Gerado"] = "generated";
55
+ PagarMeV5PaymentStatus["Visualizado"] = "viewed";
56
+ PagarMeV5PaymentStatus["Pago a menor"] = "underpaid";
57
+ PagarMeV5PaymentStatus["Pago a maior"] = "overpaid";
58
+ PagarMeV5PaymentStatus["Aguardando pagamento"] = "waiting_payment";
59
+ PagarMeV5PaymentStatus["Pago"] = "paid";
60
+ PagarMeV5PaymentStatus["Aguardando estorno"] = "pending_refund";
61
+ PagarMeV5PaymentStatus["Autorizada pendente de captura"] = "authorized_pending_capture";
62
+ PagarMeV5PaymentStatus["N\u00E3o autorizada"] = "not_authorized";
63
+ PagarMeV5PaymentStatus["Capturada"] = "captured";
64
+ PagarMeV5PaymentStatus["Aguardando captura"] = "waiting_capture";
65
+ PagarMeV5PaymentStatus["Com erro"] = "with_error";
66
+ PagarMeV5PaymentStatus["Estornado"] = "refunded";
67
+ PagarMeV5PaymentStatus["Cancelado"] = "voided";
68
+ PagarMeV5PaymentStatus["Falha"] = "failed";
69
+ })(PagarMeV5PaymentStatus || (PagarMeV5PaymentStatus = {}));
70
+ var PagarMeV5OrderStatus;
71
+ (function (PagarMeV5OrderStatus) {
72
+ PagarMeV5OrderStatus["Pendente"] = "pending";
73
+ PagarMeV5OrderStatus["Pago"] = "paid";
74
+ PagarMeV5OrderStatus["Cancelado"] = "canceled";
75
+ PagarMeV5OrderStatus["Falha"] = "failed";
76
+ })(PagarMeV5OrderStatus || (PagarMeV5OrderStatus = {}));
77
+
51
78
  var PaymentMethods;
52
79
  (function (PaymentMethods) {
53
80
  PaymentMethods["CARD"] = "card";
@@ -63,6 +90,13 @@ var PaymentProviders;
63
90
  PaymentProviders["GLAMPOINTS"] = "glampoints";
64
91
  })(PaymentProviders || (PaymentProviders = {}));
65
92
 
93
+ var TransactionPaymentMethods;
94
+ (function (TransactionPaymentMethods) {
95
+ TransactionPaymentMethods["CARD"] = "credit_card";
96
+ TransactionPaymentMethods["BANKSLIP"] = "boleto";
97
+ TransactionPaymentMethods["PIX"] = "pix";
98
+ })(TransactionPaymentMethods || (TransactionPaymentMethods = {}));
99
+
66
100
  class BasePaymentMethodFactory {
67
101
  constructor(methods) {
68
102
  this.methods = methods;
@@ -7294,6 +7328,12 @@ const commonFields = [
7294
7328
  to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7295
7329
  },
7296
7330
  },
7331
+ {
7332
+ imagesCard: {
7333
+ columnName: 'images_card',
7334
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
7335
+ },
7336
+ },
7297
7337
  'name',
7298
7338
  {
7299
7339
  price: {
@@ -8112,9 +8152,24 @@ const fieldsConfiguration$1 = [
8112
8152
  'validity',
8113
8153
  // { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
8114
8154
  'published',
8115
- { tagsCollection: { columnName: 'tags_collection', type: HasuraGraphQLColumnType.Jsonb } },
8116
- { tagsProfile: { columnName: 'tags_profile', type: HasuraGraphQLColumnType.Jsonb } },
8117
- { daysOfUse: { columnName: 'days_of_use' } },
8155
+ {
8156
+ images: {
8157
+ columnName: 'images',
8158
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8159
+ },
8160
+ },
8161
+ {
8162
+ miniatures: {
8163
+ columnName: 'miniatures',
8164
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8165
+ },
8166
+ },
8167
+ {
8168
+ imagesCard: {
8169
+ columnName: 'images_card',
8170
+ to: (value) => (value?.length > 0 ? `{"${value?.join?.('","') || ''}"}` : '{}'),
8171
+ },
8172
+ },
8118
8173
  ];
8119
8174
  class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
8120
8175
  constructor({ endpoint, authOptions, interceptors, cache, }) {
@@ -8647,6 +8702,201 @@ class PagarmePaymentOperationsHelper {
8647
8702
  }
8648
8703
  }
8649
8704
 
8705
+ class PagarMeV5RequestHelper {
8706
+ static build(checkout, method, card) {
8707
+ return {
8708
+ items: this.buildItems(checkout),
8709
+ customer: this.buildCustomer(checkout),
8710
+ shipping: this.buildShipping(checkout),
8711
+ payments: this.buildPayment(checkout, method, card),
8712
+ };
8713
+ }
8714
+ static buildItems(checkout) {
8715
+ return checkout.lineItems
8716
+ .filter((item) => !item.isGift)
8717
+ .map((item) => {
8718
+ return {
8719
+ amount: Math.floor(item.pricePaid * 100),
8720
+ description: item.name,
8721
+ quantity: item.quantity,
8722
+ code: item.EAN,
8723
+ };
8724
+ });
8725
+ }
8726
+ static buildCustomer(checkout) {
8727
+ return {
8728
+ name: checkout.user.displayName,
8729
+ email: checkout.user.email,
8730
+ type: 'individual',
8731
+ document: checkout.user.cpf,
8732
+ phones: {
8733
+ home_phone: {
8734
+ country_code: '55',
8735
+ number: checkout.user.phone.slice(2),
8736
+ area_code: checkout.user.phone.slice(0, 2),
8737
+ },
8738
+ mobile_phone: {
8739
+ country_code: '55',
8740
+ number: checkout.user.phone.slice(2),
8741
+ area_code: checkout.user.phone.slice(0, 2),
8742
+ },
8743
+ },
8744
+ address: {
8745
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
8746
+ line_2: `${checkout.billingAddress.extension}`,
8747
+ zip_code: checkout.shippingAddress.zip,
8748
+ city: checkout.billingAddress.city,
8749
+ state: checkout.billingAddress.state,
8750
+ country: 'BR',
8751
+ },
8752
+ };
8753
+ }
8754
+ static buildShipping(checkout) {
8755
+ return {
8756
+ amount: Math.floor(checkout.shipping.ShippingPrice * 100),
8757
+ description: `${checkout.shipping.ShippingCompanyName} - ${checkout.shipping.description}`,
8758
+ recipient_name: checkout.shippingAddress.recipient,
8759
+ recipient_phone: checkout.user.phone,
8760
+ address: {
8761
+ line_1: `${checkout.shippingAddress.number}, ${checkout.shippingAddress.street}, ${checkout.shippingAddress.district}`,
8762
+ line_2: `${checkout.shippingAddress.extension}`,
8763
+ zip_code: checkout.shippingAddress.zip,
8764
+ city: checkout.shippingAddress.city,
8765
+ state: checkout.shippingAddress.state,
8766
+ country: 'BR',
8767
+ },
8768
+ };
8769
+ }
8770
+ static buildPayment(checkout, method, card) {
8771
+ return [
8772
+ {
8773
+ payment_method: method,
8774
+ amount: Math.floor(checkout.totalPrice * 100),
8775
+ ...(method === 'pix' && {
8776
+ pix: this.getPixOrder(),
8777
+ }),
8778
+ ...(method === 'boleto' && {
8779
+ boleto: this.getBoletoOrder(),
8780
+ }),
8781
+ ...(method === 'credit_card' && {
8782
+ credit_card: this.getCardOrder(checkout, card),
8783
+ }),
8784
+ },
8785
+ ];
8786
+ }
8787
+ static getPixOrder() {
8788
+ return {
8789
+ expires_at: format(addDays(new Date(), 1), 'yyyy-MM-dd'),
8790
+ };
8791
+ }
8792
+ static getBoletoOrder() {
8793
+ return {
8794
+ due_at: format(addDays(new Date(), 3), 'yyyy-MM-dd'),
8795
+ instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
8796
+ type: 'DM',
8797
+ document_number: new Date().getTime().toString(),
8798
+ };
8799
+ }
8800
+ static getCardOrder(checkout, card) {
8801
+ return {
8802
+ installments: card.installments,
8803
+ statement_descriptor: checkout.shop === Shops.GLAMSHOP ? 'Glam' : 'Mens Market',
8804
+ card_id: card.cardId,
8805
+ card: {
8806
+ cvv: card.cardCvv,
8807
+ billing_address: {
8808
+ line_1: `${checkout.billingAddress.number}, ${checkout.billingAddress.street}, ${checkout.billingAddress.district}`,
8809
+ zip_code: checkout.billingAddress.zip,
8810
+ city: checkout.billingAddress.city,
8811
+ state: checkout.billingAddress.state,
8812
+ country: 'BR',
8813
+ },
8814
+ },
8815
+ };
8816
+ }
8817
+ }
8818
+
8819
+ class PagarMeV5ResponseHelper {
8820
+ static build(method, checkout, response) {
8821
+ return Payment.toInstance({
8822
+ createdAt: new Date(),
8823
+ updatedAt: new Date(),
8824
+ userId: checkout.user.id,
8825
+ checkoutId: checkout.id,
8826
+ totalPrice: checkout.totalPrice,
8827
+ paymentProvider: PaymentProviders.PAGARME,
8828
+ pagarMeOrderId: response.id,
8829
+ transaction: this.buildPaymentTransaction(method, response),
8830
+ });
8831
+ }
8832
+ static buildPaymentTransaction(method, response) {
8833
+ const charger = response.charges.at(0);
8834
+ const transaction = charger.last_transaction;
8835
+ return PaymentTransaction.toInstance({
8836
+ acquirer_name: 'pagar_me',
8837
+ amount: charger.amount,
8838
+ currency: charger.currency,
8839
+ gateway_id: charger.gateway_id,
8840
+ status: this.getPaymentStatus(transaction.status),
8841
+ payment_method: charger.payment_method,
8842
+ date_created: charger.created_at,
8843
+ date_updated: charger.updated_at,
8844
+ paid_amount: charger.paid_amount,
8845
+ paid_at: charger.paid_at,
8846
+ order_id: response.id,
8847
+ charger_id: charger.id,
8848
+ tid: charger.id,
8849
+ id: charger.id,
8850
+ ...(method == TransactionPaymentMethods.BANKSLIP && this.getBoletoReponse(transaction)),
8851
+ ...(method == TransactionPaymentMethods.PIX && this.getPixReponse(transaction)),
8852
+ ...(method == TransactionPaymentMethods.CARD && this.getCardReponse(transaction)),
8853
+ });
8854
+ }
8855
+ static getPaymentStatus(status) {
8856
+ if (status == PagarMeV5PaymentStatus.Gerado)
8857
+ return PagarMeV5PaymentStatus['Aguardando pagamento'];
8858
+ if (status == PagarMeV5PaymentStatus.Capturada)
8859
+ return PagarMeV5PaymentStatus.Pago;
8860
+ return status;
8861
+ }
8862
+ static getBoletoReponse(transaction) {
8863
+ return {
8864
+ boleto_url: transaction.url?.toString(),
8865
+ boleto_barcode: transaction.line?.toString(),
8866
+ boleto_qr_code: transaction.qr_code?.toString(),
8867
+ boleto_expiration_date: transaction.due_at?.toString(),
8868
+ boleto_instructions: transaction.instructions?.toString(),
8869
+ boleto_nosso_numero: transaction.nosso_numero?.toString(),
8870
+ boleto_type: transaction.type?.toString(),
8871
+ boleto_document_number: transaction.document_number?.toString(),
8872
+ };
8873
+ }
8874
+ static getPixReponse(transaction) {
8875
+ return {
8876
+ pix_qr_code: transaction.qr_code?.toString(),
8877
+ pix_qr_code_url: transaction.qr_code_url?.toString(),
8878
+ pix_expiration_date: transaction.expires_at?.toString(),
8879
+ };
8880
+ }
8881
+ static getCardReponse(transaction) {
8882
+ return {
8883
+ soft_descriptor: transaction.statement_descriptor?.toString(),
8884
+ acquirer_name: transaction.acquirer_name?.toString(),
8885
+ acquirer_id: transaction.acquirer_tid?.toString(),
8886
+ acquirer_nsu: transaction.acquirer_nsu?.toString(),
8887
+ acquirer_auth_code: transaction.acquirer_auth_code?.toString(),
8888
+ acquirer_message: transaction.acquirer_message?.toString(),
8889
+ acquirer_return_code: transaction.acquirer_return_code?.toString(),
8890
+ installments: transaction.installments ?? null,
8891
+ card_holder_name: transaction.card?.holder_name?.toString(),
8892
+ card_last_digits: transaction.card?.last_four_digits?.toString(),
8893
+ card_first_digits: transaction.card?.first_six_digits?.toString(),
8894
+ card_brand: transaction.card?.brand?.toString(),
8895
+ card_id: transaction.card?.id?.toString(),
8896
+ };
8897
+ }
8898
+ }
8899
+
8650
8900
  class PagarmeCardAxiosAdapter {
8651
8901
  constructor(credentials, paymentRepository, orderBlockedRepository) {
8652
8902
  this.credentials = credentials;
@@ -8703,8 +8953,9 @@ class PagarmeCardAxiosAdapter {
8703
8953
  });
8704
8954
  }
8705
8955
  }
8706
- async createCardHash(bu) {
8707
- const key = bu === BusinessUnitEnum.SHOP ? this.credentials.SHOP_API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
8956
+ async createCardHash(bu, shop) {
8957
+ const credentials = shop && shop == Shops.MENSMARKET ? this.credentials[Shops.MENSMARKET] : this.credentials[Shops.GLAMSHOP];
8958
+ const key = bu === BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
8708
8959
  try {
8709
8960
  const { data } = await axios({
8710
8961
  method: 'GET',
@@ -8867,6 +9118,281 @@ class PagarmePixAxiosAdapter {
8867
9118
  }
8868
9119
  }
8869
9120
 
9121
+ class PagarmeV5BankSlipAxiosAdapter {
9122
+ constructor(credentials, paymentRepository) {
9123
+ this.credentials = credentials;
9124
+ this.paymentRepository = paymentRepository;
9125
+ }
9126
+ async pay(checkout) {
9127
+ try {
9128
+ const payload = PagarMeV5RequestHelper.build(checkout, 'boleto');
9129
+ console.warn('[PAGARME BOLETO DATA TO SEND]', JSON.stringify(payload));
9130
+ const { data } = await axios({
9131
+ method: 'POST',
9132
+ url: `${this.credentials.URL}/orders`,
9133
+ headers: {
9134
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9135
+ 'Content-Type': 'application/json',
9136
+ },
9137
+ data: payload,
9138
+ });
9139
+ console.warn('[PAGARME RESPONSE BOLETO DATA]', JSON.stringify(data));
9140
+ if (data.status === PagarMeV5OrderStatus.Falha ||
9141
+ data.charges.at(0).status === PagarMeV5OrderStatus.Falha ||
9142
+ (data.charges.at(0).last_transaction.status !== PagarMeV5PaymentStatus.Gerado &&
9143
+ data.charges.at(0).last_transaction.status !== PagarMeV5PaymentStatus['Em processamento'])) {
9144
+ return Promise.reject(new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
9145
+ checkoutId: checkout.id,
9146
+ userEmail: checkout.user.email,
9147
+ info: data.charges.at(0).last_transaction?.gateway_response,
9148
+ }));
9149
+ }
9150
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(TransactionPaymentMethods.BANKSLIP, checkout, data));
9151
+ return payment;
9152
+ }
9153
+ catch (error) {
9154
+ if (error instanceof AxiosError) {
9155
+ console.error('error data: ', JSON.stringify(error.response?.data));
9156
+ }
9157
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
9158
+ checkoutId: checkout.id,
9159
+ userEmail: checkout.user.email,
9160
+ info: error.response?.data,
9161
+ });
9162
+ }
9163
+ }
9164
+ async getBoletoTransaction(paymentId) {
9165
+ try {
9166
+ const { data } = await axios({
9167
+ method: 'GET',
9168
+ url: `${this.credentials.URL}/charges/${paymentId}`,
9169
+ headers: {
9170
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9171
+ 'Content-Type': 'application/json',
9172
+ },
9173
+ });
9174
+ const payment = await this.paymentRepository.get({
9175
+ id: data.id,
9176
+ });
9177
+ return payment.transaction;
9178
+ }
9179
+ catch (error) {
9180
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
9181
+ paymentId,
9182
+ info: error.response.data,
9183
+ });
9184
+ }
9185
+ }
9186
+ }
9187
+
9188
+ class PagarmeV5CardAxiosAdapter {
9189
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
9190
+ this.credentials = credentials;
9191
+ this.paymentRepository = paymentRepository;
9192
+ this.orderBlockedRepository = orderBlockedRepository;
9193
+ }
9194
+ async pay(checkout, card) {
9195
+ try {
9196
+ const payload = PagarMeV5RequestHelper.build(checkout, 'credit_card', card);
9197
+ console.warn('[PAGARME CARD DATA TO SEND]', JSON.stringify(payload));
9198
+ const { data } = await axios({
9199
+ method: 'POST',
9200
+ url: `${this.credentials.URL}/orders`,
9201
+ headers: {
9202
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9203
+ 'Content-Type': 'application/json',
9204
+ },
9205
+ data: payload,
9206
+ });
9207
+ console.warn('[RESPONSE PAGARME CARD DATA]', JSON.stringify(data));
9208
+ if (data.status == PagarMeV5OrderStatus.Falha ||
9209
+ data.charges.at(0).status !== PagarMeV5OrderStatus.Pago ||
9210
+ data.charges.at(0).last_transaction.status !== PagarMeV5PaymentStatus.Capturada) {
9211
+ await PagarmeBlockedOrderHelper.createBlockedOrderForUnauthorizedCard({
9212
+ checkout,
9213
+ card,
9214
+ orderBlockedRepository: this.orderBlockedRepository,
9215
+ });
9216
+ throw PagarmeBlockedOrderHelper.createPaymentError(checkout, data);
9217
+ }
9218
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(TransactionPaymentMethods.CARD, checkout, data));
9219
+ return payment;
9220
+ }
9221
+ catch (error) {
9222
+ if (error instanceof PaymentError) {
9223
+ throw error;
9224
+ }
9225
+ if (error instanceof AxiosError) {
9226
+ console.error('error data: ', JSON.stringify(error.response?.data));
9227
+ }
9228
+ throw PagarmeBlockedOrderHelper.createGenericPaymentError(checkout, error.response?.data);
9229
+ }
9230
+ }
9231
+ async addCard(card, customer) {
9232
+ try {
9233
+ const { id } = await this.createOrUpdateCustomer(customer);
9234
+ const { data } = await axios({
9235
+ method: 'POST',
9236
+ url: `${this.credentials.URL}/customers/${id}/cards`,
9237
+ headers: {
9238
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9239
+ 'Content-Type': 'application/json',
9240
+ },
9241
+ data: {
9242
+ number: card.number,
9243
+ holder_name: card.name,
9244
+ holder_document: card.cpf,
9245
+ exp_month: card.expirationDate.split('/').at(0),
9246
+ exp_year: card.expirationDate.split('/').at(1),
9247
+ cvv: card.cvv,
9248
+ billing_address: {
9249
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
9250
+ line_2: `${customer.billingAddress.extension}`,
9251
+ zip_code: customer.billingAddress.zip,
9252
+ city: customer.billingAddress.city,
9253
+ state: customer.billingAddress.state,
9254
+ country: 'BR',
9255
+ },
9256
+ },
9257
+ });
9258
+ return data;
9259
+ }
9260
+ catch (error) {
9261
+ console.warn(JSON.stringify(error));
9262
+ throw error;
9263
+ }
9264
+ }
9265
+ async createCardHash(bu, shop) {
9266
+ const credentials = shop && shop == Shops.MENSMARKET ? this.credentials[Shops.MENSMARKET] : this.credentials[Shops.GLAMSHOP];
9267
+ const key = bu === BusinessUnitEnum.SHOP ? credentials.SHOP_API_KEY : credentials.SUBSCRIPTION_API_KEY;
9268
+ try {
9269
+ const { data } = await axios({
9270
+ method: 'GET',
9271
+ headers: {
9272
+ 'content-type': 'application/json',
9273
+ },
9274
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
9275
+ data: JSON.stringify({
9276
+ api_key: key,
9277
+ }),
9278
+ });
9279
+ return data;
9280
+ }
9281
+ catch (error) {
9282
+ throw new BusinessError('Houve uma falha gerar o hash', {
9283
+ info: error.response.data,
9284
+ });
9285
+ }
9286
+ }
9287
+ async getCardByToken(customerId, token) {
9288
+ try {
9289
+ const { data } = await axios({
9290
+ method: 'GET',
9291
+ url: `${this.credentials.URL}/cards/${token}`,
9292
+ data: {
9293
+ api_key: this.credentials.API_KEY,
9294
+ },
9295
+ });
9296
+ return data;
9297
+ }
9298
+ catch (error) {
9299
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + token, {
9300
+ info: error.response.data,
9301
+ });
9302
+ }
9303
+ }
9304
+ async createTransaction(info) {
9305
+ return info;
9306
+ }
9307
+ async createOrUpdateCustomer(customer) {
9308
+ try {
9309
+ const { data } = await axios({
9310
+ method: 'POST',
9311
+ url: `${this.credentials.URL}/customers`,
9312
+ headers: {
9313
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9314
+ 'Content-Type': 'application/json',
9315
+ },
9316
+ data: {
9317
+ name: customer.displayName,
9318
+ email: customer.email,
9319
+ document: customer.cpf,
9320
+ type: 'individual',
9321
+ document_type: 'CPF',
9322
+ address: {
9323
+ line_1: `${customer.billingAddress.number}, ${customer.billingAddress.street}, ${customer.billingAddress.district}`,
9324
+ line_2: `${customer.billingAddress.extension}`,
9325
+ zip_code: customer.billingAddress.zip,
9326
+ city: customer.billingAddress.city,
9327
+ state: customer.billingAddress.state,
9328
+ country: 'BR',
9329
+ },
9330
+ birthdate: format(new Date(customer.birthday), 'MM/dd/yyyy'),
9331
+ phones: {
9332
+ home_phone: {
9333
+ country_code: '55',
9334
+ number: customer.phone.slice(2),
9335
+ area_code: customer.phone.slice(0, 2),
9336
+ },
9337
+ mobile_phone: {
9338
+ country_code: '55',
9339
+ number: customer.phone.slice(2),
9340
+ area_code: customer.phone.slice(0, 2),
9341
+ },
9342
+ },
9343
+ },
9344
+ });
9345
+ return data;
9346
+ }
9347
+ catch (error) {
9348
+ console.warn(error);
9349
+ throw error;
9350
+ }
9351
+ }
9352
+ }
9353
+
9354
+ class PagarmeV5PixAxiosAdapter {
9355
+ constructor(credentials, paymentRepository) {
9356
+ this.credentials = credentials;
9357
+ this.paymentRepository = paymentRepository;
9358
+ }
9359
+ async pay(checkout) {
9360
+ try {
9361
+ const payload = PagarMeV5RequestHelper.build(checkout, 'pix');
9362
+ console.warn('[PAGARME PIX DATA TO SEND]', JSON.stringify(payload));
9363
+ const { data } = await axios({
9364
+ method: 'POST',
9365
+ url: `${this.credentials.URL}/orders`,
9366
+ headers: {
9367
+ Authorization: 'Basic ' + Buffer.from(`${this.credentials.API_KEY}:`).toString('base64'),
9368
+ 'Content-Type': 'application/json',
9369
+ },
9370
+ data: payload,
9371
+ });
9372
+ console.warn('[RESPONSE PAGARME PIX DATA]', JSON.stringify(data));
9373
+ if (data.status == PagarMeV5OrderStatus.Falha || data.status == PagarMeV5OrderStatus.Cancelado) {
9374
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
9375
+ checkoutId: checkout.id,
9376
+ userEmail: checkout.user.email,
9377
+ info: data.charges.at(0).last_transaction?.gateway_response,
9378
+ });
9379
+ }
9380
+ const payment = await this.paymentRepository.create(PagarMeV5ResponseHelper.build(TransactionPaymentMethods.PIX, checkout, data));
9381
+ return payment;
9382
+ }
9383
+ catch (error) {
9384
+ if (error instanceof AxiosError) {
9385
+ console.error('error data: ', JSON.stringify(error.response?.data));
9386
+ }
9387
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
9388
+ checkoutId: checkout.id,
9389
+ userEmail: checkout.user.email,
9390
+ info: error.response?.data,
9391
+ });
9392
+ }
9393
+ }
9394
+ }
9395
+
8870
9396
  class VertexAxiosAdapter {
8871
9397
  constructor(config) {
8872
9398
  this.config = config;
@@ -9020,4 +9546,4 @@ class ProductsVertexSearch {
9020
9546
  }
9021
9547
  }
9022
9548
 
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 };
9549
+ export { AccessoryImportances, Address, AdyenCardAxiosAdapter, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BrandEquityOptions, BusinessError, BusinessUnitEnum, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, FraudValidationError, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, Group, GroupFirestoreRepository, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, NotFoundError, ObsEmitter, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderBlockedType, OrderFirestoreRepository, OrderStatus, PagarMeV5OrderStatus, PagarMeV5PaymentStatus, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, PagarmeV5BankSlipAxiosAdapter, PagarmeV5CardAxiosAdapter, PagarmeV5PixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductErrors, ProductErrorsHasuraGraphQL, ProductErrorsHasuraGraphQLRepository, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductReview, ProductReviewHasuraGraphQLRepository, ProductSpents, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RestCacheAdapter, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, StockLimitError, StockOutError, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, TransactionPaymentMethods, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, deserialize, getClass, is, isDebuggable, isUUID, parseDateTime, registerClass, resolveClass, serialize, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infrab4a/connect",
3
- "version": "5.3.0-beta.3",
3
+ "version": "5.3.0-beta.4",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org"
6
6
  },
@@ -19,6 +19,7 @@ export declare class ProductBase<T extends ProductBase<T, I>, I = ProductIdentif
19
19
  costPrice: number;
20
20
  images?: string[];
21
21
  miniatures?: string[];
22
+ imagesCard?: string[];
22
23
  published: boolean;
23
24
  createdAt?: Date;
24
25
  updatedAt?: Date;
@@ -2,5 +2,7 @@ export * from './antifraud-providers.enum';
2
2
  export * from './business-unit.enum';
3
3
  export * from './order-blocked.enum';
4
4
  export * from './pagarme-payment-status.enum';
5
+ export * from './pagarme-v5-payment-status.enum';
5
6
  export * from './payment-methods.enum';
6
7
  export * from './payment-providers.enum';
8
+ export * from './transaction-payment-methods.enum';
@@ -0,0 +1,24 @@
1
+ export declare enum PagarMeV5PaymentStatus {
2
+ 'Em processamento' = "processing",
3
+ 'Gerado' = "generated",
4
+ 'Visualizado' = "viewed",
5
+ 'Pago a menor' = "underpaid",
6
+ 'Pago a maior' = "overpaid",
7
+ 'Aguardando pagamento' = "waiting_payment",
8
+ 'Pago' = "paid",
9
+ 'Aguardando estorno' = "pending_refund",
10
+ 'Autorizada pendente de captura' = "authorized_pending_capture",
11
+ 'Não autorizada' = "not_authorized",
12
+ 'Capturada' = "captured",
13
+ 'Aguardando captura' = "waiting_capture",
14
+ 'Com erro' = "with_error",
15
+ 'Estornado' = "refunded",
16
+ 'Cancelado' = "voided",
17
+ 'Falha' = "failed"
18
+ }
19
+ export declare enum PagarMeV5OrderStatus {
20
+ 'Pendente' = "pending",
21
+ 'Pago' = "paid",
22
+ 'Cancelado' = "canceled",
23
+ 'Falha' = "failed"
24
+ }
@@ -0,0 +1,5 @@
1
+ export declare enum TransactionPaymentMethods {
2
+ CARD = "credit_card",
3
+ BANKSLIP = "boleto",
4
+ PIX = "pix"
5
+ }