<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import Donation from './plugin'

class DonationConnected extends React.Component {
  constructor (props) {
    super(props)
    this.state = { donationCustomerData: undefined, email: undefined }
  }

  handleTransactionCreate (values) {
    const {
      mobilization,
      widget,
      selectedValue,
      selectedPaymentType,
      storedDonationCustomerData
    } = values

    return new Promise((resolve, reject) => {
      const paymentType = widget.settings.payment_type
      const recurringPeriod = widget.settings.recurring_period
      const mainColor = widget.settings.main_color
        ? widget.settings.main_color
        : '#43a2cc'

      const checkout = new window.PagarMeCheckout.Checkout({
        encryption_key: this.props.pagarmeKey || 'setup env var',
        success: (data) => {
          data.subscription = paymentType === 'users_choice'
            ? (selectedPaymentType !== 'unique')
            : data.subscription = (paymentType !== 'unique')

          data.recurring_period = recurringPeriod
          data.mobilization_id = mobilization.id
          data.widget_id = widget.id
          data.amount = widget.settings['donation_value' + selectedValue] + '00'

          this.props.donationTransactionCreate(data)
            .then(() => {
              if (this.state.donationCustomerData) {
                this.setState({ donationCustomerData: undefined })
              }
              this.props.analyticsEvents.donationFinishRequest()
              return resolve()
            })
            .catch(failure => {
              if (failure.config && failure.config.data) {
                try {
                  const failureData = JSON.parse(failure.config.data)
                  this.setState({ donationCustomerData: failureData.donation.customer })
                } catch (error) {
                  console.error('Customer data is not parsable. Cannot store the customer data.')
                  console.error(error)
                }
              } else {
                console.error(failure)
              }
            })
        },
        error: (err) => {
          console.error(err)
          return reject()
        }
      })

      const customerData = {}
      if (storedDonationCustomerData) {
        const d = storedDonationCustomerData

        // reference: https://docs.pagar.me/v2017-07-17/docs/inserindo-o-formulario
        customerData.customerName = d.name
        customerData.customerDocumentNumber = d.document_number
        customerData.customerEmail = d.email
        customerData.customerPhoneDdd = d.phone.ddd
        customerData.customerPhoneNumber = d.phone.number
        customerData.customerAddressZipcode = d.address.zipcode
        customerData.customerAddressStreet = d.address.street
        customerData.customerAddressStreetNumber = d.address.street_number
        customerData.customerAddressComplementary = d.address.complementary
        customerData.customerAddressNeighborhood = d.address.neighborhood
        customerData.customerAddressCity = d.address.city
        customerData.customerAddressState = d.address.state
        
        this.setState({ email: d.email })
      }

      const params = {
        createToken: 'false',
        amount: widget.settings['donation_value' + selectedValue] + '00',
        customerData: 'true',
        paymentMethods: widget.settings.payment_methods === 'true' ? 'credit_card,boleto' : 'credit_card',
        uiColor: mainColor,
        paymentButtonText: widget.settings.button_text,
        ...customerData
      }

      this.props.analyticsEvents.donationSetValue()

      checkout.open(params)
    })
  }

  render () {
    return (
      <Donation
        {...this.props}
        email={this.state.email}
        donationCustomerData={this.state.donationCustomerData}
        handleDonationTransactionCreate={this.handleTransactionCreate.bind(this)}
      />
    )
  }
}

DonationConnected.propTypes = {
  pagarmeKey: PropTypes.string.isRequired
}

export default DonationConnected

/* TOOD: script inserted on top level for rendering, but need thing a better solution<commit_msg>feat(admin): add handleTransactionConvert<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import Donation from './plugin'

class DonationConnected extends React.Component {
  constructor (props) {
    super(props)
    this.state = { donationCustomerData: undefined, email: undefined }
  }

  handleTransactionCreate (values) {
    const {
      mobilization,
      widget,
      selectedValue,
      selectedPaymentType,
      storedDonationCustomerData
    } = values

    return new Promise((resolve, reject) => {
      const paymentType = widget.settings.payment_type
      const recurringPeriod = widget.settings.recurring_period
      const mainColor = widget.settings.main_color
        ? widget.settings.main_color
        : '#43a2cc'

      const checkout = new window.PagarMeCheckout.Checkout({
        encryption_key: this.props.pagarmeKey || 'setup env var',
        success: (data) => {
          data.subscription = paymentType === 'users_choice'
            ? (selectedPaymentType !== 'unique')
            : data.subscription = (paymentType !== 'unique')

          data.recurring_period = recurringPeriod
          data.mobilization_id = mobilization.id
          data.widget_id = widget.id
          data.amount = widget.settings['donation_value' + selectedValue] + '00'

          this.props.donationTransactionCreate(data)
            .then(() => {
              if (this.state.donationCustomerData) {
                this.setState({ donationCustomerData: undefined })
              }
              this.props.analyticsEvents.donationFinishRequest()
              return resolve()
            })
            .catch(failure => {
              if (failure.config && failure.config.data) {
                try {
                  const failureData = JSON.parse(failure.config.data)
                  this.setState({ donationCustomerData: failureData.donation.customer })
                } catch (error) {
                  console.error('Customer data is not parsable. Cannot store the customer data.')
                  console.error(error)
                }
              } else {
                console.error(failure)
              }
            })
        },
        error: (err) => {
          console.error(err)
          return reject()
        }
      })

      const customerData = {}
      if (storedDonationCustomerData) {
        const d = storedDonationCustomerData

        // reference: https://docs.pagar.me/v2017-07-17/docs/inserindo-o-formulario
        customerData.customerName = d.name
        customerData.customerDocumentNumber = d.document_number
        customerData.customerEmail = d.email
        customerData.customerPhoneDdd = d.phone.ddd
        customerData.customerPhoneNumber = d.phone.number
        customerData.customerAddressZipcode = d.address.zipcode
        customerData.customerAddressStreet = d.address.street
        customerData.customerAddressStreetNumber = d.address.street_number
        customerData.customerAddressComplementary = d.address.complementary
        customerData.customerAddressNeighborhood = d.address.neighborhood
        customerData.customerAddressCity = d.address.city
        customerData.customerAddressState = d.address.state
        
        this.setState({ email: d.email })
      }

      const params = {
        createToken: 'false',
        amount: widget.settings['donation_value' + selectedValue] + '00',
        customerData: 'true',
        paymentMethods: widget.settings.payment_methods === 'true' ? 'credit_card,boleto' : 'credit_card',
        uiColor: mainColor,
        paymentButtonText: widget.settings.button_text,
        ...customerData
      }

      this.props.analyticsEvents.donationSetValue()

      checkout.open(params)
    })
  }

  handleTransactionConvert (values) {
    const {
      mobilization,
      widget,
      selectedValue,
      selectedPaymentType,
      storedDonationCustomerData
    } = values

    return new Promise((resolve, reject) => {
      const paymentType = widget.settings.payment_type
      const recurringPeriod = widget.settings.recurring_period

      this.props.donationTransactionConvert(data)
        .then(() => {
          if (this.state.donationCustomerData) {
            this.setState({ donationCustomerData: undefined })
          }
          this.props.analyticsEvents.donationFinishRequest()
          return resolve()
        })
        .catch(failure => {
          if (failure.config && failure.config.data) {
            try {
              const failureData = JSON.parse(failure.config.data)
              this.setState({ donationCustomerData: failureData.donation.customer })
            } catch (error) {
              console.error('Customer data is not parsable. Cannot store the customer data.')
              console.error(error)
            }
          } else {
            console.error(failure)
          }
        })
      }
    )
  }

  render () {
    return (
      <Donation
        {...this.props}
        email={this.state.email}
        donationCustomerData={this.state.donationCustomerData}
        handleDonationTransactionCreate={this.handleTransactionCreate.bind(this)}
        handleDonationTransactionConvert={this.handleDonationTransactionConvert.bind(this)}
      />
    )
  }
}

DonationConnected.propTypes = {
  pagarmeKey: PropTypes.string.isRequired
}

export default DonationConnected

/* TOOD: script inserted on top level for rendering, but need thing a better solution
{'fraction_non_alphanumeric': 0.09457508250825082, 'fraction_numerical': 0.003094059405940594, 'mean_word_length': 2.257306012764528, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 18, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3523197', 'n_tokens_mistral': 2576, 'n_tokens_neox': 2487, 'n_words': 466}