Created
August 15, 2022 20:55
-
-
Save rickychilcott/4c66a651f98b74e93a74c6d3102ff56d to your computer and use it in GitHub Desktop.
AVO Sales List Export CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class SalesListOrganizationCsvDownload < Avo::BaseAction | |
self.name = "CSV Download" | |
self.may_download_file = true | |
self.confirm_button_label = "Download" | |
def handle(**args) | |
_models, _fields, _current_user, resource = args.values_at(:models, :fields, :current_user, :resource) | |
organization_data = [] | |
headers = Set.new | |
resource | |
.model_class | |
.has_sg_events | |
.find_each do |organization| | |
attributes = organization.attributes.without("sg_events") | |
unique_event_names = organization.sg_events.map { |item| item["event_name"] }.uniq | |
unique_event_names.each do |event_name| | |
attributes["sg_event_count_#{event_name}"] = | |
organization.sg_events.count { |item| item["event_name"] == event_name } | |
end | |
headers.merge(attributes.keys) | |
organization_data << attributes | |
end | |
output = CSV.generate do |csv| | |
# add headers | |
csv << headers | |
organization_data.each do |organization| | |
# add data from each row | |
csv << organization.values_at(*headers) | |
end | |
end | |
succeed "Downloading..." | |
download output, "sales_list_organizations_with_sales_stats.csv" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment