A platform for community discussion. Free, open, simple.
DEV: Refactor automation Update service per PR #36458 feedback (#36771)
Régis Hanole70137509ea8
diff --git a/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rb b/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rbindex 4bd46c860cf..cfd5bf7fa3d 100644--- a/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rb+++ b/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rb@@ -35,9 +35,10 @@ module DiscourseAutomationenddef create- automation_params = params.require(:automation).permit(:script, :trigger)-- DiscourseAutomation::Create.call(params: automation_params.to_h, guardian:) do+ DiscourseAutomation::Create.call(+ params: params.require(:automation).to_unsafe_h,+ guardian:,+ ) doon_success { |automation:| render_serialized_automation(automation) }on_failed_policy(:can_create_automation) { raise Discourse::InvalidAccess }on_failed_contract do |contract|@@ -49,11 +50,8 @@ module DiscourseAutomationenddef update- 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),+ params: params.require(:automation).to_unsafe_h.merge(automation_id: params[:id]),guardian:,) doon_success { |automation:| render_serialized_automation(automation) }diff --git a/plugins/automation/app/services/discourse_automation/action/log_automation_update.rb b/plugins/automation/app/services/discourse_automation/action/log_automation_update.rbnew file mode 100644index 00000000000..d91d340a356--- /dev/null+++ b/plugins/automation/app/services/discourse_automation/action/log_automation_update.rb@@ -0,0 +1,71 @@+# frozen_string_literal: true++module DiscourseAutomation+ module Action+ # Logs changes made to an automation to the staff action log.+ # Compares the current state of the automation with its previous state+ # and logs any differences found in attributes or fields.+ class LogAutomationUpdate < Service::ActionBase+ # @param [DiscourseAutomation::Automation] automation The automation after updates+ # @param [Hash] previous_state The state of the automation before updates+ # @param [Guardian] guardian The guardian for the current user+ param :automation+ param :previous_state+ param :guardian++ def call+ return if changes.empty?++ StaffActionLogger.new(guardian.user).log_custom("update_automation", **details)+ end++ private++ def changes+ @changes ||= attribute_changes.merge(field_changes)+ end++ def details+ { id: automation.id, name: automation.name }.merge(changes)+ end++ def attribute_changes+ %i[name script trigger enabled]+ .index_with { |attr| [previous_state[attr], automation.public_send(attr)] }+ .reject { |_, (prev, curr)| prev == curr }+ .transform_values { |(prev, curr)| "#{format_value(prev)} → #{format_value(curr)}" }+ end++ def field_changes+ current_fields = automation.serialized_fields+ previous_fields = previous_state[:fields]++ (current_fields.keys | previous_fields.keys)+ .sort+ .index_with { |name| [previous_fields[name], current_fields[name]] }+ .reject { |_, (prev, curr)| prev == curr || (field_empty?(prev) && field_empty?(curr)) }+ .transform_values do |(prev, curr)|+ "#{format_field_value(prev)} → #{format_field_value(curr)}"+ end+ end++ def format_value(value)+ value.to_s.presence || empty_value+ end++ def field_empty?(field)+ return true if field.blank?+ value = field["value"]+ !value.in?([true, false]) && 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+ end+enddiff --git a/plugins/automation/app/services/discourse_automation/create.rb b/plugins/automation/app/services/discourse_automation/create.rbindex 9bba2efb3cf..2e2fdb3051f 100644--- a/plugins/automation/app/services/discourse_automation/create.rb+++ b/plugins/automation/app/services/discourse_automation/create.rb@@ -52,11 +52,9 @@ class DiscourseAutomation::Createenddef 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)+ StaffActionLogger.new(guardian.user).log_custom(+ "create_automation",+ automation.slice(:id, :name, :script, :trigger).compact_blank,+ )endenddiff --git a/plugins/automation/app/services/discourse_automation/destroy.rb b/plugins/automation/app/services/discourse_automation/destroy.rbindex ea4421f3bae..dcab5677acf 100644--- a/plugins/automation/app/services/discourse_automation/destroy.rb+++ b/plugins/automation/app/services/discourse_automation/destroy.rb@@ -34,12 +34,10 @@ class DiscourseAutomation::Destroyenddef 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("delete_automation", **details)+ StaffActionLogger.new(guardian.user).log_custom(+ "delete_automation",+ automation.slice(:id, :name, :script, :trigger).compact_blank,+ )enddef destroy_automation(automation:)diff --git a/plugins/automation/app/services/discourse_automation/update.rb b/plugins/automation/app/services/discourse_automation/update.rbindex 9579bb47a88..c877985676a 100644--- a/plugins/automation/app/services/discourse_automation/update.rb+++ b/plugins/automation/app/services/discourse_automation/update.rb@@ -28,7 +28,7 @@ class DiscourseAutomation::Updateendmodel :automation- step :capture_previous_state+ model :previous_state, :capture_previous_statetransaction dostep :apply_forced_triggerable@@ -51,16 +51,10 @@ class DiscourseAutomation::Updateenddef capture_previous_state(automation:)- context[:previous_state] = {- name: automation.name,- script: automation.script,- trigger: automation.trigger,- enabled: automation.enabled,- fields: automation.serialized_fields,- }+ automation.slice(:name, :script, :trigger, :enabled).merge(fields: automation.serialized_fields)end- def apply_forced_triggerable(automation:, params:)+ def apply_forced_triggerable(automation:)if automation.scriptable&.forced_triggerablecontext[:forced_trigger] = automation.scriptable.forced_triggerable[:triggerable].to_send@@ -89,95 +83,37 @@ class DiscourseAutomation::Updatedef 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 =+ params+ .slice(:name, :script)+ .merge(+ last_updated_by_id: guardian.user.id,+ trigger: context[:forced_trigger] || params.trigger,+ )+ .compact_blankattributes[: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 providedif !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)}"+ params.fields.each do |field|+ next if field[:name].blank?+ automation.upsert_field!(+ field[:name],+ field[:component],+ field[:metadata],+ target: field[:target],+ )endend- 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+ automation.assign_attributes(attributes)+ automation.save!(validate: context[:clear_trigger].blank?)+ automation.reloadend- def empty_value- @empty_value ||= I18n.t("discourse_automation.staff_action_logs.empty_value")+ def log_action(automation:, guardian:, previous_state:)+ DiscourseAutomation::Action::LogAutomationUpdate.call(automation, previous_state, guardian)endenddiff --git a/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb b/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rbindex 9d4e2fc93ce..3452fa5a5a5 100644--- a/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb+++ b/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb@@ -78,9 +78,10 @@ describe DiscourseAutomation::AdminAutomationsController dopost "/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}")+ expect(UserHistory.last).to have_attributes(+ custom_type: "create_automation",+ details: a_string_including("script: #{script}"),+ )endend@@ -128,11 +129,15 @@ describe DiscourseAutomation::AdminAutomationsController do}}.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")+ expect(UserHistory.last).to have_attributes(+ custom_type: "update_automation",+ details:+ a_string_including(+ "id: #{automation.id}",+ "name: #{original_name} → new-name",+ "enabled: true → false",+ ),+ )endit "logs field changes" do@@ -168,8 +173,9 @@ describe DiscourseAutomation::AdminAutomationsController do}}.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}")+ expect(UserHistory.last).to have_attributes(+ details: a_string_including("execute_at: #{original_time} → #{new_time}"),+ )endit "does not log a staff action when no changes are made" dodiff --git a/plugins/automation/spec/services/discourse_automation/action/log_automation_update_spec.rb b/plugins/automation/spec/services/discourse_automation/action/log_automation_update_spec.rbnew file mode 100644index 00000000000..608fab193d9--- /dev/null+++ b/plugins/automation/spec/services/discourse_automation/action/log_automation_update_spec.rb@@ -0,0 +1,71 @@+# frozen_string_literal: true++RSpec.describe DiscourseAutomation::Action::LogAutomationUpdate do+ fab!(:admin)+ fab!(:automation) { Fabricate(:automation, name: "Test", enabled: true) }++ let(:guardian) { admin.guardian }+ let(:empty_value) { I18n.t("discourse_automation.staff_action_logs.empty_value") }++ def call(previous_overrides = {})+ previous = {+ name: automation.name,+ script: automation.script,+ trigger: automation.trigger,+ enabled: automation.enabled,+ fields: automation.serialized_fields,+ }.merge(previous_overrides)++ described_class.call(automation, previous, guardian)+ end++ it "does not log when nothing changed" do+ expect { call }.not_to change { UserHistory.count }+ end++ it "logs attribute changes with automation id" do+ automation.update!(name: "New Name", enabled: false)++ expect { call(name: "Old Name", enabled: true) }.to change { UserHistory.count }.by(1)+ expect(UserHistory.last).to have_attributes(+ custom_type: "update_automation",+ details:+ a_string_including(+ "id: #{automation.id}",+ "name: Old Name → New Name",+ "enabled: true → false",+ ),+ )+ end++ it "formats empty values" do+ automation.update!(name: "New Name")+ call(name: nil)+ expect(UserHistory.last.details).to include("name: #{empty_value} → New Name")++ automation.update!(name: "")+ call(name: "Old Name")+ expect(UserHistory.last.details).to include("name: Old Name → #{empty_value}")+ end++ context "with field changes" do+ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::POINT_IN_TIME)+ end++ it "logs field value changes" do+ original_time = 1.hour.from_now.iso8601+ new_time = 2.hours.from_now.iso8601++ automation.upsert_field!(+ "execute_at",+ "date_time",+ { "value" => new_time },+ target: "trigger",+ )+ call(fields: { "execute_at" => { "value" => original_time, "target" => "trigger" } })++ expect(UserHistory.last.details).to include("execute_at: #{original_time} → #{new_time}")+ end+ end+enddiff --git a/plugins/automation/spec/services/discourse_automation/create_spec.rb b/plugins/automation/spec/services/discourse_automation/create_spec.rbindex 1cde470c2e2..6786013943d 100644--- a/plugins/automation/spec/services/discourse_automation/create_spec.rb+++ b/plugins/automation/spec/services/discourse_automation/create_spec.rb@@ -28,6 +28,8 @@ RSpec.describe DiscourseAutomation::Create doendcontext "when everything's ok" do+ it { is_expected.to run_successfully }+it "creates the automation" doexpect { result }.to change { DiscourseAutomation::Automation.count }.by(1)end@@ -36,18 +38,15 @@ RSpec.describe DiscourseAutomation::Create doexpect { 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")+ expect(UserHistory.last).to have_attributes(+ details: a_string_including("script: post", "trigger: topic"),+ )endit "does not log empty values" doparams[:trigger] = nilresult-- user_history = UserHistory.last- expect(user_history.details).not_to include("trigger:")+ expect(UserHistory.last.details).not_to include("trigger:")endend@@ -65,7 +64,6 @@ RSpec.describe DiscourseAutomation::Create doafter { DiscourseAutomation::Scriptable.remove(script_name) }it "applies the forced triggerable" do- resultexpect(result[:automation].trigger).to eq("recurring")endenddiff --git a/plugins/automation/spec/services/discourse_automation/destroy_spec.rb b/plugins/automation/spec/services/discourse_automation/destroy_spec.rbindex af6ea748e09..42d9acb2f4e 100644--- a/plugins/automation/spec/services/discourse_automation/destroy_spec.rb+++ b/plugins/automation/spec/services/discourse_automation/destroy_spec.rb@@ -34,16 +34,24 @@ RSpec.describe DiscourseAutomation::Destroy doendcontext "when everything's ok" do- it "logs the action" do- expect { result }.to change { UserHistory.count }.by(1)- expect(UserHistory.last.details).to eq(- "id: #{automation.id}\nname: #{automation.name}\nscript: #{automation.script}\ntrigger: #{automation.trigger}",- )- end+ it { is_expected.to run_successfully }it "destroys the automation" doexpect { result }.to change { DiscourseAutomation::Automation.count }.by(-1)end++ it "logs the action" do+ expect { result }.to change { UserHistory.count }.by(1)+ expect(UserHistory.last).to have_attributes(+ details:+ a_string_including(+ "id: #{automation.id}",+ "name: #{automation.name}",+ "script: #{automation.script}",+ "trigger: #{automation.trigger}",+ ),+ )+ endendendenddiff --git a/plugins/automation/spec/services/discourse_automation/update_spec.rb b/plugins/automation/spec/services/discourse_automation/update_spec.rbindex 15b822e424e..903b6d4de44 100644--- a/plugins/automation/spec/services/discourse_automation/update_spec.rb+++ b/plugins/automation/spec/services/discourse_automation/update_spec.rb@@ -35,6 +35,8 @@ RSpec.describe DiscourseAutomation::Update doendcontext "when everything's ok" do+ it { is_expected.to run_successfully }+it "updates the automation" doexpect { result }.to change { automation.reload.name }.from("Original Name").to("New Name")end@@ -43,15 +45,13 @@ RSpec.describe DiscourseAutomation::Update doexpect { 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")+ expect(UserHistory.last).to have_attributes(+ details: a_string_including("id: #{automation.id}", "name: Original Name → New Name"),+ )endit "does not log when no changes are made" doparams[:name] = automation.name-expect { result }.not_to change {UserHistory.where(custom_type: "update_automation").count}@@ -61,14 +61,17 @@ RSpec.describe DiscourseAutomation::Update docontext "when changing enabled state" dolet(:params) { { automation_id: automation.id, enabled: false } }+ it { is_expected.to run_successfully }+it "updates the enabled state" doexpect { result }.to change { automation.reload.enabled }.from(true).to(false)endit "logs the change" doresult- user_history = UserHistory.last- expect(user_history.details).to include("enabled: true → false")+ expect(UserHistory.last).to have_attributes(+ details: a_string_including("enabled: true → false"),+ )endend@@ -90,12 +93,8 @@ RSpec.describe DiscourseAutomation::Update doit "clears fields and disables automation" doexpect(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+ expect(automation.reload).to have_attributes(enabled: false, trigger: nil, fields: [])endend@@ -131,6 +130,8 @@ RSpec.describe DiscourseAutomation::Update do)end+ it { is_expected.to run_successfully }+it "updates the field" doresultautomation.reload@@ -139,8 +140,9 @@ RSpec.describe DiscourseAutomation::Update doit "logs field changes" doresult- user_history = UserHistory.last- expect(user_history.details).to include("execute_at: #{original_time} → #{new_time}")+ expect(UserHistory.last).to have_attributes(+ details: a_string_including("execute_at: #{original_time} → #{new_time}"),+ )endendend