alexgregianin
8/23/2016 - 3:06 PM

runner.rake

  #encoding: utf-8
namespace :runner do

  task :import => :environment  do
    lines = File.read("runner.csv").force_encoding("ISO-8859-1").encode("utf-8", replace: nil).split("\n")
    lines.shift
    @already_in_use = []

    lines.each do |line|

      line = line.split(";")
      duration = line[40].to_i
      location_id = 114
      birthday = Date.strptime(line[5], "%Y%m%d") rescue 18.years.ago.to_date

      # tem saldo?
      if duration.present? and duration > 0
        if birthday >= 19.years.ago.to_date
          birthday =  Date.strptime("1994#{birthday.strftime("%m%d")}", "%Y%m%d")
        end

        gender = line[7] == "M" ? true : false

        document_cpf = "%011d" % line[4].strip.to_i


        person_attributes = {
                              :name         => line[2].strip,
                              :document_cpf => document_cpf,
                              :email        => 'granja21@smartfit.com.br',
                              :gender       => gender,
                              :birthday     => birthday,
                              :user_id      => User.find_by_email("alexandre@bioritmo.com.br").id,
                              :country_id   => 1
                            }

        street, number = line[8].split(",")
        city = City.find_by_name(line[11]).id rescue 91

        zip = line[10].strip.scan(/\d/).join[0..7]

        if zip.empty? or zip.size < 8
          zip = "06709625"
        end

        if number.present?
          number = number.scan(/\d/).join.strip

          if number.empty?
            number = "1"
          end
        else
          number = "1"
        end

        region = line[9].strip

        if region.empty?
          region = "bairro"
        end

        addresses_attributes  = {
                              :street     => street.strip,
                              :zip        => zip,
                              :complement => "",
                              :number     => number,
                              :region     => region,
                              :city_id    => city
                             }

                             number = line[12].scan(/\d/).join[0..7]
                             if number.empty?
                               number = "12121212"
                             end

                             cell_number = line[14].scan(/\d/).join[0..8]
                             if cell_number.empty?
                               cell_number = "999991234"
                            end


        phones_attributes = [

                            {
                             :kind => 1,
                             :area => '11',
                             :number => number
                            },
                            {
                              :kind => 0,
                              :area => '11',
                              :number => cell_number
                            }
                           ]

        unless Phone.new(phones_attributes.first).valid?
           phones_attributes.first[:number] = "12121212"
        end

        unless Phone.new(phones_attributes.last).valid?
           phones_attributes.last[:number] = "999991234"
        end

        prospect = Visit.create(:name => line[2], :email => 'granja21@smartfit.com.br', :location_id => location_id).prospect.id

        purchases_attributes = {
                               :location_id          => location_id,
                               :plan_id              => 14, # vip black
                               :membership_price     => 0,
                               :signed_contract      => true,
                               :original_location_id => location_id,
                               :enrollment_price     => 0,
                               :enrollment_price     => 0,
                               :limit_guests         => 10,
                               :user_id              => User.find_by_email("alexandre@bioritmo.com.br").id,
                               :kind                 => 'counter',
                               :anual_fee_recurrency => nil,
                               :anual_fee_price      => 0,
                               :pro_rata             => false,
                               :prospect_id          => prospect,
                               :description          => "Importacao inicial runner km21"
                               }



        wallets_attributes  = {
                                  :payment_company_id => PaymentCompany.moneys.first.id,
                                  :responsible_cpf    => document_cpf,
                                  :responsible_name   => line[2].strip,
                                  :country_id         => Country.first.id,
                                  :state              => 'active'
                                }

        # person_attributes[:phones_attributes]    = phones_attributes
        person_attributes[:wallets_attributes]   = [wallets_attributes]
        person_attributes[:purchases_attributes] = [purchases_attributes]
        person_attributes[:addresses_attributes] = [addresses_attributes]

        @person = Person.new person_attributes
        @person.build_cell_phone phones_attributes.last
        @person.build_landline_phone phones_attributes.first

        if @person.valid? and Person.find_by_document_cpf(@person.document_cpf).nil?

          @person.save!
          purchase = @person.main_purchase
          puts "Created purchase for #{@person.document_cpf}"
          (0..(duration - 1)).each { |x| purchase.memberships.create! :plan_id => purchase.plan_id, :start_at => x.months.from_now.to_date, :end_at => (x + 1).months.from_now.to_date - 1.day }
          puts "Created memberships for #{@person.document_cpf} com duracao de #{duration}"


        else

          if @person.errors.full_messages.join =~ /CPF já está em uso/
            @person = Person.find_by_document_cpf(@person.document_cpf)
            if @person.status == "active" or @person.status == "blocked"
              puts "Já existe plano ativo para esse id #{@person.document_cpf}"

              @already_in_use << @person.document_cpf
            else
              puts "Essa person já existe, mas está cancelada #{@person.document_cpf}"
              @person.wallets.create! wallets_attributes
              @person.purchases.create! purchases_attributes
              purchase = @person.main_purchase
              (0..(duration - 1)).each { |x| purchase.memberships.create! :plan_id => purchase.plan_id, :start_at => x.months.from_now.to_date, :end_at => (x + 1).months.from_now.to_date - 1.day }
              puts "Created memberships for #{@person.document_cpf} com duracao de #{duration}"
            end
          else
            puts @person.errors.full_messages
          end
        end
      end
   end

   @already_in_use.each { |x| puts x }
  end

end