<commit_before>module Spree
  module Admin
    class SubscriptionsController < ResourceController
      before_action :require_order_id, only: [:new]

      def new
        order_id = params[:order_id]

        unless order_id.nil?
          order = Spree::Order.find(order_id)
          @subscription = build_subscription_from_order(order)

          # build subscription addresses
          user = order.user
          @subscription.build_ship_address(order.ship_address.dup.attributes.merge({user_id: user.id}))
          @subscription.build_bill_address(order.bill_address.dup.attributes.merge({user_id: user.id}))

          # build items
          build_subscription_items(@subscription, order)
        end
      end

      def create
        subscription = Spree::Subscription.new(params[:subscription].permit!)
        build_subscription_items(subscription, subscription.orders.first)

        subscription.save

        redirect_to admin_subscriptions_url
      end

      def renew
        failure_count = @object.failure_count
        ::GenerateSubscriptionOrder.new(@object).call

        # check if the failure count has increase, that means we have an error
        if failure_count != @object.failure_count
          # send a renewal failure notice
          failed_order = @object.orders.reorder('created_at desc').first
          log = SubscriptionLog.find_by_order_id(failed_order.id)
          SubscriptionMailer.renewal_failure(@object, log.reason).deliver

          flash[:error] = flash_message_for(@object, :error_renew)
        else
          flash[:success] = flash_message_for(@object, :successfully_renewed)
        end
        respond_with(@object) do |format|
          format.html { redirect_to collection_url }
        end
      end

      def cancel
        if @object.cancel
          flash[:success] = flash_message_for(@object, :successfully_cancelled)
          respond_with(@object) do |format|
            format.html { redirect_to collection_url }
          end
        end
      end

      def credit_card
        if request.post?
          begin
            subscription = Spree::Subscription.find(params[:id])
            # get the payment_method_id
            credit_card_params = object_params[:source_attributes].merge Hash[*object_params.first]
            subscription.add_new_credit_card(credit_card_params)
          rescue Spree::Core::GatewayError, CardStore::CardError => e
            flash[:error] = "#{e.message}"
          end
        end
        @payment_methods = PaymentMethod.available(:back_end).select{ |method| method.type =~ /Gateway/ }
      end

      protected
        def collection
          return @collection if defined?(@collection)
          params[:q] ||= HashWithIndifferentAccess.new
          params[:q][:s] ||= 'id desc'

          @collection = super
          @search = @collection.ransack(params[:q])
          @collection = @search.result(distinct: true).
            includes(subscription_includes).
            page(params[:page]).
            per(params[:per_page] || Spree::Config[:orders_per_page])

          @collection
        end     

      private
        def require_order_id
          if params[:order_id].blank?
            redirect_to admin_subscriptions_url
            flash[:error] = flash_message_for(@object, :requires_order_id)
          end
        end

        def build_subscription_from_order(order)
          attrs = {
            user_id: order.user.id,
            state: 'active',
            interval: order.subscription_interval,
            duration: order.subscription_duration,
            prepaid_amount: order.subscription_prepaid_amount,
            credit_card_id: order.credit_card_id_if_available
          }
          order.build_subscription(attrs)
        end

        def build_subscription_items(subscription, order)
          order.line_items.each do |line_item|
            subscription.subscription_items.build(
              subscription: subscription,
              variant: line_item.variant,
              quantity: line_item.quantity,
              price: line_item.price
            )
          end
        end

        def object_params
          if params[:payment] and params[:payment_source] and source_params = params.delete(:payment_source)[params[:payment][:payment_method_id]]<commit_msg>set default selected payment method<commit_after>module Spree
  module Admin
    class SubscriptionsController < ResourceController
      
      before_action :require_order_id, only: [:new]
      before_action :load_payment_methods, only: [:credit_card]

      def new
        order_id = params[:order_id]

        unless order_id.nil?
          order = Spree::Order.find(order_id)
          @subscription = build_subscription_from_order(order)

          # build subscription addresses
          user = order.user
          @subscription.build_ship_address(order.ship_address.dup.attributes.merge({user_id: user.id}))
          @subscription.build_bill_address(order.bill_address.dup.attributes.merge({user_id: user.id}))

          # build items
          build_subscription_items(@subscription, order)
        end
      end

      def create
        subscription = Spree::Subscription.new(params[:subscription].permit!)
        build_subscription_items(subscription, subscription.orders.first)

        subscription.save

        redirect_to admin_subscriptions_url
      end

      def renew
        failure_count = @object.failure_count
        ::GenerateSubscriptionOrder.new(@object).call

        # check if the failure count has increase, that means we have an error
        if failure_count != @object.failure_count
          # send a renewal failure notice
          failed_order = @object.orders.reorder('created_at desc').first
          log = SubscriptionLog.find_by_order_id(failed_order.id)
          SubscriptionMailer.renewal_failure(@object, log.reason).deliver

          flash[:error] = flash_message_for(@object, :error_renew)
        else
          flash[:success] = flash_message_for(@object, :successfully_renewed)
        end
        respond_with(@object) do |format|
          format.html { redirect_to collection_url }
        end
      end

      def cancel
        if @object.cancel
          flash[:success] = flash_message_for(@object, :successfully_cancelled)
          respond_with(@object) do |format|
            format.html { redirect_to collection_url }
          end
        end
      end

      def credit_card
        if request.post?
          begin
            subscription = Spree::Subscription.find(params[:id])
            # get the payment_method_id
            credit_card_params = object_params[:source_attributes].merge Hash[*object_params.first]
            subscription.add_new_credit_card(credit_card_params)
          rescue Spree::Core::GatewayError, CardStore::CardError => e
            flash[:error] = "#{e.message}"
          end
        end
      end

      protected
        def collection
          return @collection if defined?(@collection)
          params[:q] ||= HashWithIndifferentAccess.new
          params[:q][:s] ||= 'id desc'

          @collection = super
          @search = @collection.ransack(params[:q])
          @collection = @search.result(distinct: true).
            includes(subscription_includes).
            page(params[:page]).
            per(params[:per_page] || Spree::Config[:orders_per_page])

          @collection
        end     

      private
        def require_order_id
          if params[:order_id].blank?
            redirect_to admin_subscriptions_url
            flash[:error] = flash_message_for(@object, :requires_order_id)
          end
        end

        def build_subscription_from_order(order)
          attrs = {
            user_id: order.user.id,
            state: 'active',
            interval: order.subscription_interval,
            duration: order.subscription_duration,
            prepaid_amount: order.subscription_prepaid_amount,
            credit_card_id: order.credit_card_id_if_available
          }
          order.build_subscription(attrs)
        end

        def build_subscription_items(subscription, order)
          order.line_items.each do |line_item|
            subscription.subscription_items.build(
              subscription: subscription,
              variant: line_item.variant,
              quantity: line_item.quantity,
              price: line_item.price
            )
          end
        end

        def load_payment_methods
          @payment_methods = PaymentMethod.available(:back_end).select{ |method| method.type =~ /Gateway/ }
          @payment_method = @payment_methods.first
        end

        def object_params
          if params[:payment] and params[:payment_source] and source_params = params.delete(:payment_source)[params[:payment][:payment_method_id]]
{'fraction_non_alphanumeric': 0.08374717832957111, 'fraction_numerical': 0.0, 'mean_word_length': 2.3063432835820894, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, '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': '369327', 'n_tokens_mistral': 2329, 'n_tokens_neox': 2322, 'n_words': 450}