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

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 (24) hide show
  1. package/index.cjs.js +407 -404
  2. package/index.esm.js +404 -401
  3. package/package.json +1 -1
  4. package/src/domain/shopping/enums/index.d.ts +1 -0
  5. package/src/domain/shopping/enums/order-blocked.enum.d.ts +5 -0
  6. package/src/domain/shopping/models/order-blocked.d.ts +4 -6
  7. package/src/domain/shopping/services/index.d.ts +0 -4
  8. package/src/domain/shopping/types/pagarme-card-manual-hash.type.d.ts +6 -0
  9. package/src/errors/index.d.ts +1 -0
  10. package/src/errors/types/index.d.ts +1 -0
  11. package/src/errors/types/pagarme-erros.type.d.ts +9 -0
  12. package/src/{domain/shopping/services/adyen-card-payment.service.d.ts → infra/adyen/adapters/adyen-card-payment-axios.adapter.d.ts} +5 -5
  13. package/src/infra/adyen/adapters/index.d.ts +1 -0
  14. package/src/infra/adyen/index.d.ts +1 -0
  15. package/src/infra/firebase/firestore/repositories/shopping/order-blocked-firestore.repository.d.ts +2 -2
  16. package/src/infra/index.d.ts +2 -0
  17. package/src/infra/pagarme/adapters/index.d.ts +3 -0
  18. package/src/infra/pagarme/adapters/pagarme-bank-slip-payment-axios.adapter.d.ts +12 -0
  19. package/src/{domain/shopping/services/pagarme-card-payment.service.d.ts → infra/pagarme/adapters/pagarme-card-payment-axios.adapter.d.ts} +6 -6
  20. package/src/infra/pagarme/adapters/pagarme-pix-payment-axios.adapter.d.ts +11 -0
  21. package/src/infra/pagarme/index.d.ts +1 -0
  22. package/src/domain/shopping/services/pagarme-bank-slip-payment.service.d.ts +0 -12
  23. package/src/domain/shopping/services/pagarme-pix-payment.service.d.ts +0 -11
  24. package/src/infra/firebase/firestore/repositories/shopping/order-blocked-firestore.repository.ts.d.ts +0 -9
package/index.esm.js CHANGED
@@ -27,6 +27,13 @@ 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
+
30
37
  var PagarmePaymentStatus;
31
38
  (function (PagarmePaymentStatus) {
32
39
  PagarmePaymentStatus["Em processamento"] = "processing";
@@ -2409,82 +2416,6 @@ class StockOutError extends BusinessError {
2409
2416
  }
2410
2417
  }
2411
2418
 
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
-
2488
2419
  class AntifraudBankSlipService {
2489
2420
  constructor(orderBlockedRepository) {
2490
2421
  this.orderBlockedRepository = orderBlockedRepository;
@@ -2542,8 +2473,8 @@ class AntifraudCardService {
2542
2473
  }
2543
2474
  async verifyBlockedOrderAttempts(checkout, card) {
2544
2475
  var _a, _b, _c, _d;
2545
- const day = `${format(new Date(), 'YYYY-MM-DD')}T00:00:00`;
2546
- const endOfDay = `${format(new Date(), 'YYYY-MM-DD')}T23:59:59`;
2476
+ const day = `${format(new Date(), 'yyyy-MM-DD')}T00:00:00`;
2477
+ const endOfDay = `${format(new Date(), 'yyyy-MM-DD')}T23:59:59`;
2547
2478
  const ordersBlockedWithCpf = await this.orderBlockedRepository
2548
2479
  .find({
2549
2480
  filters: {
@@ -2723,329 +2654,29 @@ class GlampointsPaymentService {
2723
2654
  }
2724
2655
  }
2725
2656
 
2726
- class PagarmeBankSlipService {
2727
- constructor(credentials, paymentRepository) {
2728
- this.credentials = credentials;
2729
- this.paymentRepository = paymentRepository;
2730
- }
2731
- async pay(checkout) {
2732
- try {
2733
- const result = await axios({
2734
- method: 'POST',
2735
- url: `${this.credentials.URL}/transactions`,
2736
- data: this.createBoletoPayment(checkout),
2737
- });
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;
2755
- }
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
- });
2762
- }
2763
- }
2764
- async getBoletoTransaction(paymentId) {
2765
- try {
2766
- const { data } = await axios({
2767
- method: 'GET',
2768
- url: `${this.credentials.URL}/transactions/${paymentId}`,
2769
- data: {
2770
- api_key: this.credentials.API_KEY,
2771
- },
2772
- });
2773
- return data;
2657
+ class RoundProductPricesHelper {
2658
+ static roundProductPrices(product) {
2659
+ product.price.price = Number(product.price.price.toFixed(2));
2660
+ product.price.fullPrice = Number(product.price.fullPrice.toFixed(2));
2661
+ if (product.price.subscriberPrice) {
2662
+ product.price.subscriberPrice = Number(product.price.subscriberPrice.toFixed(2));
2774
2663
  }
2775
- catch (error) {
2776
- throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
2777
- paymentId,
2778
- info: error.response.data,
2779
- });
2664
+ if (product instanceof LineItem && product.pricePaid) {
2665
+ product.pricePaid = Number(product.pricePaid.toFixed(2));
2780
2666
  }
2781
- }
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
- };
2667
+ return product;
2804
2668
  }
2805
2669
  }
2806
2670
 
2807
- class PagarmeCardService {
2808
- constructor(credentials, paymentRepository, orderBlockedRepository) {
2809
- this.credentials = credentials;
2810
- this.paymentRepository = paymentRepository;
2811
- this.orderBlockedRepository = orderBlockedRepository;
2812
- }
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
- }
2847
- }
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
- }
2671
+ class LogDocument extends BaseModel {
2672
+ static get identifiersFields() {
2673
+ return ['id'];
2868
2674
  }
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'];
2675
+ }
2676
+
2677
+ class Sequence extends BaseModel {
2678
+ static get identifiersFields() {
2679
+ return ['id'];
3049
2680
  }
3050
2681
  }
3051
2682
 
@@ -3187,6 +2818,82 @@ class ShopSettings extends BaseModel {
3187
2818
  }
3188
2819
  }
3189
2820
 
2821
+ class AdyenCardAxiosAdapter {
2822
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
2823
+ this.credentials = credentials;
2824
+ this.paymentRepository = paymentRepository;
2825
+ this.orderBlockedRepository = orderBlockedRepository;
2826
+ }
2827
+ async pay(checkout, card) {
2828
+ try {
2829
+ const result = await axios({
2830
+ method: 'POST',
2831
+ url: this.credentials.URL_TRANSACTION,
2832
+ headers: {
2833
+ 'x-api-key': this.credentials.API_KEY,
2834
+ 'content-type': 'application/json',
2835
+ },
2836
+ data: this.createCardPayment(checkout, card),
2837
+ });
2838
+ if (result.data.resultCode !== 'Authorised') {
2839
+ this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2840
+ 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`, {
2841
+ checkoutId: checkout.id,
2842
+ userEmail: checkout.user.email,
2843
+ info: result.data,
2844
+ }));
2845
+ }
2846
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2847
+ createdAt: new Date(),
2848
+ updatedAt: new Date(),
2849
+ userId: checkout.user.id,
2850
+ checkoutId: checkout.id,
2851
+ totalPrice: checkout.totalPrice,
2852
+ paymentProvider: 'adyen',
2853
+ transaction: Object.assign(Object.assign({}, result.data), { status: 'paid' }),
2854
+ }));
2855
+ return payment;
2856
+ }
2857
+ catch (error) {
2858
+ 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', {
2859
+ checkoutId: checkout.id,
2860
+ userEmail: checkout.user.email,
2861
+ info: error.message,
2862
+ });
2863
+ }
2864
+ }
2865
+ createCardPayment(checkout, card) {
2866
+ return {
2867
+ amount: {
2868
+ currency: 'BRL',
2869
+ value: ((checkout === null || checkout === void 0 ? void 0 : checkout.totalPrice) || 0) * 100,
2870
+ },
2871
+ paymentMethod: {
2872
+ type: 'scheme',
2873
+ storedPaymentMethodId: card.cardId,
2874
+ },
2875
+ reference: checkout.id,
2876
+ shopperInteraction: 'Ecommerce',
2877
+ merchantAccount: this.credentials.MERCHANT_ACCOUNT,
2878
+ shopperReference: checkout.user.id,
2879
+ recurringProcessingModel: 'CardOnFile',
2880
+ returnUrl: this.credentials.URL_POSTBACK,
2881
+ installments: {
2882
+ value: card.installments,
2883
+ },
2884
+ };
2885
+ }
2886
+ addCard() {
2887
+ throw new Error('Method not implemented.');
2888
+ }
2889
+ getCardByToken(token) {
2890
+ throw new Error('Method not implemented.');
2891
+ }
2892
+ createTransaction(info) {
2893
+ throw new Error('Method not implemented.');
2894
+ }
2895
+ }
2896
+
3190
2897
  class AxiosAdapter {
3191
2898
  constructor(config) {
3192
2899
  this.config = config;
@@ -4336,11 +4043,7 @@ class OrderBlockedFirestoreRepository extends withCrudFirestore(withHelpers(with
4336
4043
  limiteRange,
4337
4044
  type,
4338
4045
  card,
4339
- checkout: {
4340
- id: checkout.id,
4341
- shop: checkout.shop,
4342
- total: checkout.totalPrice,
4343
- },
4046
+ checkout,
4344
4047
  date: new Date(),
4345
4048
  }));
4346
4049
  }
@@ -7239,6 +6942,306 @@ __decorate([
7239
6942
  __metadata("design:returntype", Promise)
7240
6943
  ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
7241
6944
 
6945
+ class PagarmeBankSlipAxiosAdapter {
6946
+ constructor(credentials, paymentRepository) {
6947
+ this.credentials = credentials;
6948
+ this.paymentRepository = paymentRepository;
6949
+ }
6950
+ async pay(checkout) {
6951
+ try {
6952
+ const result = await axios({
6953
+ method: 'POST',
6954
+ url: `${this.credentials.URL}/transactions`,
6955
+ data: this.createBoletoPayment(checkout),
6956
+ });
6957
+ if (result.data.status !== PagarmePaymentStatus['Em processamento']) {
6958
+ return Promise.reject(new PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
6959
+ checkoutId: checkout.id,
6960
+ userEmail: checkout.user.email,
6961
+ info: result.data,
6962
+ }));
6963
+ }
6964
+ const payment = await this.paymentRepository.create(Payment.toInstance({
6965
+ createdAt: new Date(),
6966
+ updatedAt: new Date(),
6967
+ userId: checkout.user.id,
6968
+ checkoutId: checkout.id,
6969
+ totalPrice: checkout.totalPrice,
6970
+ paymentProvider: 'pagarMe',
6971
+ transaction: result.data,
6972
+ }));
6973
+ return payment;
6974
+ }
6975
+ catch (error) {
6976
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
6977
+ checkoutId: checkout.id,
6978
+ userEmail: checkout.user.email,
6979
+ info: error.response.data,
6980
+ });
6981
+ }
6982
+ }
6983
+ async getBoletoTransaction(paymentId) {
6984
+ try {
6985
+ const { data } = await axios({
6986
+ method: 'GET',
6987
+ url: `${this.credentials.URL}/transactions/${paymentId}`,
6988
+ data: {
6989
+ api_key: this.credentials.API_KEY,
6990
+ },
6991
+ });
6992
+ return data;
6993
+ }
6994
+ catch (error) {
6995
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
6996
+ paymentId,
6997
+ info: error.response.data,
6998
+ });
6999
+ }
7000
+ }
7001
+ createBoletoPayment(checkout) {
7002
+ return {
7003
+ api_key: this.credentials.API_KEY,
7004
+ amount: Math.floor(checkout.totalPrice * 100),
7005
+ boleto_rules: ['strict_expiration_date'],
7006
+ boleto_instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
7007
+ boleto_expiration_date: format(addDays(new Date(), 3), 'yyyy-MM-dd'),
7008
+ payment_method: 'boleto',
7009
+ postback_url: this.credentials.URL_POSTBACK,
7010
+ customer: {
7011
+ external_id: checkout.user.id,
7012
+ type: 'individual',
7013
+ country: 'br',
7014
+ name: checkout.user.displayName,
7015
+ documents: [
7016
+ {
7017
+ type: 'cpf',
7018
+ number: checkout.user.cpf,
7019
+ },
7020
+ ],
7021
+ },
7022
+ };
7023
+ }
7024
+ }
7025
+
7026
+ class PagarmeCardAxiosAdapter {
7027
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
7028
+ this.credentials = credentials;
7029
+ this.paymentRepository = paymentRepository;
7030
+ this.orderBlockedRepository = orderBlockedRepository;
7031
+ }
7032
+ async pay(checkout, card) {
7033
+ var _a;
7034
+ try {
7035
+ const result = await axios({
7036
+ method: 'POST',
7037
+ url: `${this.credentials.URL}/transactions`,
7038
+ data: this.createCardPayment(checkout, card),
7039
+ });
7040
+ if (result.data.status !== PagarmePaymentStatus.Pago) {
7041
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
7042
+ 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`, {
7043
+ checkoutId: checkout.id,
7044
+ userEmail: checkout.user.email,
7045
+ info: result.data,
7046
+ }));
7047
+ }
7048
+ const payment = await this.paymentRepository.create(Payment.toInstance({
7049
+ createdAt: new Date(),
7050
+ updatedAt: new Date(),
7051
+ userId: checkout.user.id,
7052
+ checkoutId: checkout.id,
7053
+ totalPrice: checkout.totalPrice,
7054
+ paymentProvider: PaymentProviders.PAGARME,
7055
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
7056
+ }));
7057
+ return payment;
7058
+ }
7059
+ catch (error) {
7060
+ 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', {
7061
+ checkoutId: checkout.id,
7062
+ userEmail: checkout.user.email,
7063
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
7064
+ });
7065
+ }
7066
+ }
7067
+ async addCard(card) {
7068
+ try {
7069
+ const { data } = await axios({
7070
+ method: 'POST',
7071
+ url: `${this.credentials.URL}/cards`,
7072
+ data: {
7073
+ api_key: this.credentials.API_KEY,
7074
+ card_number: card.number,
7075
+ card_expiration_date: card.expirationDate.replace('/', ''),
7076
+ card_holder_name: card.name,
7077
+ card_cvv: card.cvv,
7078
+ },
7079
+ });
7080
+ return data;
7081
+ }
7082
+ catch (error) {
7083
+ throw new BusinessError('Houve uma falha adicionar o cartão', {
7084
+ info: error.response.data,
7085
+ });
7086
+ }
7087
+ }
7088
+ async createCardHash(bu) {
7089
+ const key = bu === BusinessUnitEnum.SHOP ? this.credentials.SHOP_API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
7090
+ try {
7091
+ const { data } = await axios({
7092
+ method: 'GET',
7093
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
7094
+ data: {
7095
+ api_key: key,
7096
+ },
7097
+ });
7098
+ return data;
7099
+ }
7100
+ catch (error) {
7101
+ throw new BusinessError('Houve uma falha gerar o hash', {
7102
+ info: error.response.data,
7103
+ });
7104
+ }
7105
+ }
7106
+ async getCardByToken(id) {
7107
+ try {
7108
+ const { data } = await axios({
7109
+ method: 'POST',
7110
+ url: `${this.credentials.URL}/cards/${id}`,
7111
+ data: {
7112
+ api_key: this.credentials.API_KEY,
7113
+ },
7114
+ });
7115
+ return data;
7116
+ }
7117
+ catch (error) {
7118
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + id, {
7119
+ info: error.response.data,
7120
+ });
7121
+ }
7122
+ }
7123
+ async createTransaction(info) {
7124
+ try {
7125
+ const { data } = await axios({
7126
+ method: 'POST',
7127
+ url: `${this.credentials.URL}/transactions`,
7128
+ data: Object.assign(Object.assign({}, info), { api_key: this.credentials.API_KEY }),
7129
+ });
7130
+ return data;
7131
+ }
7132
+ catch (error) {
7133
+ throw new BusinessError('Houve uma falha ao criar a transação', {
7134
+ info: error.response.data,
7135
+ });
7136
+ }
7137
+ }
7138
+ createCardPayment(checkout, card) {
7139
+ var _a, _b, _c, _d, _e, _f;
7140
+ return {
7141
+ api_key: this.credentials.API_KEY,
7142
+ amount: Math.floor(checkout.totalPrice * 100),
7143
+ card_id: card.cardId,
7144
+ payment_method: 'credit_card',
7145
+ installments: card.installments,
7146
+ soft_descriptor: checkout.shop === Shops.GLAMSHOP ? 'Glam' : "Men's Market",
7147
+ customer: {
7148
+ external_id: checkout.user.id,
7149
+ name: checkout.user.displayName,
7150
+ type: 'individual',
7151
+ country: 'br',
7152
+ email: checkout.user.email,
7153
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
7154
+ documents: [
7155
+ {
7156
+ type: 'cpf',
7157
+ number: checkout.user.cpf,
7158
+ },
7159
+ ],
7160
+ },
7161
+ billing: {
7162
+ name: checkout.user.displayName,
7163
+ address: {
7164
+ country: 'br',
7165
+ state: checkout.billingAddress ? checkout.billingAddress.state : (_a = checkout.shippingAddress) === null || _a === void 0 ? void 0 : _a.state,
7166
+ city: checkout.billingAddress ? checkout.billingAddress.city : (_b = checkout.shippingAddress) === null || _b === void 0 ? void 0 : _b.city,
7167
+ neighborhood: checkout.billingAddress ? checkout.billingAddress.district : (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.district,
7168
+ street: checkout.billingAddress ? checkout.billingAddress.street : (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.street,
7169
+ street_number: checkout.billingAddress ? checkout.billingAddress.number : (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.number,
7170
+ zipcode: checkout.billingAddress
7171
+ ? checkout.billingAddress.zip.replace('-', '')
7172
+ : (_f = checkout.shippingAddress) === null || _f === void 0 ? void 0 : _f.zip.replace('-', ''),
7173
+ },
7174
+ },
7175
+ items: checkout.lineItems.map((item) => {
7176
+ return {
7177
+ id: item.id,
7178
+ title: checkout.user.isSubscriber ? `${item.name} - ASSINANTE` : item.name,
7179
+ unit_price: Math.floor(item.pricePaid * 100),
7180
+ quantity: item.quantity,
7181
+ tangible: true,
7182
+ };
7183
+ }),
7184
+ };
7185
+ }
7186
+ }
7187
+
7188
+ class PagarmePixAxiosAdapter {
7189
+ constructor(credentials, paymentRepository) {
7190
+ this.credentials = credentials;
7191
+ this.paymentRepository = paymentRepository;
7192
+ }
7193
+ async pay(checkout) {
7194
+ var _a;
7195
+ try {
7196
+ const result = await axios({
7197
+ method: 'POST',
7198
+ url: `${this.credentials.URL}/transactions`,
7199
+ data: this.createPixPayment(checkout),
7200
+ });
7201
+ const payment = await this.paymentRepository.create(Payment.toInstance({
7202
+ createdAt: new Date(),
7203
+ updatedAt: new Date(),
7204
+ userId: checkout.user.id,
7205
+ checkoutId: checkout.id,
7206
+ totalPrice: checkout.totalPrice,
7207
+ paymentProvider: 'pagarMe',
7208
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
7209
+ }));
7210
+ return payment;
7211
+ }
7212
+ catch (error) {
7213
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
7214
+ checkoutId: checkout.id,
7215
+ userEmail: checkout.user.email,
7216
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
7217
+ });
7218
+ }
7219
+ }
7220
+ createPixPayment(checkout) {
7221
+ return {
7222
+ payment_method: 'pix',
7223
+ amount: Math.floor(checkout.totalPrice * 100),
7224
+ api_key: this.credentials.API_KEY,
7225
+ postback_url: this.credentials.URL_POSTBACK,
7226
+ pix_expiration_date: format(addDays(new Date(), 1), 'yyyy-MM-dd'),
7227
+ customer: {
7228
+ external_id: checkout.user.id,
7229
+ type: 'individual',
7230
+ country: 'br',
7231
+ name: checkout.user.displayName,
7232
+ email: checkout.user.email.trim(),
7233
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
7234
+ documents: [
7235
+ {
7236
+ type: 'cpf',
7237
+ number: checkout.user.cpf,
7238
+ },
7239
+ ],
7240
+ },
7241
+ };
7242
+ }
7243
+ }
7244
+
7242
7245
  class VertexAxiosAdapter {
7243
7246
  constructor(config) {
7244
7247
  this.config = config;
@@ -7392,4 +7395,4 @@ class ProductsVertexSearch {
7392
7395
  }
7393
7396
  }
7394
7397
 
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 };
7398
+ 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 };