Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add generic post event finder filters (#43131)

Gabriel Grubba2e9dc47bd88e
diff --git a/plugins/discourse-events/app/controllers/discourse_events/events_controller.rb b/plugins/discourse-events/app/controllers/discourse_events/events_controller.rb
index bc20f8a3b25..2a53d74292f 100644
--- a/plugins/discourse-events/app/controllers/discourse_events/events_controller.rb
+++ b/plugins/discourse-events/app/controllers/discourse_events/events_controller.rb
@@ -26,8 +26,10 @@ module DiscourseEvents
format.ics do
@calendar_name = calendar_name_for_ics
- after_time = filtered_events_params[:after]&.to_datetime || Time.current
- before_time = filtered_events_params[:before]&.to_datetime || 1.year.from_now
+ after_time =
+ Events::Finder.time_param(filtered_events_params[:after], :after) || Time.current
+ before_time =
+ Events::Finder.time_param(filtered_events_params[:before], :before) || 1.year.from_now
@ics_events =
@events.flat_map do |event|
@@ -53,24 +55,33 @@ module DiscourseEvents
end
format.json do
- # The detailed serializer is currently not used anywhere in the frontend, but available via API
serializer =
(
if params[:include_details] == "true"
Events::EventSerializer
+ elsif params[:include_card] == "true"
+ Events::EventCardSerializer
else
Events::BasicEventSerializer
end
)
+ sample_invitees_by_event =
+ Events::EventCardSerializer.sample_invitees_by_event(@events) if serializer ==
+ Events::EventCardSerializer
+
+ after_time =
+ Events::Finder.time_param(filtered_events_params[:after], :after) || Time.current
+ before_time = Events::Finder.time_param(filtered_events_params[:before], :before)
+
serialized_events =
@events.map do |event|
expanded =
DiscourseEvents::Events::Action::ExpandOccurrences.call(
event: event,
- after: filtered_events_params[:after]&.to_datetime || Time.current,
- before: filtered_events_params[:before]&.to_datetime,
- limit: filtered_events_params[:limit]&.to_i || 50,
+ after: after_time,
+ before: before_time,
+ limit: event_limit,
current_occurrence_only: current_occurrence_only_event_ids.include?(event.id),
)
@@ -88,6 +99,7 @@ module DiscourseEvents
root: false,
occurrences: formatted_occurrences,
include_occurrences: true,
+ sample_invitees_by_event:,
).as_json
end
@@ -185,9 +197,18 @@ module DiscourseEvents
:before,
:after,
:order,
+ :tags,
+ :search,
+ :status,
+ :event_format,
+ tags: [],
)
end
+ def event_limit
+ Events::Finder.limit_param(filtered_events_params[:limit]) || 50
+ end
+
def current_occurrence_only_event_ids
@current_occurrence_only_event_ids ||= single_occurrence_rsvp_event_ids
end
diff --git a/plugins/discourse-events/app/serializers/discourse_events/events/event_card_serializer.rb b/plugins/discourse-events/app/serializers/discourse_events/events/event_card_serializer.rb
new file mode 100644
index 00000000000..a6c4207ea75
--- /dev/null
+++ b/plugins/discourse-events/app/serializers/discourse_events/events/event_card_serializer.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+module DiscourseEvents
+ module Events
+ class EventCardSerializer < BasicEventSerializer
+ attributes :creator, :description, :location, :url, :sample_invitees
+
+ has_one :image_upload, embed: :object, serializer: UploadSerializer
+
+ def self.sample_invitees_by_event(events)
+ event_ids = events.map(&:id)
+ return {} if event_ids.empty?
+
+ limit = SiteSetting.displayed_invitees_limit
+ ranked_invitees =
+ Invitee
+ .unscoped
+ .joins(:user)
+ .merge(User.not_suspended)
+ .merge(User.not_silenced)
+ .merge(User.not_staged)
+ .where.not(users: { id: nil })
+ .where(post_id: event_ids)
+ .select(
+ "discourse_post_event_invitees.*, " \
+ "ROW_NUMBER() OVER (" \
+ "PARTITION BY discourse_post_event_invitees.post_id " \
+ "ORDER BY discourse_post_event_invitees.status, " \
+ "discourse_post_event_invitees.created_at, " \
+ "discourse_post_event_invitees.user_id" \
+ ") AS rank",
+ )
+
+ Invitee
+ .from("(#{ranked_invitees.to_sql}) discourse_post_event_invitees")
+ .where("rank <= ?", limit)
+ .preload(:user)
+ .group_by(&:post_id)
+ end
+
+ def creator
+ BasicUserSerializer.new(object.post.user, scope:, root: false).as_json
+ end
+
+ def sample_invitees
+ ActiveModel::ArraySerializer.new(
+ @options.fetch(:sample_invitees_by_event, {})[object.id] || object.most_likely_going,
+ each_serializer: InviteeSerializer,
+ scope:,
+ ).as_json
+ end
+
+ def include_sample_invitees?
+ scope.can_display_invitee_details?(object)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-events/lib/discourse_events/events/finder.rb b/plugins/discourse-events/lib/discourse_events/events/finder.rb
index 826b7a896d9..a36b9f130da 100644
--- a/plugins/discourse-events/lib/discourse_events/events/finder.rb
+++ b/plugins/discourse-events/lib/discourse_events/events/finder.rb
@@ -12,10 +12,32 @@ module DiscourseEvents
.then { |query| filter_by_attending_user(query, params, guardian, user) }
.then { |query| filter_by_dates(query, params) }
.then { |query| filter_by_category(query, params) }
+ .then { |query| filter_by_tags(query, params, guardian) }
+ .then { |query| filter_by_search(query, params) }
+ .then { |query| filter_by_status(query, params) }
+ .then { |query| filter_by_format(query, params) }
.then { |query| apply_ordering(query, params) }
.then { |query| apply_limit(query, params) }
end
+ def self.time_param(value, name)
+ return if value.blank?
+ return Time.current if value == "now"
+
+ value.to_datetime
+ rescue ArgumentError, Date::Error
+ raise Discourse::InvalidParameters.new(name)
+ end
+
+ def self.limit_param(value)
+ return if value.blank?
+
+ limit = Integer(value, exception: false)
+ raise Discourse::InvalidParameters.new(:limit) if limit.nil? || limit < 1
+
+ [limit, 200].min
+ end
+
private
def self.build_base_query(guardian, user, params)
@@ -117,8 +139,8 @@ module DiscourseEvents
def self.filter_by_dates(events, params)
return events if params[:before].blank? && params[:after].blank?
- before_date = params[:before] == "now" ? Time.current : params[:before]&.to_datetime
- after_date = params[:after] == "now" ? Time.current : params[:after]&.to_datetime
+ before_date = time_param(params[:before], :before)
+ after_date = time_param(params[:after], :after)
include_ongoing = params[:include_ongoing].present?
recurring_scope = build_recurring_date_scope(after_date, before_date)
@@ -186,6 +208,67 @@ module DiscourseEvents
events.where(topics: { category_id: category_ids })
end
+ def self.filter_by_tags(events, params, guardian)
+ tag_names =
+ Array(params[:tags])
+ .flat_map { |tag| tag.to_s.split(",") }
+ .filter_map { |tag| tag.strip.downcase.presence }
+ .uniq
+ return events if tag_names.empty?
+
+ tags = DiscourseTagging.visible_tags(guardian).where(name: tag_names)
+ return events.none unless tags.count == tag_names.length
+
+ matching_topic_ids =
+ TopicTag
+ .where(tag_id: tags.select(:id))
+ .group(:topic_id)
+ .having("COUNT(DISTINCT tag_id) = ?", tag_names.length)
+ .select(:topic_id)
+
+ events.where(topics: { id: matching_topic_ids })
+ end
+
+ def self.filter_by_search(events, params)
+ search = params[:search].to_s.strip[0, 100]
+ return events if search.blank?
+
+ pattern = "%#{ActiveRecord::Base.sanitize_sql_like(search)}%"
+ events.where(
+ "discourse_post_event_events.name ILIKE :pattern OR " \
+ "discourse_post_event_events.description ILIKE :pattern OR " \
+ "discourse_post_event_events.location ILIKE :pattern",
+ pattern:,
+ )
+ end
+
+ def self.filter_by_status(events, params)
+ statuses =
+ Array(params[:status])
+ .flat_map { |status| status.to_s.split(",") }
+ .filter_map { |status| Event.statuses[status.to_sym] }
+ .uniq
+ return events if params[:status].blank?
+ return events.none if statuses.empty?
+
+ events.where(status: statuses)
+ end
+
+ def self.filter_by_format(events, params)
+ case params[:event_format]
+ when nil, ""
+ events
+ when "virtual"
+ events.where.not(url: nil).where(location: [nil, ""])
+ when "in_person"
+ events.where(url: [nil, ""]).where.not(location: nil).where.not(location: "")
+ when "hybrid"
+ events.where.not(url: [nil, ""]).where.not(location: [nil, ""])
+ else
+ events.none
+ end
+ end
+
def self.apply_ordering(events, params)
order_direction = params[:order] == "desc" ? "DESC" : "ASC"
events.order(
@@ -194,8 +277,7 @@ module DiscourseEvents
end
def self.apply_limit(events, params)
- limit = params[:limit]&.to_i || 200
- events.limit(limit.clamp(1, 200))
+ events.limit(limit_param(params[:limit]) || 200)
end
def self.listable_topics(guardian)
diff --git a/plugins/discourse-events/spec/requests/api/events_spec.rb b/plugins/discourse-events/spec/requests/api/events_spec.rb
index 6286c63df91..81742dd3140 100644
--- a/plugins/discourse-events/spec/requests/api/events_spec.rb
+++ b/plugins/discourse-events/spec/requests/api/events_spec.rb
@@ -24,6 +24,15 @@ RSpec.describe "events" do
},
description: "Include detailed event information (creator, invitees, stats, etc.)"
+ parameter name: :include_card,
+ in: :query,
+ required: false,
+ schema: {
+ type: :string,
+ enum: %w[true false],
+ },
+ description: "Include card fields without detailed event HTML or statistics"
+
parameter name: :category_id,
in: :query,
required: false,
@@ -95,6 +104,43 @@ RSpec.describe "events" do
},
description: "Maximum number of events to return (default: 200)"
+ parameter name: :tags,
+ in: :query,
+ required: false,
+ schema: {
+ type: :array,
+ items: {
+ type: :string,
+ },
+ },
+ description: "Filter to events whose topic has every specified tag"
+
+ parameter name: :search,
+ in: :query,
+ required: false,
+ schema: {
+ type: :string,
+ },
+ description: "Search event names, descriptions, and locations"
+
+ parameter name: :status,
+ in: :query,
+ required: false,
+ schema: {
+ type: :string,
+ enum: %w[public private standalone],
+ },
+ description: "Filter by event attendance status"
+
+ parameter name: :event_format,
+ in: :query,
+ required: false,
+ schema: {
+ type: :string,
+ enum: %w[virtual in_person hybrid],
+ },
+ description: "Filter by whether the event has a URL, location, or both"
+
produces "application/json"
response "200", "success response (basic)" do
diff --git a/plugins/discourse-events/spec/requests/events_controller_spec.rb b/plugins/discourse-events/spec/requests/events_controller_spec.rb
index c6f55b41675..b67e033773c 100644
--- a/plugins/discourse-events/spec/requests/events_controller_spec.rb
+++ b/plugins/discourse-events/spec/requests/events_controller_spec.rb
@@ -78,6 +78,98 @@ module DiscourseEvents::Events
expect(description_html).to include("<p>Bring snacks</p>")
end
+ it "returns card fields without cooking event text for every event" do
+ creator = Fabricate(:user)
+ event =
+ Fabricate(
+ :event,
+ user: creator,
+ original_starts_at: 1.day.from_now,
+ description: "Discuss the launch",
+ location: "Room 5",
+ url: "https://example.com/launch",
+ )
+ attendee = Fabricate(:user)
+ event.create_invitees(
+ [{ user_id: attendee.id, status: DiscourseEvents::Events::Invitee.statuses[:going] }],
+ )
+
+ get "/discourse-post-event/events.json", params: { include_card: "true" }
+
+ expect(response.status).to eq(200)
+ card = response.parsed_body["events"].find { |event_json| event_json["id"] == event.id }
+ expect(card).to include(
+ "creator" => hash_including("username" => creator.username),
+ "description" => "Discuss the launch",
+ "location" => "Room 5",
+ "url" => "https://example.com/launch",
+ )
+ expect(card["sample_invitees"].map { |invitee| invitee.dig("user", "username") }).to eq(
+ [attendee.username],
+ )
+ expect(card).not_to have_key("description_html")
+ end
+
+ it "rejects invalid dates and limits" do
+ [
+ { after: "garbage" },
+ { before: "2025-13-45" },
+ { limit: "abc" },
+ { limit: "0" },
+ ].each do |params|
+ get "/discourse-post-event/events.json", params: params
+
+ expect(response.status).to eq(400)
+ end
+ end
+
+ it "accepts now as the lower date bound" do
+ Fabricate(:event, original_starts_at: 1.day.from_now)
+
+ get "/discourse-post-event/events.json", params: { after: "now" }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["events"]).not_to be_empty
+ end
+
+ it "filters by tags, text, status, and format" do
+ tag = Fabricate(:tag, name: "launch")
+ tagged_event =
+ Fabricate(
+ :event,
+ original_starts_at: 1.day.from_now,
+ name: "Launch briefing",
+ location: "Room 5",
+ post: Fabricate(:post, topic: Fabricate(:topic, tags: [tag])),
+ )
+ private_event =
+ Fabricate(
+ :event,
+ original_starts_at: 2.days.from_now,
+ status: DiscourseEvents::Events::Event.statuses[:private],
+ url: "https://example.com/meeting",
+ )
+ hybrid_event =
+ Fabricate(
+ :event,
+ original_starts_at: 3.days.from_now,
+ url: "https://example.com/meeting",
+ location: "Room 6",
+ )
+
+ get "/discourse-post-event/events.json", params: { tags: [tag.name] }
+ expect(response.parsed_body["events"].pluck("id")).to contain_exactly(tagged_event.id)
+
+ get "/discourse-post-event/events.json", params: { search: "briefing" }
+ expect(response.parsed_body["events"].pluck("id")).to contain_exactly(tagged_event.id)
+
+ get "/discourse-post-event/events.json", params: { status: "private" }
+ expect(response.parsed_body["events"].pluck("id")).to contain_exactly(private_event.id)
+
+ get "/discourse-post-event/events.json", params: { event_format: "hybrid" }
+ expect(response.parsed_body["events"].pluck("id")).to contain_exactly(hybrid_event.id)
+ end
+
it "should return events in ics format" do
event1 = Fabricate(:event, original_starts_at: 1.day.from_now, name: "Test Event 1")
event2 = Fabricate(:event, original_starts_at: 2.days.from_now, name: "Test Event 2")