diff --git a/lib/discourse_chat/rule.rb b/lib/discourse_chat/rule.rb index 03d82b5..0de9f99 100644 --- a/lib/discourse_chat/rule.rb +++ b/lib/discourse_chat/rule.rb @@ -8,7 +8,7 @@ @provider = '' @channel = '' @category_id = nil - @tags = [] + @tags = nil @filter = 'watch' @error_key = nil h.each {|k,v| public_send("#{k}=",v)} @@ -141,6 +141,10 @@ self.where("value::json->>'provider'=?", provider) end + def self.all_for_channel(provider, channel) + self.where("value::json->>'provider'=? AND value::json->>'channel'=?", provider, channel) + end + def self.all_for_category(category_id) if category_id.nil? self.where("json_typeof(value::json->'category_id')='null'") @@ -167,9 +171,13 @@ end def self._from_psr_rows(raw) - raw.map do |psr| + rules = raw.map do |psr| from_hash PluginStore.cast_value(psr.type_name, psr.value) end + + filter_order = ["mute", "watch", "follow"] + rules = rules.sort_by{ |r| [r.channel, r.category_id.nil? ? 0 : r.category_id, filter_order.index(r.filter)] } + return rules end def self.destroy_all diff --git a/plugin.rb b/plugin.rb index 13392b5..b5aabb6 100644 --- a/plugin.rb +++ b/plugin.rb @@ -123,9 +123,6 @@ after_initialize do raise Discourse::NotFound end - filter_order = ["watch", "follow", "mute"] - rules = rules.sort_by{ |r| [r.channel, r.category_id.nil? ? 0 : r.category_id, filter_order.index(r.filter)] } - render_serialized rules, DiscourseChat::RuleSerializer, root: 'rules' end diff --git a/spec/lib/discourse_chat/rule_spec.rb b/spec/lib/discourse_chat/rule_spec.rb index f976ccf..2d6abee 100644 --- a/spec/lib/discourse_chat/rule_spec.rb +++ b/spec/lib/discourse_chat/rule_spec.rb @@ -90,6 +90,18 @@ RSpec.describe DiscourseChat::Rule do expect(DiscourseChat::Rule.all_for_provider('telegram').length).to eq(1) end + it 'can be filtered by channel' do + rule2 = DiscourseChat::Rule.new({provider:'telegram', channel:'blah'}).save! + rule3 = DiscourseChat::Rule.new({provider:'slack', channel:'#blah'}).save! + rule4 = DiscourseChat::Rule.new({provider:'slack', channel:'#general'}).save! + rule5 = DiscourseChat::Rule.new({provider:'slack', channel:'#general'}).save! + + expect(DiscourseChat::Rule.all.length).to eq(5) + + expect(DiscourseChat::Rule.all_for_channel('slack','#general').length).to eq(3) + expect(DiscourseChat::Rule.all_for_channel('slack', '#blah').length).to eq(1) + end + it 'can be filtered by category' do rule2 = DiscourseChat::Rule.new({provider:'slack', channel:'#blah', category_id: 1}).save! rule3 = DiscourseChat::Rule.new({provider:'slack', channel:'#blah', category_id: nil}).save!