Skip to content

Commit a360f6f

Browse files
committed
Add service for csv exporting adjustments
1 parent 00066ef commit a360f6f

2 files changed

Lines changed: 59 additions & 11 deletions

File tree

app/models/adjustment.rb

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -34,18 +34,13 @@ def split_difference
3434
[increasing_adjustment, decreasing_adjustment]
3535
end
3636

37-
def self.csv_export_headers
38-
["Created", "Organization", "Storage Location", "Comment", "Changes"]
39-
end
37+
def self.generate_csv(adjustments)
38+
return nil if adjustments.empty?
4039

41-
def csv_export_attributes
42-
[
43-
created_at.strftime("%F"),
44-
organization.name,
45-
storage_location.name,
46-
comment,
47-
line_items.count
48-
]
40+
Exports::ExportAdjustmentsCSVService.new(
41+
adjustments: adjustments,
42+
organization: adjustments.first.organization
43+
).generate_csv
4944
end
5045

5146
private
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
module Exports
2+
class ExportAdjustmentsCSVService
3+
def initialize(adjustments:, organization:)
4+
@adjustments = adjustments
5+
@organization = organization
6+
end
7+
8+
def generate_csv
9+
CSV.generate(headers: true) do |csv|
10+
generate_csv_data.each { |row| csv << row }
11+
end
12+
end
13+
14+
def generate_csv_data
15+
[headers] + @adjustments.map { |adjustment| build_row(adjustment) }
16+
end
17+
18+
private
19+
20+
def headers
21+
[
22+
"Created", "Storage Location",
23+
"Comment", "User", "Changes"
24+
] + item_names
25+
end
26+
27+
def item_names
28+
@organization.items.order(:name).pluck(:name).uniq
29+
end
30+
31+
def build_row(adjustment)
32+
row = [
33+
adjustment.created_at.strftime("%F"),
34+
adjustment.storage_location.name,
35+
adjustment.comment,
36+
adjustment.user&.name || "Unknown",
37+
adjustment.line_items.count { |item| !item.quantity.eql?(0) }
38+
]
39+
40+
item_quantities = Hash.new(0)
41+
42+
adjustment.line_items.each do |line_item|
43+
item_quantities[line_item.item.name] += line_item.quantity
44+
end
45+
46+
item_names.each do |item_name|
47+
row << item_quantities[item_name]
48+
end
49+
50+
row
51+
end
52+
end
53+
end

0 commit comments

Comments
 (0)