Class: RailsDbAdmin::Services::ReportHelper

Inherits:
AbstractController::Base
  • Object
show all
Includes:
AbstractController::AssetPaths, AbstractController::Helpers, AbstractController::Rendering, AbstractController::Translation
Defined in:
lib/rails_db_admin/services/report_helper.rb

Defined Under Namespace

Classes: Cache

Instance Method Summary collapse

Instance Method Details

#build_report(report_iid, formats = [:pdf, :csv], report_params = {}) ⇒ Object

Renders report for formats

Parameters:

  • report_iid (String)

    IID of Report

  • format (Symbol)

    Format to render the report in (:pdf, :csv)

  • report_params (Hash) (defaults to: {})

    Parameters for report



18
19
20
21
22
23
24
25
26
27
28
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/rails_db_admin/services/report_helper.rb', line 18

def build_report(report_iid, formats=[:pdf, :csv], report_params={})
  begin
    @formats = formats

    database_connection_class = RailsDbAdmin::ConnectionHandler.create_connection_class(Rails.env)
    @query_support = RailsDbAdmin::QuerySupport.new(database_connection_class, Rails.env)

    @report = Report.find_by_internal_identifier(report_iid)
    @report_params = report_params

    add_report_view_paths
    build_report_data

    missing_params = check_required_params

    if missing_params.count > 0
      if missing_params.count == 1
        "#{missing_params.join(', ')} is required"
      else
        "#{missing_params.join(', ')} are required"
      end

    else
      file_attachments = []

      if @data[:error]
        @data[:error]
      else
        @formats.each do |format|
          case format
            when :html
              data = render inline: @report.template,
                            locals: build_tpl_locals

              file_attachments.push({name: "#{@report.name}.html", data: data})

            when :pdf
              data = render_to_string({
                                          template: 'base.html.erb',
                                          locals: build_tpl_locals
                                      })

              file_attachments << {
                  name: "#{@report.name}.pdf",
                  data: WickedPdf.new.pdf_from_string(data, build_pdf_config)
              }

            when :csv
              business_module = @report_params[:business_module_id].present? ? BusinessModule.where(id: @report_params[:business_module_id]).first : nil

              csv_data = CSV.generate do |csv|
  
                custom_data_columns = []
                if @data[:columns].include?('custom_fields')

                  custom_data = JSON.parse(@data[:rows].first['custom_fields'])

                  if business_module
                    custom_data.each do |field_name, field_value|
                      custom_data_columns << business_module.organizer_view.selected_fields.where('field_name = ?', field_name).first.label
                    end
                  else
                    custom_data_columns = custom_data.keys
                  end

                  # remove the custom_fields column if it exists
                  @data[:columns].delete('custom_fields')
                end

                csv << @data[:columns] + custom_data_columns

                @data[:rows].each do |row|
                  custom_values = []

                  custom_fields = row.delete('custom_fields')

                  unless custom_fields.blank?
                    custom_data = JSON.parse(custom_fields)

                    if business_module
                      custom_data.each do |field_name, field_value|
                        case business_module.organizer_view.selected_fields.where('field_name = ?', field_name).first.field_type.internal_identifier
                          when 'address'
                            if field_value.blank?
                              custom_values << ''
                            else
                              custom_values << "#{field_value['address_line_1']} #{field_value['address_line_2']} #{field_value['city']} #{field_value['state']}, #{field_value['zip']} #{field_value['country']}"
                            end
                          else
                            custom_values << field_value
                        end

                      end
                    else
                      custom_values = custom_data.values
                    end
                  end

                  csv << row.values + custom_values
                end
              end

              file_attachments << {
                  name: "#{@report.name}.csv",
                  data: csv_data
              }
            else
              raise 'Invalid Format'
          end
        end

        file_attachments
      end

    end

  rescue StandardError => ex
    Rails.logger.error ex.message
    Rails.logger.error ex.backtrace.join("\n")

    # email notification
    ExceptionNotifier.notify_exception(ex) if defined? ExceptionNotifier

    "Error running report"
  end
end