Skip to content

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

FEATURE: Scope post-level workflow triggers to specific topics

Régis Hanole83d41388c29
diff --git a/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rb b/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rb
index 7116c5ace78..dccd6e10c66 100644
--- a/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rb
+++ b/plugins/boards/lib/discourse_workflows/nodes/create_board/v1.rb
@@ -70,7 +70,7 @@ if defined?(DiscourseWorkflows)
exec_ctx.get_node_parameter("tag_names", item_index, default: []),
),
"category_ids" =>
- DiscourseWorkflows::NodeType.normalize_category_ids(
+ DiscourseWorkflows::NodeType.normalize_ids(
exec_ctx.get_node_parameter("category_ids", item_index, default: []),
),
"acl" => exec_ctx.get_node_parameter("acl", item_index, default: []),
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs
index b5efcef7b97..74489fe5714 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs
@@ -7,18 +7,9 @@ import { service } from "@ember/service";
import Category from "discourse/models/category";
import CategoryChooser from "discourse/select-kit/components/category-chooser";
import CategorySelector from "discourse/select-kit/components/category-selector";
+import { integerIdsFromValue, sameIds } from "../../../lib/workflows/id-values";
import ExpressionWrapper from "./expression-wrapper";
-function categoryIdsFromValue(value) {
- if (value == null || value === "") {
- return [];
- }
-
- return (Array.isArray(value) ? value : [value])
- .map((id) => parseInt(id, 10))
- .filter((id) => !isNaN(id));
-}
-
export default class CategoryControl extends Component {
@service siteSettings;
@@ -45,7 +36,7 @@ export default class CategoryControl extends Component {
}
get categoryIds() {
- return categoryIdsFromValue(this.args.field.value);
+ return integerIdsFromValue(this.args.field.value);
}
async updateSelectedCategories(previousRequest) {
@@ -60,7 +51,7 @@ export default class CategoryControl extends Component {
await previousRequest;
- if (this.isDestroying || !this.#sameIds(this.categoryIds, requestedIds)) {
+ if (this.isDestroying || !sameIds(this.categoryIds, requestedIds)) {
return;
}
@@ -71,7 +62,7 @@ export default class CategoryControl extends Component {
hydrateSelectedCategories() {
const ids = this.categoryIds;
if (
- this.#sameIds(
+ sameIds(
ids,
this.selectedCategories.map((category) => category.id)
)
@@ -96,10 +87,6 @@ export default class CategoryControl extends Component {
this.args.field.set(categories.map((category) => category.id));
}
- #sameIds(a, b) {
- return a.length === b.length && a.every((id, index) => id === b[index]);
- }
-
<template>
<ExpressionWrapper
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/topic-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/topic-control.gjs
new file mode 100644
index 00000000000..42eec98b716
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/topic-control.gjs
@@ -0,0 +1,135 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { isEmpty } from "@ember/utils";
+import { classNames } from "@ember-decorators/component";
+import { makeArray } from "discourse/lib/helpers";
+import { searchForTerm } from "discourse/lib/search";
+import MultiSelect from "discourse/select-kit/components/multi-select";
+import { selectKitOptions } from "discourse/select-kit/components/select-kit";
+import TopicRow from "discourse/select-kit/components/topic-row";
+import { i18n } from "discourse-i18n";
+import { integerIdsFromValue, sameIds } from "../../../lib/workflows/id-values";
+import ExpressionWrapper from "./expression-wrapper";
+
+async function findTopics(term) {
+ const results = await searchForTerm(term, {
+ typeFilter: "topic",
+ searchForId: true,
+ });
+
+ return makeArray(results?.posts)
+ .map((post) => post.topic)
+ .filter(Boolean);
+}
+
+@classNames("topic-selector")
+@selectKitOptions({
+ filterable: true,
+ filterPlaceholder: "choose_topic.title.placeholder",
+})
+class TopicSelector extends MultiSelect {
+ nameProperty = "title";
+ labelProperty = "title";
+ titleProperty = "title";
+
+ modifyComponentForRow() {
+ return TopicRow;
+ }
+
+ async search(filter) {
+ if (isEmpty(filter)) {
+ return [];
+ }
+
+ const selectedIds = new Set(this.value);
+ const topics = await findTopics(filter);
+
+ return topics.filter((topic) => !selectedIds.has(topic.id));
+ }
+}
+
+export default class TopicControl extends Component {
+ @tracked selectedTopics = [];
+
+ constructor() {
+ super(...arguments);
+ this.hydrateSelectedTopics();
+ }
+
+ get topicIds() {
+ return integerIdsFromValue(this.args.field.value);
+ }
+
+ @action
+ hydrateSelectedTopics() {
+ const shownIds = this.selectedTopics.map((topic) => topic.id);
+ if (!sameIds(this.topicIds, shownIds)) {
+ this.#updateSelectedTopics();
+ }
+ }
+
+ @action
+ handleChange(topicIds, topics) {
+ this.selectedTopics = makeArray(topics);
+ this.args.field.set(topicIds);
+ }
+
+ async #updateSelectedTopics() {
+ const requestedIds = this.topicIds;
+ const topics = await Promise.all(
+ requestedIds.map((id) => this.#findTopic(id))
+ );
+
+ // A newer value may have arrived while we were fetching.
+ if (this.isDestroying || !sameIds(this.topicIds, requestedIds)) {
+ return;
+ }
+
+ // Keep unresolvable ids (deleted or hidden topics) visible so they can be removed.
+ this.selectedTopics = topics.map(
+ (topic, index) =>
+ topic ?? {
+ id: requestedIds[index],
+ title: i18n("discourse_workflows.topic_control.unavailable_topic", {
+ id: requestedIds[index],
+ }),
+ }
+ );
+ }
+
+ async #findTopic(id) {
+ const known = this.selectedTopics.find((topic) => topic.id === id);
+ if (known) {
+ return known;
+ }
+
+ try {
+ const topics = await findTopics(String(id));
+ return topics.find((topic) => topic.id === id) ?? null;
+ } catch {
+ return null;
+ }
+ }
+
+ <template>
+ <ExpressionWrapper
+ @dynamicValueHint={{@dynamicValueHint}}
+ @field={{@field}}
+ @placeholder={{@placeholder}}
+ @schema={{@schema}}
+ @session={{@session}}
+ @supportsExpression={{@supportsExpression}}
+ >
+ <TopicSelector
+ @content={{this.selectedTopics}}
+ @onChange={{this.handleChange}}
+ @options={{hash translatedNone=@placeholder}}
+ @value={{this.topicIds}}
+ {{didUpdate this.hydrateSelectedTopics @field.value}}
+ />
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js
index 3e244f8ab3d..20739030bde 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js
@@ -23,6 +23,7 @@ import SelectControl from "../../components/workflows/configurators/select-contr
import SummarizeAggregations from "../../components/workflows/configurators/summarize-aggregations";
import TagsControl from "../../components/workflows/configurators/tags-control";
import TimezoneControl from "../../components/workflows/configurators/timezone-control";
+import TopicControl from "../../components/workflows/configurators/topic-control";
import UrlPreview from "../../components/workflows/configurators/url-preview";
import UserControl from "../../components/workflows/configurators/user-control";
import UserOrGroupControl from "../../components/workflows/configurators/user-or-group-control";
@@ -89,6 +90,7 @@ const FIELD_CONTROL_REGISTRY = {
renderer: DefaultInputControl,
},
timezone: { kind: "field", type: "custom", renderer: TimezoneControl },
+ topic: { kind: "field", type: "custom", renderer: TopicControl },
default: {
kind: "field",
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/id-values.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/id-values.js
new file mode 100644
index 00000000000..f42500fc430
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/id-values.js
@@ -0,0 +1,11 @@
+import { makeArray } from "discourse/lib/helpers";
+
+export function integerIdsFromValue(value) {
+ return makeArray(value)
+ .map((id) => parseInt(id, 10))
+ .filter((id) => !isNaN(id));
+}
+
+export function sameIds(a, b) {
+ return a.length === b.length && a.every((id, index) => id === b[index]);
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js
index 37480f393d0..a9ea213b141 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js
@@ -159,6 +159,8 @@ function dynamicValueKey(schema = {}, fieldName) {
: "group_id";
case "tags":
return "tag_names";
+ case "topic":
+ return "topic_ids";
case "user":
return ui.multiple ? "usernames" : "username";
case "user_or_group":
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index 7490471fe97..15f6678ace8 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -765,6 +765,8 @@ en:
fixed: "Fixed"
plain: "Plain"
dynamic: "Dynamic"
+ topic_control:
+ unavailable_topic: "Topic #%{id}"
expression_preview:
result: "Result"
empty: "Empty"
@@ -871,6 +873,9 @@ en:
reviewable_types_placeholder: "All types"
tag_names: "Tags"
tag_names_description: "Only trigger for topics that have at least one of these tags"
+ topic_ids: "Topics"
+ topic_ids_description: "Only trigger for these topics. Leave empty to match all topics."
+ topic_ids_placeholder: "All topics"
dynamic_values:
badge_id: "a badge ID"
boolean: "true or false"
@@ -885,6 +890,7 @@ en:
option_value: "an option value"
query_id: "a query ID"
tag_names: "tag names"
+ topic_ids: "topic IDs"
username: "a username"
usernames: "usernames"
user_or_group_name: "a username or group name"
@@ -1010,6 +1016,7 @@ en:
category_ids_description: "Only trigger for posts in these categories. Leave empty to match all categories."
tag_names: "Tags"
tag_names_description: "Only trigger for posts in topics that have at least one of these tags"
+ topic_ids_description: "Only trigger for posts in these topics. Leave empty to match all topics."
post_lifecycle:
topic_type: "Topic type"
topic_type_description: "Choose whether topics, personal messages, or both should trigger the workflow"
@@ -1019,10 +1026,12 @@ en:
category_ids_description: "Only trigger for posts in these categories. Leave empty to match all categories."
tag_names: "Tags"
tag_names_description: "Only trigger for posts in topics that have at least one of these tags"
+ topic_ids_description: "Only trigger for posts in these topics. Leave empty to match all topics."
post_edited:
category_ids_description: "Only trigger for posts in these categories. Leave empty to match all categories."
tag_names: "Tags"
tag_names_description: "Only trigger for posts in topics that have at least one of these tags"
+ topic_ids_description: "Only trigger for posts in these topics. Leave empty to match all topics."
post_scope: "Post scope"
post_scope_description: "Choose which posts should trigger the workflow"
post_scope_first_post: "First post"
@@ -1035,6 +1044,8 @@ en:
category_ids_description: "Only trigger for posts moved into these categories. Leave empty to match all categories."
tag_names: "Destination tags"
tag_names_description: "Only trigger for posts moved into topics that have at least one of these tags"
+ topic_ids: "Destination topics"
+ topic_ids_description: "Only trigger for posts moved into these topics. Leave empty to match all topics."
topic_created:
topic_type: "Topic type"
topic_type_description: "Choose whether topics, personal messages, or both should trigger the workflow"
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
index 498caed42ff..1c05154ae31 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
@@ -50,6 +50,24 @@ module DiscourseWorkflows
},
}.freeze
+ TOPIC_FILTER_PROPERTIES = {
+ topic_ids: {
+ type: :array,
+ required: false,
+ ui: {
+ control: :topic,
+ multiple: true,
+ },
+ },
+ }.freeze
+
+ # For triggers whose event can repeat inside one long-lived topic (posts, reactions, votes).
+ TOPIC_SCOPE_FILTER_PROPERTIES = {
+ **CATEGORY_FILTER_PROPERTIES,
+ **TAG_FILTER_PROPERTIES,
+ **TOPIC_FILTER_PROPERTIES,
+ }.freeze
+
def self.actor_property(allow_anonymous: true, **options)
property = { type: :string, required: false, default: "system", ui: { control: :actor } }
property[:control_options] = { allow_anonymous: false } if !allow_anonymous
@@ -323,7 +341,7 @@ module DiscourseWorkflows
.filter_map { |name| name.strip.presence }
end
- def self.normalize_category_ids(value)
+ def self.normalize_ids(value)
Array.wrap(value).filter_map { |entry| entry.to_s.strip.presence&.to_i }.uniq
end
@@ -332,7 +350,7 @@ module DiscourseWorkflows
def self.category_ids_parameter(trigger_ctx)
value = trigger_ctx.get_node_parameter("category_ids")
value = trigger_ctx.get_node_parameter("category_id") if value.nil?
- normalize_category_ids(value)
+ normalize_ids(value)
end
def self.expand_subcategory_ids(category_ids)
@@ -406,12 +424,23 @@ module DiscourseWorkflows
changes.empty? || changes.include?(change)
end
+ # Filters a node doesn't declare are skipped: the editor never shows them, so a stray value
+ # would filter invisibly. Cheapest check first: topic ids are an integer compare, tags query
+ # the database.
def matches_topic_filters?(topic, trigger_ctx)
- matches_category_ids?(
- topic.category_id,
- category_ids_parameter(trigger_ctx),
- include_subcategories: trigger_ctx.get_node_parameter("include_subcategories", true),
- ) && matches_tags?(topic, normalize_tag_names(trigger_ctx.get_node_parameter("tag_names")))
+ declared = self.class.properties
+
+ topic_ids = self.class.normalize_ids(trigger_ctx.get_node_parameter("topic_ids"))
+ return false if declared.key?(:topic_ids) && !matches_topic_ids?(topic.id, topic_ids)
+
+ category_ids = category_ids_parameter(trigger_ctx)
+ subcategories = trigger_ctx.get_node_parameter("include_subcategories", true)
+ category_match =
+ matches_category_ids?(topic.category_id, category_ids, include_subcategories: subcategories)
+ return false if declared.key?(:category_ids) && !category_match
+ return true if !declared.key?(:tag_names)
+
+ matches_tags?(topic, normalize_tag_names(trigger_ctx.get_node_parameter("tag_names")))
end
def matches_category_ids?(topic_category_id, category_ids, include_subcategories: true)
@@ -422,6 +451,10 @@ module DiscourseWorkflows
category_ids.include?(topic_category_id)
end
+ def matches_topic_ids?(topic_id, topic_ids)
+ topic_ids.empty? || topic_ids.include?(topic_id)
+ end
+
def matches_topic_type?(topic, topic_type)
case topic_type.presence || "topics"
when "all"
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb
index 6532e551d8e..685f40a8f43 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb
@@ -46,8 +46,7 @@ module DiscourseWorkflows
none: "discourse_workflows.post_created.group_inbox_id_placeholder",
},
},
- **CATEGORY_FILTER_PROPERTIES,
- **TAG_FILTER_PROPERTIES,
+ **TOPIC_SCOPE_FILTER_PROPERTIES,
},
)
@@ -80,14 +79,10 @@ module DiscourseWorkflows
def matches?(trigger_ctx)
topic = @post.topic
- matches_topic_type?(topic, trigger_ctx.get_node_parameter("topic_type", "topics")) &&
- matches_group_inbox?(topic, trigger_ctx.get_node_parameter("group_inbox_id")) &&
- matches_category_ids?(
- topic.category_id,
- category_ids_parameter(trigger_ctx),
- include_subcategories: trigger_ctx.get_node_parameter("include_subcategories", true),
- ) &&
- matches_tags?(topic, normalize_tag_names(trigger_ctx.get_node_parameter("tag_names")))
+ return false if !matches_topic_type?(topic, trigger_ctx.get_node_parameter("topic_type"))
+ return false if !matches_topic_filters?(topic, trigger_ctx)
+
+ matches_group_inbox?(topic, trigger_ctx.get_node_parameter("group_inbox_id"))
end
private
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_edited/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_edited/v1.rb
index eea24df196a..77abcf356cb 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_edited/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_edited/v1.rb
@@ -39,8 +39,7 @@ module DiscourseWorkflows
default: "first_post",
options: POST_SCOPE_OPTIONS,
},
- **CATEGORY_FILTER_PROPERTIES,
- **TAG_FILTER_PROPERTIES,
+ **TOPIC_SCOPE_FILTER_PROPERTIES,
trust_levels: {
type: :multi_options,
required: false,
@@ -71,16 +70,10 @@ module DiscourseWorkflows
end
def matches?(trigger_ctx)
- matches_post_scope?(trigger_ctx.get_node_parameter("post_scope", "first_post")) &&
- matches_category_ids?(
- @post.topic.category_id,
- category_ids_parameter(trigger_ctx),
- include_subcategories: trigger_ctx.get_node_parameter("include_subcategories", true),
- ) &&
- matches_tags?(
- @post.topic,
- normalize_tag_names(trigger_ctx.get_node_parameter("tag_names")),
- ) && matches_trust_level?(trigger_ctx.get_node_parameter("trust_levels"))
+ return false if !matches_post_scope?(trigger_ctx.get_node_parameter("post_scope"))
+ return false if !matches_topic_filters?(@post.topic, trigger_ctx)
+
+ matches_trust_level?(trigger_ctx.get_node_parameter("trust_levels"))
end
private
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_lifecycle.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_lifecycle.rb
index 74845167e3f..8be7dba1f1c 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_lifecycle.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_lifecycle.rb
@@ -6,8 +6,7 @@ module DiscourseWorkflows
I18N_SCOPE = "post_lifecycle"
PROPERTIES = {
**NodeType::TOPIC_TYPE_FILTER_PROPERTIES,
- **NodeType::CATEGORY_FILTER_PROPERTIES,
- **NodeType::TAG_FILTER_PROPERTIES,
+ **NodeType::TOPIC_SCOPE_FILTER_PROPERTIES,
}.freeze
OUTPUT_CONTRACTS = [
@@ -34,13 +33,8 @@ module DiscourseWorkflows
end
def matches?(trigger_ctx)
- matches_topic_type?(topic, trigger_ctx.get_node_parameter("topic_type", "topics")) &&
- matches_category_ids?(
- topic.category_id,
- category_ids_parameter(trigger_ctx),
- include_subcategories: trigger_ctx.get_node_parameter("include_subcategories", true),
- ) &&
- matches_tags?(topic, normalize_tag_names(trigger_ctx.get_node_parameter("tag_names")))
+ matches_topic_type?(topic, trigger_ctx.get_node_parameter("topic_type")) &&
+ matches_topic_filters?(topic, trigger_ctx)
end
private
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_like_changed/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_like_changed/v1.rb
index 120a7775aea..3f32c63b2da 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_like_changed/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_like_changed/v1.rb
@@ -31,8 +31,7 @@ module DiscourseWorkflows
default: [],
options: CHANGES.values,
},
- **CATEGORY_FILTER_PROPERTIES,
- **TAG_FILTER_PROPERTIES,
+ **TOPIC_SCOPE_FILTER_PROPERTIES,
},
)
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_moved/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_moved/v1.rb
index 0f4d94180cf..1236a12da34 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_moved/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_moved/v1.rb
@@ -29,8 +29,7 @@ module DiscourseWorkflows
event: :post_moved,
output_contracts: [{ schema: OUTPUT_SCHEMA }],
properties: {
- **CATEGORY_FILTER_PROPERTIES,
- **TAG_FILTER_PROPERTIES,
+ **TOPIC_SCOPE_FILTER_PROPERTIES,
},
)
@@ -54,15 +53,7 @@ module DiscourseWorkflows
end
def matches?(trigger_ctx)
- matches_category_ids?(
- destination_topic.category_id,
- category_ids_parameter(trigger_ctx),
- include_subcategories: trigger_ctx.get_node_parameter("include_subcategories", true),
- ) &&
- matches_tags?(
- destination_topic,
- normalize_tag_names(trigger_ctx.get_node_parameter("tag_names")),
- )
+ matches_topic_filters?(destination_topic, trigger_ctx)
end
private
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_created/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_created/v1.rb
index 8b6fda94693..1c3ba95d0c7 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_created/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_created/v1.rb
@@ -70,14 +70,10 @@ module DiscourseWorkflows
end
def matches?(trigger_ctx)
- matches_topic_type?(@topic, trigger_ctx.get_node_parameter("topic_type", "topics")) &&
- matches_group_inbox?(@topic, trigger_ctx.get_node_parameter("group_inbox_id")) &&
- matches_category_ids?(
- @topic.category_id,
- category_ids_parameter(trigger_ctx),
- include_subcategories: trigger_ctx.get_node_parameter("include_subcategories", true),
- ) &&
- matches_tags?(@topic, normalize_tag_names(trigger_ctx.get_node_parameter("tag_names")))
+ return false if !matches_topic_type?(@topic, trigger_ctx.get_node_parameter("topic_type"))
+ return false if !matches_topic_filters?(@topic, trigger_ctx)
+
+ matches_group_inbox?(@topic, trigger_ctx.get_node_parameter("group_inbox_id"))
end
private
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_tag_changed/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_tag_changed/v1.rb
index 322834a7b4b..893b903be42 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_tag_changed/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_tag_changed/v1.rb
@@ -54,11 +54,7 @@ module DiscourseWorkflows
end
def matches?(trigger_ctx)
- matches_category_ids?(
- @topic.category_id,
- category_ids_parameter(trigger_ctx),
- include_subcategories: trigger_ctx.get_node_parameter("include_subcategories", true),
- )
+ matches_topic_filters?(@topic, trigger_ctx)
end
private
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb b/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
index 0fb89db7c87..da1082154ff 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
@@ -126,6 +126,7 @@ module DiscourseWorkflows
textarea
time
timezone
+ topic
url_preview
user
user_seen_trigger_options
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_spec.rb
index a57cef4acda..8677a7300d0 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_spec.rb
@@ -286,27 +286,23 @@ RSpec.describe DiscourseWorkflows::NodeType do
end
end
- describe ".normalize_category_ids" do
+ describe ".normalize_ids" do
it "coerces scalars, arrays, and mixed values to unique integer ids" do
- expect(described_class.normalize_category_ids(nil)).to eq([])
- expect(described_class.normalize_category_ids("")).to eq([])
- expect(described_class.normalize_category_ids([])).to eq([])
- expect(described_class.normalize_category_ids("12")).to eq([12])
- expect(described_class.normalize_category_ids(12)).to eq([12])
- expect(described_class.normalize_category_ids(["12", 3, " 12 "])).to eq([12, 3])
- expect(described_class.normalize_category_ids([nil, ""])).to eq([])
+ expect(described_class.normalize_ids(nil)).to eq([])
+ expect(described_class.normalize_ids("")).to eq([])
+ expect(described_class.normalize_ids([])).to eq([])
+ expect(described_class.normalize_ids("12")).to eq([12])
+ expect(described_class.normalize_ids(12)).to eq([12])
+ expect(described_class.normalize_ids(["12", 3, " 12 "])).to eq([12, 3])
+ expect(described_class.normalize_ids([nil, ""])).to eq([])
end
it "coerces unresolved expression strings to a non-matching id" do
- expect(described_class.normalize_category_ids(["=$json.category_id"])).to eq([0])
+ expect(described_class.normalize_ids(["=$json.category_id"])).to eq([0])
end
end
describe ".category_ids_parameter" do
- def trigger_context(parameters)
- DiscourseWorkflows::TriggerNodeContext.new({ "parameters" => parameters })
- end
-
it "reads category_ids when present" do
expect(
described_class.category_ids_parameter(trigger_context("category_ids" => %w[1 2])),
@@ -332,6 +328,55 @@ RSpec.describe DiscourseWorkflows::NodeType do
end
end
+ describe "#matches_topic_filters?" do
+ fab!(:topic)
+
+ let(:node_class) { Class.new(described_class) { public :matches_topic_filters? } }
+
+ def node_declaring(properties)
+ node_class.description(properties:)
+ node_class.new
+ end
+
+ it "ignores filters the node does not declare" do
+ node = node_declaring(described_class::TAG_FILTER_PROPERTIES)
+ stray_filters = { topic_ids: [topic.id + 1], category_ids: [topic.category_id + 1] }
+
+ expect(node.matches_topic_filters?(topic, trigger_context(stray_filters))).to eq(true)
+ end
+
+ it "declares the topic filter only on triggers whose event repeats inside a topic",
+ :aggregate_failures do
+ repeating = %w[
+ post_created
+ post_edited
+ post_destroyed
+ post_recovered
+ post_moved
+ post_like_changed
+ ]
+ once_per_topic = %w[
+ topic_created
+ topic_closed
+ topic_published
+ topic_timer_changed
+ stale_topic
+ topic_tag_changed
+ ]
+
+ repeating.each do |name|
+ expect(
+ DiscourseWorkflows::Registry.find_node_type("trigger:#{name}").properties,
+ ).to have_key(:topic_ids)
+ end
+ once_per_topic.each do |name|
+ expect(
+ DiscourseWorkflows::Registry.find_node_type("trigger:#{name}").properties,
+ ).not_to have_key(:topic_ids)
+ end
+ end
+ end
+
describe "#matches_category_ids?" do
subject(:node) { Class.new(described_class) { public :matches_category_ids? }.new }
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb
index 67baeb52de6..cf6b0808b01 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb
@@ -241,8 +241,4 @@ RSpec.describe DiscourseWorkflows::Nodes::PostCreated::V1 do
).to eq(false)
end
end
-
- def trigger_context(parameters)
- DiscourseWorkflows::TriggerNodeContext.new({ "parameters" => parameters })
- end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_edited/v1_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_edited/v1_spec.rb
index ea9175ab6df..187a5eef2a8 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_edited/v1_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_edited/v1_spec.rb
@@ -174,8 +174,4 @@ RSpec.describe DiscourseWorkflows::Nodes::PostEdited::V1 do
expect(trigger.matches?(trigger_context("trust_levels" => ["1"]))).to eq(false)
end
end
-
- def trigger_context(parameters)
- DiscourseWorkflows::TriggerNodeContext.new({ "parameters" => parameters })
- end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_lifecycle_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_lifecycle_spec.rb
index cdd270808a8..8d5c217126c 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_lifecycle_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_lifecycle_spec.rb
@@ -18,10 +18,6 @@ RSpec.describe DiscourseWorkflows::Nodes::PostLifecycle do
topic.tags << tag
end
- def trigger_context(parameters)
- DiscourseWorkflows::TriggerNodeContext.new({ "parameters" => parameters })
- end
-
describe "#valid?" do
it "accepts a regular post, including once it is deleted" do
expect(trigger).to be_valid
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_like_changed_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_like_changed_spec.rb
index 55893786c98..d999711bc45 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_like_changed_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_like_changed_spec.rb
@@ -10,7 +10,7 @@ RSpec.describe DiscourseWorkflows::Nodes::PostLikeChanged::V1 do
fab!(:tag)
describe "#matches?" do
- it "filters changes, categories, and tags" do
+ it "filters changes, categories, tags, and topics" do
SiteSetting.tagging_enabled = true
topic.tags << tag
trigger = described_class.from_event(:like_created, PostAction.new(post:, user: liker))
@@ -19,9 +19,15 @@ RSpec.describe DiscourseWorkflows::Nodes::PostLikeChanged::V1 do
expect(trigger.matches?(trigger_context(changes: ["unliked"]))).to eq(false)
expect(trigger.matches?(trigger_context(category_ids: [other_category.id]))).to eq(false)
expect(trigger.matches?(trigger_context(tag_names: ["missing"]))).to eq(false)
+ expect(trigger.matches?(trigger_context(topic_ids: [topic.id + 1]))).to eq(false)
expect(
trigger.matches?(
- trigger_context(changes: ["liked"], category_ids: [category.id], tag_names: [tag.name]),
+ trigger_context(
+ changes: ["liked"],
+ category_ids: [category.id],
+ tag_names: [tag.name],
+ topic_ids: [topic.id],
+ ),
),
).to eq(true)
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_moved_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_moved_spec.rb
index 9f3eb5ef51b..a089c908194 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_moved_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_moved_spec.rb
@@ -78,6 +78,7 @@ RSpec.describe DiscourseWorkflows::Nodes::PostMoved::V1 do
trigger_context(
"category_ids" => [destination_category.id.to_s],
"tag_names" => [tag.name],
+ "topic_ids" => [destination_topic.id],
),
),
).to eq(true)
@@ -131,7 +132,7 @@ RSpec.describe DiscourseWorkflows::Nodes::PostMoved::V1 do
)
end
- it "returns false when the destination topic does not match category or tags" do
+ it "returns false when the destination topic does not match category, tags, or topics" do
other_category = Fabricate(:category)
trigger = described_class.new(moved_post, source_topic.id)
@@ -139,10 +140,7 @@ RSpec.describe DiscourseWorkflows::Nodes::PostMoved::V1 do
false,
)
expect(trigger.matches?(trigger_context("tag_names" => ["missing"]))).to eq(false)
+ expect(trigger.matches?(trigger_context("topic_ids" => [source_topic.id]))).to eq(false)
end
end
-
- def trigger_context(parameters)
- DiscourseWorkflows::TriggerNodeContext.new({ "parameters" => parameters })
- end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_closed_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_closed_spec.rb
index 9a4ab3ae4b5..1378a6b856f 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_closed_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_closed_spec.rb
@@ -60,8 +60,4 @@ RSpec.describe DiscourseWorkflows::Nodes::TopicClosed::V1 do
).to eq(false)
end
end
-
- def trigger_context(parameters)
- DiscourseWorkflows::TriggerNodeContext.new({ "parameters" => parameters })
- end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_tag_changed_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_tag_changed_spec.rb
index c95a53c0368..bd721b58d47 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_tag_changed_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_tag_changed_spec.rb
@@ -132,8 +132,4 @@ RSpec.describe DiscourseWorkflows::Nodes::TopicTagChanged::V1 do
)
end
end
-
- def trigger_context(parameters)
- DiscourseWorkflows::TriggerNodeContext.new({ "parameters" => parameters })
- end
end
diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb
index 7247c462db7..3b122c5d383 100644
--- a/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb
+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb
@@ -137,6 +137,19 @@ module PageObjects
self
end
+ def filter_by_topic(topic)
+ selector =
+ PageObjects::Components::SelectKit.new("[data-name='topic_ids'] .topic-selector")
+ selector.expand
+ selector.search(topic.id.to_s)
+ selector.select_row_by_value(topic.id)
+ self
+ end
+
+ def has_topic_filter?(topic)
+ page.has_css?("[data-name='topic_ids'] .select-kit-header", text: topic.title)
+ end
+
def has_fixed_topic_filters?(category)
page.has_css?("[data-name='category_ids'] .select-kit-header", text: category.name) &&
page.has_css?("[data-name='include_subcategories']") &&
diff --git a/plugins/discourse-workflows/spec/system/workflows_spec.rb b/plugins/discourse-workflows/spec/system/workflows_spec.rb
index a74d95e7f68..d69fb067058 100644
--- a/plugins/discourse-workflows/spec/system/workflows_spec.rb
+++ b/plugins/discourse-workflows/spec/system/workflows_spec.rb
@@ -82,6 +82,31 @@ RSpec.describe "Discourse Workflows" do
expect(workflows_page).to have_workflow("My workflow")
end
+ it "lets an admin scope a post trigger to specific topics" do
+ topic = Fabricate(:post).topic
+ workflow =
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ nodes: [
+ {
+ "id" => "post-created",
+ "type" => "trigger:post_created",
+ "typeVersion" => "1.0",
+ "name" => "Post created",
+ "parameters" => {
+ },
+ },
+ ],
+ )
+
+ editor_page.visit_node(workflow, "post-created")
+ editor_page.filter_by_topic(topic)
+ expect(editor_page).to have_saved_node_configuration
+ page.refresh
+ expect(editor_page).to have_topic_filter(topic)
+ end
+
it "lets an admin add fixed event triggers while keeping existing status filters editable" do
category = Fabricate(:category)
node_id = "existing-status"
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/topic-control-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/topic-control-test.gjs
new file mode 100644
index 00000000000..92003f3ec4c
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/topic-control-test.gjs
@@ -0,0 +1,104 @@
+import { tracked } from "@glimmer/tracking";
+import { render, waitFor } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+import TopicControl from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/topic-control";
+
+const TOPICS = [
+ { id: 280, title: "Cube challenge", fancy_title: "Cube challenge" },
+ { id: 34, title: "Cube leaderboard", fancy_title: "Cube leaderboard" },
+];
+
+class TestField {
+ @tracked value;
+
+ constructor(value) {
+ this.value = value;
+ }
+
+ set(newValue) {
+ this.value = newValue;
+ }
+}
+
+function searchResponse(term) {
+ const topics = TOPICS.filter(
+ (topic) =>
+ String(topic.id) === term ||
+ topic.title.toLowerCase().includes(term.toLowerCase())
+ );
+
+ return {
+ posts: topics.map((topic) => ({
+ id: topic.id * 10,
+ topic_id: topic.id,
+ blurb: "",
+ })),
+ topics: topics.map((topic) => ({ ...topic, slug: "cube", category_id: 1 })),
+ grouped_search_result: { term, type_filter: "topic" },
+ };
+}
+
+async function renderControl(context, value) {
+ context.field = new TestField(value);
+
+ await render(
+ <template>
+ <TopicControl @field={{context.field}} @supportsExpression={{false}} />
+ </template>
+ );
+}
+
+module("Integration | Component | Workflows | TopicControl", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ pretender.get("/search/query", (request) =>
+ response(searchResponse(request.queryParams.term))
+ );
+ });
+
+ test("stores an array of topic ids", async function (assert) {
+ await renderControl(this, []);
+
+ const selector = selectKit(".topic-selector");
+
+ await selector.expand();
+ await selector.fillInFilter("cube");
+ await selector.selectRowByValue(280);
+
+ assert.deepEqual(this.field.value, [280], "stores the first selection");
+
+ await selector.fillInFilter("leaderboard");
+ await selector.selectRowByValue(34);
+
+ assert.deepEqual(this.field.value, [280, 34], "appends later selections");
+ });
+
+ test("hydrates selected topics from stored ids", async function (assert) {
+ await renderControl(this, [280]);
+
+ await waitFor(".topic-selector .select-kit-header[data-value='280']");
+
+ assert
+ .dom(".topic-selector .select-kit-header")
+ .includesText("Cube challenge", "shows the topic title");
+ });
+
+ test("shows unresolvable ids and drops non-numeric entries", async function (assert) {
+ await renderControl(this, ["=$json.topic_ids", 999]);
+
+ await waitFor(".topic-selector .select-kit-header[data-value='999']");
+
+ assert.strictEqual(
+ selectKit(".topic-selector").header().value(),
+ "999",
+ "keeps only the numeric id"
+ );
+ assert
+ .dom(".topic-selector .select-kit-header")
+ .includesText("Topic #999", "shows a placeholder for the missing topic");
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-property-engine-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-property-engine-test.js
index dcb0cb8f651..c03b019af7e 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-property-engine-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-property-engine-test.js
@@ -119,6 +119,10 @@ module("Unit | Utility | workflows property engine", function () {
propertyLabel("trigger:topic_tag_changed", "include_subcategories"),
"Include subcategories"
);
+ assert.strictEqual(
+ propertyLabel("trigger:post_created", "topic_ids"),
+ "Topics"
+ );
assert.strictEqual(
propertyLabel("trigger:user_updated", "group_ids"),
"Groups"