A platform for community discussion. Free, open, simple.
FEATURE: workflows flag post node (#41769)
Joffrey JAFFEUXdff50be40230
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.ymlindex feb89e20203..ab61ffd9955 100644--- a/plugins/discourse-workflows/config/locales/client.en.yml+++ b/plugins/discourse-workflows/config/locales/client.en.yml@@ -228,6 +228,7 @@ en:"action:code": "Code""action:topic": "Topic""action:post": "Post"+ "action:flag_post": "Flag post""action:send_personal_message": "Send personal message""action:set_fields": "Set fields""trigger:stale_topic": "Stale topic"@@ -276,6 +277,7 @@ en:"action:code": "Run custom JavaScript code""action:topic": "Create, retrieve, list, close, archive, or set custom fields on topics""action:post": "Create, edit, retrieve, or list posts"+ "action:flag_post": "Flag a post as spam or add it to the review queue, optionally hiding or deleting the post and silencing its author""action:send_personal_message": "Send a personal message to users or groups""action:set_fields": "Set or modify data fields in the workflow context""trigger:stale_topic": "Fires when a topic has had no activity for a period"@@ -480,6 +482,19 @@ en:advanced_filter: "Advanced filter"advanced_filter_description: "Additional PostsFilter query string appended to the configured filters"actor_username: "Performed by user"+ flag_post:+ post_id: "Post ID"+ flag_type: "Flag type"+ flag_types:+ review: "Add post to review queue"+ review_hide: "Add post to review queue and hide post"+ review_delete: "Add post to review queue and delete post"+ review_delete_silence: "Add post to review queue, delete post and silence user"+ spam: "Flag as spam and hide post"+ spam_silence: "Flag as spam, hide post and silence user"+ reason: "Reason"+ reason_description: "Optional note shown to moderators alongside the flag in the review queue"+ actor_username: "Performed by user"topic:operation: "Operation"operations:diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.ymlindex fc863661c68..da3c22ab221 100644--- a/plugins/discourse-workflows/config/locales/server.en.yml+++ b/plugins/discourse-workflows/config/locales/server.en.yml@@ -79,6 +79,11 @@ en:edit_failed: "Failed to edit post."unknown_operation: "Unknown operation: %{operation}."invalid_filter: "Invalid post filter fragment: %{fragments}."+ flag_post:+ unknown_flag_type: "Unknown flag type: %{flag_type}."+ actor_not_staff: "The acting user must be a staff member to flag posts."+ cannot_flag: "This post cannot be flagged as spam. It may already be hidden or authored by a staff member."+ flag_failed: "Failed to flag post: %{errors}"user:unknown_operation: "Unknown operation: %{operation}."invalid_updates: "User updates must be an object."@@ -136,6 +141,8 @@ en:execution_failed: "Called workflow finished with status '%{status}'."execution_failed_with_error: "Called workflow finished with status '%{status}': %{error}"payload_too_large: "Workflow call payload exceeds the maximum size of %{max} bytes."+ flag_post:+ flagged_by_workflow: "Flagged by the '%{workflow_name}' workflow."pin_data:errors:unsupported_node: "Only nodes with a single output can have pinned data."diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rbindex 98571b344e0..bb960ad3265 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb@@ -198,6 +198,8 @@ module DiscourseWorkflows"trigger:badge_granted" => "badge award achievement medal granted earned","action:user" =>"user profile bio title trust level lock groups fields lookup edit update",+ "action:flag_post" =>+ "flag spam moderation review queue reviewable hide delete silence triage report",}.freezedef self.signaturediff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rbnew file mode 100644index 00000000000..7cc5042c028--- /dev/null+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/flag_post/v1.rb@@ -0,0 +1,250 @@+# frozen_string_literal: true++module DiscourseWorkflows+ module Nodes+ module FlagPost+ class V1 < NodeType+ FLAG_TYPES = %w[+ review+ review_hide+ review_delete+ review_delete_silence+ spam+ spam_silence+ ].freeze+ SPAM_FLAG_TYPES = %w[spam spam_silence].freeze++ description(+ name: "action:flag_post",+ version: "1.0",+ defaults: {+ icon: "flag",+ color: "red",+ },+ group: "discourse_actions",+ capabilities: {+ run_scope: "per_item",+ },+ output_contracts: [+ {+ schema: {+ "$schema" => Schema::DRAFT_URI,+ "type" => "object",+ "properties" => {+ "post_id" => {+ "type" => "integer",+ },+ "flag_type" => {+ "type" => "string",+ },+ "reviewable_id" => {+ "type" => "integer",+ },+ "post_hidden" => {+ "type" => "boolean",+ },+ "post_deleted" => {+ "type" => "boolean",+ },+ "user_silenced" => {+ "type" => "boolean",+ },+ },+ },+ },+ ],+ properties: {+ post_id: {+ type: :string,+ required: true,+ },+ flag_type: {+ type: :options,+ required: true,+ options: FLAG_TYPES,+ default: "review",+ ui: {+ expression: true,+ },+ },+ reason: {+ type: :string,+ required: false,+ ui: {+ control: :textarea,+ },+ },+ actor_username: {+ type: :string,+ required: false,+ default: "system",+ ui: {+ control: :actor,+ },+ },+ },+ )++ def execute(exec_ctx)+ items =+ exec_ctx.input_items.map.with_index do |_item, item_index|+ config = {+ "post_id" => exec_ctx.get_node_parameter("post_id", item_index),+ "flag_type" =>+ exec_ctx.get_node_parameter("flag_type", item_index, default: "review"),+ "reason" => exec_ctx.get_node_parameter("reason", item_index),+ }++ wrap(process(exec_ctx, config, item_index))+ end++ [items]+ end++ private++ def process(exec_ctx, config, item_index)+ flag_type = config["flag_type"].to_s+ if !FLAG_TYPES.include?(flag_type)+ raise_node_error!(+ I18n.t(+ "discourse_workflows.errors.flag_post.unknown_flag_type",+ flag_type: flag_type,+ ),+ )+ end++ post = ::Post.find(config["post_id"])+ actor = exec_ctx.actor_from_parameter("actor_username", item_index)+ if !actor.staff?+ raise_node_error!(I18n.t("discourse_workflows.errors.flag_post.actor_not_staff"))+ end+ raise Discourse::InvalidAccess if !actor.guardian.can_see?(post)++ reason = score_reason_for(exec_ctx, config["reason"])++ reviewable =+ if SPAM_FLAG_TYPES.include?(flag_type)+ flag_as_spam(post, actor, flag_type, reason)+ else+ add_to_review_queue(post, actor, flag_type, reason, attribution_for(exec_ctx))+ end++ output(post, flag_type, reviewable)+ end++ def attribution_for(exec_ctx, escape: false)+ workflow_name = exec_ctx.get_workflow.name+ workflow_name = ERB::Util.html_escape(workflow_name) if escape+ I18n.t("discourse_workflows.flag_post.flagged_by_workflow", workflow_name: workflow_name)+ end++ def score_reason_for(exec_ctx, custom_reason)+ parts = [attribution_for(exec_ctx, escape: true)]+ custom_reason = custom_reason.to_s.strip+ parts << ERB::Util.html_escape(custom_reason) if custom_reason.present?+ parts.join("<br>")+ end++ def flag_as_spam(post, actor, flag_type, reason)+ if !actor.guardian.post_can_act?(post, :spam)+ raise_node_error!(I18n.t("discourse_workflows.errors.flag_post.cannot_flag"))+ end++ promote_pending_reviewable_to_flagged!(post)++ result =+ PostActionCreator.new(+ actor,+ post,+ PostActionType.types[:spam],+ reason: reason,+ queue_for_review: true,+ ).perform++ if !result.success?+ raise_node_error!(+ I18n.t(+ "discourse_workflows.errors.flag_post.flag_failed",+ errors: result.errors.full_messages.join(", "),+ ),+ )+ end++ if flag_type == "spam_silence" && post.user.present?+ SpamRule::AutoSilence.new(post.user, post).silence_user+ end++ result.reviewable+ end++ def add_to_review_queue(post, actor, flag_type, reason, attribution)+ destroying = %w[review_delete review_delete_silence].include?(flag_type)++ if destroying+ PostDestroyer.new(actor, post, context: attribution).destroy++ if flag_type == "review_delete_silence" && post.user.present?+ UserSilencer.silence(post.user, actor, message: :silenced_by_staff, post_id: post.id)+ end+ end++ reviewable =+ (ReviewableFlaggedPost.pending.find_by(target: post) if !destroying) ||+ ReviewablePost.needs_review!(+ target: post,+ created_by: actor,+ reviewable_by_moderator: true,+ )++ add_review_score(reviewable, actor, reason)++ post.hide!(PostActionType.types[:notify_moderators]) if flag_type == "review_hide"++ reviewable+ end++ def add_review_score(reviewable, actor, reason)+ score_type = ReviewableScore.types[:needs_approval]+ if reviewable.reviewable_scores.pending.exists?(+ user_id: actor.id,+ reviewable_score_type: score_type,+ )+ return+ end++ reviewable.add_score(actor, score_type, reason: reason, force_review: true)+ end++ def promote_pending_reviewable_to_flagged!(post)+ reviewable = ReviewablePost.pending.find_by(target: post)+ return if reviewable.blank?+ return if ReviewableFlaggedPost.exists?(target: post)++ reviewable.update!(+ type: ReviewableFlaggedPost.name,+ potential_spam: true,+ reviewable_by_moderator: true,+ payload: {+ targets_topic: false,+ },+ )+ rescue ActiveRecord::RecordNotUnique+ raise if !ReviewableFlaggedPost.exists?(target: post)+ end++ def output(post, flag_type, reviewable)+ post.reload+ {+ post_id: post.id,+ flag_type: flag_type,+ reviewable_id: reviewable&.id,+ post_hidden: post.hidden?,+ post_deleted: post.deleted_at.present?,+ user_silenced: post.user&.reload&.silenced? || false,+ }+ end+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rbindex 4ab3dc90af9..9d046ef9ef4 100644--- a/plugins/discourse-workflows/plugin.rb+++ b/plugins/discourse-workflows/plugin.rb@@ -39,6 +39,7 @@ register_svg_icon "note-sticky"register_svg_icon "palette"register_svg_icon "reply"register_svg_icon "triangle-exclamation"+register_svg_icon "flag"register_svg_icon "clock"register_svg_icon "dollar-sign"register_svg_icon "comments"diff --git a/plugins/discourse-workflows/spec/integration/post_created_flag_post_spec.rb b/plugins/discourse-workflows/spec/integration/post_created_flag_post_spec.rbnew file mode 100644index 00000000000..e40087fc62f--- /dev/null+++ b/plugins/discourse-workflows/spec/integration/post_created_flag_post_spec.rb@@ -0,0 +1,59 @@+# frozen_string_literal: true++RSpec.describe "Workflow: post created -> flag post" do+ fab!(:admin)+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:topic_owner) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:first_post) { create_post(user: topic_owner, raw: "First post") }+ fab!(:topic) { first_post.topic }++ before do+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear++ graph =+ build_workflow_graph do |g|+ g.node "trigger-1", "trigger:post_created"+ g.node "action-1",+ "action:flag_post",+ configuration: {+ "post_id" => "={{ $trigger.post.id }}",+ "flag_type" => "spam",+ "reason" => "Automated spam detection",+ }+ g.chain "trigger-1", "action-1"+ end++ Fabricate(+ :discourse_workflows_workflow,+ created_by: admin,+ published: true,+ name: "Flag <b>spam</b> replies",+ **graph,+ )+ end++ it "flags a newly created reply as spam and hides it", :aggregate_failures do+ reply = PostCreator.create!(user, topic_id: topic.id, raw: "This is a spammy reply")++ job_data = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last+ expect(job_data).to be_present++ Jobs::DiscourseWorkflows::ExecuteWorkflow.new.execute(job_data["args"].first.symbolize_keys)++ reviewable = ReviewableFlaggedPost.pending.find_by(target: reply)+ expect(reviewable).to be_present+ expect(reviewable.reviewable_scores.last.reason).to eq(+ "#{+ I18n.t(+ "discourse_workflows.flag_post.flagged_by_workflow",+ workflow_name: "Flag <b>spam</b> replies",+ )+ }<br>Automated spam detection",+ )+ expect(reply.reload.hidden?).to eq(true)+ expect(topic.reload.visible).to eq(true)++ execution = DiscourseWorkflows::Execution.last+ expect(execution.status).to eq("success")+ end+enddiff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/flag_post_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/flag_post_spec.rbnew file mode 100644index 00000000000..1c8a02e6952--- /dev/null+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/flag_post_spec.rb@@ -0,0 +1,315 @@+# frozen_string_literal: true++RSpec.describe DiscourseWorkflows::Nodes::FlagPost::V1 do+ fab!(:moderator)+ fab!(:author, :user)+ fab!(:post) { Fabricate(:post, user: author) }+ fab!(:workflow, :discourse_workflows_workflow)++ let(:attribution) do+ I18n.t("discourse_workflows.flag_post.flagged_by_workflow", workflow_name: workflow.name)+ end++ describe "#execute" do+ it "adds the post to the review queue", :aggregate_failures do+ result = nil++ expect do+ result =+ execute_node(+ configuration: {+ "post_id" => post.id.to_s,+ "flag_type" => "review",+ },+ workflow: workflow,+ )+ end.to change { ReviewablePost.pending.where(target: post).count }.by(1)++ reviewable = ReviewablePost.pending.find_by(target: post)+ score = reviewable.reviewable_scores.last++ expect(score.reviewable_score_type).to eq(ReviewableScore.types[:needs_approval])+ expect(score.user).to eq(Discourse.system_user)+ expect(score.reason).to eq(attribution)+ expect(post.reload.hidden?).to eq(false)+ expect(result).to include(+ "post_id" => post.id,+ "flag_type" => "review",+ "reviewable_id" => reviewable.id,+ "post_hidden" => false,+ "post_deleted" => false,+ "user_silenced" => false,+ )+ end++ it "appends the configured reason to the moderator-facing score reason, escaping HTML" do+ execute_node(+ configuration: {+ "post_id" => post.id.to_s,+ "flag_type" => "review",+ "reason" => "Contains suspicious <script>alert(1)</script> links",+ },+ workflow: workflow,+ )++ score = ReviewablePost.pending.find_by(target: post).reviewable_scores.last+ expect(score.reason).to eq(+ "#{attribution}<br>Contains suspicious <script>alert(1)</script> links",+ )+ end++ it "reuses a pending flagged post reviewable instead of creating a second review item",+ :aggregate_failures do+ existing = Fabricate(:reviewable_flagged_post, target: post, topic: post.topic)++ result =+ execute_node(+ configuration: {+ "post_id" => post.id.to_s,+ "flag_type" => "review",+ },+ workflow: workflow,+ )++ score =+ existing.reviewable_scores.find_by(+ user: Discourse.system_user,+ reviewable_score_type: ReviewableScore.types[:needs_approval],+ )++ expect(result["reviewable_id"]).to eq(existing.id)+ expect(ReviewablePost.where(target: post)).to be_empty+ expect(score.reason).to eq(attribution)+ end++ it "adds a single score when the same workflow flags the same post twice" do+ execute_node(configuration: { "post_id" => post.id.to_s, "flag_type" => "review" })++ expect do+ execute_node(configuration: { "post_id" => post.id.to_s, "flag_type" => "review" })+ end.not_to change { ReviewableScore.count }+ end++ it "hides the post with review_hide", :aggregate_failures do+ result =+ execute_node(configuration: { "post_id" => post.id.to_s, "flag_type" => "review_hide" })++ expect(post.reload.hidden?).to eq(true)+ expect(post.deleted_at).to be_nil+ expect(result).to include("post_hidden" => true, "post_deleted" => false)+ end++ it "soft-deletes the post with review_delete", :aggregate_failures do+ result =+ execute_node(+ configuration: {+ "post_id" => post.id.to_s,+ "flag_type" => "review_delete",+ "actor_username" => moderator.username,+ },+ )++ expect(post.reload.deleted_at).to be_present+ expect(post.deleted_by_id).to eq(moderator.id)+ expect(author.reload.silenced?).to eq(false)+ expect(ReviewablePost.pending.where(target: post).count).to eq(1)+ expect(result).to include("post_deleted" => true, "user_silenced" => false)+ end++ it "keeps a pending review item when deleting a post that already has a pending flag",+ :aggregate_failures do+ Fabricate(:reviewable_flagged_post, target: post, topic: post.topic)++ execute_node(+ configuration: {+ "post_id" => post.id.to_s,+ "flag_type" => "review_delete",+ "actor_username" => moderator.username,+ },+ )++ expect(post.reload.deleted_at).to be_present+ expect(Reviewable.pending.where(target: post).count).to eq(1)+ end++ it "soft-deletes the post and silences the author with review_delete_silence",+ :aggregate_failures do+ result =+ execute_node(+ configuration: {+ "post_id" => post.id.to_s,+ "flag_type" => "review_delete_silence",+ "actor_username" => moderator.username,+ },+ )++ expect(post.reload.deleted_at).to be_present+ expect(author.reload.silenced?).to eq(true)+ expect(result).to include("post_deleted" => true, "user_silenced" => true)+ end++ it "flags the post as spam and hides it", :aggregate_failures do+ result = nil++ expect do+ result =+ execute_node(+ configuration: {+ "post_id" => post.id.to_s,+ "flag_type" => "spam",+ "actor_username" => moderator.username,+ },+ )+ end.to change {+ PostAction.where(post: post, post_action_type_id: PostActionType.types[:spam]).count+ }.by(1)++ reviewable = ReviewableFlaggedPost.pending.find_by(target: post)++ expect(PostAction.last.user).to eq(moderator)+ expect(post.reload.hidden?).to eq(true)+ expect(post.topic.reload.visible).to eq(false)+ expect(author.reload.silenced?).to eq(false)+ expect(result).to include(+ "flag_type" => "spam",+ "reviewable_id" => reviewable.id,+ "post_hidden" => true,+ "post_deleted" => false,+ "user_silenced" => false,+ )+ end++ it "flags the post as spam and silences the author with spam_silence", :aggregate_failures do+ result =+ execute_node(configuration: { "post_id" => post.id.to_s, "flag_type" => "spam_silence" })++ expect(post.reload.hidden?).to eq(true)+ expect(author.reload.silenced?).to eq(true)+ expect(result).to include("post_hidden" => true, "user_silenced" => true)+ end++ it "promotes a pending review item to a flagged post reviewable when flagging as spam",+ :aggregate_failures do+ execute_node(configuration: { "post_id" => post.id.to_s, "flag_type" => "review" })+ reviewable = ReviewablePost.pending.find_by(target: post)++ execute_node(configuration: { "post_id" => post.id.to_s, "flag_type" => "spam" })++ expect(Reviewable.find(reviewable.id).type).to eq(ReviewableFlaggedPost.name)+ expect(Reviewable.where(target: post).count).to eq(1)+ end++ it "raises without silencing the author when a hidden post is flagged as spam",+ :aggregate_failures do+ post.hide!(PostActionType.types[:spam])++ expect do+ execute_node(configuration: { "post_id" => post.id.to_s, "flag_type" => "spam_silence" })+ end.to raise_error(+ DiscourseWorkflows::NodeError,+ I18n.t("discourse_workflows.errors.flag_post.cannot_flag"),+ )++ expect(author.reload.silenced?).to eq(false)+ end++ it "skips silencing when the post author no longer exists", :aggregate_failures do+ author.destroy!+ post.reload++ result =+ execute_node(+ configuration: {+ "post_id" => post.id.to_s,+ "flag_type" => "review_delete_silence",+ "actor_username" => moderator.username,+ },+ )++ expect(post.reload.deleted_at).to be_present+ expect(result).to include("post_deleted" => true, "user_silenced" => false)+ end++ it "flags each input item's post separately", :aggregate_failures do+ second_post = Fabricate(:post)++ output =+ execute_node_output(+ configuration: {+ "post_id" => "={{ $json.post_id }}",+ "flag_type" => "review",+ },+ input_items: [+ { "json" => { "post_id" => post.id } },+ { "json" => { "post_id" => second_post.id } },+ ],+ )++ items = output.first+ expect(items.map { |item| item.dig("json", "post_id") }).to eq([post.id, second_post.id])+ expect(ReviewablePost.pending.where(target: post).count).to eq(1)+ expect(ReviewablePost.pending.where(target: second_post).count).to eq(1)+ end++ it "raises when the acting user cannot see the post" do+ pm_post = Fabricate(:private_message_post)++ expect do+ execute_node(+ configuration: {+ "post_id" => pm_post.id.to_s,+ "flag_type" => "review",+ "actor_username" => moderator.username,+ },+ )+ end.to raise_error(Discourse::InvalidAccess)+ end++ it "resolves dynamic post id and flag type expressions" do+ result =+ execute_node(+ configuration: {+ "post_id" => "={{ $json.post.id }}",+ "flag_type" => "={{ $json.severity }}",+ },+ item: {+ "json" => {+ "post" => {+ "id" => post.id,+ },+ "severity" => "review_hide",+ },+ },+ )++ expect(post.reload.hidden?).to eq(true)+ expect(result).to include("post_id" => post.id, "flag_type" => "review_hide")+ end++ it "raises when the flag type is unknown" do+ expect do+ execute_node(configuration: { "post_id" => post.id.to_s, "flag_type" => "nuke" })+ end.to raise_error(+ DiscourseWorkflows::NodeError,+ I18n.t("discourse_workflows.errors.flag_post.unknown_flag_type", flag_type: "nuke"),+ )+ end++ it "raises when the acting user is not a staff member" do+ non_staff = Fabricate(:user)++ expect do+ execute_node(+ configuration: {+ "post_id" => post.id.to_s,+ "flag_type" => "review",+ "actor_username" => non_staff.username,+ },+ )+ end.to raise_error(+ DiscourseWorkflows::NodeError,+ I18n.t("discourse_workflows.errors.flag_post.actor_not_staff"),+ )+ end+ end+enddiff --git a/plugins/discourse-workflows/spec/support/node_execution_helpers.rb b/plugins/discourse-workflows/spec/support/node_execution_helpers.rbindex 9e5b8256942..6129d4a0085 100644--- a/plugins/discourse-workflows/spec/support/node_execution_helpers.rb+++ b/plugins/discourse-workflows/spec/support/node_execution_helpers.rb@@ -8,6 +8,7 @@ module NodeExecutionHelpersinput_groups: nil,node_context: nil,user: nil,+ workflow: nil,&block)item = { "json" => {} } if item.nil? && input_items.nil?@@ -32,6 +33,7 @@ module NodeExecutionHelpersuser: user,}kwargs[:node_context] = node_context if node_context+ kwargs[:workflow] = workflow if workflowctx = DiscourseWorkflows::Executor::NodeExecutionContext.new(**kwargs)output_arrays = action.execute(ctx)@@ -47,8 +49,8 @@ module NodeExecutionHelperssandbox&.disposeend- def execute_node(configuration:, item: { "json" => {} })- result = execute_node_output(configuration: configuration, item: item)+ def execute_node(configuration:, item: { "json" => {} }, workflow: nil)+ result = execute_node_output(configuration: configuration, item: item, workflow: workflow)result.first.first["json"]endend