Files
discourse-data-explorer/lib/result_to_markdown.rb
T
David Battersby 705753216c FEATURE: Allow data explorer query result to be sent as recurring PM (#233)
This feature enables admins to create reports automatically based on a recurring schedule.

It introduces a new automation script that includes the new email_group_user field added to discourse-automation, along with a query_id and query_params to pass in parameters to the existing data explorer query.

The output of the report will be sent via pm (as a markdown table) to the recipients entered within the automation script.

The automation (supports individual users, email addresses and groups).
2023-03-24 16:38:42 +08:00

50 lines
1.5 KiB
Ruby

# frozen_string_literal: true
include HasSanitizableFields
module ::DiscourseDataExplorer
class ResultToMarkdown
def self.convert(pg_result)
relations, colrender = DataExplorer.add_extra_data(pg_result)
result_data = []
# column names to search in place of id columns (topic_id, user_id etc)
cols = %w[name title username]
# find values from extra data, based on result id
pg_result.values.each do |row|
row_data = []
row.each_with_index do |col, col_index|
col_name = pg_result.fields[col_index]
related = relations.dig(colrender[col_index].to_sym) if col_index < colrender.size
if related.is_a?(ActiveModel::ArraySerializer)
related_row = related.object.find_by(id: col)
if col_name.include?("_id")
column = cols.find { |c| related_row.try c }
else
column = related_row.try(col_name)
end
if column.nil?
row_data[col_index] = col
else
row_data[col_index] = related_row[column]
end
else
row_data[col_index] = col
end
end
result_data << row_data.map { |c| "| #{sanitize_field(c.to_s)} " }.join + "|\n"
end
table_headers = pg_result.fields.map { |c| " #{c.gsub("_id", "")} |" }.join
table_body = pg_result.fields.size.times.map { " :-----: |" }.join
"|#{table_headers}\n|#{table_body}\n#{result_data.join}"
end
end
end