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