FIX: do not error when private message is sent (#41)

FIX: do not error when private message is sent (#41)

Bug was introduced here https://github.com/discourse/discourse-category-experts/commit/dd7fbd2f0999adf3fee234119ac299839816abb4#diff-040b0c3e0e3b0c377ccb9da72d51e1a9716135b8958e74aa81f104651972ee23R112

When private message is sent there is no category and this code was crashing

diff --git a/lib/category_experts/post_handler.rb b/lib/category_experts/post_handler.rb
index 51b2130..c7a87c7 100644
--- a/lib/category_experts/post_handler.rb
+++ b/lib/category_experts/post_handler.rb
@@ -96,8 +96,10 @@ module CategoryExperts
 
     def users_expert_group
       return @users_expert_group if defined?(@users_expert_group) # memoizing a potentially falsy value
+      category = post.topic&.category
+      return if !category
 
-      group_id = user.expert_group_ids_for_category(post.topic.category)&.first
+      group_id = user.expert_group_ids_for_category(category)&.first
       @users_expert_group = group_id.nil? ? nil : Group.find_by(id: group_id)
     end
   end
diff --git a/spec/lib/post_handler_spec.rb b/spec/lib/post_handler_spec.rb
index f45ecfc..7110a90 100644
--- a/spec/lib/post_handler_spec.rb
+++ b/spec/lib/post_handler_spec.rb
@@ -10,6 +10,11 @@ describe CategoryExperts::PostHandler do
   fab!(:group) { Fabricate(:group, users: [expert]) }
   fab!(:second_group) { Fabricate(:group, users: [second_expert]) }
   fab!(:topic) { Fabricate(:topic, category: category) }
+  fab!(:private_message_topic) { Fabricate(:private_message_topic, topic_allowed_users: [
+    Fabricate.build(:topic_allowed_user, user: user),
+    Fabricate.build(:topic_allowed_user, user: expert),
+    Fabricate.build(:topic_allowed_user, user: second_expert),
+  ]) }
 
   before do
     category.custom_fields[CategoryExperts::CATEGORY_EXPERT_GROUP_IDS] = "#{group.id}|#{second_group.id}|#{group.id + 1}"
@@ -31,6 +36,10 @@ describe CategoryExperts::PostHandler do
       end
     end
 
+    it "topic without category like private message should not error" do
+      expect { NewPostManager.new(expert, raw: 'this is a new post', topic_id: private_message_topic.id).perform }.not_to raise_error
+    end
+
     describe "With an existing approved expert post" do
       it "marks the post as needing approval, but not the topic" do
         existing_post = create_post(topic_id: topic.id, user: expert)

GitHub sha: 075bc43c4b517c70bed62a2c265b267c586fca0a

This commit appears in #41 which was approved by tgxworld. It was merged by lis2.