@infrab4a/connect 4.20.0-beta.15 → 4.20.0-beta.5

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 (33) hide show
  1. package/index.cjs.js +615 -525
  2. package/index.esm.js +613 -523
  3. package/package.json +1 -1
  4. package/src/domain/shopping/enums/index.d.ts +0 -1
  5. package/src/domain/shopping/interfaces/payment-provider-card.interface.d.ts +0 -2
  6. package/src/domain/shopping/interfaces/payment-provider-glampoints.interface.d.ts +0 -4
  7. package/src/domain/shopping/models/order-blocked.d.ts +6 -4
  8. package/src/domain/shopping/models/payment-transaction.d.ts +60 -60
  9. package/src/{infra/adyen/adapters/adyen-card-payment-axios.adapter.d.ts → domain/shopping/services/adyen-card-payment.service.d.ts} +5 -7
  10. package/src/domain/shopping/services/glampoints-payment.service.d.ts +2 -7
  11. package/src/domain/shopping/services/index.d.ts +4 -0
  12. package/src/domain/shopping/services/pagarme-bank-slip-payment.service.d.ts +12 -0
  13. package/src/domain/shopping/services/pagarme-card-payment.service.d.ts +17 -0
  14. package/src/domain/shopping/services/pagarme-pix-payment.service.d.ts +11 -0
  15. package/src/domain/shopping/types/index.d.ts +0 -1
  16. package/src/domain/shopping/types/payment-card-info.type.d.ts +0 -3
  17. package/src/errors/index.d.ts +0 -1
  18. package/src/errors/types/index.d.ts +0 -1
  19. package/src/infra/firebase/firestore/mixins/with-helpers.mixin.d.ts +1 -1
  20. package/src/infra/firebase/firestore/repositories/shopping/order-blocked-firestore.repository.d.ts +2 -2
  21. package/src/infra/firebase/firestore/repositories/shopping/order-blocked-firestore.repository.ts.d.ts +9 -0
  22. package/src/infra/index.d.ts +0 -2
  23. package/src/domain/shopping/enums/order-blocked.enum.d.ts +0 -5
  24. package/src/domain/shopping/types/glam-credentials.type.d.ts +0 -6
  25. package/src/domain/shopping/types/pagarme-card-manual-hash.type.d.ts +0 -6
  26. package/src/errors/types/pagarme-erros.type.d.ts +0 -9
  27. package/src/infra/adyen/adapters/index.d.ts +0 -1
  28. package/src/infra/adyen/index.d.ts +0 -1
  29. package/src/infra/pagarme/adapters/index.d.ts +0 -3
  30. package/src/infra/pagarme/adapters/pagarme-bank-slip-payment-axios.adapter.d.ts +0 -12
  31. package/src/infra/pagarme/adapters/pagarme-card-payment-axios.adapter.d.ts +0 -17
  32. package/src/infra/pagarme/adapters/pagarme-pix-payment-axios.adapter.d.ts +0 -11
  33. package/src/infra/pagarme/index.d.ts +0 -1
package/index.cjs.js CHANGED
@@ -33,13 +33,6 @@ exports.BusinessUnitEnum = void 0;
33
33
  BusinessUnitEnum[BusinessUnitEnum["SHOP"] = 2] = "SHOP";
34
34
  })(exports.BusinessUnitEnum || (exports.BusinessUnitEnum = {}));
35
35
 
36
- exports.OrderBlockedType = void 0;
37
- (function (OrderBlockedType) {
38
- OrderBlockedType["Checkout"] = "Checkout";
39
- OrderBlockedType["Card"] = "Card";
40
- OrderBlockedType["Boleto"] = "Boleto";
41
- })(exports.OrderBlockedType || (exports.OrderBlockedType = {}));
42
-
43
36
  exports.PagarmePaymentStatus = void 0;
44
37
  (function (PagarmePaymentStatus) {
45
38
  PagarmePaymentStatus["Em processamento"] = "processing";
@@ -650,7 +643,171 @@ exports.Status = void 0;
650
643
  })(exports.Status || (exports.Status = {}));
651
644
 
652
645
  class PaymentTransaction extends BaseModel {
653
- }
646
+ }
647
+ tslib.__decorate([
648
+ classTransformer.Expose({ name: 'refuse_reason' }),
649
+ tslib.__metadata("design:type", String)
650
+ ], PaymentTransaction.prototype, "refuseReason", void 0);
651
+ tslib.__decorate([
652
+ classTransformer.Expose({ name: 'status_reason' }),
653
+ tslib.__metadata("design:type", String)
654
+ ], PaymentTransaction.prototype, "statusReason", void 0);
655
+ tslib.__decorate([
656
+ classTransformer.Expose({ name: 'acquirer_response_code' }),
657
+ tslib.__metadata("design:type", String)
658
+ ], PaymentTransaction.prototype, "acquirerResponseCode", void 0);
659
+ tslib.__decorate([
660
+ classTransformer.Expose({ name: 'acquirer_name' }),
661
+ tslib.__metadata("design:type", String)
662
+ ], PaymentTransaction.prototype, "acquirerName", void 0);
663
+ tslib.__decorate([
664
+ classTransformer.Expose({ name: 'acquirer_id' }),
665
+ tslib.__metadata("design:type", String)
666
+ ], PaymentTransaction.prototype, "acquirerId", void 0);
667
+ tslib.__decorate([
668
+ classTransformer.Expose({ name: 'authorization_code' }),
669
+ tslib.__metadata("design:type", String)
670
+ ], PaymentTransaction.prototype, "authorizationCode", void 0);
671
+ tslib.__decorate([
672
+ classTransformer.Expose({ name: 'soft_descriptor' }),
673
+ tslib.__metadata("design:type", String)
674
+ ], PaymentTransaction.prototype, "softDescriptor", void 0);
675
+ tslib.__decorate([
676
+ classTransformer.Expose({ name: 'date_created' }),
677
+ tslib.__metadata("design:type", String)
678
+ ], PaymentTransaction.prototype, "dateCreated", void 0);
679
+ tslib.__decorate([
680
+ classTransformer.Expose({ name: 'date_updated' }),
681
+ tslib.__metadata("design:type", String)
682
+ ], PaymentTransaction.prototype, "dateUpdated", void 0);
683
+ tslib.__decorate([
684
+ classTransformer.Expose({ name: 'authorized_amount' }),
685
+ tslib.__metadata("design:type", Number)
686
+ ], PaymentTransaction.prototype, "authorizedAmount", void 0);
687
+ tslib.__decorate([
688
+ classTransformer.Expose({ name: 'paid_amount' }),
689
+ tslib.__metadata("design:type", Number)
690
+ ], PaymentTransaction.prototype, "paidAmount", void 0);
691
+ tslib.__decorate([
692
+ classTransformer.Expose({ name: 'paid_at' }),
693
+ tslib.__metadata("design:type", String)
694
+ ], PaymentTransaction.prototype, "paidAt", void 0);
695
+ tslib.__decorate([
696
+ classTransformer.Expose({ name: 'refunded_amount' }),
697
+ tslib.__metadata("design:type", Number)
698
+ ], PaymentTransaction.prototype, "refundedAmount", void 0);
699
+ tslib.__decorate([
700
+ classTransformer.Expose({ name: 'card_holder_name' }),
701
+ tslib.__metadata("design:type", String)
702
+ ], PaymentTransaction.prototype, "cardHolderName", void 0);
703
+ tslib.__decorate([
704
+ classTransformer.Expose({ name: 'card_last_digits' }),
705
+ tslib.__metadata("design:type", String)
706
+ ], PaymentTransaction.prototype, "cardLastDigits", void 0);
707
+ tslib.__decorate([
708
+ classTransformer.Expose({ name: 'card_first_digits' }),
709
+ tslib.__metadata("design:type", String)
710
+ ], PaymentTransaction.prototype, "cardFirstDigits", void 0);
711
+ tslib.__decorate([
712
+ classTransformer.Expose({ name: 'card_brand' }),
713
+ tslib.__metadata("design:type", String)
714
+ ], PaymentTransaction.prototype, "cardBrand", void 0);
715
+ tslib.__decorate([
716
+ classTransformer.Expose({ name: 'card_pin_mode' }),
717
+ tslib.__metadata("design:type", String)
718
+ ], PaymentTransaction.prototype, "cardPinMode", void 0);
719
+ tslib.__decorate([
720
+ classTransformer.Expose({ name: 'card_magstripe_fallback' }),
721
+ tslib.__metadata("design:type", Boolean)
722
+ ], PaymentTransaction.prototype, "cardMagstripeFallback", void 0);
723
+ tslib.__decorate([
724
+ classTransformer.Expose({ name: 'cvm_pin' }),
725
+ tslib.__metadata("design:type", Boolean)
726
+ ], PaymentTransaction.prototype, "cvmPin", void 0);
727
+ tslib.__decorate([
728
+ classTransformer.Expose({ name: 'postback_url' }),
729
+ tslib.__metadata("design:type", String)
730
+ ], PaymentTransaction.prototype, "postbackUrl", void 0);
731
+ tslib.__decorate([
732
+ classTransformer.Expose({ name: 'payment_method' }),
733
+ tslib.__metadata("design:type", String)
734
+ ], PaymentTransaction.prototype, "paymentMethod", void 0);
735
+ tslib.__decorate([
736
+ classTransformer.Expose({ name: 'capture_method' }),
737
+ tslib.__metadata("design:type", String)
738
+ ], PaymentTransaction.prototype, "captureMethod", void 0);
739
+ tslib.__decorate([
740
+ classTransformer.Expose({ name: 'antifraud_score' }),
741
+ tslib.__metadata("design:type", String)
742
+ ], PaymentTransaction.prototype, "antifraudScore", void 0);
743
+ tslib.__decorate([
744
+ classTransformer.Expose({ name: 'boleto_url' }),
745
+ tslib.__metadata("design:type", String)
746
+ ], PaymentTransaction.prototype, "boletoUrl", void 0);
747
+ tslib.__decorate([
748
+ classTransformer.Expose({ name: 'boleto_barcode' }),
749
+ tslib.__metadata("design:type", String)
750
+ ], PaymentTransaction.prototype, "boletoBarcode", void 0);
751
+ tslib.__decorate([
752
+ classTransformer.Expose({ name: 'boleto_expiration_date' }),
753
+ tslib.__metadata("design:type", String)
754
+ ], PaymentTransaction.prototype, "boletoExpirationDate", void 0);
755
+ tslib.__decorate([
756
+ classTransformer.Expose({ name: 'subscription_id' }),
757
+ tslib.__metadata("design:type", String)
758
+ ], PaymentTransaction.prototype, "subscriptionId", void 0);
759
+ tslib.__decorate([
760
+ classTransformer.Expose({ name: 'split_rules' }),
761
+ tslib.__metadata("design:type", String)
762
+ ], PaymentTransaction.prototype, "splitRules", void 0);
763
+ tslib.__decorate([
764
+ classTransformer.Expose({ name: 'antifraud_metadata' }),
765
+ tslib.__metadata("design:type", Object)
766
+ ], PaymentTransaction.prototype, "antifraudMetadata", void 0);
767
+ tslib.__decorate([
768
+ classTransformer.Expose({ name: 'reference_key' }),
769
+ tslib.__metadata("design:type", String)
770
+ ], PaymentTransaction.prototype, "referenceKey", void 0);
771
+ tslib.__decorate([
772
+ classTransformer.Expose({ name: 'local_transaction_id' }),
773
+ tslib.__metadata("design:type", String)
774
+ ], PaymentTransaction.prototype, "localTransactionId", void 0);
775
+ tslib.__decorate([
776
+ classTransformer.Expose({ name: 'local_time' }),
777
+ tslib.__metadata("design:type", String)
778
+ ], PaymentTransaction.prototype, "localTime", void 0);
779
+ tslib.__decorate([
780
+ classTransformer.Expose({ name: 'fraud_covered' }),
781
+ tslib.__metadata("design:type", Boolean)
782
+ ], PaymentTransaction.prototype, "fraudCovered", void 0);
783
+ tslib.__decorate([
784
+ classTransformer.Expose({ name: 'fraud_reimbursed' }),
785
+ tslib.__metadata("design:type", String)
786
+ ], PaymentTransaction.prototype, "fraudReimbursed", void 0);
787
+ tslib.__decorate([
788
+ classTransformer.Expose({ name: 'order_id' }),
789
+ tslib.__metadata("design:type", String)
790
+ ], PaymentTransaction.prototype, "orderId", void 0);
791
+ tslib.__decorate([
792
+ classTransformer.Expose({ name: 'risk_level' }),
793
+ tslib.__metadata("design:type", String)
794
+ ], PaymentTransaction.prototype, "riskLevel", void 0);
795
+ tslib.__decorate([
796
+ classTransformer.Expose({ name: 'receipt_url' }),
797
+ tslib.__metadata("design:type", String)
798
+ ], PaymentTransaction.prototype, "receiptUrl", void 0);
799
+ tslib.__decorate([
800
+ classTransformer.Expose({ name: 'private_label' }),
801
+ tslib.__metadata("design:type", String)
802
+ ], PaymentTransaction.prototype, "privateLabel", void 0);
803
+ tslib.__decorate([
804
+ classTransformer.Expose({ name: 'pix_qr_code' }),
805
+ tslib.__metadata("design:type", String)
806
+ ], PaymentTransaction.prototype, "pixQrCode", void 0);
807
+ tslib.__decorate([
808
+ classTransformer.Expose({ name: 'pix_expiration_date' }),
809
+ tslib.__metadata("design:type", String)
810
+ ], PaymentTransaction.prototype, "pixExpirationDate", void 0);
654
811
 
655
812
  class Payment extends BaseModel {
656
813
  static get identifiersFields() {
@@ -2258,6 +2415,82 @@ class StockOutError extends BusinessError {
2258
2415
  }
2259
2416
  }
2260
2417
 
2418
+ class AdyenCardService {
2419
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
2420
+ this.credentials = credentials;
2421
+ this.paymentRepository = paymentRepository;
2422
+ this.orderBlockedRepository = orderBlockedRepository;
2423
+ }
2424
+ async pay(checkout, card) {
2425
+ try {
2426
+ const result = await axios__default["default"]({
2427
+ method: 'POST',
2428
+ url: this.credentials.URL_TRANSACTION,
2429
+ headers: {
2430
+ 'x-api-key': this.credentials.API_KEY,
2431
+ 'content-type': 'application/json',
2432
+ },
2433
+ data: this.createCardPayment(checkout, card),
2434
+ });
2435
+ if (result.data.resultCode !== 'Authorised') {
2436
+ this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2437
+ return Promise.reject(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`, {
2438
+ checkoutId: checkout.id,
2439
+ userEmail: checkout.user.email,
2440
+ info: result.data,
2441
+ }));
2442
+ }
2443
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2444
+ createdAt: new Date(),
2445
+ updatedAt: new Date(),
2446
+ userId: checkout.user.id,
2447
+ checkoutId: checkout.id,
2448
+ totalPrice: checkout.totalPrice,
2449
+ paymentProvider: 'adyen',
2450
+ transaction: Object.assign(Object.assign({}, result.data), { status: 'paid' }),
2451
+ }));
2452
+ return payment;
2453
+ }
2454
+ catch (error) {
2455
+ 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', {
2456
+ checkoutId: checkout.id,
2457
+ userEmail: checkout.user.email,
2458
+ info: error.message,
2459
+ });
2460
+ }
2461
+ }
2462
+ createCardPayment(checkout, card) {
2463
+ return {
2464
+ amount: {
2465
+ currency: 'BRL',
2466
+ value: ((checkout === null || checkout === void 0 ? void 0 : checkout.totalPrice) || 0) * 100,
2467
+ },
2468
+ paymentMethod: {
2469
+ type: 'scheme',
2470
+ storedPaymentMethodId: card.cardId,
2471
+ },
2472
+ reference: checkout.id,
2473
+ shopperInteraction: 'Ecommerce',
2474
+ merchantAccount: this.credentials.MERCHANT_ACCOUNT,
2475
+ shopperReference: checkout.user.id,
2476
+ recurringProcessingModel: 'CardOnFile',
2477
+ returnUrl: this.credentials.URL_POSTBACK,
2478
+ installments: {
2479
+ value: card.installments,
2480
+ },
2481
+ };
2482
+ }
2483
+ addCard() {
2484
+ throw new Error('Method not implemented.');
2485
+ }
2486
+ getCardByToken(token) {
2487
+ throw new Error('Method not implemented.');
2488
+ }
2489
+ createTransaction(info) {
2490
+ throw new Error('Method not implemented.');
2491
+ }
2492
+ }
2493
+
2261
2494
  class AntifraudBankSlipService {
2262
2495
  constructor(orderBlockedRepository) {
2263
2496
  this.orderBlockedRepository = orderBlockedRepository;
@@ -2315,8 +2548,8 @@ class AntifraudCardService {
2315
2548
  }
2316
2549
  async verifyBlockedOrderAttempts(checkout, card) {
2317
2550
  var _a, _b, _c, _d;
2318
- const day = `${dateFns.format(new Date(), 'yyyy-MM-dd')}T00:00:00`;
2319
- const endOfDay = `${dateFns.format(new Date(), 'yyyy-MM-dd')}T23:59:59`;
2551
+ const day = `${dateFns.format(new Date(), 'YYYY-MM-DD')}T00:00:00`;
2552
+ const endOfDay = `${dateFns.format(new Date(), 'YYYY-MM-DD')}T23:59:59`;
2320
2553
  const ordersBlockedWithCpf = await this.orderBlockedRepository
2321
2554
  .find({
2322
2555
  filters: {
@@ -2464,8 +2697,7 @@ class AntifraudPixService {
2464
2697
  }
2465
2698
 
2466
2699
  class GlampointsPaymentService {
2467
- constructor(glamCredentials, paymentRepository) {
2468
- this.glamCredentials = glamCredentials;
2700
+ constructor(paymentRepository) {
2469
2701
  this.paymentRepository = paymentRepository;
2470
2702
  }
2471
2703
  async pay(checkout) {
@@ -2478,114 +2710,356 @@ class GlampointsPaymentService {
2478
2710
  paymentProvider: 'glampoints',
2479
2711
  transaction: {
2480
2712
  amount: 0,
2481
- acquirer_response_code: '0000',
2482
- acquirer_name: 'glampoints',
2483
- authorized_amount: 0,
2484
- capture_method: 'ecommerce',
2713
+ acquirerResponseCode: '0000',
2714
+ acquirerName: 'glampoints',
2715
+ authorizedAmount: 0,
2716
+ captureMethod: 'ecommerce',
2485
2717
  installments: 1,
2486
2718
  cost: 0,
2487
- paid_amount: 0,
2488
- paid_at: new Date().toISOString(),
2489
- payment_method: 'glampoints',
2719
+ paidAmount: 0,
2720
+ paidAt: new Date().toISOString(),
2721
+ paymentMethod: 'glampoints',
2490
2722
  referer: 'api_key',
2491
- refunded_amount: 0,
2723
+ refundedAmount: 0,
2492
2724
  status: 'paid',
2493
- status_reason: 'acquirer',
2494
- date_created: new Date().toISOString(),
2725
+ statusReason: 'acquirer',
2495
2726
  },
2496
2727
  }));
2497
2728
  return payment;
2498
2729
  }
2499
- async rewardByOrder(orderId, user, lineItens) {
2730
+ }
2731
+
2732
+ class PagarmeBankSlipService {
2733
+ constructor(credentials, paymentRepository) {
2734
+ this.credentials = credentials;
2735
+ this.paymentRepository = paymentRepository;
2736
+ }
2737
+ async pay(checkout) {
2500
2738
  try {
2501
- const points = lineItens.filter((item) => !item.isGift).reduce((acc, li) => acc + li.quantity, 0);
2502
2739
  const result = await axios__default["default"]({
2503
2740
  method: 'POST',
2504
- url: `${this.glamCredentials.baseUrl}/integration/win/reward`,
2505
- headers: {
2506
- 'Content-Type': 'application/json',
2507
- Authorization: `Bearer ${this.glamCredentials.integrationToken}`,
2508
- Origin: 'https://cloudfunctions.b4a.com.br',
2509
- },
2510
- timeout: 60000,
2511
- data: JSON.stringify({
2512
- personId: user.id,
2513
- rewardType: 50,
2514
- referenceId: 0,
2515
- referenceName: `Compra - ${points} produto(s)`,
2516
- points: points,
2517
- productId: '',
2518
- token: this.glamCredentials.integrationToken,
2519
- orderId,
2520
- glambeauty: lineItens === null || lineItens === void 0 ? void 0 : lineItens.some((doc) => doc.brand && doc.brand.toUpperCase() === 'GLAM BEAUTY'),
2521
- }),
2741
+ url: `${this.credentials.URL}/transactions`,
2742
+ data: this.createBoletoPayment(checkout),
2522
2743
  });
2523
- console.info('[rewards - rewardByOrder] reward success:', JSON.stringify(result));
2524
- return result.data;
2744
+ if (result.data.status !== exports.PagarmePaymentStatus['Em processamento']) {
2745
+ return Promise.reject(new PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
2746
+ checkoutId: checkout.id,
2747
+ userEmail: checkout.user.email,
2748
+ info: result.data,
2749
+ }));
2750
+ }
2751
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2752
+ createdAt: new Date(),
2753
+ updatedAt: new Date(),
2754
+ userId: checkout.user.id,
2755
+ checkoutId: checkout.id,
2756
+ totalPrice: checkout.totalPrice,
2757
+ paymentProvider: 'pagarMe',
2758
+ transaction: result.data,
2759
+ }));
2760
+ return payment;
2525
2761
  }
2526
- catch (err) {
2527
- console.log(err);
2528
- console.error('[rewards - rewardByOrder] reward request error', JSON.stringify(err));
2762
+ catch (error) {
2763
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
2764
+ checkoutId: checkout.id,
2765
+ userEmail: checkout.user.email,
2766
+ info: error.response.data,
2767
+ });
2529
2768
  }
2530
2769
  }
2531
- async negativateRewardByOrderId(orderId, orderNumber) {
2770
+ async getBoletoTransaction(paymentId) {
2532
2771
  try {
2533
- const result = await axios__default["default"]({
2534
- method: 'POST',
2535
- url: `${this.glamCredentials.baseUrl}/integration/negativate/reward`,
2536
- headers: {
2537
- 'Content-Type': 'application/json',
2538
- Authorization: `Bearer ${this.glamCredentials.integrationToken}`,
2539
- Origin: 'https://cloudfunctions.b4a.com.br',
2772
+ const { data } = await axios__default["default"]({
2773
+ method: 'GET',
2774
+ url: `${this.credentials.URL}/transactions/${paymentId}`,
2775
+ data: {
2776
+ api_key: this.credentials.API_KEY,
2540
2777
  },
2541
- timeout: 60000,
2542
- data: JSON.stringify({
2543
- rewardType: 51,
2544
- referenceName: `Pedido #${orderId} cancelado`,
2545
- token: '$2a$12$2DAPE64UUWAo4TT/1eQ9TOJO40b5z2jdomOJG3X7LeexwOHYtPydW',
2546
- orderId,
2547
- orderNumber: parseInt(orderNumber.replace(/\D/g, ''), 10),
2548
- }),
2549
2778
  });
2550
- return result;
2779
+ return data;
2551
2780
  }
2552
2781
  catch (error) {
2553
- return error;
2782
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
2783
+ paymentId,
2784
+ info: error.response.data,
2785
+ });
2554
2786
  }
2555
2787
  }
2556
- }
2557
-
2558
- class RoundProductPricesHelper {
2559
- static roundProductPrices(product) {
2560
- product.price.price = Number(product.price.price.toFixed(2));
2561
- product.price.fullPrice = Number(product.price.fullPrice.toFixed(2));
2562
- if (product.price.subscriberPrice) {
2563
- product.price.subscriberPrice = Number(product.price.subscriberPrice.toFixed(2));
2564
- }
2565
- if (product instanceof LineItem && product.pricePaid) {
2566
- product.pricePaid = Number(product.pricePaid.toFixed(2));
2567
- }
2568
- return product;
2788
+ createBoletoPayment(checkout) {
2789
+ return {
2790
+ api_key: this.credentials.API_KEY,
2791
+ amount: Math.floor(checkout.totalPrice * 100),
2792
+ boleto_rules: ['strict_expiration_date'],
2793
+ boleto_instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
2794
+ boleto_expiration_date: dateFns.format(dateFns.addDays(new Date(), 3), 'yyyy-MM-dd'),
2795
+ payment_method: 'boleto',
2796
+ postback_url: this.credentials.URL_POSTBACK,
2797
+ customer: {
2798
+ external_id: checkout.user.id,
2799
+ type: 'individual',
2800
+ country: 'br',
2801
+ name: checkout.user.displayName,
2802
+ documents: [
2803
+ {
2804
+ type: 'cpf',
2805
+ number: checkout.user.cpf,
2806
+ },
2807
+ ],
2808
+ },
2809
+ };
2569
2810
  }
2570
2811
  }
2571
2812
 
2572
- class LogDocument extends BaseModel {
2573
- static get identifiersFields() {
2574
- return ['id'];
2813
+ class PagarmeCardService {
2814
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
2815
+ this.credentials = credentials;
2816
+ this.paymentRepository = paymentRepository;
2817
+ this.orderBlockedRepository = orderBlockedRepository;
2575
2818
  }
2576
- }
2577
-
2578
- class Sequence extends BaseModel {
2579
- static get identifiersFields() {
2580
- return ['id'];
2819
+ async pay(checkout, card) {
2820
+ var _a;
2821
+ try {
2822
+ const result = await axios__default["default"]({
2823
+ method: 'POST',
2824
+ url: `${this.credentials.URL}/transactions`,
2825
+ data: this.createCardPayment(checkout, card),
2826
+ });
2827
+ if (result.data.status !== exports.PagarmePaymentStatus.Pago) {
2828
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2829
+ return Promise.reject(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`, {
2830
+ checkoutId: checkout.id,
2831
+ userEmail: checkout.user.email,
2832
+ info: result.data,
2833
+ }));
2834
+ }
2835
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2836
+ createdAt: new Date(),
2837
+ updatedAt: new Date(),
2838
+ userId: checkout.user.id,
2839
+ checkoutId: checkout.id,
2840
+ totalPrice: checkout.totalPrice,
2841
+ paymentProvider: exports.PaymentProviders.PAGARME,
2842
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
2843
+ }));
2844
+ return payment;
2845
+ }
2846
+ catch (error) {
2847
+ 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', {
2848
+ checkoutId: checkout.id,
2849
+ userEmail: checkout.user.email,
2850
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
2851
+ });
2852
+ }
2581
2853
  }
2582
- }
2583
-
2584
- exports.FilterType = void 0;
2585
- (function (FilterType) {
2586
- FilterType["ACCESSORY_IMPORTANCE"] = "accessoryImportance";
2587
- FilterType["BEARD_PROBLEMS"] = "beardProblems";
2588
- FilterType["BEARD_SIZE"] = "beardSize";
2854
+ async addCard(card) {
2855
+ try {
2856
+ const { data } = await axios__default["default"]({
2857
+ method: 'POST',
2858
+ url: `${this.credentials.URL}/cards`,
2859
+ data: {
2860
+ api_key: this.credentials.API_KEY,
2861
+ card_number: card.number,
2862
+ card_expiration_date: card.expirationDate.replace('/', ''),
2863
+ card_holder_name: card.name,
2864
+ card_cvv: card.cvv,
2865
+ },
2866
+ });
2867
+ return data;
2868
+ }
2869
+ catch (error) {
2870
+ throw new BusinessError('Houve uma falha adicionar o cartão', {
2871
+ info: error.response.data,
2872
+ });
2873
+ }
2874
+ }
2875
+ async createCardHash(bu) {
2876
+ const key = bu === exports.BusinessUnitEnum.SHOP ? this.credentials.API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
2877
+ try {
2878
+ const { data } = await axios__default["default"]({
2879
+ method: 'POST',
2880
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
2881
+ data: {
2882
+ api_key: key,
2883
+ },
2884
+ });
2885
+ return data;
2886
+ }
2887
+ catch (error) {
2888
+ throw new BusinessError('Houve uma falha gerar o hash', {
2889
+ info: error.response.data,
2890
+ });
2891
+ }
2892
+ }
2893
+ async getCardByToken(id) {
2894
+ try {
2895
+ const { data } = await axios__default["default"]({
2896
+ method: 'POST',
2897
+ url: `${this.credentials.URL}/cards/${id}`,
2898
+ data: {
2899
+ api_key: this.credentials.API_KEY,
2900
+ },
2901
+ });
2902
+ return data;
2903
+ }
2904
+ catch (error) {
2905
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + id, {
2906
+ info: error.response.data,
2907
+ });
2908
+ }
2909
+ }
2910
+ async createTransaction(info) {
2911
+ try {
2912
+ const { data } = await axios__default["default"]({
2913
+ method: 'POST',
2914
+ url: `${this.credentials.URL}/transactions`,
2915
+ data: Object.assign(Object.assign({}, info), { api_key: this.credentials.API_KEY }),
2916
+ });
2917
+ return data;
2918
+ }
2919
+ catch (error) {
2920
+ throw new BusinessError('Houve uma falha ao criar a transação', {
2921
+ info: error.response.data,
2922
+ });
2923
+ }
2924
+ }
2925
+ createCardPayment(checkout, card) {
2926
+ var _a, _b, _c, _d, _e, _f;
2927
+ return {
2928
+ api_key: this.credentials.API_KEY,
2929
+ amount: Math.floor(checkout.totalPrice * 100),
2930
+ card_id: card.cardId,
2931
+ payment_method: 'credit_card',
2932
+ installments: card.installments,
2933
+ soft_descriptor: checkout.shop === exports.Shops.GLAMSHOP ? 'Glam' : "Men's Market",
2934
+ customer: {
2935
+ external_id: checkout.user.id,
2936
+ name: checkout.user.displayName,
2937
+ type: 'individual',
2938
+ country: 'br',
2939
+ email: checkout.user.email,
2940
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
2941
+ documents: [
2942
+ {
2943
+ type: 'cpf',
2944
+ number: checkout.user.cpf,
2945
+ },
2946
+ ],
2947
+ },
2948
+ billing: {
2949
+ name: checkout.user.displayName,
2950
+ address: {
2951
+ country: 'br',
2952
+ state: checkout.billingAddress ? checkout.billingAddress.state : (_a = checkout.shippingAddress) === null || _a === void 0 ? void 0 : _a.state,
2953
+ city: checkout.billingAddress ? checkout.billingAddress.city : (_b = checkout.shippingAddress) === null || _b === void 0 ? void 0 : _b.city,
2954
+ neighborhood: checkout.billingAddress ? checkout.billingAddress.district : (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.district,
2955
+ street: checkout.billingAddress ? checkout.billingAddress.street : (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.street,
2956
+ street_number: checkout.billingAddress ? checkout.billingAddress.number : (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.number,
2957
+ zipcode: checkout.billingAddress
2958
+ ? checkout.billingAddress.zip.replace('-', '')
2959
+ : (_f = checkout.shippingAddress) === null || _f === void 0 ? void 0 : _f.zip.replace('-', ''),
2960
+ },
2961
+ },
2962
+ items: checkout.lineItems.map((item) => {
2963
+ return {
2964
+ id: item.id,
2965
+ title: checkout.user.isSubscriber ? `${item.name} - ASSINANTE` : item.name,
2966
+ unit_price: Math.floor(item.pricePaid * 100),
2967
+ quantity: item.quantity,
2968
+ tangible: true,
2969
+ };
2970
+ }),
2971
+ };
2972
+ }
2973
+ }
2974
+
2975
+ class PagarmePixService {
2976
+ constructor(credentials, paymentRepository) {
2977
+ this.credentials = credentials;
2978
+ this.paymentRepository = paymentRepository;
2979
+ }
2980
+ async pay(checkout) {
2981
+ var _a;
2982
+ try {
2983
+ const result = await axios__default["default"]({
2984
+ method: 'POST',
2985
+ url: `${this.credentials.URL}/transactions`,
2986
+ data: this.createPixPayment(checkout),
2987
+ });
2988
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2989
+ createdAt: new Date(),
2990
+ updatedAt: new Date(),
2991
+ userId: checkout.user.id,
2992
+ checkoutId: checkout.id,
2993
+ totalPrice: checkout.totalPrice,
2994
+ paymentProvider: 'pagarMe',
2995
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
2996
+ }));
2997
+ return payment;
2998
+ }
2999
+ catch (error) {
3000
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
3001
+ checkoutId: checkout.id,
3002
+ userEmail: checkout.user.email,
3003
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
3004
+ });
3005
+ }
3006
+ }
3007
+ createPixPayment(checkout) {
3008
+ return {
3009
+ payment_method: 'pix',
3010
+ amount: Math.floor(checkout.totalPrice * 100),
3011
+ api_key: this.credentials.API_KEY,
3012
+ postback_url: this.credentials.URL_POSTBACK,
3013
+ pix_expiration_date: dateFns.format(dateFns.addDays(new Date(), 1), 'yyyy-MM-dd'),
3014
+ customer: {
3015
+ external_id: checkout.user.id,
3016
+ type: 'individual',
3017
+ country: 'br',
3018
+ name: checkout.user.displayName,
3019
+ email: checkout.user.email.trim(),
3020
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
3021
+ documents: [
3022
+ {
3023
+ type: 'cpf',
3024
+ number: checkout.user.cpf,
3025
+ },
3026
+ ],
3027
+ },
3028
+ };
3029
+ }
3030
+ }
3031
+
3032
+ class RoundProductPricesHelper {
3033
+ static roundProductPrices(product) {
3034
+ product.price.price = Number(product.price.price.toFixed(2));
3035
+ product.price.fullPrice = Number(product.price.fullPrice.toFixed(2));
3036
+ if (product.price.subscriberPrice) {
3037
+ product.price.subscriberPrice = Number(product.price.subscriberPrice.toFixed(2));
3038
+ }
3039
+ if (product instanceof LineItem && product.pricePaid) {
3040
+ product.pricePaid = Number(product.pricePaid.toFixed(2));
3041
+ }
3042
+ return product;
3043
+ }
3044
+ }
3045
+
3046
+ class LogDocument extends BaseModel {
3047
+ static get identifiersFields() {
3048
+ return ['id'];
3049
+ }
3050
+ }
3051
+
3052
+ class Sequence extends BaseModel {
3053
+ static get identifiersFields() {
3054
+ return ['id'];
3055
+ }
3056
+ }
3057
+
3058
+ exports.FilterType = void 0;
3059
+ (function (FilterType) {
3060
+ FilterType["ACCESSORY_IMPORTANCE"] = "accessoryImportance";
3061
+ FilterType["BEARD_PROBLEMS"] = "beardProblems";
3062
+ FilterType["BEARD_SIZE"] = "beardSize";
2589
3063
  FilterType["BEAUTY_PRODUCT_IMPORTANCE"] = "beautyProductImportance";
2590
3064
  FilterType["BODY_PROBLEMS"] = "bodyProblems";
2591
3065
  FilterType["BODY_SHAPE"] = "bodyShape";
@@ -2719,126 +3193,47 @@ class ShopSettings extends BaseModel {
2719
3193
  }
2720
3194
  }
2721
3195
 
2722
- class AdyenCardAxiosAdapter {
2723
- constructor(credentials, paymentRepository, orderBlockedRepository) {
2724
- this.credentials = credentials;
2725
- this.paymentRepository = paymentRepository;
2726
- this.orderBlockedRepository = orderBlockedRepository;
3196
+ class AxiosAdapter {
3197
+ constructor(config) {
3198
+ this.config = config;
3199
+ this.logger = DebugHelper.from(this);
2727
3200
  }
2728
- createCardHash(bu) {
2729
- throw new Error('Method not implemented.');
3201
+ async get(index, id) {
3202
+ const logger = this.logger.with('get');
3203
+ const req = {
3204
+ url: `${this.config.url}/${index}/_doc/${id}`,
3205
+ method: 'GET',
3206
+ responseType: 'json',
3207
+ headers: {
3208
+ 'Content-Type': 'application/json',
3209
+ Authorization: `ApiKey ${this.config.credential}`,
3210
+ },
3211
+ };
3212
+ try {
3213
+ const { data } = await axios__default["default"](req);
3214
+ logger.log({ req, res: data });
3215
+ return data._source;
3216
+ }
3217
+ catch (error) {
3218
+ logger.error({ req, res: error });
3219
+ if (!(error instanceof Error))
3220
+ throw error;
3221
+ throw new NotFoundError(error.message);
3222
+ }
2730
3223
  }
2731
- async pay(checkout, card) {
2732
- try {
2733
- const result = await axios__default["default"]({
2734
- method: 'POST',
2735
- url: this.credentials.URL_TRANSACTION,
2736
- headers: {
2737
- 'x-api-key': this.credentials.API_KEY,
2738
- 'content-type': 'application/json',
2739
- },
2740
- data: this.createCardPayment(checkout, card),
2741
- });
2742
- if (result.data.resultCode !== 'Authorised') {
2743
- this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2744
- return Promise.reject(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`, {
2745
- checkoutId: checkout.id,
2746
- userEmail: checkout.user.email,
2747
- info: result.data,
2748
- }));
2749
- }
2750
- const payment = await this.paymentRepository.create(Payment.toInstance({
2751
- createdAt: new Date(),
2752
- updatedAt: new Date(),
2753
- userId: checkout.user.id,
2754
- checkoutId: checkout.id,
2755
- totalPrice: checkout.totalPrice,
2756
- paymentProvider: 'adyen',
2757
- transaction: Object.assign(Object.assign({}, result.data), { status: 'paid' }),
2758
- }));
2759
- return payment;
2760
- }
2761
- catch (error) {
2762
- 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', {
2763
- checkoutId: checkout.id,
2764
- userEmail: checkout.user.email,
2765
- info: error.message,
2766
- });
2767
- }
2768
- }
2769
- createCardPayment(checkout, card) {
2770
- return {
2771
- amount: {
2772
- currency: 'BRL',
2773
- value: ((checkout === null || checkout === void 0 ? void 0 : checkout.totalPrice) || 0) * 100,
2774
- },
2775
- paymentMethod: {
2776
- type: 'scheme',
2777
- storedPaymentMethodId: card.cardId,
2778
- },
2779
- reference: checkout.id,
2780
- shopperInteraction: 'Ecommerce',
2781
- merchantAccount: this.credentials.MERCHANT_ACCOUNT,
2782
- shopperReference: checkout.user.id,
2783
- recurringProcessingModel: 'CardOnFile',
2784
- returnUrl: this.credentials.URL_POSTBACK,
2785
- installments: {
2786
- value: card.installments,
2787
- },
2788
- };
2789
- }
2790
- addCard() {
2791
- throw new Error('Method not implemented.');
2792
- }
2793
- getCardByToken(token) {
2794
- throw new Error('Method not implemented.');
2795
- }
2796
- createTransaction(info) {
2797
- throw new Error('Method not implemented.');
2798
- }
2799
- }
2800
-
2801
- class AxiosAdapter {
2802
- constructor(config) {
2803
- this.config = config;
2804
- this.logger = DebugHelper.from(this);
2805
- }
2806
- async get(index, id) {
2807
- const logger = this.logger.with('get');
2808
- const req = {
2809
- url: `${this.config.url}/${index}/_doc/${id}`,
2810
- method: 'GET',
2811
- responseType: 'json',
2812
- headers: {
2813
- 'Content-Type': 'application/json',
2814
- Authorization: `ApiKey ${this.config.credential}`,
2815
- },
2816
- };
2817
- try {
2818
- const { data } = await axios__default["default"](req);
2819
- logger.log({ req, res: data });
2820
- return data._source;
2821
- }
2822
- catch (error) {
2823
- logger.error({ req, res: error });
2824
- if (!(error instanceof Error))
2825
- throw error;
2826
- throw new NotFoundError(error.message);
2827
- }
2828
- }
2829
- async query(index, query) {
2830
- const logger = this.logger.with('query');
2831
- const req = {
2832
- url: `${this.config.url}/${index}/_search`,
2833
- method: 'POST',
2834
- responseType: 'json',
2835
- headers: {
2836
- Accept: 'application/vnd.elasticsearch+json;compatible-with=7',
2837
- 'Content-Type': 'application/vnd.elasticsearch+json;compatible-with=7',
2838
- Authorization: `ApiKey ${this.config.credential}`,
2839
- },
2840
- data: query,
2841
- };
3224
+ async query(index, query) {
3225
+ const logger = this.logger.with('query');
3226
+ const req = {
3227
+ url: `${this.config.url}/${index}/_search`,
3228
+ method: 'POST',
3229
+ responseType: 'json',
3230
+ headers: {
3231
+ Accept: 'application/vnd.elasticsearch+json;compatible-with=7',
3232
+ 'Content-Type': 'application/vnd.elasticsearch+json;compatible-with=7',
3233
+ Authorization: `ApiKey ${this.config.credential}`,
3234
+ },
3235
+ data: query,
3236
+ };
2842
3237
  try {
2843
3238
  const { data } = await axios__default["default"](req);
2844
3239
  const res = {
@@ -3947,7 +4342,11 @@ class OrderBlockedFirestoreRepository extends withCrudFirestore(withHelpers(with
3947
4342
  limiteRange,
3948
4343
  type,
3949
4344
  card,
3950
- checkout,
4345
+ checkout: {
4346
+ id: checkout.id,
4347
+ shop: checkout.shop,
4348
+ total: checkout.totalPrice,
4349
+ },
3951
4350
  date: new Date(),
3952
4351
  }));
3953
4352
  }
@@ -6846,315 +7245,6 @@ tslib.__decorate([
6846
7245
  tslib.__metadata("design:returntype", Promise)
6847
7246
  ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
6848
7247
 
6849
- class PagarmeBankSlipAxiosAdapter {
6850
- constructor(credentials, paymentRepository) {
6851
- this.credentials = credentials;
6852
- this.paymentRepository = paymentRepository;
6853
- }
6854
- async pay(checkout) {
6855
- try {
6856
- const payload = this.createBoletoPayment(checkout);
6857
- const result = await axios__default["default"]({
6858
- method: 'POST',
6859
- url: `${this.credentials.URL}/transactions`,
6860
- data: this.createBoletoPayment(checkout),
6861
- });
6862
- console.log('[PAGARME BOLETO DATA TO SEND]', payload);
6863
- if (result.data.status !== exports.PagarmePaymentStatus['Em processamento']) {
6864
- return Promise.reject(new PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
6865
- checkoutId: checkout.id,
6866
- userEmail: checkout.user.email,
6867
- info: result.data,
6868
- }));
6869
- }
6870
- const payment = await this.paymentRepository.create({
6871
- createdAt: new Date(),
6872
- updatedAt: new Date(),
6873
- userId: checkout.user.id,
6874
- checkoutId: checkout.id,
6875
- totalPrice: checkout.totalPrice,
6876
- paymentProvider: 'pagarMe',
6877
- transaction: result.data,
6878
- });
6879
- return payment;
6880
- }
6881
- catch (error) {
6882
- throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
6883
- checkoutId: checkout.id,
6884
- userEmail: checkout.user.email,
6885
- info: error.response.data,
6886
- });
6887
- }
6888
- }
6889
- async getBoletoTransaction(paymentId) {
6890
- try {
6891
- const { data } = await axios__default["default"]({
6892
- method: 'GET',
6893
- url: `${this.credentials.URL}/transactions/${paymentId}`,
6894
- data: {
6895
- api_key: this.credentials.API_KEY,
6896
- },
6897
- });
6898
- return data;
6899
- }
6900
- catch (error) {
6901
- throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
6902
- paymentId,
6903
- info: error.response.data,
6904
- });
6905
- }
6906
- }
6907
- createBoletoPayment(checkout) {
6908
- return {
6909
- api_key: this.credentials.API_KEY,
6910
- amount: Math.floor(checkout.totalPrice * 100),
6911
- boleto_rules: ['strict_expiration_date'],
6912
- boleto_instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
6913
- boleto_expiration_date: dateFns.format(dateFns.addDays(new Date(), 3), 'yyyy-MM-dd'),
6914
- payment_method: 'boleto',
6915
- postback_url: this.credentials.URL_POSTBACK,
6916
- customer: {
6917
- external_id: checkout.user.id,
6918
- type: 'individual',
6919
- country: 'br',
6920
- name: checkout.user.displayName,
6921
- documents: [
6922
- {
6923
- type: 'cpf',
6924
- number: checkout.user.cpf,
6925
- },
6926
- ],
6927
- },
6928
- };
6929
- }
6930
- }
6931
-
6932
- class PagarmeCardAxiosAdapter {
6933
- constructor(credentials, paymentRepository, orderBlockedRepository) {
6934
- this.credentials = credentials;
6935
- this.paymentRepository = paymentRepository;
6936
- this.orderBlockedRepository = orderBlockedRepository;
6937
- }
6938
- async pay(checkout, card) {
6939
- var _a;
6940
- try {
6941
- const payload = this.createCardPayment(checkout, card);
6942
- const result = await axios__default["default"]({
6943
- method: 'POST',
6944
- url: `${this.credentials.URL}/transactions`,
6945
- data: payload,
6946
- });
6947
- console.log('[PAGARME CARD DATA TO SEND]', payload);
6948
- if (result.data.status !== exports.PagarmePaymentStatus.Pago) {
6949
- await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
6950
- return Promise.reject(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`, {
6951
- checkoutId: checkout.id,
6952
- userEmail: checkout.user.email,
6953
- info: result.data,
6954
- }));
6955
- }
6956
- const payment = await this.paymentRepository.create({
6957
- createdAt: new Date(),
6958
- updatedAt: new Date(),
6959
- userId: checkout.user.id,
6960
- checkoutId: checkout.id,
6961
- totalPrice: checkout.totalPrice,
6962
- paymentProvider: exports.PaymentProviders.PAGARME,
6963
- transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
6964
- });
6965
- return payment;
6966
- }
6967
- catch (error) {
6968
- 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', {
6969
- checkoutId: checkout.id,
6970
- userEmail: checkout.user.email,
6971
- info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
6972
- });
6973
- }
6974
- }
6975
- async addCard(card) {
6976
- try {
6977
- const { data } = await axios__default["default"]({
6978
- method: 'POST',
6979
- url: `${this.credentials.URL}/cards`,
6980
- data: {
6981
- api_key: this.credentials.API_KEY,
6982
- card_number: card.number,
6983
- card_expiration_date: card.expirationDate.replace('/', ''),
6984
- card_holder_name: card.name,
6985
- card_cvv: card.cvv,
6986
- },
6987
- });
6988
- return data;
6989
- }
6990
- catch (error) {
6991
- throw new BusinessError('Houve uma falha adicionar o cartão', {
6992
- info: error.response.data,
6993
- });
6994
- }
6995
- }
6996
- async createCardHash(bu) {
6997
- const key = bu === exports.BusinessUnitEnum.SHOP ? this.credentials.SHOP_API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
6998
- try {
6999
- const { data } = await axios__default["default"]({
7000
- method: 'GET',
7001
- headers: {
7002
- 'content-type': 'application/json',
7003
- },
7004
- url: `${this.credentials.URL}/transactions/card_hash_key`,
7005
- data: JSON.stringify({
7006
- api_key: key,
7007
- }),
7008
- });
7009
- return data;
7010
- }
7011
- catch (error) {
7012
- throw new BusinessError('Houve uma falha gerar o hash', {
7013
- info: error.response.data,
7014
- });
7015
- }
7016
- }
7017
- async getCardByToken(id) {
7018
- try {
7019
- const { data } = await axios__default["default"]({
7020
- method: 'POST',
7021
- url: `${this.credentials.URL}/cards/${id}`,
7022
- data: {
7023
- api_key: this.credentials.API_KEY,
7024
- },
7025
- });
7026
- return data;
7027
- }
7028
- catch (error) {
7029
- throw new BusinessError('Houve uma falha buscar o cartão com id: ' + id, {
7030
- info: error.response.data,
7031
- });
7032
- }
7033
- }
7034
- async createTransaction(info) {
7035
- try {
7036
- const { data } = await axios__default["default"]({
7037
- method: 'POST',
7038
- url: `${this.credentials.URL}/transactions`,
7039
- data: Object.assign(Object.assign({}, info), { api_key: this.credentials.API_KEY }),
7040
- });
7041
- return data;
7042
- }
7043
- catch (error) {
7044
- throw new BusinessError('Houve uma falha ao criar a transação', {
7045
- info: error.response.data,
7046
- });
7047
- }
7048
- }
7049
- createCardPayment(checkout, card) {
7050
- var _a, _b, _c, _d, _e, _f;
7051
- return {
7052
- api_key: this.credentials.API_KEY,
7053
- amount: Math.floor(checkout.totalPrice * 100),
7054
- card_id: card.cardId,
7055
- payment_method: 'credit_card',
7056
- installments: card.installments,
7057
- soft_descriptor: checkout.shop === exports.Shops.GLAMSHOP ? 'Glam' : "Men's Market",
7058
- customer: {
7059
- external_id: checkout.user.id,
7060
- name: checkout.user.displayName,
7061
- type: 'individual',
7062
- country: 'br',
7063
- email: checkout.user.email,
7064
- phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
7065
- documents: [
7066
- {
7067
- type: 'cpf',
7068
- number: checkout.user.cpf,
7069
- },
7070
- ],
7071
- },
7072
- billing: {
7073
- name: checkout.user.displayName,
7074
- address: {
7075
- country: 'br',
7076
- state: checkout.billingAddress ? checkout.billingAddress.state : (_a = checkout.shippingAddress) === null || _a === void 0 ? void 0 : _a.state,
7077
- city: checkout.billingAddress ? checkout.billingAddress.city : (_b = checkout.shippingAddress) === null || _b === void 0 ? void 0 : _b.city,
7078
- neighborhood: checkout.billingAddress ? checkout.billingAddress.district : (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.district,
7079
- street: checkout.billingAddress ? checkout.billingAddress.street : (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.street,
7080
- street_number: checkout.billingAddress ? checkout.billingAddress.number : (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.number,
7081
- zipcode: checkout.billingAddress
7082
- ? checkout.billingAddress.zip.replace('-', '')
7083
- : (_f = checkout.shippingAddress) === null || _f === void 0 ? void 0 : _f.zip.replace('-', ''),
7084
- },
7085
- },
7086
- items: checkout.lineItems.map((item) => {
7087
- return {
7088
- id: item.id,
7089
- title: checkout.user.isSubscriber ? `${item.name} - ASSINANTE` : item.name,
7090
- unit_price: Math.floor(item.pricePaid * 100),
7091
- quantity: item.quantity,
7092
- tangible: true,
7093
- };
7094
- }),
7095
- };
7096
- }
7097
- }
7098
-
7099
- class PagarmePixAxiosAdapter {
7100
- constructor(credentials, paymentRepository) {
7101
- this.credentials = credentials;
7102
- this.paymentRepository = paymentRepository;
7103
- }
7104
- async pay(checkout) {
7105
- var _a;
7106
- try {
7107
- const payload = this.createPixPayment(checkout);
7108
- const result = await axios__default["default"]({
7109
- method: 'POST',
7110
- url: `${this.credentials.URL}/transactions`,
7111
- data: payload,
7112
- });
7113
- console.log('[PAGARME PIX DATA TO SEND]', payload);
7114
- const payment = await this.paymentRepository.create({
7115
- createdAt: new Date(),
7116
- updatedAt: new Date(),
7117
- userId: checkout.user.id,
7118
- checkoutId: checkout.id,
7119
- totalPrice: checkout.totalPrice,
7120
- paymentProvider: 'pagarMe',
7121
- transaction: result.data,
7122
- });
7123
- return payment;
7124
- }
7125
- catch (error) {
7126
- throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
7127
- checkoutId: checkout.id,
7128
- userEmail: checkout.user.email,
7129
- info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
7130
- });
7131
- }
7132
- }
7133
- createPixPayment(checkout) {
7134
- return {
7135
- payment_method: 'pix',
7136
- amount: Math.floor(checkout.totalPrice * 100),
7137
- api_key: this.credentials.API_KEY,
7138
- postback_url: this.credentials.URL_POSTBACK,
7139
- pix_expiration_date: dateFns.format(dateFns.addDays(new Date(), 1), 'yyyy-MM-dd'),
7140
- customer: {
7141
- external_id: checkout.user.id,
7142
- type: 'individual',
7143
- country: 'br',
7144
- name: checkout.user.displayName,
7145
- email: checkout.user.email.trim(),
7146
- phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
7147
- documents: [
7148
- {
7149
- type: 'cpf',
7150
- number: checkout.user.cpf,
7151
- },
7152
- ],
7153
- },
7154
- };
7155
- }
7156
- }
7157
-
7158
7248
  class VertexAxiosAdapter {
7159
7249
  constructor(config) {
7160
7250
  this.config = config;
@@ -7429,7 +7519,7 @@ Object.defineProperty(exports, 'unset', {
7429
7519
  get: function () { return lodash.unset; }
7430
7520
  });
7431
7521
  exports.Address = Address;
7432
- exports.AdyenCardAxiosAdapter = AdyenCardAxiosAdapter;
7522
+ exports.AdyenCardService = AdyenCardService;
7433
7523
  exports.AdyenPaymentMethodFactory = AdyenPaymentMethodFactory;
7434
7524
  exports.AntifraudBankSlipService = AntifraudBankSlipService;
7435
7525
  exports.AntifraudCardService = AntifraudCardService;
@@ -7502,10 +7592,10 @@ exports.Order = Order;
7502
7592
  exports.OrderBlocked = OrderBlocked;
7503
7593
  exports.OrderBlockedFirestoreRepository = OrderBlockedFirestoreRepository;
7504
7594
  exports.OrderFirestoreRepository = OrderFirestoreRepository;
7505
- exports.PagarmeBankSlipAxiosAdapter = PagarmeBankSlipAxiosAdapter;
7506
- exports.PagarmeCardAxiosAdapter = PagarmeCardAxiosAdapter;
7595
+ exports.PagarmeBankSlipService = PagarmeBankSlipService;
7596
+ exports.PagarmeCardService = PagarmeCardService;
7507
7597
  exports.PagarmePaymentMethodFactory = PagarmePaymentMethodFactory;
7508
- exports.PagarmePixAxiosAdapter = PagarmePixAxiosAdapter;
7598
+ exports.PagarmePixService = PagarmePixService;
7509
7599
  exports.Payment = Payment;
7510
7600
  exports.PaymentError = PaymentError;
7511
7601
  exports.PaymentFirestoreRepository = PaymentFirestoreRepository;