Class: Decidim::Accountability::ResultsCsvImporter

Inherits:
Object
  • Object
show all
Includes:
FormFactory
Defined in:
decidim-accountability/app/services/decidim/accountability/results_csv_importer.rb

Overview

This class handles importing results from a CSV file. Needs a `current_component` param with a `Decidim::component` in order to import the results in that component.

Instance Method Summary collapse

Constructor Details

#initialize(component, csv_file, current_user) ⇒ ResultsCsvImporter

Public: Initializes the service. component - A Decidim::component to import the results into. csv_file - The contents of the CSV to read.


16
17
18
19
20
21
22
23
24
25
26
27
# File 'decidim-accountability/app/services/decidim/accountability/results_csv_importer.rb', line 16

def initialize(component, csv_file, current_user)
  @component = component
  @csv_file = csv_file

  @extra_context = {
    current_component: component,
    current_organization: component.organization,
    current_user: current_user,
    current_participatory_space: component.participatory_space
  }
  @matches_ids = []
end

Instance Method Details

#import!Object


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'decidim-accountability/app/services/decidim/accountability/results_csv_importer.rb', line 29

def import!
  errors = []

  ActiveRecord::Base.transaction do
    i = 1
    csv = CSV.new(@csv_file, headers: true, col_sep: ";")
    while (row = csv.shift).present?
      i += 1
      next if row.empty?

      params = set_params_for_import_result_form(row, @component)
      existing_result = Decidim::Accountability::Result.find_by(id: row["id"], component: @component) if row["id"].present?
      params["result"].merge!(parse_date_params(row, "start_date"))
      params["result"].merge!(parse_date_params(row, "end_date"))
      @form = form(Decidim::Accountability::Admin::ResultForm).from_params(params, @extra_context)
      errors << [i, @form.errors.full_messages] if @form.errors.any?

      if existing_result.present?
        Decidim::Accountability::Admin::UpdateImportedResult.call(@form, existing_result, params["result"]["parent/id"]) do
          on(:invalid) do
            errors << [i, @form.errors.full_messages]
          end
        end
      else
        Decidim::Accountability::Admin::CreateImportedResult.call(@form, params["result"]["parent/id"]) do
          on(:invalid) do
            errors << [i, @form.errors.full_messages]
          end
        end
        add_match_id(row["id"])
      end

    end

    raise ActiveRecord::Rollback if errors.any?

    update_parents
    remove_invalid_results

    Rails.logger.info "Processed: #{i}"
  end

  errors
end