11module Exports
22 class ExportDonationsCSVService
3- def initialize ( donation_ids :)
3+ def initialize ( donation_ids :, organization : )
44 # Use a where lookup so that I can eager load all the resources
55 # needed rather than depending on external code to do it for me.
66 # This makes this code more self contained and efficient!
@@ -13,6 +13,8 @@ def initialize(donation_ids:)
1313 ) . where (
1414 id : donation_ids ,
1515 ) . order ( created_at : :asc )
16+
17+ @organization = organization
1618 end
1719
1820 def generate_csv
@@ -80,7 +82,7 @@ def base_table
8082 "Variety of Items" => -> ( donation ) {
8183 donation . line_items . map ( &:name ) . uniq . size
8284 } ,
83- "In-Kind Value " => -> ( donation ) {
85+ "In-Kind Total " => -> ( donation ) {
8486 donation . in_kind_value_money
8587 } ,
8688 "Comments" => -> ( donation ) {
@@ -105,20 +107,30 @@ def item_headers
105107 end
106108
107109 @item_headers = item_names . sort
110+
111+ @item_headers = @item_headers . flat_map { |header | [ header , "#{ header } In-Kind Value" ] } if @organization . include_in_kind_values_in_exported_files
112+
113+ @item_headers
108114 end
109115
110116 def build_row_data ( donation )
111117 row = base_table . values . map { |closure | closure . call ( donation ) }
112-
113- row += Array . new ( item_headers . size , 0 )
118+ row += make_item_quantity_and_value_slots
114119
115120 donation . line_items . each do |line_item |
116121 item_name = line_item . item . name
117122 item_column_idx = headers_with_indexes [ item_name ]
118123 row [ item_column_idx ] += line_item . quantity
124+ row [ item_column_idx + 1 ] += Money . new ( line_item . value_per_line_item ) if @organization . include_in_kind_values_in_exported_files
119125 end
120126
121127 row
122128 end
129+
130+ def make_item_quantity_and_value_slots
131+ slots = Array . new ( item_headers . size , 0 )
132+ slots = slots . map . with_index { |value , index | index . odd? ? Money . new ( 0 ) : value } if @organization . include_in_kind_values_in_exported_files
133+ slots
134+ end
123135 end
124136end
0 commit comments