Skip to content

Commit 5fe5761

Browse files
committed
refactor controller and create separate reports service
1 parent a4383f8 commit 5fe5761

2 files changed

Lines changed: 24 additions & 22 deletions

File tree

app/controllers/reports/annual_reports_controller.rb

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
class Reports::AnnualReportsController < ApplicationController
22
before_action :validate_show_params, only: [:show, :recalculate]
3-
before_action :validate_range_params, only: [:range]
43

54
def index
65
# 2813_update_annual_report -- changed to earliest_reporting_year
@@ -34,12 +33,14 @@ def recalculate
3433
end
3534

3635
def range
37-
year_start = [range_params[:year_start].to_i, current_organization.earliest_reporting_year].max
38-
year_end = [range_params[:year_end].to_i, Time.current.year].min
36+
year_start, year_end = range_params[:year_start], range_params[:year_end]
3937

40-
year_start, year_end = [year_start, year_end].minmax
38+
if year_end < year_start
39+
flash[:error] = "End year must be greater than or equal to start year."
40+
redirect_to reports_annual_reports_path and return
41+
end
4142

42-
reports = get_range_report(year_start, year_end)
43+
reports = Reports::AnnualSurveyReportService.new(organization: current_organization, year_start: year_start, year_end: year_end).call
4344

4445
respond_to do |format|
4546
format.csv do
@@ -51,15 +52,6 @@ def range
5152

5253
private
5354

54-
def get_range_report(year_start, year_end)
55-
(year_start..year_end).map do |year|
56-
Reports.retrieve_report(organization: current_organization, year: year, recalculate: true)
57-
rescue ActiveRecord::RecordInvalid => e
58-
Rails.logger.error("Failed to retrieve annual report for year #{year}: #{e.message}")
59-
nil
60-
end.compact
61-
end
62-
6355
def year_param
6456
params.require(:year)
6557
end
@@ -71,12 +63,4 @@ def range_params
7163
def validate_show_params
7264
not_found! unless year_param.to_i.positive?
7365
end
74-
75-
def validate_range_params
76-
not_found! unless range_params[:year_start] =~ year_regex && range_params[:year_end] =~ year_regex
77-
end
78-
79-
def year_regex
80-
/^\d{4}$/
81-
end
8266
end
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
module Reports
2+
class AnnualSurveyReportService
3+
def initialize(organization:, year_start:, year_end:)
4+
@organization = organization
5+
@year_start = year_start
6+
@year_end = year_end
7+
end
8+
9+
def call
10+
(@year_start..@year_end).map do |year|
11+
Reports.retrieve_report(organization: @organization, year: year, recalculate: true)
12+
rescue ActiveRecord::RecordInvalid => e
13+
Rails.logger.error("Failed to retrieve annual report for year #{year}: #{e.message}")
14+
nil
15+
end.compact
16+
end
17+
end
18+
end

0 commit comments

Comments
 (0)