-
-
Notifications
You must be signed in to change notification settings - Fork 573
Expand file tree
/
Copy pathchildren_served_report_service.rb
More file actions
66 lines (57 loc) · 2.34 KB
/
children_served_report_service.rb
File metadata and controls
66 lines (57 loc) · 2.34 KB
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
module Reports
class ChildrenServedReportService
include ActionView::Helpers::NumberHelper
attr_reader :year, :organization
# @param year [Integer]
# @param organization [Organization]
def initialize(year:, organization:)
@year = year
@organization = organization
end
# @return [Hash]
def report
@report ||= { name: 'Children Served',
entries: {
'Average children served monthly' => number_with_delimiter(average_children_monthly),
'Total children served' => number_with_delimiter(total_children_served),
'Repackages diapers?' => organization.repackage_essentials? ? 'Y' : 'N',
'Monthly diaper distributions?' => organization.distribute_monthly? ? 'Y' : 'N'
} }
end
# @return [Integer]
def total_children_served
@total_children_served ||= total_children_served_with_loose_disposables + children_served_with_kits_containing_disposables
end
# @return [Float]
def average_children_monthly
(total_children_served / 12.0).round(2)
end
private
def total_children_served_with_loose_disposables
organization
.distributions
.for_year(year)
.joins(line_items: :item)
.merge(Item.loose.disposable_diapers)
.pick(Arel.sql("CEILING(SUM(line_items.quantity::numeric / COALESCE(items.distribution_quantity, 50)))"))
.to_i
end
# These joins look circular but are needed due to polymorphic relationships.
# A distribution has many line_items and items, but kits also
# have the same relationships and we want to perform calculations on the
# items in the kits not the kit items themselves.
def children_served_with_kits_containing_disposables
kits_subquery = organization
.distributions
.for_year(year)
.joins(line_items: { item: { kit: { kit_item: { line_items: :item} } }})
.where("items_line_items.reporting_category = 'disposable_diapers'")
.select("DISTINCT ON (distributions.id, line_items.id, kits.id) line_items.quantity, items.distribution_quantity")
.to_sql
Distribution
.from("(#{kits_subquery}) AS q")
.pick(Arel.sql("CEILING(SUM(q.quantity::numeric / COALESCE(q.distribution_quantity, 1)))"))
.to_i
end
end
end