Forked from victorgiraldes/gist:0c9d0d55c8d4f0248990afe6c9bfeff3
          
        
    
          Last active
          October 8, 2019 22:15 
        
      - 
      
- 
        Save leandro/45529e5884130f1ef864c10222e1c761 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | def create | |
| @block_edit = false | |
| debit_params = BankDebit.new(permitted_params[:bank_debit]) | |
| .attributes.symbolize_keys.merge(user_id: current_user.id) | |
| Bank.transaction do | |
| current_user.up_score!(1.3) if current_user.Potencial? | |
| create_plot_debits!(debit_params) | |
| create_debits!(debit_params) | |
| redirect_to cash_path, notice: 'Lançamento realizado com sucesso' | |
| rescue ActiveRecord::RecordInvalid => exc | |
| render 'new' | |
| end | |
| end | |
| private | |
| def create_debits!(debit_params) | |
| repeat_number, repeat_method = params.values_at(:repeat_number, :repeat_method).map(&:to_i) | |
| created_debits = [] | |
| repeat_number.times.map do |i| | |
| i += 1 | |
| duration = repeat_method == 7 ? (i * repeat_method).days : i.months | |
| description = "#{debit_params[:description]} #{i}/#{repeat_number}" | |
| paid_at = debit_params[:paid_at].to_datetime + duration | |
| attributes = { description: description, paid_at: paid_at } | |
| current_company.bank_debits.create!(debit_params.merge(attributes)) | |
| end | |
| end | |
| def create_plot_debits!(debit_params) | |
| plots = params[:bank_debit][:plots] | |
| plots_count = params[:plots_count].to_i | |
| generated_code = SecureRandom.urlsafe_base64(30) | |
| attributes_base = debit_params | |
| .slice(:resoursable_type, :resoursable_id, :provider_id, :date, :cicle, | |
| :bank_category_id, :observation, :avatar) | |
| .merge(unificator: generated_code) | |
| } | |
| plots.map do |i, plot_attributes| | |
| bank = Bank.find_by(id: plot_attributes[:bank_id]) | |
| final_debit_attributes = attributes_base.merge( | |
| plot_attributes.slice(:paid_method, :paid_info, :year_company_id, | |
| :value, :paid) | |
| ).merge( | |
| bank_id: bank.try(:id), | |
| children: i.to_i != 1, | |
| description: "#{debit_params[:description]} #{i}/#{plots_count}", | |
| paid_at: plot_attributes[:date] | |
| ) | |
| current_company.bank_debits.create!(final_debit_attributes) | |
| end | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment