A platform for community discussion. Free, open, simple.
FEATURE: enhance post created edited trigger in automation (#31900)
Sam0e62acd57fff
diff --git a/plugins/automation/admin/assets/javascripts/admin/components/fields/da-choices-field.gjs b/plugins/automation/admin/assets/javascripts/admin/components/fields/da-choices-field.gjsindex e7c226c4ff8..a67d6258251 100644--- a/plugins/automation/admin/assets/javascripts/admin/components/fields/da-choices-field.gjs+++ b/plugins/automation/admin/assets/javascripts/admin/components/fields/da-choices-field.gjs@@ -1,6 +1,7 @@import { hash } from "@ember/helper";import { i18n } from "discourse-i18n";import ComboBox from "select-kit/components/combo-box";+import MultiSelect from "select-kit/components/multi-select";import BaseField from "./da-base-field";import DAFieldDescription from "./da-field-description";import DAFieldLabel from "./da-field-label";@@ -11,22 +12,39 @@ export default class ChoicesField extends BaseField {<DAFieldLabel @label={{@label}} @field={{@field}} /><div class="controls">- <ComboBox- @value={{@field.metadata.value}}- @content={{this.replacedContent}}- @onChange={{this.mutValue}}- @options={{hash- allowAny=false- clearable=true- }}- />+ {{#if this.multiselect}}+ <MultiSelect+ @value={{@field.metadata.value}}+ @content={{this.replacedContent}}+ @onChange={{this.mutValue}}+ @options={{hash+ allowAny=false+ clearable=true+ }}+ />+ {{else}}+ <ComboBox+ @value={{@field.metadata.value}}+ @content={{this.replacedContent}}+ @onChange={{this.mutValue}}+ @options={{hash+ allowAny=false+ clearable=true+ }}+ />+ {{/if}}<DAFieldDescription @description={{@description}} /></div></div></template>+ get multiselect() {+ return !!this.args.field.extra.multiselect;+ }+get replacedContent() {return (this.args.field.extra.content || []).map((r) => {return {diff --git a/plugins/automation/app/models/discourse_automation/field.rb b/plugins/automation/app/models/discourse_automation/field.rbindex 4dea55a2b26..6e6689f4ea6 100644--- a/plugins/automation/app/models/discourse_automation/field.rb+++ b/plugins/automation/app/models/discourse_automation/field.rb@@ -94,7 +94,7 @@ module DiscourseAutomation},"choices" => {"value" => {- "type" => %w[string integer null],+ "type" => %w[string integer null array],},},"tags" => {diff --git a/plugins/automation/config/locales/client.en.yml b/plugins/automation/config/locales/client.en.ymlindex 8b768ba8b46..018e274ba14 100644--- a/plugins/automation/config/locales/client.en.yml+++ b/plugins/automation/config/locales/client.en.yml@@ -168,15 +168,15 @@ en:restricted_archetype:label: Topic Typedescription: Optional, allow to trigger only on topics or personal messages- restricted_user_group:- label: Restricted user group- description: Optional, will trigger only if the post user is in this grouprestricted_groups:+ label: Restricted groups+ description: Optional, will trigger only if the post user is in any of these groups+ restricted_inbox_groups:label: Restricted inboxes groupsdescription: Optional, will trigger only if the post's topic is a personal message in one of the group inboxes- ignore_group_members:- label: Ignore group members- description: Skip the trigger if sender is a member of the Group specified above+ excluded_groups:+ label: Excluded groups+ description: Optional, Skip the trigger if the post user belongs to any of these groupsignore_automated:label: Ignore automateddescription: Skip the trigger if the sender has a noreply email or is from an automated source. Only applies to posts created via email@@ -189,10 +189,18 @@ en:skip_via_email:label: "Skip via email"description: "Skip the trigger if the post was created via email"+ post_features:+ label: Post features+ description: "Optional, limit triggering to only posts with these features"created: Creatededited: Edited- topics: Topics+ topics: All Topicspersonal_messages: Personal Messages+ public_topics: Public Topics (exclude all secure categories)+ with_images: Images+ with_links: Links+ with_code: Code+ with_uploads: Uploadsuser_updated:fields:user_profile:diff --git a/plugins/automation/db/post_migrate/20250319052218_rename_post_automation_fields.rb b/plugins/automation/db/post_migrate/20250319052218_rename_post_automation_fields.rbnew file mode 100644index 00000000000..235624a46ed--- /dev/null+++ b/plugins/automation/db/post_migrate/20250319052218_rename_post_automation_fields.rb@@ -0,0 +1,93 @@+# frozen_string_literal: true+class RenamePostAutomationFields < ActiveRecord::Migration[7.2]+ def up+ # Rename restricted_groups to restricted_inbox_groups+ execute <<~SQL+ UPDATE discourse_automation_fields+ SET name = 'restricted_inbox_groups'+ WHERE name = 'restricted_groups'+ AND target = 'trigger'+ AND component = 'groups'+ AND automation_id IN (+ SELECT id FROM discourse_automation_automations+ WHERE trigger = 'post_created_edited'+ )+ SQL++ # Migrate restricted_user_group (single group) to restricted_groups (array of groups)+ execute <<~SQL+ INSERT INTO discourse_automation_fields (+ automation_id, component, name, target, metadata, created_at, updated_at+ )+ SELECT+ f.automation_id,+ 'groups' as component,+ 'restricted_groups' as name,+ f.target,+ jsonb_build_object('value', ARRAY[CAST(f.metadata->>'value' AS INTEGER)]) as metadata,+ NOW() as created_at,+ NOW() as updated_at+ FROM discourse_automation_fields f+ JOIN discourse_automation_automations a ON a.id = f.automation_id+ WHERE f.component = 'group'+ AND f.name = 'restricted_user_group'+ AND f.target = 'trigger'+ AND f.metadata->>'value' IS NOT NULL+ AND a.trigger = 'post_created_edited'+ AND NOT EXISTS (+ SELECT 1 FROM discourse_automation_fields+ WHERE automation_id = f.automation_id+ AND name = 'restricted_groups'+ AND target = 'trigger'+ )+ SQL++ # Handle ignore_group_members boolean + restricted_inbox_groups+ # Copy the restricted_inbox_groups values to excluded_groups when ignore_group_members is true+ execute <<~SQL+ INSERT INTO discourse_automation_fields (+ automation_id, component, name, target, metadata, created_at, updated_at+ )+ SELECT+ i.automation_id,+ 'groups' as component,+ 'excluded_groups' as name,+ i.target,+ r.metadata,+ NOW() as created_at,+ NOW() as updated_at+ FROM discourse_automation_fields i+ JOIN discourse_automation_fields r ON r.automation_id = i.automation_id+ AND r.name = 'restricted_inbox_groups'+ AND r.target = 'trigger'+ WHERE i.name = 'ignore_group_members'+ AND i.target = 'trigger'+ AND i.metadata->>'value' = 'true'+ AND i.automation_id IN (+ SELECT id FROM discourse_automation_automations+ WHERE trigger = 'post_created_edited'+ )+ AND NOT EXISTS (+ SELECT 1 FROM discourse_automation_fields+ WHERE automation_id = i.automation_id+ AND name = 'excluded_groups'+ AND target = 'trigger'+ )+ SQL++ # Clean up old fields+ execute <<~SQL+ DELETE FROM discourse_automation_fields+ WHERE name IN ('restricted_user_group', 'ignore_group_members')+ AND target = 'trigger'+ AND automation_id IN (+ SELECT id FROM discourse_automation_automations+ WHERE trigger = 'post_created_edited'+ )+ SQL+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/automation/lib/discourse_automation/event_handlers.rb b/plugins/automation/lib/discourse_automation/event_handlers.rbindex 938f47e743e..91d7adaad90 100644--- a/plugins/automation/lib/discourse_automation/event_handlers.rb+++ b/plugins/automation/lib/discourse_automation/event_handlers.rb@@ -12,10 +12,24 @@ module DiscourseAutomationDiscourseAutomation::Automation.where(trigger: name, enabled: true).find_each do |automation|+ action_type = automation.trigger_field("action_type")+ selected_action = action_type["value"]&.to_sym++ if selected_action+ next if selected_action == :created && action != :create+ next if selected_action == :edited && action != :edit+ end+restricted_archetype = automation.trigger_field("restricted_archetype")["value"]if restricted_archetype.present?- topic_archetype = topic.archetype- next if restricted_archetype != topic_archetype+ if restricted_archetype == "public"+ next if topic.archetype != Archetype.default+ next if !topic.category+ next if topic.category.read_restricted?+ else+ topic_archetype = topic.archetype+ next if restricted_archetype != topic_archetype+ endendoriginal_post_only = automation.trigger_field("original_post_only")@@ -66,29 +80,35 @@ module DiscourseAutomationnext if (restricted_tags["value"] & topic.tags.map(&:name)).empty?end- restricted_group_ids = automation.trigger_field("restricted_groups")["value"]- if restricted_group_ids.present?+ restricted_inbox_group_ids = automation.trigger_field("restricted_inbox_groups")["value"]+ if restricted_inbox_group_ids.present?next if !topic.private_message?target_group_ids = topic.allowed_groups.pluck(:id)- next if (restricted_group_ids & target_group_ids).empty?-- ignore_group_members = automation.trigger_field("ignore_group_members")["value"]- next if ignore_group_members && post.user.in_any_groups?(restricted_group_ids)+ next if (restricted_inbox_group_ids & target_group_ids).empty?end- user_group = automation.trigger_field("restricted_user_group")["value"]- next if user_group && !post.user.in_any_groups?([user_group])+ user_group_ids = automation.trigger_field("restricted_groups")["value"]+ next if user_group_ids.present? && !post.user.in_any_groups?(user_group_ids)++ excluded_group_ids = automation.trigger_field("excluded_groups")["value"]+ next if excluded_group_ids.present? && post.user.in_any_groups?(excluded_group_ids)ignore_automated = automation.trigger_field("ignore_automated")next if ignore_automated["value"] && post.incoming_email&.is_auto_generated?- action_type = automation.trigger_field("action_type")- selected_action = action_type["value"]&.to_sym-- if selected_action- next if selected_action == :created && action != :create- next if selected_action == :edited && action != :edit+ post_features = automation.trigger_field("post_features")["value"]+ if post_features.present?+ cooked = post.cooked+ # note the only 100% correct way is to lean on an actual HTML parser+ # however triggers may pop up during the post creation process, we can not afford a full parse+ next if post_features.include?("with_images") && !cooked.match?(/<img[^>]+>/i)+ next if post_features.include?("with_links") && !cooked.match?(/<a[^>]+>/i)+ next if post_features.include?("with_code") && !cooked.match?(/<pre[^>]+>/i)+ if post_features.include?("with_uploads") &&+ !cooked.match?(/<a[^>]+class=["']attachment[^>]+>/i)+ next+ endendautomation.trigger!(diff --git a/plugins/automation/lib/discourse_automation/triggers/post_created_edited.rb b/plugins/automation/lib/discourse_automation/triggers/post_created_edited.rbindex 282c0ab5598..af73e6b5315 100644--- a/plugins/automation/lib/discourse_automation/triggers/post_created_edited.rb+++ b/plugins/automation/lib/discourse_automation/triggers/post_created_edited.rb@@ -17,6 +17,10 @@ DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::POST_CREATEDextra: {content: [{ id: "regular", name: "discourse_automation.triggerables.post_created_edited.topics" },+ {+ id: "public",+ name: "discourse_automation.triggerables.post_created_edited.public_topics",+ },{id: "private_message",name: "discourse_automation.triggerables.post_created_edited.personal_messages",@@ -27,11 +31,34 @@ DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::POST_CREATEDfield :exclude_subcategories, component: :booleanfield :restricted_tags, component: :tagsfield :restricted_groups, component: :groups- field :restricted_user_group, component: :group+ field :excluded_groups, component: :groups+ field :restricted_inbox_groups, component: :groupsfield :ignore_automated, component: :boolean- field :ignore_group_members, component: :booleanfield :valid_trust_levels, component: :"trust-levels"field :original_post_only, component: :boolean+ field :post_features,+ component: :choices,+ extra: {+ multiselect: true,+ content: [+ {+ id: "with_images",+ name: "discourse_automation.triggerables.post_created_edited.with_images",+ },+ {+ id: "with_links",+ name: "discourse_automation.triggerables.post_created_edited.with_links",+ },+ {+ id: "with_code",+ name: "discourse_automation.triggerables.post_created_edited.with_code",+ },+ {+ id: "with_uploads",+ name: "discourse_automation.triggerables.post_created_edited.with_uploads",+ },+ ],+ }field :first_post_only, component: :booleanfield :first_topic_only, component: :booleanfield :skip_via_email, component: :booleandiff --git a/plugins/automation/spec/models/field_spec.rb b/plugins/automation/spec/models/field_spec.rbindex 83c3c9d8376..df32cba5307 100644--- a/plugins/automation/spec/models/field_spec.rb+++ b/plugins/automation/spec/models/field_spec.rb@@ -92,7 +92,8 @@ describe DiscourseAutomation::Field doexpect(field).to be_validend- it "does not work with an array value" do+ it "does work with an array value" do+ # this is legit for multiselect choicesfield =DiscourseAutomation::Field.create(automation: automation,@@ -102,7 +103,7 @@ describe DiscourseAutomation::Field dovalue: [1, 2, 3],},)- expect(field).to_not be_valid+ expect(field).to be_validendit "works with a nil value" dodiff --git a/plugins/automation/spec/triggers/post_created_edited_spec.rb b/plugins/automation/spec/triggers/post_created_edited_spec.rbindex 94d1eeaa26d..ed4625cdfbf 100644--- a/plugins/automation/spec/triggers/post_created_edited_spec.rb+++ b/plugins/automation/spec/triggers/post_created_edited_spec.rb@@ -10,6 +10,7 @@ describe "PostCreatedEdited" dolet(:subcategory) { Fabricate(:category_with_definition, parent_category_id: parent_category.id) }fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:admin) { Fabricate(:admin, refresh_auto_groups: true) }fab!(:automation) { Fabricate(:automation, trigger: "post_created_edited") }context "when filtering on first post only" do@@ -131,9 +132,9 @@ describe "PostCreatedEdited" dobefore doautomation.upsert_field!(- "restricted_user_group",- "group",- { value: group.id },+ "restricted_groups",+ "groups",+ { value: [group.id] },target: "trigger",)end@@ -200,7 +201,7 @@ describe "PostCreatedEdited" dobefore doautomation.upsert_field!(- "restricted_groups",+ "restricted_inbox_groups","groups",{ value: [target_group.id, another_group.id] },target: "trigger",@@ -254,33 +255,6 @@ describe "PostCreatedEdited" doendend- context "when members of the group are ignored" do- before do- automation.upsert_field!(- "ignore_group_members",- "boolean",- { value: true },- target: "trigger",- )- end-- it "doesn’t fire the trigger" do- list =- capture_contexts do- user.groups << target_group- PostCreator.create(- user,- basic_topic_params.merge(- target_group_names: [target_group.name],- archetype: Archetype.private_message,- ),- )- end-- expect(list).to be_blank- end- end-context "when a different group is used" doit "does not fire the trigger" dolist =@@ -507,6 +481,34 @@ describe "PostCreatedEdited" doendend+ context "when only public topics are allowed" do+ before do+ automation.upsert_field!(+ "restricted_archetype",+ "choices",+ { value: "public" },+ target: "trigger",+ )+ end++ it "fires the trigger for public topics" do+ list = capture_contexts { PostCreator.create(user, basic_topic_params) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end++ it "doesn't fire the trigger for secure categories" do+ secure_category = Fabricate(:category, read_restricted: true)+ list =+ capture_contexts do+ PostCreator.create(admin, basic_topic_params.merge(category: secure_category.id))+ end++ expect(list.length).to eq(0)+ end+ end+context "when archetype is restricted" docontext "when only regular topics are allowed" dobefore do@@ -595,4 +597,193 @@ describe "PostCreatedEdited" doendendend++ context "when excluded groups are defined" do+ fab!(:excluded_group) { Fabricate(:group) }++ before do+ automation.upsert_field!(+ "excluded_groups",+ "groups",+ { value: [excluded_group.id] },+ target: "trigger",+ )+ end++ context "when user is in an excluded group" do+ before { excluded_group.add(user) }++ it "doesn't fire the trigger" do+ list = capture_contexts { PostCreator.create(user, basic_topic_params) }++ expect(list).to be_blank+ end+ end++ context "when user is not in any excluded group" do+ it "fires the trigger" do+ list = capture_contexts { PostCreator.create(user, basic_topic_params) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end+ end+ end++ context "when filtering on post features" do+ fab!(:topic) { Fabricate(:topic, user: user) }++ context "with images filter" do+ before do+ automation.upsert_field!(+ "post_features",+ "choices",+ { value: ["with_images"] },+ target: "trigger",+ )+ end++ it "fires the trigger when post has an image" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ raw: "Look at this image: ",+ topic_id: topic.id,+ )+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end++ it "doesn't fire the trigger when post has no image" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ raw: "This is just regular text with no images",+ topic_id: topic.id,+ )+ end++ expect(list.length).to eq(0)+ end+ end++ context "with links filter" do+ before do+ automation.upsert_field!(+ "post_features",+ "choices",+ { value: ["with_links"] },+ target: "trigger",+ )+ end++ it "fires the trigger when post has a link" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ raw: "Check out this [link](https://example.com)",+ topic_id: topic.id,+ )+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end++ it "doesn't fire the trigger when post has no link" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ raw: "This is just regular text with no links",+ topic_id: topic.id,+ )+ end++ expect(list.length).to eq(0)+ end+ end++ context "with code filter" do+ before do+ automation.upsert_field!(+ "post_features",+ "choices",+ { value: ["with_code"] },+ target: "trigger",+ )+ end++ it "fires the trigger when post has a code block" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ raw: "```ruby\ndef hello_world\n puts 'hello world'\nend\n```",+ topic_id: topic.id,+ )+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end++ it "doesn't fire the trigger when post has no code block" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ raw: "This is just regular text with no code blocks",+ topic_id: topic.id,+ )+ end++ expect(list.length).to eq(0)+ end+ end++ context "with multiple features" do+ before do+ automation.upsert_field!(+ "post_features",+ "choices",+ { value: %w[with_links with_images] },+ target: "trigger",+ )+ end++ it "fires the trigger when post has all required features" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ raw:+ "Check this [link](https://example.com) and ",+ topic_id: topic.id,+ )+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end++ it "doesn't fire the trigger when post is missing a required feature" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ raw: "This only has a [link](https://example.com) but no image",+ topic_id: topic.id,+ )+ end++ expect(list.length).to eq(0)+ end+ end+ endend