Skip to content

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

FEATURE: log staff actions when creating and updating automations (#36458)

Régis Hanolc8dddaac0cd2
diff --git a/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rb b/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rb
index c32e60bcd17..4bd46c860cf 100644
--- a/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rb
+++ b/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rb
@@ -37,69 +37,34 @@ module DiscourseAutomation
def create
automation_params = params.require(:automation).permit(:script, :trigger)
- automation =
- DiscourseAutomation::Automation.new(
- automation_params.merge(last_updated_by_id: current_user.id),
- )
-
- if automation.scriptable&.forced_triggerable
- automation.trigger = automation.scriptable.forced_triggerable[:triggerable].to_s
+ DiscourseAutomation::Create.call(params: automation_params.to_h, guardian:) do
+ on_success { |automation:| render_serialized_automation(automation) }
+ on_failed_policy(:can_create_automation) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
+ end
+ on_failure { raise Discourse::InvalidParameters }
end
-
- automation.save!
-
- render_serialized_automation(automation)
end
def update
- params.require(:automation)
-
- automation =
- DiscourseAutomation::Automation.includes(:fields, :pending_automations).find(params[:id])
-
- automation.perform_required_fields_validation = true
-
- if automation.scriptable.forced_triggerable
- params[:trigger] = automation.scriptable.forced_triggerable[:triggerable].to_s
- end
-
- attributes =
- request.parameters[:automation].slice(:name, :id, :script, :trigger, :enabled).merge(
- last_updated_by_id: current_user.id,
- )
-
- if attributes.key?(:trigger) && automation.trigger != params[:automation][:trigger]
- params[:automation][:fields] = []
- attributes[:enabled] = false
- automation.fields.destroy_all
- end
-
- if attributes.key?(:script)
- if automation.script != params[:automation][:script]
- attributes[:trigger] = nil
- params[:automation][:fields] = []
- attributes[:enabled] = false
- automation.fields.destroy_all
- automation.tap { |r| r.assign_attributes(attributes) }.save!(validate: false)
- else
- Array(params[:automation][:fields])
- .reject(&:empty?)
- .each do |field|
- automation.upsert_field!(
- field[:name],
- field[:component],
- field[:metadata],
- target: field[:target],
- )
- end
-
- automation.update!(attributes)
+ automation_params = params.require(:automation).permit(:name, :script, :trigger, :enabled)
+ fields = params[:automation][:fields]&.map(&:to_unsafe_h)
+
+ DiscourseAutomation::Update.call(
+ params: automation_params.to_h.merge(automation_id: params[:id], fields: fields),
+ guardian:,
+ ) do
+ on_success { |automation:| render_serialized_automation(automation) }
+ on_model_not_found(:automation) { raise Discourse::NotFound }
+ on_failed_policy(:can_update_automation) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request
end
- else
- automation.update!(attributes)
+ on_failure { raise Discourse::InvalidParameters }
end
-
- render_serialized_automation(automation)
end
def destroy
diff --git a/plugins/automation/app/services/discourse_automation/create.rb b/plugins/automation/app/services/discourse_automation/create.rb
new file mode 100644
index 00000000000..9bba2efb3cf
--- /dev/null
+++ b/plugins/automation/app/services/discourse_automation/create.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+class DiscourseAutomation::Create
+ include Service::Base
+
+ # @!method self.call(guardian:, params:)
+ # @param [Guardian] guardian
+ # @param [Hash] params
+ # @option params [String] :script
+ # @option params [String] :trigger
+ # @return [Service::Base::Context]
+
+ policy :can_create_automation
+
+ params do
+ attribute :script, :string
+ attribute :trigger, :string
+
+ validates :script, presence: true
+ end
+
+ model :automation, :instantiate_automation
+
+ transaction do
+ step :apply_forced_triggerable
+ step :save_automation
+ step :log_action
+ end
+
+ private
+
+ def can_create_automation(guardian:)
+ guardian.is_admin?
+ end
+
+ def instantiate_automation(params:, guardian:)
+ DiscourseAutomation::Automation.new(
+ script: params.script,
+ trigger: params.trigger,
+ last_updated_by_id: guardian.user.id,
+ )
+ end
+
+ def apply_forced_triggerable(automation:)
+ if automation.scriptable&.forced_triggerable
+ automation.trigger = automation.scriptable.forced_triggerable[:triggerable].to_s
+ end
+ end
+
+ def save_automation(automation:)
+ automation.save!
+ end
+
+ def log_action(automation:, guardian:)
+ details = { id: automation.id }
+ details[:name] = automation.name if automation.name.present?
+ details[:script] = automation.script if automation.script.present?
+ details[:trigger] = automation.trigger if automation.trigger.present?
+
+ StaffActionLogger.new(guardian.user).log_custom("create_automation", **details)
+ end
+end
diff --git a/plugins/automation/app/services/discourse_automation/destroy.rb b/plugins/automation/app/services/discourse_automation/destroy.rb
index 0584c4160de..ea4421f3bae 100644
--- a/plugins/automation/app/services/discourse_automation/destroy.rb
+++ b/plugins/automation/app/services/discourse_automation/destroy.rb
@@ -34,10 +34,12 @@ class DiscourseAutomation::Destroy
end
def log_action(automation:, guardian:)
- StaffActionLogger.new(guardian.user).log_custom(
- "delete_automation",
- **automation.slice(:id, :name, :script, :trigger),
- )
+ details = { id: automation.id }
+ details[:name] = automation.name if automation.name.present?
+ details[:script] = automation.script if automation.script.present?
+ details[:trigger] = automation.trigger if automation.trigger.present?
+
+ StaffActionLogger.new(guardian.user).log_custom("delete_automation", **details)
end
def destroy_automation(automation:)
diff --git a/plugins/automation/app/services/discourse_automation/update.rb b/plugins/automation/app/services/discourse_automation/update.rb
new file mode 100644
index 00000000000..9579bb47a88
--- /dev/null
+++ b/plugins/automation/app/services/discourse_automation/update.rb
@@ -0,0 +1,183 @@
+# frozen_string_literal: true
+
+class DiscourseAutomation::Update
+ include Service::Base
+
+ # @!method self.call(guardian:, params:)
+ # @param [Guardian] guardian
+ # @param [Hash] params
+ # @option params [Integer] :automation_id
+ # @option params [String] :name
+ # @option params [String] :script
+ # @option params [String] :trigger
+ # @option params [Boolean] :enabled
+ # @option params [Array] :fields
+ # @return [Service::Base::Context]
+
+ policy :can_update_automation
+
+ params do
+ attribute :automation_id, :integer
+ attribute :name, :string
+ attribute :script, :string
+ attribute :trigger, :string
+ attribute :enabled, :boolean
+ attribute :fields, :array
+
+ validates :automation_id, presence: true
+ end
+
+ model :automation
+ step :capture_previous_state
+
+ transaction do
+ step :apply_forced_triggerable
+ step :handle_trigger_change
+ step :handle_script_change
+ step :update_automation
+ step :log_action
+ end
+
+ private
+
+ def can_update_automation(guardian:)
+ guardian.is_admin?
+ end
+
+ def fetch_automation(params:)
+ DiscourseAutomation::Automation.includes(:fields, :pending_automations).find_by(
+ id: params.automation_id,
+ )
+ end
+
+ def capture_previous_state(automation:)
+ context[:previous_state] = {
+ name: automation.name,
+ script: automation.script,
+ trigger: automation.trigger,
+ enabled: automation.enabled,
+ fields: automation.serialized_fields,
+ }
+ end
+
+ def apply_forced_triggerable(automation:, params:)
+ if automation.scriptable&.forced_triggerable
+ context[:forced_trigger] = automation.scriptable.forced_triggerable[:triggerable].to_s
+ end
+ end
+
+ def handle_trigger_change(automation:, params:)
+ new_trigger = context[:forced_trigger] || params.trigger
+ return if new_trigger.blank?
+ return if automation.trigger == new_trigger
+
+ automation.fields.destroy_all
+ context[:fields_cleared] = true
+ context[:force_disable] = true
+ end
+
+ def handle_script_change(automation:, params:)
+ return if params.script.blank?
+ return if automation.script == params.script
+
+ automation.fields.destroy_all
+ context[:fields_cleared] = true
+ context[:force_disable] = true
+ context[:clear_trigger] = true
+ end
+
+ def update_automation(automation:, params:, guardian:)
+ automation.perform_required_fields_validation = true
+
+ attributes = { last_updated_by_id: guardian.user.id }
+ attributes[:name] = params.name if params.name.present?
+ attributes[:script] = params.script if params.script.present?
+ attributes[:trigger] = context[:forced_trigger] || params.trigger if params.trigger.present? ||
+ context[:forced_trigger].present?
+ attributes[:trigger] = nil if context[:clear_trigger]
+ attributes[:enabled] = params.enabled unless params.enabled.nil?
+ attributes[:enabled] = false if context[:force_disable]
+
+ # Update fields if not cleared and fields provided
+ if !context[:fields_cleared] && params.fields.present?
+ Array(params.fields)
+ .reject(&:empty?)
+ .each do |field|
+ automation.upsert_field!(
+ field[:name],
+ field[:component],
+ field[:metadata],
+ target: field[:target],
+ )
+ end
+ end
+
+ if context[:clear_trigger]
+ automation.assign_attributes(attributes)
+ automation.save!(validate: false)
+ else
+ automation.update!(attributes)
+ end
+
+ automation.reload
+ end
+
+ def log_action(automation:, guardian:)
+ previous_state = context[:previous_state]
+ changes = {}
+
+ %i[name script trigger enabled].each do |attr|
+ current_value = automation.public_send(attr)
+ previous_value = previous_state[attr]
+ if current_value != previous_value
+ changes[attr] = "#{format_value(previous_value)} → #{format_value(current_value)}"
+ end
+ end
+
+ current_fields = automation.serialized_fields
+ previous_fields = previous_state[:fields]
+
+ all_field_names = (current_fields.keys + previous_fields.keys).uniq.sort
+
+ all_field_names.each do |field_name|
+ current_field = current_fields[field_name]
+ previous_field = previous_fields[field_name]
+
+ next if current_field == previous_field
+ next if field_empty?(previous_field) && field_empty?(current_field)
+
+ changes[
+ field_name
+ ] = "#{format_field_value(previous_field)} → #{format_field_value(current_field)}"
+ end
+
+ return if changes.empty?
+
+ details = { id: automation.id }
+ # Only show name as identifier if it wasn't changed
+ details[:name] = automation.name unless changes.key?(:name)
+ details.merge!(changes)
+
+ StaffActionLogger.new(guardian.user).log_custom("update_automation", **details)
+ end
+
+ def format_value(value)
+ return value.to_s if value.is_a?(TrueClass) || value.is_a?(FalseClass)
+ value.blank? ? empty_value : value.to_s
+ end
+
+ def field_empty?(field)
+ return true if field.blank?
+ value = field["value"]
+ return false if value.is_a?(TrueClass) || value.is_a?(FalseClass)
+ value.blank?
+ end
+
+ def format_field_value(field)
+ field_empty?(field) ? empty_value : field["value"].to_s
+ end
+
+ def empty_value
+ @empty_value ||= I18n.t("discourse_automation.staff_action_logs.empty_value")
+ end
+end
diff --git a/plugins/automation/config/locales/client.en.yml b/plugins/automation/config/locales/client.en.yml
index 9a8512ad76a..ec9320b058a 100644
--- a/plugins/automation/config/locales/client.en.yml
+++ b/plugins/automation/config/locales/client.en.yml
@@ -4,6 +4,8 @@ en:
logs:
staff_actions:
actions:
+ create_automation: create automation
+ update_automation: update automation
delete_automation: delete automation
discourse_automation:
title: Automation
diff --git a/plugins/automation/config/locales/server.en.yml b/plugins/automation/config/locales/server.en.yml
index 087b11a30d6..9bbac53a215 100644
--- a/plugins/automation/config/locales/server.en.yml
+++ b/plugins/automation/config/locales/server.en.yml
@@ -2,6 +2,8 @@ en:
site_settings:
discourse_automation_enabled: "Enable discourse-automation plugin"
discourse_automation:
+ staff_action_logs:
+ empty_value: "(empty)"
models:
automations:
validations:
diff --git a/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb b/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb
index 4aad3e88785..9d4e2fc93ce 100644
--- a/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb
+++ b/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb
@@ -72,6 +72,16 @@ describe DiscourseAutomation::AdminAutomationsController do
}
expect(response.status).to eq(200)
end
+
+ it "logs a staff action" do
+ expect {
+ post "/admin/plugins/automation/automations.json", params: { automation: { script: } }
+ }.to change { UserHistory.where(custom_type: "create_automation").count }.by(1)
+
+ user_history = UserHistory.last
+ expect(user_history.custom_type).to eq("create_automation")
+ expect(user_history.details).to include("script: #{script}")
+ end
end
context "when logged in as a regular user" do
@@ -104,6 +114,76 @@ describe DiscourseAutomation::AdminAutomationsController do
expect(response.status).to eq(200)
end
+ it "logs a staff action when changes are made" do
+ automation.update!(enabled: true)
+ original_name = automation.name
+
+ expect {
+ put "/admin/plugins/automation/automations/#{automation.id}.json",
+ params: {
+ automation: {
+ name: "new-name",
+ enabled: false,
+ },
+ }
+ }.to change { UserHistory.where(custom_type: "update_automation").count }.by(1)
+
+ user_history = UserHistory.last
+ expect(user_history.custom_type).to eq("update_automation")
+ expect(user_history.details).to include("id: #{automation.id}")
+ expect(user_history.details).to include("name: #{original_name} → new-name")
+ expect(user_history.details).to include("enabled: true → false")
+ end
+
+ it "logs field changes" do
+ point_in_time_automation =
+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::POINT_IN_TIME)
+ original_time = 1.hour.from_now.iso8601
+ new_time = 2.hours.from_now.iso8601
+
+ point_in_time_automation.upsert_field!(
+ "execute_at",
+ "date_time",
+ { "value" => original_time },
+ target: "trigger",
+ )
+
+ expect {
+ put "/admin/plugins/automation/automations/#{point_in_time_automation.id}.json",
+ params: {
+ automation: {
+ script: point_in_time_automation.script,
+ trigger: point_in_time_automation.trigger,
+ fields: [
+ {
+ name: "execute_at",
+ component: "date_time",
+ target: "trigger",
+ metadata: {
+ value: new_time,
+ },
+ },
+ ],
+ },
+ }
+ }.to change { UserHistory.where(custom_type: "update_automation").count }.by(1)
+
+ user_history = UserHistory.last
+ expect(user_history.details).to include("execute_at: #{original_time} → #{new_time}")
+ end
+
+ it "does not log a staff action when no changes are made" do
+ expect {
+ put "/admin/plugins/automation/automations/#{automation.id}.json",
+ params: {
+ automation: {
+ name: automation.name,
+ enabled: automation.enabled,
+ },
+ }
+ }.not_to change { UserHistory.where(custom_type: "update_automation").count }
+ end
+
describe "invalid field’s component" do
it "errors" do
put "/admin/plugins/automation/automations/#{automation.id}.json",
diff --git a/plugins/automation/spec/services/discourse_automation/create_spec.rb b/plugins/automation/spec/services/discourse_automation/create_spec.rb
new file mode 100644
index 00000000000..1cde470c2e2
--- /dev/null
+++ b/plugins/automation/spec/services/discourse_automation/create_spec.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAutomation::Create do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of :script }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:guardian) { admin.guardian }
+ let(:params) { { script: "post", trigger: "topic" } }
+ let(:dependencies) { { guardian: } }
+
+ context "when user can't create an automation" do
+ fab!(:user)
+ let(:guardian) { user.guardian }
+
+ it { is_expected.to fail_a_policy(:can_create_automation) }
+ end
+
+ context "when data is invalid" do
+ before { params[:script] = nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when everything's ok" do
+ it "creates the automation" do
+ expect { result }.to change { DiscourseAutomation::Automation.count }.by(1)
+ end
+
+ it "logs the action" do
+ expect { result }.to change {
+ UserHistory.where(custom_type: "create_automation").count
+ }.by(1)
+
+ user_history = UserHistory.last
+ expect(user_history.details).to include("script: post")
+ expect(user_history.details).to include("trigger: topic")
+ end
+
+ it "does not log empty values" do
+ params[:trigger] = nil
+ result
+
+ user_history = UserHistory.last
+ expect(user_history.details).not_to include("trigger:")
+ end
+ end
+
+ context "with forced triggerable" do
+ let(:script_name) { "test_forced_triggerable" }
+
+ before do
+ DiscourseAutomation::Scriptable.add(script_name) do
+ triggerable! :recurring, { recurrence: { interval: 1, frequency: "day" } }
+ end
+ params[:script] = script_name
+ params[:trigger] = nil
+ end
+
+ after { DiscourseAutomation::Scriptable.remove(script_name) }
+
+ it "applies the forced triggerable" do
+ result
+ expect(result[:automation].trigger).to eq("recurring")
+ end
+ end
+ end
+end
diff --git a/plugins/automation/spec/services/discourse_automation/update_spec.rb b/plugins/automation/spec/services/discourse_automation/update_spec.rb
new file mode 100644
index 00000000000..15b822e424e
--- /dev/null
+++ b/plugins/automation/spec/services/discourse_automation/update_spec.rb
@@ -0,0 +1,147 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAutomation::Update do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of :automation_id }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:automation) { Fabricate(:automation, name: "Original Name", enabled: true) }
+
+ let(:guardian) { admin.guardian }
+ let(:params) { { automation_id: automation.id, name: "New Name" } }
+ let(:dependencies) { { guardian: } }
+
+ context "when user can't update an automation" do
+ fab!(:user)
+ let(:guardian) { user.guardian }
+
+ it { is_expected.to fail_a_policy(:can_update_automation) }
+ end
+
+ context "when data is invalid" do
+ before { params[:automation_id] = nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the automation is not found" do
+ before { params[:automation_id] = 999 }
+
+ it { is_expected.to fail_to_find_a_model(:automation) }
+ end
+
+ context "when everything's ok" do
+ it "updates the automation" do
+ expect { result }.to change { automation.reload.name }.from("Original Name").to("New Name")
+ end
+
+ it "logs the action with changes" do
+ expect { result }.to change {
+ UserHistory.where(custom_type: "update_automation").count
+ }.by(1)
+
+ user_history = UserHistory.last
+ expect(user_history.details).to include("id: #{automation.id}")
+ expect(user_history.details).to include("name: Original Name → New Name")
+ end
+
+ it "does not log when no changes are made" do
+ params[:name] = automation.name
+
+ expect { result }.not_to change {
+ UserHistory.where(custom_type: "update_automation").count
+ }
+ end
+ end
+
+ context "when changing enabled state" do
+ let(:params) { { automation_id: automation.id, enabled: false } }
+
+ it "updates the enabled state" do
+ expect { result }.to change { automation.reload.enabled }.from(true).to(false)
+ end
+
+ it "logs the change" do
+ result
+ user_history = UserHistory.last
+ expect(user_history.details).to include("enabled: true → false")
+ end
+ end
+
+ context "when changing script" do
+ fab!(:automation) do
+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::POINT_IN_TIME, enabled: true)
+ end
+
+ let(:params) { { automation_id: automation.id, script: "new_script" } }
+
+ before do
+ automation.upsert_field!(
+ "execute_at",
+ "date_time",
+ { "value" => 1.hour.from_now.iso8601 },
+ target: "trigger",
+ )
+ end
+
+ it "clears fields and disables automation" do
+ expect(automation.fields).not_to be_empty
+
+ result
+ automation.reload
+ expect(automation.enabled).to eq(false)
+ expect(automation.fields).to be_empty
+ expect(automation.trigger).to be_nil
+ end
+ end
+
+ context "when updating fields" do
+ fab!(:automation) do
+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::POINT_IN_TIME)
+ end
+
+ let(:original_time) { 1.hour.from_now.iso8601 }
+ let(:new_time) { 2.hours.from_now.iso8601 }
+ let(:params) do
+ {
+ automation_id: automation.id,
+ fields: [
+ {
+ name: "execute_at",
+ component: "date_time",
+ target: "trigger",
+ metadata: {
+ value: new_time,
+ },
+ },
+ ],
+ }
+ end
+
+ before do
+ automation.upsert_field!(
+ "execute_at",
+ "date_time",
+ { "value" => original_time },
+ target: "trigger",
+ )
+ end
+
+ it "updates the field" do
+ result
+ automation.reload
+ expect(automation.trigger_field("execute_at")["value"]).to eq(new_time)
+ end
+
+ it "logs field changes" do
+ result
+ user_history = UserHistory.last
+ expect(user_history.details).to include("execute_at: #{original_time} → #{new_time}")
+ end
+ end
+ end
+end