/
region_report_service.rb
69 lines (58 loc) · 2.26 KB
/
region_report_service.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
class RegionReportService
include SQLHelpers
MAX_MONTHS_OF_DATA = 24
CACHE_VERSION = 8
def initialize(region:, period:, current_user:, top_region_benchmarks_enabled: false)
@current_user = current_user
@organizations = Pundit.policy_scope(current_user, [:cohort_report, Organization]).order(:name)
@region = region
@period = period
@facilities = region.facilities.to_a
start_period = period.advance(months: -(MAX_MONTHS_OF_DATA - 1))
@range = start_period..@period
@top_region_benchmarks_enabled = top_region_benchmarks_enabled
@result = Reports::Result.new(@range)
end
attr_reader :current_user
attr_reader :result
attr_reader :facilities
attr_reader :organizations
attr_reader :period
attr_reader :range
attr_reader :region
def top_region_benchmarks_enabled?
@top_region_benchmarks_enabled
end
def call
result.merge! ControlRateService.new(region, periods: range).call
result.merge! compile_cohort_trend_data
result.visited_without_bp_taken = NoBPMeasureService.new(region, periods: range).call
result.calculate_percentages(:visited_without_bp_taken)
result.count_missed_visits
result.calculate_missed_visits_percentages
# TODO refactor top region benchmarks - this isn't used right now and doesn't follow the most recent refactoring
result[:top_region_benchmarks].merge!(top_region_benchmarks) if top_region_benchmarks_enabled?
result
end
private
# We want to return cohort result for the current quarter for the selected date, and then
# the previous three quarters.
def compile_cohort_trend_data
Rails.cache.fetch(cohort_cache_key, version: cohort_cache_version, expires_in: 7.days, force: force_cache?) do
CohortService.new(region: region, quarters: period.to_quarter_period.value.downto(3)).call
end
end
def cohort_cache_key
"#{self.class}/cohort_trend_data/#{region.model_name}/#{region.id}/#{organizations.map(&:id)}/#{period}/#{CACHE_VERSION}"
end
def cohort_cache_version
"#{region.updated_at.utc.to_s(:usec)}/#{CACHE_VERSION}"
end
def force_cache?
RequestStore.store[:force_cache]
end
def top_region_benchmarks
scope = region.class.to_s.underscore.to_sym
TopRegionService.new(organizations, period, scope: scope).call
end
end