FEATURE: Add ability to skip sending the PM if there are no results (#286)

This commit is contained in:
Natalie Tay 2024-04-18 21:40:28 +08:00 committed by GitHub
parent d8d7bbb778
commit b9d875cc3e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 17 additions and 4 deletions

View File

@ -107,4 +107,6 @@ en:
label: Data Explorer Query
query_params:
label: Data Explorer Query parameters
skip_empty:
label: Skip sending PM if there are no results

View File

@ -2,17 +2,18 @@
module ::DiscourseDataExplorer
class ReportGenerator
def self.generate(query_id, query_params, recipients)
def self.generate(query_id, query_params, recipients, opts = {})
query = DiscourseDataExplorer::Query.find(query_id)
return [] if !query || recipients.empty?
recipients = filter_recipients_by_query_access(recipients, query)
params = params_to_hash(query_params)
result = DataExplorer.run_query(query, params)
result = DataExplorer.run_query(query, params)[:pg_result]
query.update!(last_run_at: Time.now)
table = ResultToMarkdown.convert(result[:pg_result])
return [] if opts[:skip_empty] && result.values.empty?
table = ResultToMarkdown.convert(result)
build_report_pms(query, table, recipients)
end

View File

@ -89,6 +89,7 @@ after_initialize do
field :recipients, component: :email_group_user, required: true
field :query_id, component: :choices, required: true, extra: { content: queries }
field :query_params, component: :"key-value", accepts_placeholders: true
field :skip_empty, component: :boolean
version 1
triggerables [:recurring]
@ -97,6 +98,7 @@ after_initialize do
recipients = Array(fields.dig("recipients", "value")).uniq
query_id = fields.dig("query_id", "value")
query_params = fields.dig("query_params", "value") || {}
skip_empty = fields.dig("skip_empty", "value") || false
unless SiteSetting.data_explorer_enabled
Rails.logger.warn "#{DiscourseDataExplorer::PLUGIN_NAME} - plugin must be enabled to run automation #{automation.id}"
@ -109,7 +111,7 @@ after_initialize do
end
DiscourseDataExplorer::ReportGenerator
.generate(query_id, query_params, recipients)
.generate(query_id, query_params, recipients, { skip_empty: })
.each do |pm|
begin
utils.send_pm(pm, automation_id: automation.id, prefers_encrypt: false)

View File

@ -84,5 +84,13 @@ describe "RecurringDataExplorerResultPm" do
"Hi #{another_group.name}, your data explorer report is ready.\n\nQuery Name:\n#{query.name}",
)
end
it "does not send the PM if skip_empty" do
automation.upsert_field!("skip_empty", "boolean", { value: true })
automation.update(last_updated_by_id: admin.id)
expect { automation.trigger! }.to_not change { Post.count }
end
end
end