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

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.
package/index.esm.js CHANGED
@@ -2409,82 +2409,6 @@ class StockOutError extends BusinessError {
2409
2409
  }
2410
2410
  }
2411
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
-
2488
2412
  class AntifraudBankSlipService {
2489
2413
  constructor(orderBlockedRepository) {
2490
2414
  this.orderBlockedRepository = orderBlockedRepository;
@@ -2723,329 +2647,29 @@ class GlampointsPaymentService {
2723
2647
  }
2724
2648
  }
2725
2649
 
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;
2650
+ class RoundProductPricesHelper {
2651
+ static roundProductPrices(product) {
2652
+ product.price.price = Number(product.price.price.toFixed(2));
2653
+ product.price.fullPrice = Number(product.price.fullPrice.toFixed(2));
2654
+ if (product.price.subscriberPrice) {
2655
+ product.price.subscriberPrice = Number(product.price.subscriberPrice.toFixed(2));
2774
2656
  }
2775
- catch (error) {
2776
- throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
2777
- paymentId,
2778
- info: error.response.data,
2779
- });
2657
+ if (product instanceof LineItem && product.pricePaid) {
2658
+ product.pricePaid = Number(product.pricePaid.toFixed(2));
2780
2659
  }
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
- };
2660
+ return product;
2804
2661
  }
2805
2662
  }
2806
2663
 
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
- }
2664
+ class LogDocument extends BaseModel {
2665
+ static get identifiersFields() {
2666
+ return ['id'];
2868
2667
  }
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'];
2668
+ }
2669
+
2670
+ class Sequence extends BaseModel {
2671
+ static get identifiersFields() {
2672
+ return ['id'];
3049
2673
  }
3050
2674
  }
3051
2675
 
@@ -3187,6 +2811,82 @@ class ShopSettings extends BaseModel {
3187
2811
  }
3188
2812
  }
3189
2813
 
2814
+ class AdyenCardAxiosAdapter {
2815
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
2816
+ this.credentials = credentials;
2817
+ this.paymentRepository = paymentRepository;
2818
+ this.orderBlockedRepository = orderBlockedRepository;
2819
+ }
2820
+ async pay(checkout, card) {
2821
+ try {
2822
+ const result = await axios({
2823
+ method: 'POST',
2824
+ url: this.credentials.URL_TRANSACTION,
2825
+ headers: {
2826
+ 'x-api-key': this.credentials.API_KEY,
2827
+ 'content-type': 'application/json',
2828
+ },
2829
+ data: this.createCardPayment(checkout, card),
2830
+ });
2831
+ if (result.data.resultCode !== 'Authorised') {
2832
+ this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2833
+ 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`, {
2834
+ checkoutId: checkout.id,
2835
+ userEmail: checkout.user.email,
2836
+ info: result.data,
2837
+ }));
2838
+ }
2839
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2840
+ createdAt: new Date(),
2841
+ updatedAt: new Date(),
2842
+ userId: checkout.user.id,
2843
+ checkoutId: checkout.id,
2844
+ totalPrice: checkout.totalPrice,
2845
+ paymentProvider: 'adyen',
2846
+ transaction: Object.assign(Object.assign({}, result.data), { status: 'paid' }),
2847
+ }));
2848
+ return payment;
2849
+ }
2850
+ catch (error) {
2851
+ 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', {
2852
+ checkoutId: checkout.id,
2853
+ userEmail: checkout.user.email,
2854
+ info: error.message,
2855
+ });
2856
+ }
2857
+ }
2858
+ createCardPayment(checkout, card) {
2859
+ return {
2860
+ amount: {
2861
+ currency: 'BRL',
2862
+ value: ((checkout === null || checkout === void 0 ? void 0 : checkout.totalPrice) || 0) * 100,
2863
+ },
2864
+ paymentMethod: {
2865
+ type: 'scheme',
2866
+ storedPaymentMethodId: card.cardId,
2867
+ },
2868
+ reference: checkout.id,
2869
+ shopperInteraction: 'Ecommerce',
2870
+ merchantAccount: this.credentials.MERCHANT_ACCOUNT,
2871
+ shopperReference: checkout.user.id,
2872
+ recurringProcessingModel: 'CardOnFile',
2873
+ returnUrl: this.credentials.URL_POSTBACK,
2874
+ installments: {
2875
+ value: card.installments,
2876
+ },
2877
+ };
2878
+ }
2879
+ addCard() {
2880
+ throw new Error('Method not implemented.');
2881
+ }
2882
+ getCardByToken(token) {
2883
+ throw new Error('Method not implemented.');
2884
+ }
2885
+ createTransaction(info) {
2886
+ throw new Error('Method not implemented.');
2887
+ }
2888
+ }
2889
+
3190
2890
  class AxiosAdapter {
3191
2891
  constructor(config) {
3192
2892
  this.config = config;
@@ -7239,6 +6939,306 @@ __decorate([
7239
6939
  __metadata("design:returntype", Promise)
7240
6940
  ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
7241
6941
 
6942
+ class PagarmeBankSlipAxiosAdapter {
6943
+ constructor(credentials, paymentRepository) {
6944
+ this.credentials = credentials;
6945
+ this.paymentRepository = paymentRepository;
6946
+ }
6947
+ async pay(checkout) {
6948
+ try {
6949
+ const result = await axios({
6950
+ method: 'POST',
6951
+ url: `${this.credentials.URL}/transactions`,
6952
+ data: this.createBoletoPayment(checkout),
6953
+ });
6954
+ if (result.data.status !== PagarmePaymentStatus['Em processamento']) {
6955
+ return Promise.reject(new PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
6956
+ checkoutId: checkout.id,
6957
+ userEmail: checkout.user.email,
6958
+ info: result.data,
6959
+ }));
6960
+ }
6961
+ const payment = await this.paymentRepository.create(Payment.toInstance({
6962
+ createdAt: new Date(),
6963
+ updatedAt: new Date(),
6964
+ userId: checkout.user.id,
6965
+ checkoutId: checkout.id,
6966
+ totalPrice: checkout.totalPrice,
6967
+ paymentProvider: 'pagarMe',
6968
+ transaction: result.data,
6969
+ }));
6970
+ return payment;
6971
+ }
6972
+ catch (error) {
6973
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
6974
+ checkoutId: checkout.id,
6975
+ userEmail: checkout.user.email,
6976
+ info: error.response.data,
6977
+ });
6978
+ }
6979
+ }
6980
+ async getBoletoTransaction(paymentId) {
6981
+ try {
6982
+ const { data } = await axios({
6983
+ method: 'GET',
6984
+ url: `${this.credentials.URL}/transactions/${paymentId}`,
6985
+ data: {
6986
+ api_key: this.credentials.API_KEY,
6987
+ },
6988
+ });
6989
+ return data;
6990
+ }
6991
+ catch (error) {
6992
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
6993
+ paymentId,
6994
+ info: error.response.data,
6995
+ });
6996
+ }
6997
+ }
6998
+ createBoletoPayment(checkout) {
6999
+ return {
7000
+ api_key: this.credentials.API_KEY,
7001
+ amount: Math.floor(checkout.totalPrice * 100),
7002
+ boleto_rules: ['strict_expiration_date'],
7003
+ boleto_instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
7004
+ boleto_expiration_date: format(addDays(new Date(), 3), 'yyyy-MM-dd'),
7005
+ payment_method: 'boleto',
7006
+ postback_url: this.credentials.URL_POSTBACK,
7007
+ customer: {
7008
+ external_id: checkout.user.id,
7009
+ type: 'individual',
7010
+ country: 'br',
7011
+ name: checkout.user.displayName,
7012
+ documents: [
7013
+ {
7014
+ type: 'cpf',
7015
+ number: checkout.user.cpf,
7016
+ },
7017
+ ],
7018
+ },
7019
+ };
7020
+ }
7021
+ }
7022
+
7023
+ class PagarmeCardAxiosAdapter {
7024
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
7025
+ this.credentials = credentials;
7026
+ this.paymentRepository = paymentRepository;
7027
+ this.orderBlockedRepository = orderBlockedRepository;
7028
+ }
7029
+ async pay(checkout, card) {
7030
+ var _a;
7031
+ try {
7032
+ const result = await axios({
7033
+ method: 'POST',
7034
+ url: `${this.credentials.URL}/transactions`,
7035
+ data: this.createCardPayment(checkout, card),
7036
+ });
7037
+ if (result.data.status !== PagarmePaymentStatus.Pago) {
7038
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
7039
+ 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`, {
7040
+ checkoutId: checkout.id,
7041
+ userEmail: checkout.user.email,
7042
+ info: result.data,
7043
+ }));
7044
+ }
7045
+ const payment = await this.paymentRepository.create(Payment.toInstance({
7046
+ createdAt: new Date(),
7047
+ updatedAt: new Date(),
7048
+ userId: checkout.user.id,
7049
+ checkoutId: checkout.id,
7050
+ totalPrice: checkout.totalPrice,
7051
+ paymentProvider: PaymentProviders.PAGARME,
7052
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
7053
+ }));
7054
+ return payment;
7055
+ }
7056
+ catch (error) {
7057
+ 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', {
7058
+ checkoutId: checkout.id,
7059
+ userEmail: checkout.user.email,
7060
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
7061
+ });
7062
+ }
7063
+ }
7064
+ async addCard(card) {
7065
+ try {
7066
+ const { data } = await axios({
7067
+ method: 'POST',
7068
+ url: `${this.credentials.URL}/cards`,
7069
+ data: {
7070
+ api_key: this.credentials.API_KEY,
7071
+ card_number: card.number,
7072
+ card_expiration_date: card.expirationDate.replace('/', ''),
7073
+ card_holder_name: card.name,
7074
+ card_cvv: card.cvv,
7075
+ },
7076
+ });
7077
+ return data;
7078
+ }
7079
+ catch (error) {
7080
+ throw new BusinessError('Houve uma falha adicionar o cartão', {
7081
+ info: error.response.data,
7082
+ });
7083
+ }
7084
+ }
7085
+ async createCardHash(bu) {
7086
+ const key = bu === BusinessUnitEnum.SHOP ? this.credentials.API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
7087
+ try {
7088
+ const { data } = await axios({
7089
+ method: 'POST',
7090
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
7091
+ data: {
7092
+ api_key: key,
7093
+ },
7094
+ });
7095
+ return data;
7096
+ }
7097
+ catch (error) {
7098
+ throw new BusinessError('Houve uma falha gerar o hash', {
7099
+ info: error.response.data,
7100
+ });
7101
+ }
7102
+ }
7103
+ async getCardByToken(id) {
7104
+ try {
7105
+ const { data } = await axios({
7106
+ method: 'POST',
7107
+ url: `${this.credentials.URL}/cards/${id}`,
7108
+ data: {
7109
+ api_key: this.credentials.API_KEY,
7110
+ },
7111
+ });
7112
+ return data;
7113
+ }
7114
+ catch (error) {
7115
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + id, {
7116
+ info: error.response.data,
7117
+ });
7118
+ }
7119
+ }
7120
+ async createTransaction(info) {
7121
+ try {
7122
+ const { data } = await axios({
7123
+ method: 'POST',
7124
+ url: `${this.credentials.URL}/transactions`,
7125
+ data: Object.assign(Object.assign({}, info), { api_key: this.credentials.API_KEY }),
7126
+ });
7127
+ return data;
7128
+ }
7129
+ catch (error) {
7130
+ throw new BusinessError('Houve uma falha ao criar a transação', {
7131
+ info: error.response.data,
7132
+ });
7133
+ }
7134
+ }
7135
+ createCardPayment(checkout, card) {
7136
+ var _a, _b, _c, _d, _e, _f;
7137
+ return {
7138
+ api_key: this.credentials.API_KEY,
7139
+ amount: Math.floor(checkout.totalPrice * 100),
7140
+ card_id: card.cardId,
7141
+ payment_method: 'credit_card',
7142
+ installments: card.installments,
7143
+ soft_descriptor: checkout.shop === Shops.GLAMSHOP ? 'Glam' : "Men's Market",
7144
+ customer: {
7145
+ external_id: checkout.user.id,
7146
+ name: checkout.user.displayName,
7147
+ type: 'individual',
7148
+ country: 'br',
7149
+ email: checkout.user.email,
7150
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
7151
+ documents: [
7152
+ {
7153
+ type: 'cpf',
7154
+ number: checkout.user.cpf,
7155
+ },
7156
+ ],
7157
+ },
7158
+ billing: {
7159
+ name: checkout.user.displayName,
7160
+ address: {
7161
+ country: 'br',
7162
+ state: checkout.billingAddress ? checkout.billingAddress.state : (_a = checkout.shippingAddress) === null || _a === void 0 ? void 0 : _a.state,
7163
+ city: checkout.billingAddress ? checkout.billingAddress.city : (_b = checkout.shippingAddress) === null || _b === void 0 ? void 0 : _b.city,
7164
+ neighborhood: checkout.billingAddress ? checkout.billingAddress.district : (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.district,
7165
+ street: checkout.billingAddress ? checkout.billingAddress.street : (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.street,
7166
+ street_number: checkout.billingAddress ? checkout.billingAddress.number : (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.number,
7167
+ zipcode: checkout.billingAddress
7168
+ ? checkout.billingAddress.zip.replace('-', '')
7169
+ : (_f = checkout.shippingAddress) === null || _f === void 0 ? void 0 : _f.zip.replace('-', ''),
7170
+ },
7171
+ },
7172
+ items: checkout.lineItems.map((item) => {
7173
+ return {
7174
+ id: item.id,
7175
+ title: checkout.user.isSubscriber ? `${item.name} - ASSINANTE` : item.name,
7176
+ unit_price: Math.floor(item.pricePaid * 100),
7177
+ quantity: item.quantity,
7178
+ tangible: true,
7179
+ };
7180
+ }),
7181
+ };
7182
+ }
7183
+ }
7184
+
7185
+ class PagarmePixAxiosAdapter {
7186
+ constructor(credentials, paymentRepository) {
7187
+ this.credentials = credentials;
7188
+ this.paymentRepository = paymentRepository;
7189
+ }
7190
+ async pay(checkout) {
7191
+ var _a;
7192
+ try {
7193
+ const result = await axios({
7194
+ method: 'POST',
7195
+ url: `${this.credentials.URL}/transactions`,
7196
+ data: this.createPixPayment(checkout),
7197
+ });
7198
+ const payment = await this.paymentRepository.create(Payment.toInstance({
7199
+ createdAt: new Date(),
7200
+ updatedAt: new Date(),
7201
+ userId: checkout.user.id,
7202
+ checkoutId: checkout.id,
7203
+ totalPrice: checkout.totalPrice,
7204
+ paymentProvider: 'pagarMe',
7205
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
7206
+ }));
7207
+ return payment;
7208
+ }
7209
+ catch (error) {
7210
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
7211
+ checkoutId: checkout.id,
7212
+ userEmail: checkout.user.email,
7213
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
7214
+ });
7215
+ }
7216
+ }
7217
+ createPixPayment(checkout) {
7218
+ return {
7219
+ payment_method: 'pix',
7220
+ amount: Math.floor(checkout.totalPrice * 100),
7221
+ api_key: this.credentials.API_KEY,
7222
+ postback_url: this.credentials.URL_POSTBACK,
7223
+ pix_expiration_date: format(addDays(new Date(), 1), 'yyyy-MM-dd'),
7224
+ customer: {
7225
+ external_id: checkout.user.id,
7226
+ type: 'individual',
7227
+ country: 'br',
7228
+ name: checkout.user.displayName,
7229
+ email: checkout.user.email.trim(),
7230
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
7231
+ documents: [
7232
+ {
7233
+ type: 'cpf',
7234
+ number: checkout.user.cpf,
7235
+ },
7236
+ ],
7237
+ },
7238
+ };
7239
+ }
7240
+ }
7241
+
7242
7242
  class VertexAxiosAdapter {
7243
7243
  constructor(config) {
7244
7244
  this.config = config;
@@ -7392,4 +7392,4 @@ class ProductsVertexSearch {
7392
7392
  }
7393
7393
  }
7394
7394
 
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 };
7395
+ 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, 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 };