<commit_before>module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    class OptimalPaymentGateway < Gateway
      TEST_URL = 'https://webservices.test.optimalpayments.com/creditcardWS/CreditCardServlet/v1'
      LIVE_URL = 'https://webservices.optimalpayments.com/creditcardWS/CreditCardServlet/v1'

      # The countries the gateway supports merchants from as 2 digit ISO country codes
      self.supported_countries = ['CA', 'US', 'GB']

      # The card types supported by the payment gateway
      self.supported_cardtypes = [:visa, :master, :american_express, :discover, :diners_club, :solo] # :switch?

      # The homepage URL of the gateway
      self.homepage_url = 'http://www.optimalpayments.com/'

      # The name of the gateway
      self.display_name = 'Optimal Payments'

      def initialize(options = {})
        #requires!(options, :login, :password)
        @options = options
        super
      end

      def authorize(money, card_or_auth, options = {})
        parse_card_or_auth(card_or_auth, options)
        commit("cc#{@stored_data}Authorize", money, options)
      end
      alias stored_authorize authorize # back-compat

      def purchase(money, card_or_auth, options = {})
        parse_card_or_auth(card_or_auth, options)
        commit("cc#{@stored_data}Purchase", money, options)
      end
      alias stored_purchase purchase # back-compat

      def refund(money, authorization, options = {})
        options[:confirmationNumber] = authorization
        commit('ccCredit', money, options)
      end

      def void(authorization, options = {})
        options[:confirmationNumber] = authorization
        commit('ccAuthorizeReversal', nil, options)
      end

      def capture(money, authorization, options = {})
        options[:confirmationNumber] = authorization
        commit('ccSettlement', money, options)
      end

      def test?
        super || @options[:test]
      end

    private

      def parse_card_or_auth(card_or_auth, options)
        if card_or_auth.respond_to?(:number)
          @credit_card = card_or_auth
          @stored_data = ""
        else
          options[:confirmationNumber] = card_or_auth
          @stored_data = "StoredData"
        end
      end

      def parse(body)
        REXML::Document.new(body || '')
      end

      def commit(action, money, post)
        post[:order_id] ||= 'order_id'

        xml = case action
        when 'ccAuthorize', 'ccPurchase', 'ccVerification'
          cc_auth_request(money, post)
        when 'ccCredit', 'ccSettlement'
          cc_post_auth_request(money, post)
        when 'ccStoredDataAuthorize', 'ccStoredDataPurchase'
          cc_stored_data_request(money, post)
        when 'ccAuthorizeReversal'
          cc_auth_reversal_request(post)
        #when 'ccCancelSettle', 'ccCancelCredit', 'ccCancelPayment'
        #  cc_cancel_request(money, post)
        #when 'ccPayment'
        #  cc_payment_request(money, post)
        #when 'ccAuthenticate'
        #  cc_authenticate_request(money, post)
        else
          raise 'Unknown Action'
        end
        txnRequest = URI.encode(xml)
        response = parse(ssl_post(test? ? TEST_URL : LIVE_URL, "txnMode=#{action}&txnRequest=#{txnRequest}"))

        Response.new(successful?(response), message_from(response), hash_from_xml(response),
          :test          => test?,
          :authorization => authorization_from(response)
        )
      end

      def successful?(response)
        REXML::XPath.first(response, '//decision').text == 'ACCEPTED' rescue false
      end

      def message_from(response)
        REXML::XPath.each(response, '//detail') do |detail|
          if detail.is_a?(REXML::Element) && detail.elements['tag'].text == 'InternalResponseDescription'
            return detail.elements['value'].text
          end
        end
        nil
      end

      def authorization_from(response)
        REXML::XPath.first(response, '//confirmationNumber').text rescue nil
      end

      def hash_from_xml(response)
        hsh = {}
        %w(confirmationNumber authCode
           decision code description
           actionCode avsResponse cvdResponse
           txnTime duplicateFound
        ).each do |tag|
          node = REXML::XPath.first(response, "//#{tag}")
          hsh[tag] = node.text if node
        end
        REXML::XPath.each(response, '//detail') do |detail|
          next unless detail.is_a?(REXML::Element)
          tag = detail.elements['tag'].text
          value = detail.elements['value'].text
          hsh[tag] = value
        end
        hsh
      end

      def xml_document(root_tag)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.tag!(root_tag, schema) do
          yield xml
        end
        xml.target!
      end

      def cc_auth_request(money, opts)
        xml_document('ccAuthRequestV1') do |xml|
          build_merchant_account(xml, @options)
          xml.merchantRefNum opts[:order_id]
          xml.amount(money/100.0)
          build_card(xml, opts)
          build_billing_details(xml, opts)<commit_msg>update optimal_payment test? method<commit_after>module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    class OptimalPaymentGateway < Gateway
      TEST_URL = 'https://webservices.test.optimalpayments.com/creditcardWS/CreditCardServlet/v1'
      LIVE_URL = 'https://webservices.optimalpayments.com/creditcardWS/CreditCardServlet/v1'

      # The countries the gateway supports merchants from as 2 digit ISO country codes
      self.supported_countries = ['CA', 'US', 'GB']

      # The card types supported by the payment gateway
      self.supported_cardtypes = [:visa, :master, :american_express, :discover, :diners_club, :solo] # :switch?

      # The homepage URL of the gateway
      self.homepage_url = 'http://www.optimalpayments.com/'

      # The name of the gateway
      self.display_name = 'Optimal Payments'

      def initialize(options = {})
        #requires!(options, :login, :password)
        @options = options
        super
      end

      def authorize(money, card_or_auth, options = {})
        parse_card_or_auth(card_or_auth, options)
        commit("cc#{@stored_data}Authorize", money, options)
      end
      alias stored_authorize authorize # back-compat

      def purchase(money, card_or_auth, options = {})
        parse_card_or_auth(card_or_auth, options)
        commit("cc#{@stored_data}Purchase", money, options)
      end
      alias stored_purchase purchase # back-compat

      def refund(money, authorization, options = {})
        options[:confirmationNumber] = authorization
        commit('ccCredit', money, options)
      end

      def void(authorization, options = {})
        options[:confirmationNumber] = authorization
        commit('ccAuthorizeReversal', nil, options)
      end

      def capture(money, authorization, options = {})
        options[:confirmationNumber] = authorization
        commit('ccSettlement', money, options)
      end

      # this was returning true from the super call in production
      # mode. Could only get things working as expected if I explicitly
      # passed in :test => false in intialization and also
      # had mode set to :production
      def test?
        if @options[:test]
          return @options[:test]
        else
          super
        end

      end

      private

      def parse_card_or_auth(card_or_auth, options)
        if card_or_auth.respond_to?(:number)
          @credit_card = card_or_auth
          @stored_data = ""
        else
          options[:confirmationNumber] = card_or_auth
          @stored_data = "StoredData"
        end
      end

      def parse(body)
        REXML::Document.new(body || '')
      end

      def commit(action, money, post)
        post[:order_id] ||= 'order_id'

        xml = case action
              when 'ccAuthorize', 'ccPurchase', 'ccVerification'
                cc_auth_request(money, post)
              when 'ccCredit', 'ccSettlement'
                cc_post_auth_request(money, post)
              when 'ccStoredDataAuthorize', 'ccStoredDataPurchase'
                cc_stored_data_request(money, post)
              when 'ccAuthorizeReversal'
                cc_auth_reversal_request(post)
                #when 'ccCancelSettle', 'ccCancelCredit', 'ccCancelPayment'
                #  cc_cancel_request(money, post)
                #when 'ccPayment'
                #  cc_payment_request(money, post)
                #when 'ccAuthenticate'
                #  cc_authenticate_request(money, post)
              else
                raise 'Unknown Action'
              end
        txnRequest = URI.encode(xml)
        response = parse(ssl_post(test? ? TEST_URL : LIVE_URL, "txnMode=#{action}&txnRequest=#{txnRequest}"))

        Response.new(successful?(response), message_from(response), hash_from_xml(response),
                     :test          => test?,
                     :authorization => authorization_from(response)
                    )
      end

      def successful?(response)
        REXML::XPath.first(response, '//decision').text == 'ACCEPTED' rescue false
      end

      def message_from(response)
        REXML::XPath.each(response, '//detail') do |detail|
          if detail.is_a?(REXML::Element) && detail.elements['tag'].text == 'InternalResponseDescription'
            return detail.elements['value'].text
          end
        end
        nil
      end

      def authorization_from(response)
        REXML::XPath.first(response, '//confirmationNumber').text rescue nil
      end

      def hash_from_xml(response)
        hsh = {}
        %w(confirmationNumber authCode
           decision code description
           actionCode avsResponse cvdResponse
           txnTime duplicateFound
          ).each do |tag|
          node = REXML::XPath.first(response, "//#{tag}")
          hsh[tag] = node.text if node
          end
        REXML::XPath.each(response, '//detail') do |detail|
          next unless detail.is_a?(REXML::Element)
          tag = detail.elements['tag'].text
          value = detail.elements['value'].text
          hsh[tag] = value
        end
        hsh
      end

      def xml_document(root_tag)
        xml = Builder::XmlMarkup.new :indent => 2
        xml.tag!(root_tag, schema) do
          yield xml
        end
        xml.target!
      end

      def cc_auth_request(money, opts)
        xml_document('ccAuthRequestV1') do |xml|
          build_merchant_account(xml, @options)
          xml.merchantRefNum opts[:order_id]
          xml.amount(money/100.0)
          build_card(xml, opts)
          build_billing_details(xml, opts)
{'fraction_non_alphanumeric': 0.10011269722013523, 'fraction_numerical': 0.0016904583020285499, 'mean_word_length': 2.337198370416797, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 10, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 32}, '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': '3398156', 'n_tokens_mistral': 3152, 'n_tokens_neox': 3013, 'n_words': 671}