main
 1class CategoryList
 2    # Add the uncategorized "magic" category
 3    def add_uncategorized
 4      # Support for uncategorized topics
 5      uncategorized_topics = Topic
 6                        .listable_topics
 7                        .where(category_id: nil)
 8                        .topic_list_order
 9                        .limit(SiteSetting.category_featured_topics)
10      if uncategorized_topics.present?
11
12        totals = Topic.exec_sql("SELECT SUM(CASE WHEN created_at >= (CURRENT_TIMESTAMP - INTERVAL '1 WEEK') THEN 1 ELSE 0 END) as topics_week,
13                                        SUM(CASE WHEN created_at >= (CURRENT_TIMESTAMP - INTERVAL '1 MONTH') THEN 1 ELSE 0 END) as topics_month,
14                                        SUM(CASE WHEN created_at >= (CURRENT_TIMESTAMP - INTERVAL '1 YEAR') THEN 1 ELSE 0 END) as topics_year,
15                                        COUNT(*) AS topic_count
16                                 FROM topics
17                                 WHERE topics.visible
18                                  AND topics.deleted_at IS NULL
19                                  AND topics.category_id IS NULL
20                                  AND topics.archetype <> '#{Archetype.private_message}'").first
21
22
23        uncategorized = Category.new({name: SiteSetting.uncategorized_name,
24                                      slug: Slug.for(SiteSetting.uncategorized_name),
25                                      color: SiteSetting.uncategorized_color,
26                                      text_color: SiteSetting.uncategorized_text_color,
27                                      featured_topics: uncategorized_topics}.merge(totals))
28
29        # Find the appropriate place to insert it:
30        insert_at = nil
31        @categories.each_with_index do |c, idx|
32          if (uncategorized.topics_week || 0) > (c.topics_week || 0)
33            insert_at = idx
34            break
35          end
36        end
37
38        @categories.insert(insert_at || @categories.size, uncategorized)
39      end
40
41      if @all_topics.present? && uncategorized.present?
42        uncategorized.displayable_topics = uncategorized_topics
43        @all_topics << uncategorized_topics
44        @all_topics.flatten!
45      end
46    end
47end