From 41ee039443a6d848a235f6fdec2f82f810e7db57 Mon Sep 17 00:00:00 2001 From: Ted Johansson Date: Thu, 13 Mar 2025 17:50:16 +0800 Subject: [PATCH] FIX: Discourse automation reports with parameters (#363) When setting up an automation to create a DM or a post with a report on a recurring basis, and using a Data Explorer query that has parameters, we encounter an error. The `.params_to_hash` method currently expects an array of arrays for the parameters, but in reality they seem to be arrays of hashes. This change makes `.params_to_hash` work with arrays of hashes. It also preserves the ability to work with nested arrays in case this is used somewhere else. --- .../report_generator.rb | 18 +---------------- spec/report_generator_spec.rb | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/lib/discourse_data_explorer/report_generator.rb b/lib/discourse_data_explorer/report_generator.rb index cc85d48..b014d01 100644 --- a/lib/discourse_data_explorer/report_generator.rb +++ b/lib/discourse_data_explorer/report_generator.rb @@ -35,26 +35,10 @@ module ::DiscourseDataExplorer build_report_post(query, table, attach_csv: opts[:attach_csv], result:) end - private - def self.params_to_hash(query_params) params = JSON.parse(query_params) - params_hash = {} - if !params.blank? - param_key, param_value = [], [] - params.flatten.each.with_index do |data, i| - if i % 2 == 0 - param_key << data - else - param_value << data - end - end - - params_hash = Hash[param_key.zip(param_value)] - end - - params_hash + params.map { |p| p.is_a?(Hash) ? [p["key"], p["value"]] : p }.to_h end def self.build_report_pms(query, table = "", targets = [], attach_csv: false, result: nil) diff --git a/spec/report_generator_spec.rb b/spec/report_generator_spec.rb index 86198da..6c28bda 100644 --- a/spec/report_generator_spec.rb +++ b/spec/report_generator_spec.rb @@ -253,4 +253,24 @@ describe DiscourseDataExplorer::ReportGenerator do ) end end + + describe ".params_to_hash" do + context "when passing nothing" do + let(:query_params) { "[]" } + + it { expect(described_class.params_to_hash(query_params)).to eq({}) } + end + + context "when passing an array of arrays" do + let(:query_params) { '[["foo", 1], ["bar", 2]]' } + + it { expect(described_class.params_to_hash(query_params)).to eq({ "foo" => 1, "bar" => 2 }) } + end + + context "when passing an array of hashes" do + let(:query_params) { '[{ "key": "foo", "value": 1 }, { "key": "bar", "value": 2 }]' } + + it { expect(described_class.params_to_hash(query_params)).to eq({ "foo" => 1, "bar" => 2 }) } + end + end end