Skip to content

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

FEATURE: post menu button trigger (#42023)

Joffrey JAFFEUXbb5b344d69ac
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/post_button_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/post_button_controller.rb
new file mode 100644
index 00000000000..955f0e7c9fb
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/post_button_controller.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class PostButtonController < ::ApplicationController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ before_action :ensure_logged_in
+
+ def create
+ DiscourseWorkflows::Workflow::TriggerPostButton.call(service_params) do
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:published_trigger) { raise Discourse::NotFound }
+ on_model_not_found(:post) { raise Discourse::NotFound }
+ on_failed_policy(:can_use_post_button) { raise Discourse::InvalidAccess }
+ on_failed_policy(:can_see_post) { raise Discourse::NotFound }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
index a70ea352422..0b5f723b695 100644
--- a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
@@ -45,6 +45,33 @@ module DiscourseWorkflows
end
end
+ def self.cached_post_buttons
+ cached_published_triggers("trigger:post_button").map do |published_trigger|
+ parameters = NodeData.parameters(published_trigger.trigger_node)
+ {
+ trigger_node_id: published_trigger.trigger_node_id,
+ workflow_id: published_trigger.workflow_id,
+ label: parameters["label"],
+ icon: parameters["icon"],
+ position: DiscourseWorkflows::Nodes::PostButton::V1.resolved_position(parameters),
+ confirmation: parameters["confirmation"] == true,
+ confirmation_message: parameters["confirmation_message"].presence,
+ group_ids: DiscourseWorkflows::Nodes::PostButton::V1.normalized_group_ids(parameters),
+ }
+ end
+ end
+
+ def self.post_buttons_for(user)
+ return [] if user.blank?
+
+ cached_post_buttons.filter_map do |post_button|
+ next if post_button[:group_ids].blank?
+ next if !user.in_any_groups?(post_button[:group_ids])
+
+ post_button.except(:group_ids)
+ end
+ end
+
def self.active_node_types
cached_dependency_index[:active_node_types].to_set
end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/trigger_post_button.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/trigger_post_button.rb
new file mode 100644
index 00000000000..0d05d3c062f
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/trigger_post_button.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::TriggerPostButton
+ include Service::Base
+
+ params do
+ attribute :trigger_node_id, :string
+ attribute :post_id, :integer
+
+ validates :trigger_node_id, presence: true
+ validates :post_id, presence: true
+ end
+
+ model :published_trigger
+ policy :can_use_post_button
+ model :post
+ policy :can_see_post
+ step :enqueue_workflow
+
+ private
+
+ def fetch_published_trigger(params:)
+ DiscourseWorkflows::Workflow::Action::FindPublishedTriggers.call(
+ trigger_type: "trigger:post_button",
+ filter: ->(published_trigger) do
+ published_trigger.trigger_node_id == params.trigger_node_id
+ end,
+ ).first
+ end
+
+ def can_use_post_button(published_trigger:, guardian:)
+ DiscourseWorkflows::Nodes::PostButton::V1.available_to?(
+ guardian.user,
+ NodeData.parameters(published_trigger.trigger_node),
+ )
+ end
+
+ def fetch_post(params:)
+ Post.find_by(id: params.post_id)
+ end
+
+ def can_see_post(post:, guardian:)
+ guardian.can_see?(post)
+ end
+
+ def enqueue_workflow(published_trigger:, post:, guardian:)
+ trigger = DiscourseWorkflows::Nodes::PostButton::V1.new(post)
+ DiscourseWorkflows::TriggerDispatcher.enqueue(
+ published_trigger,
+ trigger_data: trigger.output,
+ user_id: guardian.user.id,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/initializers/post-button-workflows.gjs b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/post-button-workflows.gjs
new file mode 100644
index 00000000000..7bfdf00c5d7
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/post-button-workflows.gjs
@@ -0,0 +1,165 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+
+const ANCHOR_KEYS = {
+ read: "read",
+ like: "like",
+ copy_link: "copyLink",
+ flag: "flag",
+ edit: "edit",
+ bookmark: "bookmark",
+ delete: "delete",
+ admin: "admin",
+ reply: "reply",
+};
+
+function dagPosition(workflow, context, postMenuOrder) {
+ const position = workflow.position;
+
+ if (position === "first") {
+ return { before: context.firstButtonKey };
+ }
+
+ if (position === "more_menu") {
+ return {
+ before: context.lastHiddenButtonKey,
+ after: context.secondLastHiddenButtonKey,
+ };
+ }
+
+ const match = position?.match(/^(before|after)_(.+)$/);
+ if (match) {
+ const anchor = ANCHOR_KEYS[match[2]];
+ if (!anchor) {
+ // key from plugin or theme
+ return { [match[1]]: match[2] };
+ }
+
+ const index = postMenuOrder.indexOf(anchor);
+ if (index === -1) {
+ // key not in site menu
+ return { [match[1]]: anchor };
+ }
+
+ if (match[1] === "before") {
+ const previous = postMenuOrder[index - 1];
+ return previous
+ ? { before: anchor, after: previous }
+ : { before: anchor };
+ }
+
+ return {
+ after: anchor,
+ before: postMenuOrder[index + 1] || context.buttonKeys.SHOW_MORE,
+ };
+ }
+
+ return undefined;
+}
+
+function buildButtonComponent(workflow) {
+ const className = `post-action-menu__workflow-post-button workflow-post-button-${workflow.workflow_id}`;
+
+ class WorkflowPostButton extends Component {
+ @service dialog;
+
+ @tracked triggering = false;
+
+ @action
+ trigger() {
+ if (workflow.confirmation) {
+ this.dialog.yesNoConfirm({
+ message:
+ workflow.confirmation_message ||
+ i18n(
+ "discourse_workflows.post_button.confirmation_default_message"
+ ),
+ didConfirm: () => this.triggerWorkflow(),
+ });
+ } else {
+ return this.triggerWorkflow();
+ }
+ }
+
+ async triggerWorkflow() {
+ this.triggering = true;
+ try {
+ await ajax("/discourse-workflows/trigger-post-button", {
+ type: "POST",
+ data: {
+ trigger_node_id: workflow.trigger_node_id,
+ post_id: this.args.post.id,
+ },
+ });
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.triggering = false;
+ }
+ }
+
+ <template>
+ <DButton
+ class={{className}}
+ ...attributes
+ @action={{this.trigger}}
+ @disabled={{this.triggering}}
+ @icon={{if workflow.icon workflow.icon "bolt"}}
+ @translatedTitle={{workflow.label}}
+ @translatedLabel={{if @showLabel workflow.label}}
+ />
+ </template>
+ }
+
+ if (workflow.position === "more_menu") {
+ WorkflowPostButton.hidden = true;
+ }
+
+ return WorkflowPostButton;
+}
+
+export default {
+ name: "discourse-workflows-post-button",
+
+ initialize(container) {
+ const site = container.lookup("service:site");
+ const workflows = site.post_button_workflows || [];
+
+ if (!workflows.length) {
+ return;
+ }
+
+ const siteSettings = container.lookup("service:site-settings");
+ const postMenuOrder = (siteSettings.post_menu || "")
+ .split("|")
+ .filter(Boolean);
+
+ const buttons = workflows.map((workflow) => ({
+ key: `workflow-post-button-${workflow.workflow_id}-${workflow.trigger_node_id}`,
+ workflow,
+ component: buildButtonComponent(workflow),
+ }));
+
+ withPluginApi((api) => {
+ api.registerValueTransformer(
+ "post-menu-buttons",
+ ({ value: dag, context }) => {
+ buttons.forEach(({ key, workflow, component }) => {
+ dag.add(
+ key,
+ component,
+ dagPosition(workflow, context, postMenuOrder)
+ );
+ });
+ }
+ );
+ });
+ },
+};
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index 3d4dbc10ed4..0edd9735a2d 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -251,6 +251,7 @@ en:
"action:template": "Template"
"action:respond_to_webhook": "Respond to webhook"
"trigger:topic_admin_button": "Topic admin button"
+ "trigger:post_button": "Post button"
"trigger:error": "Error trigger"
"flow:wait": "Wait"
"action:modal": "Modal"
@@ -302,6 +303,7 @@ en:
"action:template": "Render text with a template"
"action:respond_to_webhook": "Send a custom HTTP response to the webhook caller"
"trigger:topic_admin_button": "Adds a button to the topic admin menu that triggers this workflow"
+ "trigger:post_button": "Adds a button to the post actions menu that triggers this workflow"
"trigger:error": "Fires when another workflow fails"
"flow:wait": "Pause workflow execution and resume after a delay or webhook callback"
"action:modal": "Shows a modal to a user and waits for them to choose an option"
@@ -310,6 +312,40 @@ en:
label: "Button label"
label_placeholder: "Run workflow"
icon: "Button icon"
+ post_button:
+ label: "Button label"
+ label_placeholder: "Run workflow"
+ icon: "Button icon"
+ group_ids: "Groups"
+ group_ids_description: "Only members of at least one of these groups can see and use the button"
+ position: "Position"
+ position_first: "First in the row"
+ position_last: "Last in the row"
+ position_more_menu: "In the show-more menu"
+ position_relative: "Relative to another button"
+ position_direction: "Placement"
+ position_direction_before: "Before"
+ position_direction_after: "After"
+ position_anchor: "Button"
+ position_anchor_description: "If that button is hidden or moved to the show-more menu on a post, this only affects ordering"
+ position_anchor_read: "Read indicator"
+ position_anchor_like: "Like"
+ position_anchor_copy_link: "Copy link"
+ position_anchor_flag: "Flag"
+ position_anchor_edit: "Edit"
+ position_anchor_bookmark: "Bookmark"
+ position_anchor_delete: "Delete"
+ position_anchor_admin: "Admin wrench"
+ position_anchor_reply: "Reply"
+ position_anchor_custom: "Custom key"
+ position_custom_key: "Custom button key"
+ position_custom_key_description: "The internal key a plugin or theme registers for its button in the post menu"
+ position_custom_key_placeholder: "button-key"
+ confirmation: "Ask for confirmation"
+ confirmation_description: "Show a confirmation dialog before triggering the workflow"
+ confirmation_message: "Confirmation message"
+ confirmation_message_placeholder: "Are you sure?"
+ confirmation_default_message: "Are you sure?"
modal:
target_user: "Target user"
target_user_placeholder: "Defaults to the user who triggered the workflow"
diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rb
index 8919cf9e94a..43143a49e26 100644
--- a/plugins/discourse-workflows/config/routes.rb
+++ b/plugins/discourse-workflows/config/routes.rb
@@ -85,6 +85,7 @@ DiscourseWorkflows::Engine.routes.draw do
scope "/discourse-workflows", defaults: { format: :json } do
post "/trigger-topic-admin-button" => "topic_admin_button#create"
+ post "/trigger-post-button" => "post_button#create"
post "/modal-responses" => "modal_responses#create"
end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_button/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_button/v1.rb
new file mode 100644
index 00000000000..4f57250b3b5
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_button/v1.rb
@@ -0,0 +1,181 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module PostButton
+ class V1 < NodeType
+ POSITION_OPTIONS = %w[first last more_menu relative].freeze
+ POSITION_DIRECTION_OPTIONS = %w[before after].freeze
+ POSITION_ANCHOR_OPTIONS = %w[
+ read
+ like
+ copy_link
+ flag
+ edit
+ bookmark
+ delete
+ admin
+ reply
+ custom
+ ].freeze
+
+ description(
+ name: "trigger:post_button",
+ version: "1.0",
+ defaults: {
+ icon: "arrow-pointer",
+ color: "cyan",
+ },
+ group: "discourse_triggers",
+ properties: {
+ label: {
+ type: :string,
+ required: true,
+ },
+ icon: {
+ type: :icon,
+ required: false,
+ },
+ group_ids: {
+ type: :array,
+ required: true,
+ type_options: {
+ load_options_method: "groups",
+ },
+ ui: {
+ control: :group_select,
+ multiple: true,
+ },
+ control_options: {
+ value_property: "id",
+ name_property: "name",
+ filterable: true,
+ },
+ },
+ position: {
+ type: :options,
+ required: false,
+ default: "last",
+ options: POSITION_OPTIONS,
+ },
+ position_direction: {
+ type: :options,
+ required: false,
+ default: "before",
+ options: POSITION_DIRECTION_OPTIONS,
+ display_options: {
+ show: {
+ position: ["relative"],
+ },
+ },
+ },
+ position_anchor: {
+ type: :options,
+ required: false,
+ default: "reply",
+ options: POSITION_ANCHOR_OPTIONS,
+ display_options: {
+ show: {
+ position: ["relative"],
+ },
+ },
+ },
+ position_custom_key: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ position: ["relative"],
+ position_anchor: ["custom"],
+ },
+ },
+ },
+ confirmation: {
+ type: :boolean,
+ required: false,
+ default: false,
+ },
+ confirmation_message: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ confirmation: [true],
+ },
+ },
+ },
+ },
+ capabilities: {
+ manually_triggerable: true,
+ provides_current_user: true,
+ },
+ output_contracts: [
+ { schema: Schema.merge(Schema::POST_SCHEMA, Schema::TOPIC_LIST_ITEM_SCHEMA) },
+ ],
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "groups"
+ ::Group
+ .order(:name)
+ .pluck(:id, :name)
+ .select { |_, name| context.matches_filter?(name) }
+ .map { |id, name| { id:, name: } }
+ end
+ end
+
+ def self.normalized_group_ids(parameters)
+ Array
+ .wrap(parameters["group_ids"])
+ .filter_map do |group_id|
+ value = group_id.to_s
+ value.to_i if value.match?(/\A\d+\z/)
+ end
+ end
+
+ def self.available_to?(user, parameters)
+ return false if user.blank?
+
+ group_ids = normalized_group_ids(parameters)
+ group_ids.present? && user.in_any_groups?(group_ids)
+ end
+
+ def self.resolved_position(parameters)
+ position = parameters["position"].presence || "last"
+ return position if position != "relative"
+
+ direction = parameters["position_direction"].presence || "before"
+ anchor = parameters["position_anchor"].presence || "reply"
+ anchor = parameters["position_custom_key"].to_s.strip.presence if anchor == "custom"
+ return "last" if anchor.blank?
+
+ "#{direction}_#{anchor}"
+ end
+
+ def initialize(post)
+ super(parameters: {})
+ @post = post
+ end
+
+ def valid?
+ @post.present? && @post.topic.present?
+ end
+
+ def output
+ { post: post_data(@post), topic: topic_data(@post.topic) }
+ end
+
+ private
+
+ def post_data(post)
+ serialize_post(post)
+ end
+
+ def topic_data(topic)
+ serialize_record(topic, TopicListItemSerializer)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rb
index 66d3b3b1809..dbc8c5cdc8e 100644
--- a/plugins/discourse-workflows/plugin.rb
+++ b/plugins/discourse-workflows/plugin.rb
@@ -124,6 +124,15 @@ after_initialize do
DiscourseWorkflows::WorkflowDependency.cached_topic_admin_buttons
end
+ add_to_serializer :site,
+ :post_button_workflows,
+ include_condition: -> do
+ scope.user.present? &&
+ DiscourseWorkflows::WorkflowDependency.cached_post_buttons.present?
+ end do
+ DiscourseWorkflows::WorkflowDependency.post_buttons_for(scope.user)
+ end
+
add_to_serializer :current_user,
:discourse_workflows_user_modal_last_id,
include_condition: -> do
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_button_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_button_spec.rb
new file mode 100644
index 00000000000..e6840f50458
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_button_spec.rb
@@ -0,0 +1,113 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::PostButton::V1 do
+ fab!(:group)
+ fab!(:user)
+ fab!(:post)
+
+ describe "#valid?" do
+ it "returns true when the post is present" do
+ trigger = described_class.new(post)
+ expect(trigger).to be_valid
+ end
+
+ it "returns false when the post is nil" do
+ trigger = described_class.new(nil)
+ expect(trigger).not_to be_valid
+ end
+ end
+
+ describe "#output" do
+ it "returns post and topic data" do
+ output = described_class.new(post).output
+
+ expect(output).to include(
+ post: include(id: post.id, post_number: post.post_number, topic_id: post.topic_id),
+ topic: include(id: post.topic.id, title: post.topic.title),
+ )
+ end
+ end
+
+ describe ".normalized_group_ids" do
+ it "keeps only numeric ids" do
+ expect(described_class.normalized_group_ids("group_ids" => [1, "2", "junk", nil, ""])).to eq(
+ [1, 2],
+ )
+ end
+
+ it "returns an empty array when the parameter is missing" do
+ expect(described_class.normalized_group_ids({})).to eq([])
+ end
+ end
+
+ describe ".available_to?" do
+ it "returns false for an anonymous user" do
+ expect(described_class.available_to?(nil, "group_ids" => [group.id])).to eq(false)
+ end
+
+ it "returns false when no groups are configured" do
+ expect(described_class.available_to?(user, "group_ids" => [])).to eq(false)
+ end
+
+ it "returns false when the user is in none of the configured groups" do
+ expect(described_class.available_to?(user, "group_ids" => [group.id])).to eq(false)
+ end
+
+ it "returns true when the user is a member of a configured group" do
+ group.add(user)
+
+ expect(described_class.available_to?(user, "group_ids" => [group.id])).to eq(true)
+ end
+
+ it "returns true for any logged-in user when the logged-in users group is configured" do
+ expect(
+ described_class.available_to?(user, "group_ids" => [Group::AUTO_GROUPS[:logged_in_users]]),
+ ).to eq(true)
+ end
+ end
+
+ describe ".resolved_position" do
+ it "defaults to last" do
+ expect(described_class.resolved_position({})).to eq("last")
+ end
+
+ it "passes through preset positions" do
+ expect(described_class.resolved_position("position" => "more_menu")).to eq("more_menu")
+ end
+
+ it "combines direction and anchor for relative positions" do
+ expect(
+ described_class.resolved_position(
+ "position" => "relative",
+ "position_direction" => "after",
+ "position_anchor" => "like",
+ ),
+ ).to eq("after_like")
+ end
+
+ it "defaults relative positions to before reply" do
+ expect(described_class.resolved_position("position" => "relative")).to eq("before_reply")
+ end
+
+ it "uses the custom key when the custom anchor is selected" do
+ expect(
+ described_class.resolved_position(
+ "position" => "relative",
+ "position_direction" => "after",
+ "position_anchor" => "custom",
+ "position_custom_key" => " custom-button ",
+ ),
+ ).to eq("after_custom-button")
+ end
+
+ it "falls back to last when the custom anchor has no key" do
+ expect(
+ described_class.resolved_position(
+ "position" => "relative",
+ "position_anchor" => "custom",
+ "position_custom_key" => "",
+ ),
+ ).to eq("last")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/post_button_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/post_button_controller_spec.rb
new file mode 100644
index 00000000000..16e4a330045
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/post_button_controller_spec.rb
@@ -0,0 +1,116 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::PostButtonController do
+ fab!(:admin)
+ fab!(:group)
+ fab!(:member) { Fabricate(:user).tap { |user| group.add(user) } }
+ fab!(:user)
+ fab!(:post_record, :post)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:post_button",
+ configuration: {
+ "label" => "Run workflow",
+ "icon" => "bolt",
+ "group_ids" => [group.id],
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ describe "POST /discourse-workflows/trigger-post-button" do
+ it "requires authentication" do
+ post "/discourse-workflows/trigger-post-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ post_id: post_record.id,
+ }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it "returns 403 when the user is in none of the configured groups" do
+ sign_in(user)
+
+ post "/discourse-workflows/trigger-post-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ post_id: post_record.id,
+ }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ context "when signed in as a group member" do
+ before { sign_in(member) }
+
+ it "returns 204 on success" do
+ post "/discourse-workflows/trigger-post-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ post_id: post_record.id,
+ }
+
+ expect(response).to have_http_status(:no_content)
+ end
+
+ it "enqueues an ExecuteWorkflow job" do
+ post "/discourse-workflows/trigger-post-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ post_id: post_record.id,
+ }
+
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first).to include(
+ "trigger_node_id" => "trigger-1",
+ "workflow_version_id" => workflow.active_version_id,
+ "user_id" => member.id,
+ )
+ end
+
+ it "returns 400 when contract is invalid" do
+ post "/discourse-workflows/trigger-post-button.json", params: {}
+
+ expect(response).to have_http_status(:bad_request)
+ end
+
+ it "returns 404 when trigger node does not exist" do
+ post "/discourse-workflows/trigger-post-button.json",
+ params: {
+ trigger_node_id: "nonexistent",
+ post_id: post_record.id,
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 when workflow is unpublished" do
+ unpublish_workflow!(workflow)
+
+ post "/discourse-workflows/trigger-post-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ post_id: post_record.id,
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 when the user cannot see the post" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ private_post = Fabricate(:post, topic: Fabricate(:topic, category: private_category))
+
+ post "/discourse-workflows/trigger-post-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ post_id: private_post.id,
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/serializers/site_serializer_spec.rb b/plugins/discourse-workflows/spec/serializers/site_serializer_spec.rb
index 69626cc0935..66f777f279b 100644
--- a/plugins/discourse-workflows/spec/serializers/site_serializer_spec.rb
+++ b/plugins/discourse-workflows/spec/serializers/site_serializer_spec.rb
@@ -69,4 +69,111 @@ RSpec.describe SiteSerializer do
expect(data[:topic_admin_button_workflows]).to be_empty
end
end
+
+ describe "#post_button_workflows" do
+ before { DiscourseWorkflows::WorkflowDependency.clear_cache! }
+
+ fab!(:group)
+ fab!(:member) { Fabricate(:user).tap { |member| group.add(member) } }
+
+ fab!(:post_button_workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:post_button",
+ configuration: {
+ "label" => "Run workflow",
+ "icon" => "bolt",
+ "group_ids" => [group.id],
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ it "includes published post button workflows for group members without leaking group ids" do
+ member_guardian = Guardian.new(member)
+ data =
+ described_class.new(Site.new(member_guardian), scope: member_guardian, root: false).as_json
+
+ expect(data[:post_button_workflows]).to contain_exactly(
+ {
+ trigger_node_id: "trigger-1",
+ workflow_id: post_button_workflow.id,
+ label: "Run workflow",
+ icon: "bolt",
+ position: "last",
+ confirmation: false,
+ confirmation_message: nil,
+ },
+ )
+ end
+
+ it "returns an empty list for users in none of the configured groups" do
+ user_guardian = Guardian.new(user)
+ data = described_class.new(Site.new(user_guardian), scope: user_guardian, root: false).as_json
+
+ expect(data[:post_button_workflows]).to be_empty
+ end
+
+ it "is not included for anonymous users" do
+ anon_guardian = Guardian.new
+ data = described_class.new(Site.new(anon_guardian), scope: anon_guardian, root: false).as_json
+
+ expect(data).not_to have_key(:post_button_workflows)
+ end
+
+ it "is not included when no post button workflow is published" do
+ unpublish_workflow!(post_button_workflow)
+ DiscourseWorkflows::WorkflowDependency.clear_cache!
+
+ member_guardian = Guardian.new(member)
+ data =
+ described_class.new(Site.new(member_guardian), scope: member_guardian, root: false).as_json
+
+ expect(data).not_to have_key(:post_button_workflows)
+ end
+
+ it "returns an empty list for everyone when the trigger has no groups configured" do
+ update_workflow_node(post_button_workflow, "trigger-1") do |node|
+ node.merge("parameters" => { "label" => "Run workflow" })
+ end
+ publish_workflow!(post_button_workflow)
+
+ member_guardian = Guardian.new(member)
+ data =
+ described_class.new(Site.new(member_guardian), scope: member_guardian, root: false).as_json
+
+ expect(data[:post_button_workflows]).to be_empty
+ end
+
+ it "serializes position and confirmation options and honors automatic groups" do
+ update_workflow_node(post_button_workflow, "trigger-1") do |node|
+ node.merge(
+ "parameters" => {
+ "label" => "Run workflow",
+ "group_ids" => [Group::AUTO_GROUPS[:logged_in_users]],
+ "position" => "more_menu",
+ "confirmation" => true,
+ "confirmation_message" => "Really run this?",
+ },
+ )
+ end
+ publish_workflow!(post_button_workflow)
+
+ user_guardian = Guardian.new(user)
+ data = described_class.new(Site.new(user_guardian), scope: user_guardian, root: false).as_json
+
+ expect(data[:post_button_workflows]).to contain_exactly(
+ {
+ trigger_node_id: "trigger-1",
+ workflow_id: post_button_workflow.id,
+ label: "Run workflow",
+ icon: nil,
+ position: "more_menu",
+ confirmation: true,
+ confirmation_message: "Really run this?",
+ },
+ )
+ end
+ end
end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/trigger_post_button_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/trigger_post_button_spec.rb
new file mode 100644
index 00000000000..3fdc804df49
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/trigger_post_button_spec.rb
@@ -0,0 +1,108 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::TriggerPostButton do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:trigger_node_id) }
+ it { is_expected.to validate_presence_of(:post_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:group)
+ fab!(:member) { Fabricate(:user).tap { |user| group.add(user) } }
+ fab!(:post_record, :post)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:post_button",
+ configuration: {
+ "label" => "Run workflow",
+ "icon" => "bolt",
+ "group_ids" => [group.id],
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:params) { { trigger_node_id: "trigger-1", post_id: post_record.id } }
+ let(:dependencies) { { guardian: Guardian.new(member) } }
+
+ before { DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow) }
+
+ context "when contract is invalid" do
+ let(:params) { { trigger_node_id: nil, post_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when workflow is not found" do
+ let(:params) { { trigger_node_id: "nonexistent", post_id: post_record.id } }
+
+ it { is_expected.to fail_to_find_a_model(:published_trigger) }
+ end
+
+ context "when workflow is unpublished" do
+ before { unpublish_workflow!(workflow) }
+
+ it { is_expected.to fail_to_find_a_model(:published_trigger) }
+ end
+
+ context "when user is in none of the configured groups" do
+ fab!(:acting_user, :user)
+ let(:dependencies) { { guardian: Guardian.new(acting_user) } }
+
+ it { is_expected.to fail_a_policy(:can_use_post_button) }
+ end
+
+ context "when the trigger has no groups configured" do
+ before do
+ update_workflow_node(workflow, "trigger-1") do |node|
+ node.merge("parameters" => { "label" => "Run workflow" })
+ end
+ publish_workflow!(workflow)
+ end
+
+ it { is_expected.to fail_a_policy(:can_use_post_button) }
+ end
+
+ context "when post does not exist" do
+ let(:params) { { trigger_node_id: "trigger-1", post_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:post) }
+ end
+
+ context "when the user cannot see the post" do
+ fab!(:private_post) do
+ category = Fabricate(:private_category, group: Fabricate(:group))
+ Fabricate(:post, topic: Fabricate(:topic, category: category))
+ end
+
+ let(:params) { { trigger_node_id: "trigger-1", post_id: private_post.id } }
+
+ it { is_expected.to fail_a_policy(:can_see_post) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "enqueues an ExecuteWorkflow job acting as the clicking user" do
+ result
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first).to include(
+ "trigger_node_id" => "trigger-1",
+ "workflow_id" => workflow.id,
+ "workflow_version_id" => workflow.active_version_id,
+ "user_id" => member.id,
+ )
+ expect(job["args"].first["trigger_data"]["post"]).to include(
+ "id" => post_record.id,
+ "post_number" => post_record.post_number,
+ )
+ expect(job["args"].first["trigger_data"]["topic"]).to include("id" => post_record.topic_id)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/test/javascripts/acceptance/post-button-workflows-test.js b/plugins/discourse-workflows/test/javascripts/acceptance/post-button-workflows-test.js
new file mode 100644
index 00000000000..7c2fc8240ef
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/acceptance/post-button-workflows-test.js
@@ -0,0 +1,180 @@
+import { click, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+acceptance("Discourse Workflows | Post button", function (needs) {
+ needs.user();
+ needs.site({
+ post_button_workflows: [
+ {
+ trigger_node_id: "trigger-1",
+ workflow_id: 1,
+ label: "Run workflow",
+ icon: "bolt",
+ position: "first",
+ confirmation: false,
+ confirmation_message: null,
+ },
+ {
+ trigger_node_id: "trigger-1",
+ workflow_id: 2,
+ label: "Escalate",
+ icon: null,
+ position: "more_menu",
+ confirmation: false,
+ confirmation_message: null,
+ },
+ {
+ trigger_node_id: "trigger-1",
+ workflow_id: 3,
+ label: "Danger",
+ icon: "triangle-exclamation",
+ position: "last",
+ confirmation: true,
+ confirmation_message: "Really run this?",
+ },
+ {
+ trigger_node_id: "trigger-1",
+ workflow_id: 4,
+ label: "Next to like",
+ icon: null,
+ position: "after_like",
+ confirmation: false,
+ confirmation_message: null,
+ },
+ {
+ trigger_node_id: "trigger-1",
+ workflow_id: 5,
+ label: "Custom anchor",
+ icon: null,
+ position: "after_some-plugin-button",
+ confirmation: false,
+ confirmation_message: null,
+ },
+ ],
+ });
+
+ let lastRequestBody = null;
+
+ needs.pretender((server, helper) => {
+ server.post("/discourse-workflows/trigger-post-button", (request) => {
+ lastRequestBody = request.requestBody;
+ return helper.response({});
+ });
+ });
+
+ needs.hooks.beforeEach(() => (lastRequestBody = null));
+
+ test("renders the button at the configured position and triggers the workflow", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom("#post_1 .post-controls .actions > :first-child")
+ .hasClass(
+ "workflow-post-button-1",
+ "the first-position button renders first in the actions row"
+ );
+
+ await click("#post_1 .post-controls .workflow-post-button-1");
+
+ const params = new URLSearchParams(lastRequestBody);
+ assert.strictEqual(
+ params.get("trigger_node_id"),
+ "trigger-1",
+ "submits the trigger node id"
+ );
+ assert.true(
+ Number(params.get("post_id")) > 0,
+ "submits the clicked post's id"
+ );
+ });
+
+ test("relative positions render immediately next to their anchor", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ const children = [
+ ...document.querySelectorAll("#post_1 .post-controls .actions > *"),
+ ];
+ const likeIndex = children.findIndex(
+ (child) =>
+ child.matches(".post-action-menu__like") ||
+ child.querySelector(".post-action-menu__like")
+ );
+ const buttonIndex = children.findIndex((child) =>
+ child.classList.contains("workflow-post-button-4")
+ );
+
+ assert.true(likeIndex >= 0, "the like button renders");
+ assert.strictEqual(
+ buttonIndex,
+ likeIndex + 1,
+ "the after-like button renders immediately after the like button"
+ );
+ });
+
+ test("custom anchors pointing at unknown buttons still render", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom("#post_1 .post-controls .workflow-post-button-5")
+ .exists("the button falls back gracefully when its anchor is absent");
+ });
+
+ test("show-more buttons render in the show-more menu", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom("#post_1 .post-controls .workflow-post-button-2")
+ .doesNotExist("the show-more button is not in the actions row");
+
+ await click("#post_1 .post-controls .show-more-actions");
+
+ assert
+ .dom("#post_1 .post-controls .workflow-post-button-2")
+ .exists("the show-more button appears after expanding");
+ });
+
+ test("confirmation buttons only trigger after the dialog is confirmed", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ await click("#post_1 .post-controls .workflow-post-button-3");
+
+ assert
+ .dom(".dialog-body")
+ .hasText("Really run this?", "shows the configured message");
+ assert.strictEqual(lastRequestBody, null, "does not trigger before answer");
+
+ await click(".dialog-footer .btn-default");
+
+ assert.strictEqual(
+ lastRequestBody,
+ null,
+ "does not trigger when cancelled"
+ );
+
+ await click("#post_1 .post-controls .workflow-post-button-3");
+ await click(".dialog-footer .btn-primary");
+
+ const params = new URLSearchParams(lastRequestBody);
+ assert.strictEqual(
+ params.get("trigger_node_id"),
+ "trigger-1",
+ "triggers the workflow after confirming"
+ );
+ });
+});
+
+acceptance(
+ "Discourse Workflows | Post button (feature unused)",
+ function (needs) {
+ needs.user();
+
+ test("does not render workflow buttons when none are published", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+
+ assert
+ .dom("#post_1 .post-controls [class*='workflow-post-button']")
+ .doesNotExist("no workflow button renders");
+ });
+ }
+);