A platform for community discussion. Free, open, simple.
FEATURE: Merge discourse-automation (#26432)
Osama Sayegh3d4faf327233
diff --git a/.gitignore b/.gitignoreindex dfd3e201c92..d576b73cc0e 100644--- a/.gitignore+++ b/.gitignore@@ -40,6 +40,8 @@!/plugins/discourse-narrative-bot!/plugins/discourse-presence!/plugins/discourse-lazy-videos/+!/plugins/automation/+/plugins/automation/gems!/plugins/chat/!/plugins/poll/!/plugins/styleguidediff --git a/app/models/post_custom_field.rb b/app/models/post_custom_field.rbindex 91384800b96..346711fcd96 100644--- a/app/models/post_custom_field.rb+++ b/app/models/post_custom_field.rb@@ -19,9 +19,11 @@ end## Indexes#-# index_post_custom_fields_on_name_and_value (name, "left"(value, 200))-# index_post_custom_fields_on_notice (post_id) UNIQUE WHERE ((name)::text = 'notice'::text)-# index_post_custom_fields_on_post_id (post_id) UNIQUE WHERE ((name)::text = 'missing uploads'::text)-# index_post_custom_fields_on_post_id_and_name (post_id,name)-# index_post_id_where_missing_uploads_ignored (post_id) UNIQUE WHERE ((name)::text = 'missing uploads ignored'::text)+# idx_post_custom_fields_discourse_automation_unique_id_partial (post_id,value) UNIQUE WHERE ((name)::text = 'discourse_automation_ids'::text)+# index_post_custom_fields_on_name_and_value (name, "left"(value, 200))+# index_post_custom_fields_on_notice (post_id) UNIQUE WHERE ((name)::text = 'notice'::text)+# index_post_custom_fields_on_post_id (post_id) UNIQUE WHERE ((name)::text = 'missing uploads'::text)+# index_post_custom_fields_on_post_id_and_name (post_id,name)+# index_post_custom_fields_on_stalled_wiki_triggered_at (post_id) UNIQUE WHERE ((name)::text = 'stalled_wiki_triggered_at'::text)+# index_post_id_where_missing_uploads_ignored (post_id) UNIQUE WHERE ((name)::text = 'missing uploads ignored'::text)#diff --git a/app/models/topic_custom_field.rb b/app/models/topic_custom_field.rbindex 6a8a799bad3..25afd75a1df 100644--- a/app/models/topic_custom_field.rb+++ b/app/models/topic_custom_field.rb@@ -19,6 +19,8 @@ end## Indexes#-# index_topic_custom_fields_on_topic_id_and_name (topic_id,name)-# topic_custom_fields_value_key_idx (value,name) WHERE ((value IS NOT NULL) AND (char_length(value) < 400))+# idx_topic_custom_fields_auto_responder_triggered_ids_partial (topic_id,value) UNIQUE WHERE ((name)::text = 'auto_responder_triggered_ids'::text)+# idx_topic_custom_fields_discourse_automation_unique_id_partial (topic_id,value) UNIQUE WHERE ((name)::text = 'discourse_automation_ids'::text)+# index_topic_custom_fields_on_topic_id_and_name (topic_id,name)+# topic_custom_fields_value_key_idx (value,name) WHERE ((value IS NOT NULL) AND (char_length(value) < 400))#diff --git a/app/models/user_custom_field.rb b/app/models/user_custom_field.rbindex e4d9b4f9182..931093bf579 100644--- a/app/models/user_custom_field.rb+++ b/app/models/user_custom_field.rb@@ -26,5 +26,6 @@ end## Indexes#-# index_user_custom_fields_on_user_id_and_name (user_id,name)+# idx_user_custom_fields_discourse_automation_unique_id_partial (user_id,value) UNIQUE WHERE ((name)::text = 'discourse_automation_ids'::text)+# index_user_custom_fields_on_user_id_and_name (user_id,name)#diff --git a/lib/plugin/metadata.rb b/lib/plugin/metadata.rbindex 5b7c9681bbd..8ee21574963 100644--- a/lib/plugin/metadata.rb+++ b/lib/plugin/metadata.rb@@ -16,7 +16,6 @@ class Plugin::Metadatadiscourse-apple-authdiscourse-assigndiscourse-auto-deactivate- discourse-automationdiscourse-bbcodediscourse-bbcode-colordiscourse-bcc@@ -91,6 +90,7 @@ class Plugin::Metadatadiscourse-yearly-reviewdiscourse-zendesk-plugindiscourse-zoom+ automationdocker_managerchatpolldiff --git a/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rb b/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rbnew file mode 100644index 00000000000..5cf6cb0c423--- /dev/null+++ b/plugins/automation/app/controllers/discourse_automation/admin_automations_controller.rb@@ -0,0 +1,96 @@+# frozen_string_literal: true++module DiscourseAutomation+ class AdminAutomationsController < ::Admin::AdminController+ requires_plugin DiscourseAutomation::PLUGIN_NAME++ def index+ automations = DiscourseAutomation::Automation.order(:name).all+ serializer =+ ActiveModel::ArraySerializer.new(+ automations,+ each_serializer: DiscourseAutomation::AutomationSerializer,+ root: "automations",+ ).as_json+ render_json_dump(serializer)+ end++ def show+ automation = DiscourseAutomation::Automation.find(params[:id])+ render_serialized_automation(automation)+ end++ def create+ automation_params = params.require(:automation).permit(:name, :script, :trigger)++ automation =+ DiscourseAutomation::Automation.new(+ automation_params.merge(last_updated_by_id: current_user.id),+ )+ if automation.scriptable.forced_triggerable+ automation.trigger = scriptable.forced_triggerable[:triggerable].to_s+ end++ automation.save!++ render_serialized_automation(automation)+ end++ def update+ params.require(:automation)++ automation = DiscourseAutomation::Automation.find(params[:id])+ 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 automation.trigger != params[:automation][:trigger]+ params[:automation][:fields] = []+ attributes[:enabled] = false+ automation.fields.destroy_all+ end++ 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.tap { |r| r.assign_attributes(attributes) }.save!+ end++ render_serialized_automation(automation)+ end++ def destroy+ automation = DiscourseAutomation::Automation.find(params[:id])+ automation.destroy!+ render json: success_json+ end++ private++ def render_serialized_automation(automation)+ serializer =+ DiscourseAutomation::AutomationSerializer.new(automation, root: "automation").as_json+ render_json_dump(serializer)+ end+ end+enddiff --git a/plugins/automation/app/controllers/discourse_automation/admin_controller.rb b/plugins/automation/app/controllers/discourse_automation/admin_controller.rbnew file mode 100644index 00000000000..aa064b88e59--- /dev/null+++ b/plugins/automation/app/controllers/discourse_automation/admin_controller.rb@@ -0,0 +1,16 @@+# frozen_string_literal: true++module DiscourseAutomation+ class AdminController < ::Admin::AdminController+ requires_plugin DiscourseAutomation::PLUGIN_NAME++ def index+ end++ def new+ end++ def edit+ end+ end+enddiff --git a/plugins/automation/app/controllers/discourse_automation/admin_scriptables_controller.rb b/plugins/automation/app/controllers/discourse_automation/admin_scriptables_controller.rbnew file mode 100644index 00000000000..83d6fe46801--- /dev/null+++ b/plugins/automation/app/controllers/discourse_automation/admin_scriptables_controller.rb@@ -0,0 +1,23 @@+# frozen_string_literal: true++module DiscourseAutomation+ class AdminScriptablesController < ::Admin::AdminController+ requires_plugin DiscourseAutomation::PLUGIN_NAME++ def index+ scriptables =+ DiscourseAutomation::Scriptable.all.map do |s|+ id = s.to_s.gsub(/^__scriptable_/, "")+ {+ id: id,+ name: I18n.t("discourse_automation.scriptables.#{id}.title"),+ description: I18n.t("discourse_automation.scriptables.#{id}.description", default: ""),+ doc: I18n.t("discourse_automation.scriptables.#{id}.doc", default: ""),+ }+ end++ scriptables.sort_by! { |s| s[:name] }+ render_json_dump(scriptables: scriptables)+ end+ end+enddiff --git a/plugins/automation/app/controllers/discourse_automation/admin_triggerables_controller.rb b/plugins/automation/app/controllers/discourse_automation/admin_triggerables_controller.rbnew file mode 100644index 00000000000..3c6be2891e9--- /dev/null+++ b/plugins/automation/app/controllers/discourse_automation/admin_triggerables_controller.rb@@ -0,0 +1,30 @@+# frozen_string_literal: true++module DiscourseAutomation+ class AdminTriggerablesController < ::Admin::AdminController+ requires_plugin DiscourseAutomation::PLUGIN_NAME++ def index+ if params[:automation_id].present?+ automation = DiscourseAutomation::Automation.find(params[:automation_id])+ scriptable = automation.scriptable+ triggerables = scriptable.triggerables+ else+ triggerables = DiscourseAutomation::Triggerable.all+ end++ triggerables =+ triggerables.map do |s|+ id = s.to_s.gsub(/^__triggerable_/, "")+ {+ id: id,+ name: I18n.t("discourse_automation.triggerables.#{id}.title"),+ description: I18n.t("discourse_automation.triggerables.#{id}.description", default: ""),+ doc: I18n.t("discourse_automation.triggerables.#{id}.doc", default: ""),+ }+ end++ render_json_dump(triggerables: triggerables)+ end+ end+enddiff --git a/plugins/automation/app/controllers/discourse_automation/append_last_checked_by_controller.rb b/plugins/automation/app/controllers/discourse_automation/append_last_checked_by_controller.rbnew file mode 100644index 00000000000..b2c9c727f58--- /dev/null+++ b/plugins/automation/app/controllers/discourse_automation/append_last_checked_by_controller.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++module DiscourseAutomation+ class AppendLastCheckedByController < ApplicationController+ requires_plugin DiscourseAutomation::PLUGIN_NAME+ requires_login++ def post_checked+ post = Post.find(params[:post_id])+ guardian.ensure_can_edit!(post)++ topic = post.topic+ raise Discourse::NotFound if topic.blank?++ topic.custom_fields[DiscourseAutomation::TOPIC_LAST_CHECKED_BY] = current_user.username+ topic.custom_fields[DiscourseAutomation::TOPIC_LAST_CHECKED_AT] = Time.zone.now.to_s+ topic.save_custom_fields++ post.rebake!++ render json: success_json+ end+ end+enddiff --git a/plugins/automation/app/controllers/discourse_automation/automations_controller.rb b/plugins/automation/app/controllers/discourse_automation/automations_controller.rbnew file mode 100644index 00000000000..eb0147838e9--- /dev/null+++ b/plugins/automation/app/controllers/discourse_automation/automations_controller.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true++module DiscourseAutomation+ class AutomationsController < ApplicationController+ requires_plugin DiscourseAutomation::PLUGIN_NAME+ before_action :ensure_admin++ def trigger+ automation = DiscourseAutomation::Automation.find(params[:id])+ automation.trigger_in_background!(params.merge(kind: DiscourseAutomation::Triggers::API_CALL))+ render json: success_json+ end+ end+enddiff --git a/plugins/automation/app/controllers/discourse_automation/user_global_notices_controller.rb b/plugins/automation/app/controllers/discourse_automation/user_global_notices_controller.rbnew file mode 100644index 00000000000..edadec9e4a0--- /dev/null+++ b/plugins/automation/app/controllers/discourse_automation/user_global_notices_controller.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++module DiscourseAutomation+ class UserGlobalNoticesController < ApplicationController+ requires_plugin DiscourseAutomation::PLUGIN_NAME+ requires_login++ def destroy+ notice =+ DiscourseAutomation::UserGlobalNotice.find_by(user_id: current_user.id, id: params[:id])++ raise Discourse::NotFound unless notice++ notice.destroy!++ head :no_content+ end+ end+enddiff --git a/plugins/automation/app/jobs/regular/discourse_automation_call_zapier_webhook.rb b/plugins/automation/app/jobs/regular/discourse_automation_call_zapier_webhook.rbnew file mode 100644index 00000000000..30180f7dbc1--- /dev/null+++ b/plugins/automation/app/jobs/regular/discourse_automation_call_zapier_webhook.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++module Jobs+ class DiscourseAutomationCallZapierWebhook < ::Jobs::Base+ def execute(args)+ RateLimiter.new(nil, "discourse_automation_call_zapier", 5, 30).performed!++ result =+ Excon.post(+ args["webhook_url"],+ body: args["context"].to_json,+ headers: {+ "Content-Type" => "application/json",+ "Accept" => "application/json",+ },+ )++ if result.status != 200+ Rails.logger.warn(+ "Failed to call Zapier webhook at #{args["webhook_url"]} Status: #{result.status}: #{result.status_line}",+ )+ end+ end+ end+enddiff --git a/plugins/automation/app/jobs/regular/discourse_automation_trigger.rb b/plugins/automation/app/jobs/regular/discourse_automation_trigger.rbnew file mode 100644index 00000000000..ad1134acdb1--- /dev/null+++ b/plugins/automation/app/jobs/regular/discourse_automation_trigger.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++module Jobs+ class DiscourseAutomationTrigger < ::Jobs::Base+ RETRY_TIMES = [5.minute, 15.minute, 120.minute]++ sidekiq_options retry: RETRY_TIMES.size++ sidekiq_retry_in do |count, exception|+ # returning nil/0 will trigger the default sidekiq+ # retry formula+ #+ # See https://github.com/mperham/sidekiq/blob/3330df0ee37cfd3e0cd3ef01e3e66b584b99d488/lib/sidekiq/job_retry.rb#L216-L234+ case exception.wrapped+ when SocketError+ return RETRY_TIMES[count]+ end+ end++ def execute(args)+ automation = DiscourseAutomation::Automation.find_by(id: args[:automation_id], enabled: true)++ return if !automation++ context = DiscourseAutomation::Automation.deserialize_context(args[:context])++ automation.running_in_background!+ automation.trigger!(context)+ end+ end+enddiff --git a/plugins/automation/app/jobs/scheduled/discourse_automation_tracker.rb b/plugins/automation/app/jobs/scheduled/discourse_automation_tracker.rbnew file mode 100644index 00000000000..2e8f60542c6--- /dev/null+++ b/plugins/automation/app/jobs/scheduled/discourse_automation_tracker.rb@@ -0,0 +1,44 @@+# frozen_string_literal: true++module Jobs+ class DiscourseAutomationTracker < ::Jobs::Scheduled+ every 1.minute++ BATCH_LIMIT ||= 300++ def execute(_args = nil)+ return unless SiteSetting.discourse_automation_enabled++ DiscourseAutomation::PendingAutomation+ .includes(:automation)+ .limit(BATCH_LIMIT)+ .where("execute_at < ?", Time.now)+ .find_each { |pending_automation| run_pending_automation(pending_automation) }++ DiscourseAutomation::PendingPm+ .includes(:automation)+ .limit(BATCH_LIMIT)+ .where("execute_at < ?", Time.now)+ .find_each { |pending_pm| send_pending_pm(pending_pm) }+ end++ def send_pending_pm(pending_pm)+ DiscourseAutomation::Scriptable::Utils.send_pm(+ pending_pm.attributes.slice("target_usernames", "title", "raw"),+ sender: pending_pm.sender,+ prefers_encrypt: pending_pm.prefers_encrypt,+ )++ pending_pm.destroy!+ end++ def run_pending_automation(pending_automation)+ pending_automation.automation.trigger!(+ "kind" => pending_automation.automation.trigger,+ "execute_at" => pending_automation.execute_at,+ )++ pending_automation.destroy!+ end+ end+enddiff --git a/plugins/automation/app/jobs/scheduled/stalled_topic_tracker.rb b/plugins/automation/app/jobs/scheduled/stalled_topic_tracker.rbnew file mode 100644index 00000000000..558fcde2d31--- /dev/null+++ b/plugins/automation/app/jobs/scheduled/stalled_topic_tracker.rb@@ -0,0 +1,41 @@+# frozen_string_literal: true++module Jobs+ class StalledTopicTracker < ::Jobs::Scheduled+ every 1.hour++ def execute(_args = nil)+ name = DiscourseAutomation::Triggers::STALLED_TOPIC++ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each do |automation|+ fields = automation.serialized_fields+ stalled_after = fields.dig("stalled_after", "value")+ stalled_duration = ISO8601::Duration.new(stalled_after).to_seconds+ stalled_date = stalled_duration.seconds.ago+ categories = fields.dig("categories", "value")+ tags = fields.dig("tags", "value")++ StalledTopicFinder+ .call(stalled_date, categories: categories, tags: tags)+ .each do |result|+ topic = Topic.find_by(id: result.id)+ next unless topic++ run_trigger(automation, topic)+ end+ end+ end++ def run_trigger(automation, topic)+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::STALLED_TOPIC,+ "topic" => topic,+ "placeholders" => {+ "topic_url" => topic.url,+ },+ )+ end+ end+enddiff --git a/plugins/automation/app/jobs/scheduled/stalled_wiki_tracker.rb b/plugins/automation/app/jobs/scheduled/stalled_wiki_tracker.rbnew file mode 100644index 00000000000..58dc17caa59--- /dev/null+++ b/plugins/automation/app/jobs/scheduled/stalled_wiki_tracker.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++module Jobs+ class StalledWikiTracker < ::Jobs::Scheduled+ every 10.minutes++ def execute(_args = nil)+ name = DiscourseAutomation::Triggers::STALLED_WIKI++ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each do |automation|+ stalled_after = automation.trigger_field("stalled_after")+ stalled_duration = ISO8601::Duration.new(stalled_after["value"]).to_seconds+ finder = Post.where("wiki = TRUE AND last_version_at <= ?", stalled_duration.seconds.ago)++ restricted_category = automation.trigger_field("restricted_category")+ if restricted_category["value"]+ finder =+ finder.joins(:topic).where("topics.category_id = ?", restricted_category["value"])+ end++ finder.each do |post|+ last_trigger_date = post.custom_fields["stalled_wiki_triggered_at"]+ if last_trigger_date+ retriggered_after = automation.trigger_field("retriggered_after")+ retrigger_duration = ISO8601::Duration.new(retriggered_after["value"]).to_seconds++ next if Time.parse(last_trigger_date) + retrigger_duration >= Time.zone.now+ end++ post.upsert_custom_fields(stalled_wiki_triggered_at: Time.zone.now)+ run_trigger(automation, post)+ end+ end+ end++ def run_trigger(automation, post)+ user_ids =+ (+ post.post_revisions.order("post_revisions.created_at DESC").limit(5).pluck(:user_id) ++ [post.user_id]+ ).compact.uniq++ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::STALLED_WIKI,+ "post" => post,+ "topic" => post.topic,+ "usernames" => User.where(id: user_ids).pluck(:username),+ "placeholders" => {+ "wiki_url" => Discourse.base_url + post.url,+ },+ )+ end+ end+enddiff --git a/plugins/automation/app/models/discourse_automation/automation.rb b/plugins/automation/app/models/discourse_automation/automation.rbnew file mode 100644index 00000000000..15b7b0ccc0f--- /dev/null+++ b/plugins/automation/app/models/discourse_automation/automation.rb@@ -0,0 +1,172 @@+# frozen_string_literal: true++module DiscourseAutomation+ class Automation < ActiveRecord::Base+ self.table_name = "discourse_automation_automations"++ has_many :fields,+ class_name: "DiscourseAutomation::Field",+ dependent: :delete_all,+ foreign_key: "automation_id"+ has_many :pending_automations,+ class_name: "DiscourseAutomation::PendingAutomation",+ dependent: :delete_all,+ foreign_key: "automation_id"+ has_many :pending_pms,+ class_name: "DiscourseAutomation::PendingPm",+ dependent: :delete_all,+ foreign_key: "automation_id"++ validates :script, presence: true+ validate :validate_trigger_fields++ attr_accessor :running_in_background++ def running_in_background!+ @running_in_background = true+ end++ MIN_NAME_LENGTH = 5+ MAX_NAME_LENGTH = 30+ validates :name, length: { in: MIN_NAME_LENGTH..MAX_NAME_LENGTH }++ def attach_custom_field(target)+ if ![Topic, Post, User].any? { |m| target.is_a?(m) }+ raise "Expected an instance of Topic/Post/User."+ end++ now = Time.now+ fk = target.custom_fields_fk+ row = {+ fk => target.id,+ :name => DiscourseAutomation::CUSTOM_FIELD,+ :value => id,+ :created_at => now,+ :updated_at => now,+ }++ relation = "#{target.class.name}CustomField".constantize+ relation.upsert(+ row,+ unique_by:+ "idx_#{target.class.name.downcase}_custom_fields_discourse_automation_unique_id_partial",+ )+ end++ def detach_custom_field(target)+ if ![Topic, Post, User].any? { |m| target.is_a?(m) }+ raise "Expected an instance of Topic/Post/User."+ end++ fk = target.custom_fields_fk+ relation = "#{target.class.name}CustomField".constantize+ relation.where(+ fk => target.id,+ :name => DiscourseAutomation::CUSTOM_FIELD,+ :value => id,+ ).delete_all+ end++ def trigger_field(name)+ field = fields.find_by(target: "trigger", name: name)+ field ? field.metadata : {}+ end++ def has_trigger_field?(name)+ !!fields.find_by(target: "trigger", name: name)+ end++ def script_field(name)+ field = fields.find_by(target: "script", name: name)+ field ? field.metadata : {}+ end++ def upsert_field!(name, component, metadata, target: "script")+ field = fields.find_or_initialize_by(name: name, component: component, target: target)+ field.update!(metadata: metadata)+ end++ def self.deserialize_context(context)+ new_context = ActiveSupport::HashWithIndifferentAccess.new++ context.each do |key, value|+ if key.start_with?("_serialized_")+ new_key = key[12..-1]+ found = nil+ if value["class"] == "Symbol"+ found = value["value"].to_sym+ else+ found = value["class"].constantize.find_by(id: value["id"])+ end+ new_context[new_key] = found+ else+ new_context[key] = value+ end+ end+ new_context+ end++ def self.serialize_context(context)+ new_context = {}+ context.each do |k, v|+ if v.is_a?(Symbol)+ new_context["_serialized_#{k}"] = { "class" => "Symbol", "value" => v.to_s }+ elsif v.is_a?(ActiveRecord::Base)+ new_context["_serialized_#{k}"] = { "class" => v.class.name, "id" => v.id }+ else+ new_context[k] = v+ end+ end+ new_context+ end++ def trigger_in_background!(context = {})+ Jobs.enqueue(+ :discourse_automation_trigger,+ automation_id: id,+ context: self.class.serialize_context(context),+ )+ end++ def trigger!(context = {})+ if enabled+ if scriptable.background && !running_in_background+ trigger_in_background!(context)+ else+ triggerable&.on_call&.call(self, serialized_fields)+ scriptable.script.call(context, serialized_fields, self)+ end+ end+ end++ def triggerable+ trigger && @triggerable ||= DiscourseAutomation::Triggerable.new(trigger, self)+ end++ def scriptable+ script && @scriptable ||= DiscourseAutomation::Scriptable.new(script, self)+ end++ def serialized_fields+ fields+ &.pluck(:name, :metadata)+ &.reduce({}) do |acc, hash|+ name, field = hash+ acc[name] = field+ acc+ end || {}+ end++ def reset!+ pending_automations.delete_all+ pending_pms.delete_all+ scriptable&.on_reset&.call(self)+ end++ private++ def validate_trigger_fields+ !triggerable || triggerable.valid?(self)+ end+ end+enddiff --git a/plugins/automation/app/models/discourse_automation/field.rb b/plugins/automation/app/models/discourse_automation/field.rbnew file mode 100644index 00000000000..567598fc251--- /dev/null+++ b/plugins/automation/app/models/discourse_automation/field.rb@@ -0,0 +1,246 @@+# frozen_string_literal: true++module DiscourseAutomation+ class Field < ActiveRecord::Base+ self.table_name = "discourse_automation_fields"++ belongs_to :automation, class_name: "DiscourseAutomation::Automation"++ around_save :on_update_callback++ def on_update_callback+ previous_fields = automation.serialized_fields++ automation.reset!++ yield++ automation&.triggerable&.on_update&.call(+ automation,+ automation.serialized_fields,+ previous_fields,+ )+ end++ validate :required_field+ def required_field+ if template && template[:required] && metadata && metadata["value"].blank?+ raise_required_field(name, target, targetable)+ end+ end++ validate :validator+ def validator+ if template && template[:validator]+ error = template[:validator].call(metadata["value"])+ errors.add(:base, error) if error+ end+ end++ def targetable+ target == "trigger" ? automation.triggerable : automation.scriptable+ end++ def template+ targetable&.fields&.find do |tf|+ targetable.id == target && tf[:name].to_s == name && tf[:component].to_s == component+ end+ end++ validate :metadata_schema+ def metadata_schema+ if !(targetable.components.include?(component.to_sym))+ errors.add(+ :base,+ I18n.t(+ "discourse_automation.models.fields.invalid_field",+ component: component,+ target: target,+ target_name: targetable.name,+ ),+ )+ else+ schema = SCHEMAS[component]+ if !schema ||+ !JSONSchemer.schema({ "type" => "object", "properties" => schema }).valid?(metadata)+ errors.add(+ :base,+ I18n.t(+ "discourse_automation.models.fields.invalid_metadata",+ component: component,+ field: name,+ ),+ )+ end+ end+ end++ SCHEMAS = {+ "key-value" => {+ "type" => "array",+ "uniqueItems" => true,+ "items" => {+ "type" => "object",+ "title" => "group",+ "properties" => {+ "key" => {+ "type" => "string",+ },+ "value" => {+ "type" => "string",+ },+ },+ },+ },+ "choices" => {+ "value" => {+ "type" => %w[string integer null],+ },+ },+ "tags" => {+ "value" => {+ "type" => "array",+ "items" => [{ type: "string" }],+ },+ },+ "trust-levels" => {+ "value" => {+ "type" => "array",+ "items" => [{ type: "integer" }],+ },+ },+ "categories" => {+ "value" => {+ "type" => "array",+ "items" => [{ type: "string" }],+ },+ },+ "category" => {+ "value" => {+ "type" => %w[string integer null],+ },+ },+ "category_notification_level" => {+ "value" => {+ "type" => "integer",+ },+ },+ "custom_field" => {+ "value" => {+ "type" => "integer",+ },+ },+ "custom_fields" => {+ "value" => {+ "type" => [{ type: "string" }],+ },+ },+ "user" => {+ "value" => {+ "type" => "string",+ },+ },+ "user_profile" => {+ "value" => {+ "type" => "array",+ "items" => [{ type: "string" }],+ },+ },+ "users" => {+ "value" => {+ "type" => "array",+ "items" => [{ type: "string" }],+ },+ },+ "text" => {+ "value" => {+ "type" => %w[string integer null],+ },+ },+ "post" => {+ "value" => {+ "type" => %w[string integer null],+ },+ },+ "message" => {+ "value" => {+ "type" => %w[string integer null],+ },+ },+ "boolean" => {+ "value" => {+ "type" => ["boolean"],+ },+ },+ "text_list" => {+ "value" => {+ "type" => "array",+ "items" => [{ type: "string" }],+ },+ },+ "date_time" => {+ "value" => {+ "type" => "string",+ },+ },+ "group" => {+ "value" => {+ "type" => "integer",+ },+ },+ "email_group_user" => {+ "value" => {+ "type" => "array",+ "items" => [{ type: "string" }],+ },+ },+ "pms" => {+ type: "array",+ items: [+ {+ type: "object",+ properties: {+ "raw" => {+ "type" => "string",+ },+ "title" => {+ "type" => "string",+ },+ "delay" => {+ "type" => "integer",+ },+ "prefers_encrypt" => {+ "type" => "boolean",+ },+ },+ },+ ],+ },+ "period" => {+ "type" => "object",+ "properties" => {+ "interval" => {+ "type" => "integer",+ },+ "frequency" => {+ "type" => "string",+ },+ },+ },+ }++ private++ def raise_required_field(name, target, targetable)+ errors.add(+ :base,+ I18n.t(+ "discourse_automation.models.fields.required_field",+ name: name,+ target: target,+ target_name: targetable.name,+ ),+ )+ end+ end+enddiff --git a/plugins/automation/app/models/discourse_automation/pending_automation.rb b/plugins/automation/app/models/discourse_automation/pending_automation.rbnew file mode 100644index 00000000000..f6c4e0e6e65--- /dev/null+++ b/plugins/automation/app/models/discourse_automation/pending_automation.rb@@ -0,0 +1,9 @@+# frozen_string_literal: true++module DiscourseAutomation+ class PendingAutomation < ActiveRecord::Base+ self.table_name = "discourse_automation_pending_automations"++ belongs_to :automation, class_name: "DiscourseAutomation::Automation"+ end+enddiff --git a/plugins/automation/app/models/discourse_automation/pending_pm.rb b/plugins/automation/app/models/discourse_automation/pending_pm.rbnew file mode 100644index 00000000000..b696ee09c27--- /dev/null+++ b/plugins/automation/app/models/discourse_automation/pending_pm.rb@@ -0,0 +1,9 @@+# frozen_string_literal: true++module DiscourseAutomation+ class PendingPm < ActiveRecord::Base+ self.table_name = "discourse_automation_pending_pms"++ belongs_to :automation, class_name: "DiscourseAutomation::Automation"+ end+enddiff --git a/plugins/automation/app/models/discourse_automation/user_global_notice.rb b/plugins/automation/app/models/discourse_automation/user_global_notice.rbnew file mode 100644index 00000000000..d41d4643592--- /dev/null+++ b/plugins/automation/app/models/discourse_automation/user_global_notice.rb@@ -0,0 +1,9 @@+# frozen_string_literal: true++module DiscourseAutomation+ class UserGlobalNotice < ActiveRecord::Base+ self.table_name = "discourse_automation_user_global_notices"++ belongs_to :user+ end+enddiff --git a/plugins/automation/app/queries/stalled_topic_finder.rb b/plugins/automation/app/queries/stalled_topic_finder.rbnew file mode 100644index 00000000000..e4e59fdd6d4--- /dev/null+++ b/plugins/automation/app/queries/stalled_topic_finder.rb@@ -0,0 +1,44 @@+# frozen_string_literal: true++class StalledTopicFinder+ def self.call(stalled_date, tags: nil, categories: nil)+ sql = <<~SQL+ SELECT t.id+ FROM topics t+ SQL++ sql += <<~SQL if tags+ JOIN topic_tags ON topic_tags.topic_id = t.id+ JOIN tags+ ON tags.name IN (:tags)+ AND tags.id = topic_tags.tag_id+ SQL++ sql += <<~SQL+ WHERE t.deleted_at IS NULL+ AND t.posts_count > 0+ AND t.archetype != 'private_message'+ AND NOT t.closed+ AND NOT t.archived+ AND NOT EXISTS (+ SELECT p.id+ FROM posts p+ WHERE t.id = p.topic_id+ AND p.deleted_at IS NULL+ AND t.user_id = p.user_id+ AND p.created_at > :stalled_date+ LIMIT 1+ )+ SQL++ sql += <<~SQL if categories+ AND t.category_id IN (:categories)+ SQL++ sql += <<~SQL+ LIMIT 250+ SQL++ DB.query(sql, categories: categories, tags: tags, stalled_date: stalled_date)+ end+enddiff --git a/plugins/automation/app/serializers/discourse_automation/automation_serializer.rb b/plugins/automation/app/serializers/discourse_automation/automation_serializer.rbnew file mode 100644index 00000000000..b5ca7079447--- /dev/null+++ b/plugins/automation/app/serializers/discourse_automation/automation_serializer.rb@@ -0,0 +1,120 @@+# frozen_string_literal: true++module DiscourseAutomation+ class AutomationSerializer < ApplicationSerializer+ attributes :id+ attributes :name+ attributes :enabled+ attributes :script+ attributes :trigger+ attributes :updated_at+ attributes :last_updated_by+ attributes :next_pending_automation_at+ attributes :placeholders++ def last_updated_by+ BasicUserSerializer.new(+ User.find_by(id: object.last_updated_by_id) || Discourse.system_user,+ root: false,+ ).as_json+ end++ def include_next_pending_automation_at?+ object.pending_automations.exists?+ end++ def next_pending_automation_at+ object&.pending_automations&.first&.execute_at+ end++ def placeholders+ scriptable_placeholders =+ DiscourseAutomation+ .filter_by_trigger(scriptable&.placeholders || [], object.trigger)+ .map { |placeholder| placeholder[:name] }+ triggerable_placeholders = triggerable&.placeholders || []++ (scriptable_placeholders + triggerable_placeholders).map do |placeholder|+ placeholder.to_s.gsub(/\s+/, "_").underscore+ end+ end++ def script+ key = "discourse_automation.scriptables"+ doc_key = "#{key}.#{object.script}.doc"+ script_with_trigger_key = "#{key}.#{object.script}_with_#{object.trigger}.doc"++ {+ id: object.script,+ version: scriptable.version,+ name: I18n.t("#{key}.#{object.script}.title"),+ description: I18n.t("#{key}.#{object.script}.description"),+ doc: I18n.exists?(doc_key, :en) ? I18n.t(doc_key) : nil,+ with_trigger_doc:+ I18n.exists?(script_with_trigger_key, :en) ? I18n.t(script_with_trigger_key) : nil,+ forced_triggerable: scriptable.forced_triggerable,+ not_found: scriptable.not_found,+ templates:+ process_templates(filter_fields_with_priority(scriptable.fields, object.trigger&.to_sym)),+ fields: process_fields(object.fields.where(target: "script")),+ }+ end++ def trigger+ key = "discourse_automation.triggerables"+ doc_key = "#{key}.#{object.trigger}.doc"++ {+ id: object.trigger,+ name: I18n.t("#{key}.#{object.trigger}.title"),+ description: I18n.t("#{key}.#{object.trigger}.description"),+ doc: I18n.exists?(doc_key, :en) ? I18n.t(doc_key) : nil,+ not_found: triggerable&.not_found,+ templates: process_templates(triggerable&.fields || []),+ fields: process_fields(object.fields.where(target: "trigger")),+ settings: triggerable&.settings,+ }+ end++ private++ def filter_fields_with_priority(arr, trigger)+ unique_with_priority = {}++ arr.each do |item|+ name = item[:name]+ if (item[:triggerable]&.to_sym == trigger&.to_sym || item[:triggerable].nil?) &&+ (!unique_with_priority.key?(name) || unique_with_priority[name][:triggerable].nil?)+ unique_with_priority[name] = item+ end+ end++ unique_with_priority.values+ end++ def process_templates(fields)+ ActiveModel::ArraySerializer.new(+ fields,+ each_serializer: DiscourseAutomation::TemplateSerializer,+ scope: {+ automation: object,+ },+ ).as_json+ end++ def process_fields(fields)+ ActiveModel::ArraySerializer.new(+ fields || [],+ each_serializer: DiscourseAutomation::FieldSerializer,+ ).as_json || []+ end++ def scriptable+ object.scriptable+ end++ def triggerable+ object.triggerable+ end+ end+enddiff --git a/plugins/automation/app/serializers/discourse_automation/field_serializer.rb b/plugins/automation/app/serializers/discourse_automation/field_serializer.rbnew file mode 100644index 00000000000..d3e630562a2--- /dev/null+++ b/plugins/automation/app/serializers/discourse_automation/field_serializer.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++module DiscourseAutomation+ class FieldSerializer < ApplicationSerializer+ attributes :id, :component, :name, :metadata, :is_required++ def metadata+ object.metadata || {}+ end++ def is_required+ object.template&.dig(:required)+ end+ end+enddiff --git a/plugins/automation/app/serializers/discourse_automation/template_serializer.rb b/plugins/automation/app/serializers/discourse_automation/template_serializer.rbnew file mode 100644index 00000000000..aafb13a4935--- /dev/null+++ b/plugins/automation/app/serializers/discourse_automation/template_serializer.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++module DiscourseAutomation+ class TemplateSerializer < ApplicationSerializer+ attributes :name,+ :component,+ :extra,+ :accepts_placeholders,+ :accepted_contexts,+ :read_only,+ :default_value,+ :is_required++ def default_value+ scope[:automation].scriptable&.forced_triggerable&.dig(:state, name) || object[:default_value]+ end++ def read_only+ scope[:automation].scriptable&.forced_triggerable&.dig(:state, name).present?+ end++ def name+ object[:name]+ end++ def component+ object[:component]+ end++ def extra+ object[:extra]+ end++ def accepts_placeholders+ object[:accepts_placeholders]+ end++ def accepted_contexts+ object[:accepted_contexts]+ end++ def is_required+ object[:required]+ end+ end+enddiff --git a/plugins/automation/app/serializers/discourse_automation/trigger_serializer.rb b/plugins/automation/app/serializers/discourse_automation/trigger_serializer.rbnew file mode 100644index 00000000000..2c7edb3b6bd--- /dev/null+++ b/plugins/automation/app/serializers/discourse_automation/trigger_serializer.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++module DiscourseAutomation+ class TriggerSerializer < ApplicationSerializer+ attributes :id, :name, :metadata++ def metadata+ ((options[:trigger_metadata] || {}).stringify_keys).merge(object.metadata || {})+ end+ end+enddiff --git a/plugins/automation/app/serializers/discourse_automation/user_global_notice_serializer.rb b/plugins/automation/app/serializers/discourse_automation/user_global_notice_serializer.rbnew file mode 100644index 00000000000..8391d6fdc21--- /dev/null+++ b/plugins/automation/app/serializers/discourse_automation/user_global_notice_serializer.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++module DiscourseAutomation+ class UserGlobalNoticeSerializer < ApplicationSerializer+ attributes :id, :notice, :level, :created_at, :updated_at, :identifier++ def level+ object.level || "info"+ end+ end+enddiff --git a/plugins/automation/app/services/discourse_automation/user_badge_granted_handler.rb b/plugins/automation/app/services/discourse_automation/user_badge_granted_handler.rbnew file mode 100644index 00000000000..ff20f6a49b7--- /dev/null+++ b/plugins/automation/app/services/discourse_automation/user_badge_granted_handler.rb@@ -0,0 +1,28 @@+# frozen_string_literal: true++module DiscourseAutomation+ class UserBadgeGrantedHandler+ def self.handle(automation, badge_id, user_id)+ tracked_badge_id = automation.trigger_field("badge")["value"]+ return if tracked_badge_id != badge_id++ badge = Badge.find(badge_id)++ only_first_grant = automation.trigger_field("only_first_grant")["value"]++ return if only_first_grant && UserBadge.where(user_id: user_id, badge_id: badge_id).count > 1++ user = User.find(user_id)++ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_BADGE_GRANTED,+ "usernames" => [user.username],+ "badge" => badge,+ "placeholders" => {+ "badge_name" => badge.name,+ "grant_count" => badge.grant_count,+ },+ )+ end+ end+enddiff --git a/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-adapter.js b/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-adapter.jsnew file mode 100644index 00000000000..b8d302bab3a--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-adapter.js@@ -0,0 +1,11 @@+import RestAdapter from "discourse/adapters/rest";++export default class Adapter extends RestAdapter {+ basePath() {+ return "/admin/plugins/discourse-automation/";+ }++ pathFor() {+ return super.pathFor(...arguments).replace("_", "-") + ".json";+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-automation.js b/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-automation.jsnew file mode 100644index 00000000000..ececd1ffc0d--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-automation.js@@ -0,0 +1,9 @@+import DiscourseAutomationAdapter from "./discourse-automation-adapter";++export default class AutomationAdapter extends DiscourseAutomationAdapter {+ jsonMode = true;++ apiNameFor() {+ return "automation";+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-scriptable.js b/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-scriptable.jsnew file mode 100644index 00000000000..aa9eb205e96--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-scriptable.js@@ -0,0 +1,9 @@+import DiscourseAutomationAdapter from "./discourse-automation-adapter";++export default class ScriptableAdapter extends DiscourseAutomationAdapter {+ jsonMode = true;++ apiNameFor() {+ return "scriptable";+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-triggerable.js b/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-triggerable.jsnew file mode 100644index 00000000000..3fdf4b39d78--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/admin/adapters/discourse-automation-triggerable.js@@ -0,0 +1,9 @@+import DiscourseAutomationAdapter from "./discourse-automation-adapter";++export default class TriggerableAdapter extends DiscourseAutomationAdapter {+ jsonMode = true;++ apiNameFor() {+ return "triggerable";+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/admin/models/discourse-automation-automation.js b/plugins/automation/assets/javascripts/discourse/admin/models/discourse-automation-automation.jsnew file mode 100644index 00000000000..29fe6530a40--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/admin/models/discourse-automation-automation.js@@ -0,0 +1,23 @@+import RestModel from "discourse/models/rest";++const ATTRIBUTES = ["name", "script", "fields", "trigger", "id"];++export default class Automation extends RestModel {+ updateProperties() {+ return {+ id: this.id,+ name: this.name,+ fields: this.fields,+ script: this.script.id,+ trigger: {+ id: this.trigger.id,+ name: this.trigger.name,+ metadata: this.trigger.metadata,+ },+ };+ }++ createProperties() {+ return this.getProperties(ATTRIBUTES);+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/admin/models/discourse-automation-field.js b/plugins/automation/assets/javascripts/discourse/admin/models/discourse-automation-field.jsnew file mode 100644index 00000000000..72c2e3f38bf--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/admin/models/discourse-automation-field.js@@ -0,0 +1,52 @@+import { tracked } from "@glimmer/tracking";+import { TrackedObject } from "@ember-compat/tracked-built-ins";++export default class DiscourseAutomationField {+ static create(template, target, json = {}) {+ const field = new DiscourseAutomationField();+ field.acceptsPlaceholders = template.accepts_placeholders;+ field.acceptedContexts = template.accepted_contexts;+ field.targetName = target.name;+ field.targetType = target.type;+ field.name = template.name;+ field.component = template.component;+ field.isDisabled = template.read_only;++ // backwards compatibility with forced scriptable fields+ if (field.isDisabled) {+ field.metadata.value =+ template.default_value || template.value || json?.metadata?.value;+ } else {+ field.metadata.value =+ template.value || json?.metadata?.value || template.default_value;+ }++ // null is not a valid value for metadata.value+ if (field.metadata.value === null) {+ field.metadata.value = undefined;+ }++ field.isRequired = template.is_required;+ field.extra = new TrackedObject(template.extra);+ return field;+ }++ @tracked acceptsPlaceholders = false;+ @tracked component;+ @tracked extra = new TrackedObject();+ @tracked isDisabled = false;+ @tracked isRequired = false;+ @tracked metadata = new TrackedObject();+ @tracked name;+ @tracked targetType;+ @tracked targetName;++ toJSON() {+ return {+ name: this.name,+ target: this.targetType,+ component: this.component,+ metadata: this.metadata,+ };+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/admin/models/discourse-automation-script.js b/plugins/automation/assets/javascripts/discourse/admin/models/discourse-automation-script.jsnew file mode 100644index 00000000000..67079776760--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/admin/models/discourse-automation-script.js@@ -0,0 +1,3 @@+import RestModel from "discourse/models/rest";++export default class Script extends RestModel {}diff --git a/plugins/automation/assets/javascripts/discourse/components/automation-field.gjs b/plugins/automation/assets/javascripts/discourse/components/automation-field.gjsnew file mode 100644index 00000000000..eaf2e8bbe05--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/automation-field.gjs@@ -0,0 +1,97 @@+import Component from "@glimmer/component";+import I18n from "I18n";+import DaBooleanField from "./fields/da-boolean-field";+import DaCategoriesField from "./fields/da-categories-field";+import DaCategoryField from "./fields/da-category-field";+import DaCategoryNotificationlevelField from "./fields/da-category-notification-level-field";+import DaChoicesField from "./fields/da-choices-field";+import DaCustomField from "./fields/da-custom-field";+import DaCustomFields from "./fields/da-custom-fields";+import DaDateTimeField from "./fields/da-date-time-field";+import DaEmailGroupUserField from "./fields/da-email-group-user-field";+import DaGroupField from "./fields/da-group-field";+import DaKeyValueField from "./fields/da-key-value-field";+import DaMessageField from "./fields/da-message-field";+import DaPeriodField from "./fields/da-period-field";+import DaPmsField from "./fields/da-pms-field";+import DaPostField from "./fields/da-post-field";+import DaTagsField from "./fields/da-tags-field";+import DaTextField from "./fields/da-text-field";+import DaTextListField from "./fields/da-text-list-field";+import DaTrustLevelsField from "./fields/da-trust-levels-field";+import DaUserField from "./fields/da-user-field";+import DaUserProfileField from "./fields/da-user-profile-field";+import DaUsersField from "./fields/da-users-field";++const FIELD_COMPONENTS = {+ period: DaPeriodField,+ date_time: DaDateTimeField,+ text_list: DaTextListField,+ pms: DaPmsField,+ text: DaTextField,+ message: DaMessageField,+ categories: DaCategoriesField,+ user: DaUserField,+ users: DaUsersField,+ user_profile: DaUserProfileField,+ post: DaPostField,+ tags: DaTagsField,+ "key-value": DaKeyValueField,+ boolean: DaBooleanField,+ "trust-levels": DaTrustLevelsField,+ category: DaCategoryField,+ group: DaGroupField,+ choices: DaChoicesField,+ category_notification_level: DaCategoryNotificationlevelField,+ email_group_user: DaEmailGroupUserField,+ custom_field: DaCustomField,+ custom_fields: DaCustomFields,+};++export default class AutomationField extends Component {+ <template>+ {{#if this.displayField}}+ <this.component+ @field={{@field}}+ @placeholders={{@automation.placeholders}}+ @label={{this.label}}+ @description={{this.description}}+ @saveAutomation={{@saveAutomation}}+ />+ {{/if}}+ </template>++ get component() {+ return FIELD_COMPONENTS[this.args.field.component];+ }++ get label() {+ return I18n.t(+ `discourse_automation${this.target}fields.${this.args.field.name}.label`+ );+ }++ get displayField() {+ const triggerId = this.args.automation?.trigger?.id;+ const triggerable = this.args.field?.triggerable;+ return triggerId && (!triggerable || triggerable === triggerId);+ }++ get placeholdersString() {+ return this.args.field.placeholders.join(", ");+ }++ get target() {+ return this.args.field.targetType === "script"+ ? `.scriptables.${this.args.automation.script.id.replace(/-/g, "_")}.`+ : `.triggerables.${this.args.automation.trigger.id.replace(/-/g, "_")}.`;+ }++ get translationKey() {+ return `discourse_automation${this.target}fields.${this.args.field.name}.description`;+ }++ get description() {+ return I18n.lookup(this.translationKey);+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-base-field.js b/plugins/automation/assets/javascripts/discourse/components/fields/da-base-field.jsnew file mode 100644index 00000000000..3c0d4475f79--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-base-field.js@@ -0,0 +1,15 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";++export default class BaseField extends Component {+ get displayPlaceholders() {+ return (+ this.args.placeholders?.length && this.args.field?.acceptsPlaceholders+ );+ }++ @action+ mutValue(newValue) {+ this.args.field.metadata.value = newValue;+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-boolean-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-boolean-field.gjsnew file mode 100644index 00000000000..b6fee3315ae--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-boolean-field.gjs@@ -0,0 +1,32 @@+import { Input } from "@ember/component";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class BooleanField extends BaseField {+ <template>+ <section class="field boolean-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <Input+ @type="checkbox"+ @checked={{@field.metadata.value}}+ {{on "input" this.onInput}}+ disabled={{@field.isDisabled}}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>++ @action+ onInput(event) {+ this.mutValue(event.target.checked);+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-categories-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-categories-field.gjsnew file mode 100644index 00000000000..396871054f1--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-categories-field.gjs@@ -0,0 +1,38 @@+import { fn, hash } from "@ember/helper";+import { action } from "@ember/object";+import Category from "discourse/models/category";+import CategorySelector from "select-kit/components/category-selector";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class CategoriesField extends BaseField {+ <template>+ {{! template-lint-disable no-redundant-fn }}+ <section class="field categories-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <CategorySelector+ @categories={{this.categories}}+ @onChange={{fn this.onChangeCategories}}+ @options={{hash clearable=true [email protected]}}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>++ get categories() {+ const ids = this.args.field?.metadata?.value || [];+ return ids.map((id) => Category.findById(id)).filter(Boolean);+ }++ @action+ onChangeCategories(categories) {+ this.mutValue(categories.mapBy("id"));+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-category-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-category-field.gjsnew file mode 100644index 00000000000..fd933888f5b--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-category-field.gjs@@ -0,0 +1,25 @@+import { hash } from "@ember/helper";+import CategoryChooser from "select-kit/components/category-chooser";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class CategoryField extends BaseField {+ <template>+ <section class="field category-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <CategoryChooser+ @value={{@field.metadata.value}}+ @onChange={{this.mutValue}}+ @options={{hash clearable=true [email protected]}}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-category-notification-level-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-category-notification-level-field.gjsnew file mode 100644index 00000000000..b84e7d6e955--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-category-notification-level-field.gjs@@ -0,0 +1,25 @@+import { hash } from "@ember/helper";+import CategoryNotificationsButton from "select-kit/components/category-notifications-button";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class CategoryNotficationLevelField extends BaseField {+ <template>+ <section class="field category-notification-level-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <CategoryNotificationsButton+ @value={{@field.metadata.value}}+ @onChange={{this.mutValue}}+ @options={{hash showFullTitle=true}}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-choices-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-choices-field.gjsnew file mode 100644index 00000000000..78082136acc--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-choices-field.gjs@@ -0,0 +1,38 @@+import { hash } from "@ember/helper";+import I18n from "I18n";+import ComboBox from "select-kit/components/combo-box";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class ChoicesField extends BaseField {+ <template>+ <div class="field control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <ComboBox+ @value={{@field.metadata.value}}+ @content={{this.replacedContent}}+ @onChange={{this.mutValue}}+ @options={{hash+ allowAny=false+ clearable=true+ }}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </template>++ get replacedContent() {+ return (this.args.field.extra.content || []).map((r) => {+ return {+ id: r.id,+ name: r.translated_name || I18n.t(r.name),+ };+ });+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-custom-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-custom-field.gjsnew file mode 100644index 00000000000..9f5f223e697--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-custom-field.gjs@@ -0,0 +1,37 @@+import { tracked } from "@glimmer/tracking";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import { inject as service } from "@ember/service";+import { bind } from "discourse-common/utils/decorators";+import ComboBox from "select-kit/components/combo-box";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class GroupField extends BaseField {+ @service store;+ @tracked allCustomFields = [];++ <template>+ <section class="field group-field" {{didInsert this.loadUserFields}}>+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <ComboBox+ @content={{this.allCustomFields}}+ @value={{@field.metadata.value}}+ @onChange={{this.mutValue}}+ />+ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>++ @bind+ loadUserFields() {+ this.store.findAll("user-field").then((fields) => {+ this.allCustomFields = fields.content;+ });+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-custom-fields.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-custom-fields.gjsnew file mode 100644index 00000000000..6f2866679a1--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-custom-fields.gjs@@ -0,0 +1,41 @@+import { tracked } from "@glimmer/tracking";+import { hash } from "@ember/helper";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import { inject as service } from "@ember/service";+import { bind } from "discourse-common/utils/decorators";+import MultiSelect from "select-kit/components/multi-select";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class GroupField extends BaseField {+ @service store;+ @tracked allCustomFields = [];++ <template>+ <section class="field group-field" {{didInsert this.loadUserFields}}>+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <MultiSelect+ @value={{@field.metadata.value}}+ @content={{this.allCustomFields}}+ @onChange={{this.mutValue}}+ @nameProperty={{null}}+ @valueProperty={{null}}+ @options={{hash allowAny=false [email protected]}}+ />+ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>++ @bind+ loadUserFields() {+ this.store.findAll("user-field").then((fields) => {+ this.allCustomFields = fields.content.map((field) => field.name);+ });+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-date-time-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-date-time-field.gjsnew file mode 100644index 00000000000..2d68cb2d8af--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-date-time-field.gjs@@ -0,0 +1,62 @@+import { Input } from "@ember/component";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import DButton from "discourse/components/d-button";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class DateTimeField extends BaseField {+ <template>+ <section class="field date-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <div class="controls-row">+ <Input+ @type="datetime-local"+ @value={{readonly this.localTime}}+ disabled={{@field.isDisabled}}+ {{on "input" this.convertToUniversalTime}}+ />++ {{#if @field.metadata.value}}+ <DButton+ @icon="trash-alt"+ @action={{this.reset}}+ @disabled={{@field.isDisabled}}+ />+ {{/if}}+ </div>++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>++ @action+ convertToUniversalTime(event) {+ const date = event.target.value;+ if (!date) {+ return;+ }++ this.mutValue(moment(date).utc().format());+ }++ @action+ reset() {+ this.mutValue(null);+ }++ get localTime() {+ return (+ this.args.field.metadata.value &&+ moment(this.args.field.metadata.value)+ .local()+ .format(moment.HTML5_FMT.DATETIME_LOCAL)+ );+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-email-group-user-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-email-group-user-field.gjsnew file mode 100644index 00000000000..d9b912d8bc3--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-email-group-user-field.gjs@@ -0,0 +1,61 @@+import { tracked } from "@glimmer/tracking";+import { hash } from "@ember/helper";+import { action } from "@ember/object";+import EmailGroupUserChooser from "select-kit/components/email-group-user-chooser";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class EmailGroupUserField extends BaseField {+ @tracked recipients;+ @tracked groups = [];++ <template>+ <section class="field email-group-user-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <EmailGroupUserChooser+ @value={{@field.metadata.value}}+ @onChange={{this.mutValue}}+ @options={{hash+ includeGroups=true+ includeMessageableGroups=true+ allowEmails=true+ autoWrap=true+ }}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>++ @action+ updateRecipients(selected, content) {+ const newGroups = content.filterBy("isGroup").mapBy("id");+ this._updateGroups(selected, newGroups);+ this.recipients = selected.join(",");+ }++ _updateGroups(selected, newGroups) {+ const groups = [];++ this.groups.forEach((existing) => {+ if (selected.includes(existing)) {+ groups.addObject(existing);+ }+ });++ newGroups.forEach((newGroup) => {+ if (!groups.includes(newGroup)) {+ groups.addObject(newGroup);+ }+ });++ this.groups = groups;+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-field-description.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-field-description.gjsnew file mode 100644index 00000000000..fbba9ab9d7e--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-field-description.gjs@@ -0,0 +1,9 @@+const FieldDescription = <template>+ {{#if @description}}+ <p class="control-description">+ {{@description}}+ </p>+ {{/if}}+</template>;++export default FieldDescription;diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-field-label.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-field-label.gjsnew file mode 100644index 00000000000..1b35f80b46f--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-field-label.gjs@@ -0,0 +1,14 @@+const FieldLabel = <template>+ {{#if @label}}+ <label class="control-label">+ <span>+ {{@label}}+ {{#if @field.isRequired}}+ *+ {{/if}}+ </span>+ </label>+ {{/if}}+</template>;++export default FieldLabel;diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-group-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-group-field.gjsnew file mode 100644index 00000000000..00c131773e7--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-group-field.gjs@@ -0,0 +1,51 @@+import { tracked } from "@glimmer/tracking";+import { hash } from "@ember/helper";+import { action } from "@ember/object";+import Group from "discourse/models/group";+import GroupChooser from "select-kit/components/group-chooser";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class GroupField extends BaseField {+ @tracked allGroups = [];++ <template>+ <section class="field group-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <GroupChooser+ @content={{this.allGroups}}+ @value={{@field.metadata.value}}+ @labelProperty="name"+ @onChange={{this.setGroupField}}+ @options={{hash maximum=1 [email protected]}}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>++ constructor() {+ super(...arguments);++ Group.findAll({+ ignore_automatic: this.args.field.extra.ignore_automatic ?? false,+ }).then((groups) => {+ if (this.isDestroying || this.isDestroyed) {+ return;+ }++ this.allGroups = groups;+ });+ }++ @action+ setGroupField(groupIds) {+ this.mutValue(groupIds?.firstObject);+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-key-value-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-key-value-field.gjsnew file mode 100644index 00000000000..669b6887df9--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-key-value-field.gjs@@ -0,0 +1,104 @@+import { tracked } from "@glimmer/tracking";+import { hash } from "@ember/helper";+import { action } from "@ember/object";+import DButton from "discourse/components/d-button";+import ModalJsonSchemaEditor from "discourse/components/modal/json-schema-editor";+import I18n from "I18n";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class KeyValueField extends BaseField {+ @tracked showJsonEditorModal = false;++ jsonSchema = {+ type: "array",+ uniqueItems: true,+ items: {+ type: "object",+ title: "group",+ properties: {+ key: {+ type: "string",+ },+ value: {+ type: "string",+ format: "textarea",+ },+ },+ },+ };++ <template>+ <section class="field key-value-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <DButton class="configure-btn" @action={{this.openModal}}>+ {{this.showJsonModalLabel}}+ </DButton>++ {{#if this.showJsonEditorModal}}+ <ModalJsonSchemaEditor+ @model={{hash+ value=this.value+ updateValue=this.handleValueChange+ settingName=@label+ jsonSchema=this.jsonSchema+ }}+ @closeModal={{this.closeModal}}+ />+ {{/if}}++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>++ get value() {+ return (+ this.args.field.metadata.value ||+ '[{"key":"example","value":"You posted {{key}}"}]'+ );+ }++ get keyCount() {+ if (this.args.field.metadata.value) {+ return JSON.parse(this.value).length;+ }++ return 0;+ }++ get showJsonModalLabel() {+ if (this.keyCount === 0) {+ return I18n.t(+ "discourse_automation.fields.key_value.label_without_count"+ );+ } else {+ return I18n.t("discourse_automation.fields.key_value.label_with_count", {+ count: this.keyCount,+ });+ }+ }++ @action+ handleValueChange(value) {+ if (value !== this.args.field.metadata.value) {+ this.mutValue(value);+ this.args.saveAutomation();+ }+ }++ @action+ openModal() {+ this.showJsonEditorModal = true;+ }++ @action+ closeModal() {+ this.showJsonEditorModal = false;+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-message-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-message-field.gjsnew file mode 100644index 00000000000..e9c1ea2fea1--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-message-field.gjs@@ -0,0 +1,41 @@+import { TextArea } from "@ember/legacy-built-in-components";+import { action } from "@ember/object";+import PlaceholdersList from "../placeholders-list";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class MessageField extends BaseField {+ <template>+ <section class="field message-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <div class="field-wrapper">+ <TextArea+ @value={{@field.metadata.value}}+ @input={{this.updateValue}}+ @disabled={{@field.isDisabled}}+ />++ <DAFieldDescription @description={{@description}} />++ {{#if this.displayPlaceholders}}+ <PlaceholdersList+ @currentValue={{@field.metadata.value}}+ @placeholders={{@placeholder}}+ @onCopy={{this.test}}+ />+ {{/if}}+ </div>+ </div>+ </div>+ </section>+ </template>++ @action+ updateValue(event) {+ this.mutValue(event.target.value);+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-period-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-period-field.gjsnew file mode 100644index 00000000000..73cb37e7bbb--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-period-field.gjs@@ -0,0 +1,86 @@+import { tracked } from "@glimmer/tracking";+import { Input } from "@ember/component";+import { hash } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { next } from "@ember/runloop";+import { TrackedObject } from "@ember-compat/tracked-built-ins";+import I18n from "I18n";+import ComboBox from "select-kit/components/combo-box";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class PeriodField extends BaseField {+ @tracked interval = 1;+ @tracked frequency = null;++ constructor() {+ super(...arguments);++ next(() => {+ if (!this.args.field.metadata.value) {+ this.args.field.metadata.value = new TrackedObject({+ interval: 1,+ frequency: null,+ });+ }++ this.interval = this.args.field.metadata.value.interval;+ this.frequency = this.args.field.metadata.value.frequency;+ });+ }++ get recurringLabel() {+ return I18n.t("discourse_automation.triggerables.recurring.every");+ }++ get replacedContent() {+ return (this.args.field?.extra?.content || []).map((r) => {+ return {+ id: r.id,+ name: I18n.t(r.name),+ };+ });+ }++ @action+ mutInterval(event) {+ this.args.field.metadata.value.interval = event.target.value;+ }++ @action+ mutFrequency(value) {+ this.args.field.metadata.value.frequency = value;+ this.frequency = value;+ }++ <template>+ <div class="field period-field control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ {{this.recurringLabel}}++ <Input+ @type="number"+ defaultValue="1"+ @value={{this.interval}}+ disabled={{@field.isDisabled}}+ required={{@field.isRequired}}+ {{on "input" this.mutInterval}}+ />++ <ComboBox+ @value={{this.frequency}}+ @content={{this.replacedContent}}+ @onChange={{this.mutFrequency}}+ @options={{hash allowAny=false [email protected]}}+ @required={{@field.isRequired}}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </template>+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-pms-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-pms-field.gjsnew file mode 100644index 00000000000..2ad0b1e53c7--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-pms-field.gjs@@ -0,0 +1,199 @@+import { Input } from "@ember/component";+import { concat, fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import { next } from "@ember/runloop";+import { inject as service } from "@ember/service";+import { TrackedArray, TrackedObject } from "@ember-compat/tracked-built-ins";+import DButton from "discourse/components/d-button";+import DEditor from "discourse/components/d-editor";+import I18n from "I18n";+import PlaceholdersList from "../placeholders-list";+import BaseField from "./da-base-field";+import DAFieldLabel from "./da-field-label";++export default class PmsField extends BaseField {+ @service dialog;++ noPmCreatedLabel = I18n.t("discourse_automation.fields.pms.no_pm_created");++ prefersEncryptLabel = I18n.t(+ "discourse_automation.fields.pms.prefers_encrypt.label"+ );++ delayLabel = I18n.t("discourse_automation.fields.pms.delay.label");++ pmTitleLabel = I18n.t("discourse_automation.fields.pms.title.label");++ rawLabel = I18n.t("discourse_automation.fields.pms.raw.label");++ <template>+ <section class="field pms-field">+ {{#if @field.metadata.value.length}}+ <section class="actions header">+ <DAFieldLabel @label={{@label}} @field={{@field}} />+ <DButton+ @icon="plus"+ @action={{this.insertPM}}+ class="btn-primary insert-pm"+ />+ </section>+ {{/if}}++ {{#each @field.metadata.value as |pm|}}+ <div class="pm-field">+ <div class="control-group">+ <DAFieldLabel @label={{this.pmTitleLabel}} @field={{@field}} />+ <div class="controls">+ <div class="field-wrapper">+ <Input+ id={{concat @field.targetType @field.name "title"}}+ @value={{pm.title}}+ class="pm-input pm-title"+ {{on "input" (fn this.mutPmTitle pm)}}+ disabled={{@field.isDisabled}}+ name={{@field.name}}+ />++ {{#if this.displayPlaceholders}}+ <PlaceholdersList+ @currentValue={{pm.title}}+ @placeholders={{@placeholders}}+ @onCopy={{fn this.updatePmTitle pm}}+ />+ {{/if}}+ </div>+ </div>+ </div>++ <div class="control-group">+ <DAFieldLabel @label={{this.rawLabel}} @field={{@field}} />+ <div class="controls">+ <div class="field-wrapper">+ <DEditor @value={{pm.raw}} />++ {{#if this.displayPlaceholders}}+ <PlaceholdersList+ @currentValue={{pm.raw}}+ @placeholders={{@placeholders}}+ @onCopy={{fn this.updatePmRaw pm}}+ />+ {{/if}}+ </div>+ </div>+ </div>++ <div class="control-group">+ <label class="control-label">+ {{this.delayLabel}}+ </label>++ <div class="controls">+ <Input+ @value={{pm.delay}}+ class="input-large pm-input pm-delay"+ {{on "input" (fn this.mutPmDelay pm)}}+ disabled={{@field.isDisabled}}+ />+ </div>+ </div>++ <div class="control-group">+ <label class="control-label">+ {{this.prefersEncryptLabel}}+ </label>++ <div class="controls">+ <Input+ @type="checkbox"+ class="pm-prefers-encrypt"+ @checked={{pm.prefers_encrypt}}+ {{on "click" (fn this.prefersEncrypt pm)}}+ disabled={{@field.isDisabled}}+ />+ </div>+ </div>+ <section class="actions">+ <DButton+ @icon="trash-alt"+ @action={{fn this.removePM pm}}+ class="btn-danger"+ @disabled={{@field.isDisabled}}+ />+ </section>+ </div>+ {{else}}+ <div class="no-pm">+ <p>{{this.noPmCreatedLabel}}</p>+ <DButton+ @icon="plus"+ @label="discourse_automation.fields.pms.add_pm"+ @action={{this.insertPM}}+ class="btn-primary insert-pm"+ @disabled={{@field.isDisabled}}+ />+ </div>+ {{/each}}+ </section>+ </template>++ constructor() {+ super(...arguments);++ // a hack to prevent warnings about modifying multiple times in the same runloop+ next(() => {+ this.args.field.metadata.value = new TrackedArray(+ (this.args.field.metadata.value || []).map((pm) => {+ return new TrackedObject(pm);+ })+ );+ });+ }++ @action+ removePM(pm) {+ this.dialog.yesNoConfirm({+ message: I18n.t("discourse_automation.fields.pms.confirm_remove_pm"),+ didConfirm: () => {+ return this.args.field.metadata.value.removeObject(pm);+ },+ });+ }++ @action+ insertPM() {+ this.args.field.metadata.value.pushObject(+ new TrackedObject({+ title: "",+ raw: "",+ delay: 0,+ prefers_encrypt: true,+ })+ );+ }++ @action+ prefersEncrypt(pm, event) {+ pm.prefers_encrypt = event.target.checked;+ }++ @action+ mutPmTitle(pm, event) {+ pm.title = event.target.value;+ }++ @action+ mutPmDelay(pm, event) {+ pm.delay = event.target.value;+ }++ @action+ updatePmRaw(pm, newRaw) {+ pm.raw = newRaw;+ }++ @action+ updatePmTitle(pm, newRaw) {+ pm.title = newRaw;+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-post-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-post-field.gjsnew file mode 100644index 00000000000..44306dd387c--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-post-field.gjs@@ -0,0 +1,31 @@+import DEditor from "discourse/components/d-editor";+import PlaceholdersList from "../placeholders-list";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class PostField extends BaseField {+ <template>+ <section class="field post-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <div class="field-wrapper">+ <DEditor @value={{@field.metadata.value}} />++ <DAFieldDescription @description={{@description}} />++ {{#if this.displayPlaceholders}}+ <PlaceholdersList+ @currentValue={{@field.metadata.value}}+ @placeholders={{@placeholders}}+ @onCopy={{this.mutValue}}+ />+ {{/if}}+ </div>+ </div>+ </div>+ </section>+ </template>+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-tags-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-tags-field.gjsnew file mode 100644index 00000000000..55e149156b8--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-tags-field.gjs@@ -0,0 +1,24 @@+import { hash } from "@ember/helper";+import TagChooser from "select-kit/components/tag-chooser";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class TagsField extends BaseField {+ <template>+ <section class="field tags-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <TagChooser+ @tags={{@field.metadata.value}}+ @options={{hash allowAny=false [email protected]}}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-text-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-text-field.gjsnew file mode 100644index 00000000000..0189692fb45--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-text-field.gjs@@ -0,0 +1,43 @@+import { Input } from "@ember/component";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import PlaceholdersList from "../placeholders-list";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class TextField extends BaseField {+ <template>+ <section class="field text-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <div class="field-wrapper">+ <Input+ @value={{@field.metadata.value}}+ disabled={{@field.isDisabled}}+ {{on "input" this.mutText}}+ name={{@field.name}}+ />++ <DAFieldDescription @description={{@description}} />++ {{#if this.displayPlaceholders}}+ <PlaceholdersList+ @currentValue={{@field.metadata.value}}+ @placeholders={{@placeholders}}+ @onCopy={{this.mutValue}}+ />+ {{/if}}+ </div>+ </div>+ </div>+ </section>+ </template>++ @action+ mutText(event) {+ this.mutValue(event.target.value);+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-text-list-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-text-list-field.gjsnew file mode 100644index 00000000000..8fb1af307db--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-text-list-field.gjs@@ -0,0 +1,28 @@+import { hash } from "@ember/helper";+import MultiSelect from "select-kit/components/multi-select";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class TextListField extends BaseField {+ <template>+ <section class="field text-list-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <MultiSelect+ @value={{@field.metadata.value}}+ @content={{@field.metadata.value}}+ @onChange={{this.mutValue}}+ @nameProperty={{null}}+ @valueProperty={{null}}+ @options={{hash allowAny=true [email protected]}}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-trust-levels-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-trust-levels-field.gjsnew file mode 100644index 00000000000..a4a232664b7--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-trust-levels-field.gjs@@ -0,0 +1,27 @@+import { inject as service } from "@ember/service";+import MultiSelect from "select-kit/components/multi-select";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class TrustLevelsField extends BaseField {+ @service site;++ <template>+ <section class="field category-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <MultiSelect+ @value={{@field.metadata.value}}+ @content={{this.site.trustLevels}}+ @onChange={{this.mutValue}}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-user-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-user-field.gjsnew file mode 100644index 00000000000..6ede6d3939c--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-user-field.gjs@@ -0,0 +1,53 @@+import { fn, hash } from "@ember/helper";+import { action } from "@ember/object";+import I18n from "I18n";+import UserChooser from "select-kit/components/user-chooser";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class UserField extends BaseField {+ @action+ onChangeUsername(usernames) {+ this.mutValue(usernames[0]);+ }++ @action+ modifyContent(field, content) {+ content = field.acceptedContexts+ .map((context) => {+ return {+ name: I18n.t(+ `discourse_automation.scriptables.${field.targetName}.fields.${field.name}.${context}_context`+ ),+ username: context,+ };+ })+ .concat(content);++ return content;+ }++ <template>+ <section class="field user-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <UserChooser+ @value={{@field.metadata.value}}+ @onChange={{this.onChangeUsername}}+ @modifyContent={{fn this.modifyContent @field}}+ @options={{hash+ maximum=1+ excludeCurrentUser=false+ }}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-user-profile-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-user-profile-field.gjsnew file mode 100644index 00000000000..eecd23f7dfb--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-user-profile-field.gjs@@ -0,0 +1,38 @@+import { tracked } from "@glimmer/tracking";+import { hash } from "@ember/helper";+import MultiSelect from "select-kit/components/multi-select";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class UserProfileField extends BaseField {+ @tracked allProfileFields = [];++ userProfileFields = [+ "bio_raw",+ "website",+ "location",+ "date_of_birth",+ "timezone",+ ];++ <template>+ <section class="field group-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />+ <div class="controls">+ <MultiSelect+ @value={{@field.metadata.value}}+ @content={{this.userProfileFields}}+ @onChange={{this.mutValue}}+ @nameProperty={{null}}+ @valueProperty={{null}}+ @options={{hash allowAny=true [email protected]}}+ />++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>+}diff --git a/plugins/automation/assets/javascripts/discourse/components/fields/da-users-field.gjs b/plugins/automation/assets/javascripts/discourse/components/fields/da-users-field.gjsnew file mode 100644index 00000000000..eb5465ec9ab--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/fields/da-users-field.gjs@@ -0,0 +1,33 @@+import { hash } from "@ember/helper";+import UserChooser from "select-kit/components/user-chooser";+import BaseField from "./da-base-field";+import DAFieldDescription from "./da-field-description";+import DAFieldLabel from "./da-field-label";++export default class UsersField extends BaseField {+ <template>+ <section class="field users-field">+ <div class="control-group">+ <DAFieldLabel @label={{@label}} @field={{@field}} />++ <div class="controls">+ <UserChooser+ @value={{@field.metadata.value}}+ @onChange={{this.mutValue}}+ @options={{hash+ excludeCurrentUser=false+ allowEmails=true+ }}+ />++ {{#if @field.metadata.allowsAutomation}}+ <span class="help-inline error">{{@field.metadata.error}}</span>+ {{/if}}++ <DAFieldDescription @description={{@description}} />+ </div>+ </div>+ </section>+ </template>+}diff --git a/plugins/automation/assets/javascripts/discourse/components/placeholders-list.gjs b/plugins/automation/assets/javascripts/discourse/components/placeholders-list.gjsnew file mode 100644index 00000000000..110a5dc2dac--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/components/placeholders-list.gjs@@ -0,0 +1,23 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import DButton from "discourse/components/d-button";++export default class PlaceholdersList extends Component {+ <template>+ <div class="placeholders-list">+ {{#each @placeholders as |placeholder|}}+ <DButton+ @translatedLabel={{placeholder}}+ class="placeholder-item"+ @action={{fn this.copyPlaceholder placeholder}}+ />+ {{/each}}+ </div>+ </template>++ @action+ copyPlaceholder(placeholder) {+ this.args.onCopy(`${this.args.currentValue}{{${placeholder}}}`);+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation-edit.js b/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation-edit.jsnew file mode 100644index 00000000000..e3a53619c9f--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation-edit.js@@ -0,0 +1,113 @@+import Controller from "@ember/controller";+import { action, computed, set } from "@ember/object";+import { filterBy, reads } from "@ember/object/computed";+import { schedule } from "@ember/runloop";+import { inject as service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { extractError } from "discourse/lib/ajax-error";+import I18n from "I18n";++export default class AutomationEdit extends Controller {+ @service dialog;+ error = null;+ isUpdatingAutomation = false;+ isTriggeringAutomation = false;++ @reads("model.automation") automation;+ @filterBy("automationForm.fields", "targetType", "script") scriptFields;+ @filterBy("automationForm.fields", "targetType", "trigger") triggerFields;++ @computed("model.automation.next_pending_automation_at")+ get nextPendingAutomationAtFormatted() {+ const date = this.model?.automation?.next_pending_automation_at;+ if (date) {+ return moment(date).format("LLLL");+ }+ }++ @action+ saveAutomation() {+ this.setProperties({ error: null, isUpdatingAutomation: true });++ return ajax(+ `/admin/plugins/discourse-automation/automations/${this.model.automation.id}.json`,+ {+ type: "PUT",+ data: JSON.stringify({ automation: this.automationForm }),+ dataType: "json",+ contentType: "application/json",+ }+ )+ .then(() => {+ this.send("refreshRoute");+ })+ .catch((e) => this._showError(e))+ .finally(() => {+ this.set("isUpdatingAutomation", false);+ });+ }++ @action+ onChangeTrigger(id) {+ if (this.automationForm.trigger && this.automationForm.trigger !== id) {+ this._confirmReset(() => {+ set(this.automationForm, "trigger", id);+ this.saveAutomation();+ });+ } else if (!this.automationForm.trigger) {+ set(this.automationForm, "trigger", id);+ this.saveAutomation();+ }+ }++ @action+ onManualAutomationTrigger(id) {+ this._confirmTrigger(() => {+ this.set("isTriggeringAutomation", true);++ return ajax(`/automations/${id}/trigger.json`, {+ type: "post",+ })+ .catch((e) => this.set("error", extractError(e)))+ .finally(() => {+ this.set("isTriggeringAutomation", false);+ });+ });+ }++ @action+ onChangeScript(id) {+ if (this.automationForm.script !== id) {+ this._confirmReset(() => {+ set(this.automationForm, "script", id);+ this.saveAutomation();+ });+ }+ }++ _confirmReset(callback) {+ this.dialog.yesNoConfirm({+ message: I18n.t("discourse_automation.confirm_automation_reset"),+ didConfirm: () => {+ return callback && callback();+ },+ });+ }++ _confirmTrigger(callback) {+ this.dialog.yesNoConfirm({+ message: I18n.t("discourse_automation.confirm_automation_trigger"),+ didConfirm: () => {+ return callback && callback();+ },+ });+ }++ _showError(error) {+ this.set("error", extractError(error));++ schedule("afterRender", () => {+ window.scrollTo(0, 0);+ });+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation-index.js b/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation-index.jsnew file mode 100644index 00000000000..37ed88519ca--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation-index.js@@ -0,0 +1,39 @@+import Controller from "@ember/controller";+import { action } from "@ember/object";+import { inject as service } from "@ember/service";+import { popupAjaxError } from "discourse/lib/ajax-error";+import escape from "discourse-common/lib/escape";+import I18n from "I18n";++export default class AutomationIndex extends Controller {+ @service dialog;+ @service router;++ @action+ editAutomation(automation) {+ this.router.transitionTo(+ "adminPlugins.discourse-automation.edit",+ automation.id+ );+ }++ @action+ newAutomation() {+ this.router.transitionTo("adminPlugins.discourse-automation.new");+ }++ @action+ destroyAutomation(automation) {+ this.dialog.deleteConfirm({+ message: I18n.t("discourse_automation.destroy_automation.confirm", {+ name: escape(automation.name),+ }),+ didConfirm: () => {+ return automation+ .destroyRecord()+ .then(() => this.send("triggerRefresh"))+ .catch(popupAjaxError);+ },+ });+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation-new.js b/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation-new.jsnew file mode 100644index 00000000000..4df9043f33b--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation-new.js@@ -0,0 +1,38 @@+import Controller from "@ember/controller";+import EmberObject, { action } from "@ember/object";+import { inject as service } from "@ember/service";+import { extractError } from "discourse/lib/ajax-error";++export default class AutomationNew extends Controller {+ @service router;++ form = null;+ error = null;++ init() {+ super.init(...arguments);+ this._resetForm();+ }++ @action+ saveAutomation(automation) {+ this.set("error", null);++ automation+ .save(this.form.getProperties("name", "script"))+ .then(() => {+ this._resetForm();+ this.router.transitionTo(+ "adminPlugins.discourse-automation.edit",+ automation.id+ );+ })+ .catch((e) => {+ this.set("error", extractError(e));+ });+ }++ _resetForm() {+ this.set("form", EmberObject.create({ name: null, script: null }));+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation.js b/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation.jsnew file mode 100644index 00000000000..59a5d7c482b--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/controllers/admin-plugins-discourse-automation.js@@ -0,0 +1,19 @@+import Controller from "@ember/controller";+import { action, computed } from "@ember/object";+import { inject as service } from "@ember/service";++export default class Automation extends Controller {+ @service router;++ @computed("router.currentRouteName")+ get showNewAutomation() {+ return (+ this.router.currentRouteName === "adminPlugins.discourse-automation.index"+ );+ }++ @action+ newAutomation() {+ this.router.transitionTo("adminPlugins.discourse-automation.new");+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/discourse-automation-route-map.js b/plugins/automation/assets/javascripts/discourse/discourse-automation-route-map.jsnew file mode 100644index 00000000000..ebcfe99c8c9--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/discourse-automation-route-map.js@@ -0,0 +1,16 @@+export default {+ resource: "admin.adminPlugins",++ path: "/plugins",++ map() {+ this.route(+ "discourse-automation",++ function () {+ this.route("new");+ this.route("edit", { path: "/:id" });+ }+ );+ },+};diff --git a/plugins/automation/assets/javascripts/discourse/helpers/format-enabled-automation.js b/plugins/automation/assets/javascripts/discourse/helpers/format-enabled-automation.jsnew file mode 100644index 00000000000..0a3675350b7--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/helpers/format-enabled-automation.js@@ -0,0 +1,20 @@+import { htmlSafe } from "@ember/template";+import { iconHTML } from "discourse-common/lib/icon-library";++export default function formatEnabledAutomation(enabled, trigger) {+ if (enabled && trigger.id) {+ return htmlSafe(+ iconHTML("check", {+ class: "enabled-automation",+ title: "discourse_automation.models.automation.enabled.label",+ })+ );+ } else {+ return htmlSafe(+ iconHTML("times", {+ class: "disabled-automation",+ title: "discourse_automation.models.automation.disabled.label",+ })+ );+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/initializers/discourse-automation.js b/plugins/automation/assets/javascripts/discourse/initializers/discourse-automation.jsnew file mode 100644index 00000000000..b8c3dc54837--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/initializers/discourse-automation.js@@ -0,0 +1,84 @@+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { withPluginApi } from "discourse/lib/plugin-api";+import { makeArray } from "discourse-common/lib/helpers";++let _lastCheckedByHandlers = {};++function _handleLastCheckedByEvent(event) {+ ajax(`/append-last-checked-by/${event.currentTarget.postId}`, {+ type: "PUT",+ }).catch(popupAjaxError);+}++function _cleanUp() {+ Object.values(_lastCheckedByHandlers || {}).forEach((handler) => {+ handler.removeEventListener("click", _handleLastCheckedByEvent);+ });++ _lastCheckedByHandlers = {};+}++function _initializeDiscourseAutomation(api) {+ _initializeGLobalUserNotices(api);++ if (api.getCurrentUser()) {+ api.decorateCookedElement(_decorateCheckedButton, {+ id: "discourse-automation",+ });++ api.cleanupStream(_cleanUp);+ }+}++function _decorateCheckedButton(element, postDecorator) {+ if (!postDecorator) {+ return;+ }++ const elems = element.querySelectorAll(".btn-checked");+ const postModel = postDecorator.getModel();++ Array.from(elems).forEach((elem) => {+ const postId = postModel.id;+ elem.postId = postId;++ if (_lastCheckedByHandlers[postId]) {+ _lastCheckedByHandlers[postId].removeEventListener(+ "click",+ _handleLastCheckedByEvent,+ false+ );+ delete _lastCheckedByHandlers[postId];+ }++ _lastCheckedByHandlers[postId] = elem;+ elem.addEventListener("click", _handleLastCheckedByEvent, false);+ });+}++function _initializeGLobalUserNotices(api) {+ const currentUser = api.getCurrentUser();++ makeArray(currentUser?.global_notices).forEach((userGlobalNotice) => {+ api.addGlobalNotice("", userGlobalNotice.identifier, {+ html: userGlobalNotice.notice,+ level: userGlobalNotice.level,+ dismissable: true,+ dismissDuration: moment.duration(1, "week"),+ onDismiss() {+ ajax(`/user-global-notices/${userGlobalNotice.id}.json`, {+ type: "DELETE",+ }).catch(popupAjaxError);+ },+ });+ });+}++export default {+ name: "discourse-automation",++ initialize() {+ withPluginApi("0.8.24", _initializeDiscourseAutomation);+ },+};diff --git a/plugins/automation/assets/javascripts/discourse/lib/fabricators.js b/plugins/automation/assets/javascripts/discourse/lib/fabricators.jsnew file mode 100644index 00000000000..fd894b548d8--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/lib/fabricators.js@@ -0,0 +1,44 @@+/*+Fabricators are used to create fake data for testing purposes.+The following fabricators are available in lib folder to allow+styleguide to use them, and eventually to generate dummy data+in a placeholder component. It should not be used for any other case.+*/++import Automation from "../admin/models/discourse-automation-automation";+import Field from "../admin/models/discourse-automation-field";++let sequence = 0;++function fieldFabricator(args = {}) {+ const template = args.template || {};+ template.accepts_placeholders = args.accepts_placeholders ?? true;+ template.accepted_contexts = args.accepted_contexts ?? [];+ template.name = args.name ?? "name";+ template.component = args.component ?? "boolean";+ template.value = args.value ?? false;+ template.is_required = args.is_required ?? false;+ template.extra = args.extra ?? {};+ return Field.create(template, {+ type: args.target ?? "script",+ name: "script_name",+ });+}++function automationFabricator(args = {}) {+ const automation = new Automation();+ automation.id = args.id || sequence++;+ automation.trigger = {+ id: (sequence++).toString(),+ };+ automation.script = {+ id: (sequence++).toString(),+ };++ return automation;+}++export default {+ field: fieldFabricator,+ automation: automationFabricator,+};diff --git a/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation-edit.js b/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation-edit.jsnew file mode 100644index 00000000000..e8746126f90--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation-edit.js@@ -0,0 +1,59 @@+import { action } from "@ember/object";+import { hash } from "rsvp";+import { ajax } from "discourse/lib/ajax";+import DiscourseRoute from "discourse/routes/discourse";+import Field from "../admin/models/discourse-automation-field";++export default class AutomationEdit extends DiscourseRoute {+ controllerName = "admin-plugins-discourse-automation-edit";++ model(params) {+ return hash({+ scriptables: this.store+ .findAll("discourse-automation-scriptable")+ .then((result) => result.content),+ triggerables: ajax(+ `/admin/plugins/discourse-automation/triggerables.json?automation_id=${params.id}`+ ).then((result) => (result ? result.triggerables : [])),+ automation: this.store.find("discourse-automation-automation", params.id),+ });+ }++ _fieldsForTarget(automation, target) {+ return (automation[target].templates || []).map((template) => {+ const jsonField = automation[target].fields.find(+ (f) => f.name === template.name && f.component === template.component+ );+ return Field.create(+ template,+ {+ name: automation[target].id,+ type: target,+ },+ jsonField+ );+ });+ }++ setupController(controller, model) {+ const automation = model.automation;+ controller.setProperties({+ model,+ error: null,+ automationForm: {+ name: automation.name,+ enabled: automation.enabled,+ trigger: automation.trigger?.id,+ script: automation.script?.id,+ fields: this._fieldsForTarget(automation, "script").concat(+ this._fieldsForTarget(automation, "trigger")+ ),+ },+ });+ }++ @action+ refreshRoute() {+ return this.refresh();+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation-index.js b/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation-index.jsnew file mode 100644index 00000000000..da2410c18fc--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation-index.js@@ -0,0 +1,15 @@+import { action } from "@ember/object";+import DiscourseRoute from "discourse/routes/discourse";++export default class AutomationIndex extends DiscourseRoute {+ controllerName = "admin-plugins-discourse-automation-index";++ model() {+ return this.store.findAll("discourse-automation-automation");+ }++ @action+ triggerRefresh() {+ this.refresh();+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation-new.js b/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation-new.jsnew file mode 100644index 00000000000..77c1145674b--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation-new.js@@ -0,0 +1,13 @@+import { hash } from "rsvp";+import DiscourseRoute from "discourse/routes/discourse";++export default class AutomationNew extends DiscourseRoute {+ controllerName = "admin-plugins-discourse-automation-new";++ model() {+ return hash({+ scriptables: this.store.findAll("discourse-automation-scriptable"),+ automation: this.store.createRecord("discourse-automation-automation"),+ });+ }+}diff --git a/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation.js b/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation.jsnew file mode 100644index 00000000000..6c41265ca47--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/routes/admin-plugins-discourse-automation.js@@ -0,0 +1,5 @@+import DiscourseRoute from "discourse/routes/discourse";++export default class Automation extends DiscourseRoute {+ controllerName = "admin-plugins-discourse-automation";+}diff --git a/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation-edit.hbs b/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation-edit.hbsnew file mode 100644index 00000000000..f8aca97b9a0--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation-edit.hbs@@ -0,0 +1,169 @@+<ScrollTracker @name="discourse-automation-edit" />++<section class="discourse-automation-form edit">+ <form class="form-horizontal">+ <FormError @error={{error}} />++ <section class="form-section edit">+ <div class="control-group">+ <label class="control-label">+ {{i18n "discourse_automation.models.automation.name.label"}}+ </label>++ <div class="controls">+ <TextField+ @value={{automationForm.name}}+ @type="text"+ @autofocus="autofocus"+ @name="automation-name"+ class="input-large"+ />+ </div>+ </div>++ <div class="control-group">+ <label class="control-label">+ {{i18n "discourse_automation.models.script.name.label"}}+ </label>++ <div class="controls">+ <ComboBox+ @value={{automationForm.script}}+ @content={{model.scriptables}}+ @onChange={{action "onChangeScript"}}+ @options={{hash filterable=true}}+ class="scriptables"+ />+ </div>+ </div>+ </section>++ <section class="trigger-section form-section edit">+ <h2 class="title">+ {{i18n "discourse_automation.edit_automation.trigger_section.title"}}+ </h2>++ <div class="control-group">+ {{#if model.automation.script.forced_triggerable}}+ <div class="alert alert-warning">+ {{i18n+ "discourse_automation.edit_automation.trigger_section.forced"+ }}+ </div>+ {{/if}}++ <label class="control-label">+ {{i18n "discourse_automation.models.trigger.name.label"}}+ </label>++ <div class="controls">+ <ComboBox+ @value={{automationForm.trigger}}+ @content={{model.triggerables}}+ @onChange={{action "onChangeTrigger"}}+ @options={{hash+ filterable=true+ none="discourse_automation.select_trigger"+ disabled=model.automation.script.forced_triggerable+ }}+ class="triggerables"+ />+ </div>+ </div>++ {{#if automationForm.trigger}}+ {{#if model.automation.trigger.doc}}+ <div class="alert alert-info">+ <p>{{model.automation.trigger.doc}}</p>+ </div>+ {{/if}}++ {{#if+ (and+ model.automation.enabled+ model.automation.trigger.settings.manual_trigger+ )+ }}+ <div class="alert alert-info next-trigger">++ {{#if nextPendingAutomationAtFormatted}}+ <p>+ {{i18n+ "discourse_automation.edit_automation.trigger_section.next_pending_automation"+ date=nextPendingAutomationAtFormatted+ }}+ </p>+ {{/if}}++ <DButton+ @label="discourse_automation.edit_automation.trigger_section.trigger_now"+ @isLoading={{isTriggeringAutomation}}+ @action={{action "onManualAutomationTrigger" model.automation.id}}+ class="btn-primary trigger-now-btn"+ />+ </div>+ {{/if}}++ {{#each triggerFields as |field|}}+ <AutomationField+ @automation={{automation}}+ @field={{field}}+ @saveAutomation={{action "saveAutomation" automation}}+ />+ {{/each}}+ {{/if}}+ </section>++ {{#if automationForm.trigger}}+ {{#if scriptFields}}+ <section class="fields-section form-section edit">+ <h2 class="title">+ {{i18n "discourse_automation.edit_automation.fields_section.title"}}+ </h2>++ {{#if model.automation.script.with_trigger_doc}}+ <div class="alert alert-info">+ <p>{{model.automation.script.with_trigger_doc}}</p>+ </div>+ {{/if}}++ <div class="control-group">+ {{#each scriptFields as |field|}}+ <AutomationField+ @automation={{automation}}+ @field={{field}}+ @saveAutomation={{action "saveAutomation" automation}}+ />+ {{/each}}+ </div>+ </section>+ {{/if}}++ {{#if automationForm.trigger}}+ <div class="control-group automation-enabled alert alert-warning">+ <span>{{i18n+ "discourse_automation.models.automation.enabled.label"+ }}</span>+ <Input+ @type="checkbox"+ @checked={{automationForm.enabled}}+ {{on+ "click"+ (action (mut automationForm.enabled) value="target.checked")+ }}+ />+ </div>+ {{/if}}++ <div class="control-group">+ <DButton+ @isLoading={{isUpdatingAutomation}}+ @label="discourse_automation.update"+ @type="submit"+ @action={{action "saveAutomation" automation}}+ class="btn-primary update-automation"+ />+ </div>+ {{/if}}+ </form>+</section>\ No newline at end of filediff --git a/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation-index.hbs b/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation-index.hbsnew file mode 100644index 00000000000..054259bb127--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation-index.hbs@@ -0,0 +1,88 @@+{{#if model.length}}+ <table class="automations">+ <thead>+ <tr>+ <th></th>+ <th>{{i18n "discourse_automation.models.automation.name.label"}}</th>+ <th>{{i18n "discourse_automation.models.automation.trigger.label"}}</th>+ <th>{{i18n "discourse_automation.models.automation.script.label"}}</th>+ <th>{{i18n+ "discourse_automation.models.automation.last_updated_by.label"+ }}</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ {{#each model as |automation|}}+ <tr>+ {{#if automation.script.not_found}}+ <td colspan="5" class="alert alert-danger">+ {{i18n+ "discourse_automation.scriptables.not_found"+ script=automation.script.id+ automation=automation.name+ }}+ </td>+ {{else if automation.trigger.not_found}}+ <td colspan="5" class="alert alert-danger">+ {{i18n+ "discourse_automation.triggerables.not_found"+ trigger=automation.trigger.id+ automation=automation.name+ }}+ </td>+ {{else}}+ <td+ role="button"+ {{on "click" (fn this.editAutomation automation)}}+ >{{format-enabled-automation+ automation.enabled+ automation.trigger+ }}</td>+ <td+ tabindex="0"+ role="button"+ {{on "keypress" (fn this.editAutomation automation)}}+ {{on "click" (fn this.editAutomation automation)}}+ >{{automation.name}}</td>+ <td+ role="button"+ {{on "click" (fn this.editAutomation automation)}}+ >{{if automation.trigger.id automation.trigger.name "-"}}</td>+ <td+ role="button"+ {{on "click" (fn this.editAutomation automation)}}+ >{{automation.script.name}} (v{{automation.script.version}})</td>+ <td>+ <a+ href={{automation.last_updated_by.userPath}}+ data-user-card={{automation.last_updated_by.username}}+ >+ {{avatar automation.last_updated_by imageSize="small"}}+ </a>+ {{format-date automation.updated_at leaveAgo="true"}}+ </td>+ {{/if}}++ <td>+ <DButton+ @icon="trash-alt"+ @action={{action "destroyAutomation" automation}}+ class="btn-danger"+ />+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+{{else}}+ <div class="alert alert-info">+ <p>{{i18n "discourse_automation.no_automation_yet"}}</p>+ <DButton+ @label="discourse_automation.create"+ @icon="plus"+ @action={{action "newAutomation"}}+ class="btn-primary"+ />+ </div>+{{/if}}\ No newline at end of filediff --git a/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation-new.hbs b/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation-new.hbsnew file mode 100644index 00000000000..967cb76166b--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation-new.hbs@@ -0,0 +1,53 @@+<section class="discourse-automation-form new">+ <form class="form-horizontal">+ <FormError @error={{error}} />++ <div class="control-group">+ <label class="control-label">+ {{i18n "discourse_automation.models.automation.name.label"}}+ </label>++ <div class="controls">+ <TextField+ @value={{form.name}}+ @type="text"+ @autofocus="autofocus"+ @name="automation-name"+ class="input-large"+ />+ </div>+ </div>++ <div class="control-group">+ <label class="control-label">+ {{i18n "discourse_automation.models.automation.script.label"}}+ </label>++ <div class="controls">+ <DropdownSelectBox+ @value={{form.script}}+ @content={{model.scriptables.content}}+ @onChange={{action (mut form.script)}}+ @options={{hash+ showCaret=true+ filterable=true+ none="discourse_automation.select_script"+ }}+ class="scriptables"+ />+ </div>+ </div>++ <div class="control-group">++ <div class="controls">+ <DButton+ @icon="plus"+ @label="discourse_automation.create"+ @action={{action "saveAutomation" model.automation}}+ class="btn-primary create-automation"+ />+ </div>+ </div>+ </form>+</section>\ No newline at end of filediff --git a/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation.hbs b/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation.hbsnew file mode 100644index 00000000000..516c8183c9c--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/templates/admin-plugins-discourse-automation.hbs@@ -0,0 +1,53 @@+<LinkTo+ @route="adminPlugins.discourse-automation"+ class="discourse-automation-title"+>+ <svg+ width="32"+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 41.3 41.3"+ ><title>Asset 4</title><path+ d="M20.42,40.21a2.52,2.52,0,0,1-1.78-.78l-.08-.07-1.94-2a2.48,2.48,0,0,1-.72-1.23l-1.15.64a2.51,2.51,0,0,1-1.25.33,2.59,2.59,0,0,1-1.86-.79l-.73-.76a1.79,1.79,0,0,1-.24-.21l-.84-.88a1.31,1.31,0,0,1-.27-.24l-4.67-4.9A2.5,2.5,0,0,1,4.5,26.3l.92-1.47-.48-.14a2.3,2.3,0,0,1-.9-.47l-.17-.14L1.72,21.93a2.09,2.09,0,0,1-.14-.17A2.55,2.55,0,0,1,1,20.1l.08-3.85a2.57,2.57,0,0,1,2-2.44l2.73-.65L6,12.78,4.59,10.33a2.57,2.57,0,0,1,.47-3.11L7.84,4.56a2.56,2.56,0,0,1,1.77-.72A2.74,2.74,0,0,1,11,4.23l2.46,1.52.3-.11.78-2.77A2.6,2.6,0,0,1,17,1l3.88.08.14,0a1,1,0,0,1,.24,0,2.65,2.65,0,0,1,.51.15h0a1.11,1.11,0,0,1,.31.15l.28.2.08.06a.52.52,0,0,1,.11.1l2.08,2.08a2.57,2.57,0,0,1,.73,1.25l.1.45,1.56-.87a2.5,2.5,0,0,1,1.24-.33,2.62,2.62,0,0,1,1.87.8l.55.57.21.19L32,7a1.43,1.43,0,0,1,.29.24l4.63,4.86a2.56,2.56,0,0,1,.43,3.12l-.84,1.36a2.66,2.66,0,0,1,.86.5,1.27,1.27,0,0,1,.12.1l.09.1,2,2a.64.64,0,0,1,.1.13,2.56,2.56,0,0,1,.69,1.77L40.21,25a2.56,2.56,0,0,1-2,2.45l-2.62.61c-.07.18-.14.35-.22.53l1.3,2.33A2.55,2.55,0,0,1,36.24,34l-2.78,2.67a2.6,2.6,0,0,1-1.78.71h0A2.61,2.61,0,0,1,30.33,37l-2.2-1.36c-.21.08-.42.17-.63.24l-.71,2.52a2.57,2.57,0,0,1-2.47,1.87Z"+ ></path><path+ d="M17,2l3.85.08.13,0h0l.07,0a1.27,1.27,0,0,1,.38.11l.1,0,.08.06.16.12.11.08,2,2h0a1.54,1.54,0,0,1,.52.83l.41,1.74,2.72-1.52a1.61,1.61,0,0,1,.75-.2h.05a1.57,1.57,0,0,1,1.1.48l.65.69h0a.25.25,0,0,1,.1.08l1.14,1.19a.32.32,0,0,1,.17.12l4.64,4.86a1.58,1.58,0,0,1,.3,1.91l-1.53,2.48,1.16.33a1.54,1.54,0,0,1,.64.38h0l0,0h0L37.82,19l0,0,1,1h0a1.55,1.55,0,0,1,.51,1.17L39.21,25A1.55,1.55,0,0,1,38,26.48l-3.13.74a12.5,12.5,0,0,1-.61,1.41l1.56,2.79a1.56,1.56,0,0,1-.28,1.9L32.77,36a1.56,1.56,0,0,1-1.09.44,1.53,1.53,0,0,1-.82-.24L28.2,34.54a13.33,13.33,0,0,1-1.52.6l-.85,3a1.57,1.57,0,0,1-1.51,1.14h0l-3.85-.09a1.57,1.57,0,0,1-1.17-.57h0L17.32,36.7a1.47,1.47,0,0,1-.45-.77l-.3-1.27L14.26,36a1.49,1.49,0,0,1-.76.2,1.61,1.61,0,0,1-1.14-.48l-.82-.86a.49.49,0,0,1-.14-.11l-1-1a.53.53,0,0,1-.17-.12L5.61,28.68a1.49,1.49,0,0,1-.26-1.85l1.58-2.55,0-.07-1.69-.48a1.55,1.55,0,0,1-.63-.37h0l-.1-.1h0L3.31,22.1h0l-.86-.87h0A1.58,1.58,0,0,1,2,20.12l.08-3.85a1.58,1.58,0,0,1,1.21-1.49L6.52,14a13.1,13.1,0,0,1,.58-1.27L5.47,9.84a1.56,1.56,0,0,1,.28-1.9L8.53,5.28a1.55,1.55,0,0,1,1.08-.43h0a1.48,1.48,0,0,1,.79.23l2.9,1.79c.39-.17.79-.32,1.21-.46l.92-3.27A1.6,1.6,0,0,1,17,2m0-2h0a3.62,3.62,0,0,0-3.46,2.6l-.49,1.74-1.56-1a3.47,3.47,0,0,0-1.8-.53H9.61a3.58,3.58,0,0,0-2.46,1L4.37,6.5a3.55,3.55,0,0,0-.65,4.32l.9,1.59-1.79.42a3.57,3.57,0,0,0-2.74,3.4L0,20.08a3.55,3.55,0,0,0,.77,2.27,2.09,2.09,0,0,0,.24.28l.87.87h0L3,24.67h0l.11.11a2.48,2.48,0,0,0,.3.25,4.53,4.53,0,0,0,.46.3l-.27.44a3.47,3.47,0,0,0,.52,4.28L8.83,35a2.67,2.67,0,0,0,.34.29l.78.82a2,2,0,0,0,.3.27l.67.7a3.59,3.59,0,0,0,2.58,1.1,3.67,3.67,0,0,0,1.74-.45l.21-.12a3.64,3.64,0,0,0,.48.56l1.92,1.92.11.11a3.55,3.55,0,0,0,2.43,1l3.85.09h.08a3.58,3.58,0,0,0,3.43-2.6l.51-1.78,1.55,1a3.55,3.55,0,0,0,4.34-.45l2.78-2.67a3.57,3.57,0,0,0,.65-4.32l-.9-1.59,1.78-.42A3.55,3.55,0,0,0,41.21,25l.09-3.84a3.55,3.55,0,0,0-.92-2.45l-.17-.19-1-.95,0,0h0l-1-1.06-.13-.12-.19-.16.3-.48a3.58,3.58,0,0,0-.57-4.35L33,6.56a2.3,2.3,0,0,0-.35-.31l-1-1A2.53,2.53,0,0,0,31.39,5l-.5-.52a3.52,3.52,0,0,0-2.49-1.1h-.1a3.53,3.53,0,0,0-1.73.46l-.49.27a3.87,3.87,0,0,0-.69-.93.46.46,0,0,0-.07-.07l-2-2a1.59,1.59,0,0,0-.24-.2L23,.83,22.75.66l0,0a2,2,0,0,0-.62-.31h0a3.83,3.83,0,0,0-.58-.16A1.59,1.59,0,0,0,21.13.1h-.22L17.06,0Z"+ ></path><path+ d="M8.78,24.14l1.93,2.21a13.21,13.21,0,0,0,.83,2.11L9.85,31.19A1.15,1.15,0,0,0,10,32.6l2.66,2.78a1.15,1.15,0,0,0,1.4.21L17,34a11.35,11.35,0,0,0,1.6.69l.77,3.27a1.15,1.15,0,0,0,1.1.89l3.85.09A1.16,1.16,0,0,0,25.43,38l.91-3.23a12.77,12.77,0,0,0,1.89-.74l2.85,1.76a1.13,1.13,0,0,0,1.4-.15L35.26,33a1.15,1.15,0,0,0,.21-1.4l-1.67-3a12.63,12.63,0,0,0,.77-1.77l3.34-.79A1.15,1.15,0,0,0,38.8,25l.09-3.85A1.16,1.16,0,0,0,38,20l-3.4-1a11.44,11.44,0,0,0-.52-1.35l2-3.2a1.18,1.18,0,0,0-.25-1.41L33.19,10.3a1.18,1.18,0,0,0-.81-.36.85.85,0,0,0-.48.15l-3.17,1.77a14.55,14.55,0,0,0-1.8-.81L24.67,9.76c-.12-.52-.23-1.5-.75-1.52L21.15,6.56A1.16,1.16,0,0,0,20,7.4l-1,3.48a11.87,11.87,0,0,0-1.57.61L14.37,9.58a1.23,1.23,0,0,0-.58-.18,1.2,1.2,0,0,0-.83.33l-2.78,2.66a1.17,1.17,0,0,0-.21,1.4l1.74,3.1A11.92,11.92,0,0,0,11,18.52l-3.45.81a1.16,1.16,0,0,0-.89,1.1l.63,2.19C7.26,23.15,9.4,22.1,8.78,24.14Zm14.1-8.74a7.33,7.33,0,1,1-7.48,7.16A7.32,7.32,0,0,1,22.88,15.4Z"+ fill="#00aeef"+ ></path><path+ d="M8.54,23.9l1.2,1.48a12.89,12.89,0,0,0,.84,2.11l-1.7,2.74A1.16,1.16,0,0,0,9,31.63l2.66,2.78a1.14,1.14,0,0,0,1.4.21L16,33a12.46,12.46,0,0,0,1.59.68l.77,3.27a1.14,1.14,0,0,0,1.1.89l3.85.09a1.17,1.17,0,0,0,1.14-.84l.91-3.24a11.3,11.3,0,0,0,1.88-.74l2.85,1.76a1.16,1.16,0,0,0,1.41-.14l2.78-2.67a1.15,1.15,0,0,0,.21-1.39l-1.67-3a12.74,12.74,0,0,0,.76-1.77l3.34-.79A1.14,1.14,0,0,0,37.83,24l.09-3.85A1.16,1.16,0,0,0,37.08,19l-3.41-1a11,11,0,0,0-.51-1.35l1.93-3.15a1.15,1.15,0,0,0-.15-1.41L32.28,9.38A1.17,1.17,0,0,0,31.47,9a1,1,0,0,0-.54.1L27.76,10.9a11.24,11.24,0,0,0-1.8-.81l-2.28.18c-1.46,2.2-.07-2.12-.59-2.13L20.18,5.59a1.16,1.16,0,0,0-1.13.84l-1,3.48a12,12,0,0,0-1.58.61L13.4,8.61a1.15,1.15,0,0,0-1.4.15L9.22,11.42A1.14,1.14,0,0,0,9,12.82l1.74,3.11A11.85,11.85,0,0,0,10,17.55l-3.44.81a1.14,1.14,0,0,0-.89,1.1l1.07,2.71C6.74,22.7,9.89,23.35,8.54,23.9Zm13.38-9.47a7.33,7.33,0,1,1-7.49,7.17A7.33,7.33,0,0,1,21.92,14.43Z"+ fill="#00a94f"+ ></path><path+ d="M3.25,21.27l3.31.93a12.89,12.89,0,0,0,.84,2.11L5.7,27.05a1.09,1.09,0,0,0,.21,1.35l2.66,2.78a1.08,1.08,0,0,0,1.34.26l2.93-1.63a12.46,12.46,0,0,0,1.59.68l.77.31a1.16,1.16,0,0,0,1.1.89l3.85,3.05a1.17,1.17,0,0,0,1.14-.84l.91-3.24a11.3,11.3,0,0,0,1.88-.74l2.85,1.77a1.18,1.18,0,0,0,1.41-.15l2.78-2.67a1.15,1.15,0,0,0,.21-1.39l-1.67-3a12.74,12.74,0,0,0,.76-1.77l3.34-.79a1.14,1.14,0,0,0,.89-1.09l-2.88-2.37a1.16,1.16,0,0,0-.84-1.14l-.44-2.44A11,11,0,0,0,30,13.54l2-3.2a1.16,1.16,0,0,0-.15-1.4L29.15,6.15a1.15,1.15,0,0,0-.81-.35,1.12,1.12,0,0,0-.59.14L24.58,7.72a11.24,11.24,0,0,0-1.8-.81L22,3.39a1.14,1.14,0,0,0-1.1-.89L17,2.41a1.16,1.16,0,0,0-1.13.84l-1,3.48a12,12,0,0,0-1.58.61L10.22,5.43a1.15,1.15,0,0,0-1.4.15L6,8.24a1.14,1.14,0,0,0-.21,1.4l1.74,3.11a11.85,11.85,0,0,0-.74,1.62l-3.44.81a1.14,1.14,0,0,0-.89,1.1l-.09,3.85A1.17,1.17,0,0,0,3.25,21.27Zm15.49-10a7.33,7.33,0,1,1-7.49,7.17A7.33,7.33,0,0,1,18.74,11.25Z"+ fill="#d0232b"+ ></path><path+ d="M24.39,20.28A4.71,4.71,0,0,1,16.8,24a4.71,4.71,0,1,0,6.61-6.61A4.74,4.74,0,0,1,24.39,20.28Z"+ fill="#00a94f"+ ></path><path+ d="M4,22,7.32,23a12.12,12.12,0,0,0,.83,2.12L6.46,27.8a1.16,1.16,0,0,0,.22,1.41L9.34,32a1.05,1.05,0,0,0,1.33.21l2.92-1.64a11.35,11.35,0,0,0,1.6.69L17.44,33a1.16,1.16,0,0,0,1.1.89l2.36,1.56A1.14,1.14,0,0,0,22,34.65L23,31.42a13.35,13.35,0,0,0,1.88-.74l2.85,1.76a1.15,1.15,0,0,0,1.41-.15l2.78-2.66a1.15,1.15,0,0,0,.21-1.4l-1.67-3a12.63,12.63,0,0,0,.77-1.77l3.34-.79a1.15,1.15,0,0,0,.89-1.1L34,19.23a1.15,1.15,0,0,0-.84-1.14l-1.92-2.45a12,12,0,0,0-.52-1.34l2-3.2a1.16,1.16,0,0,0-.14-1.41L29.9,6.91a1.15,1.15,0,0,0-.81-.36,1.26,1.26,0,0,0-.59.15L25.34,8.47a14.55,14.55,0,0,0-1.8-.81l-.83-3.52a1.15,1.15,0,0,0-1.1-.89l-3.85-.08A1.15,1.15,0,0,0,16.62,4l-1,3.48a12.58,12.58,0,0,0-1.58.61L11,6.19A1.13,1.13,0,0,0,10.4,6a1.23,1.23,0,0,0-.83.32L6.79,9a1.15,1.15,0,0,0-.21,1.4l1.74,3.1a11.4,11.4,0,0,0-.73,1.63l-3.45.81A1.15,1.15,0,0,0,3.25,17l-.08,3.85A1.15,1.15,0,0,0,4,22ZM19.49,12A7.33,7.33,0,1,1,12,19.17,7.33,7.33,0,0,1,19.49,12Z"+ fill="#f15d22"+ ></path><circle cx="20.64" cy="20.86" r="8.33" fill="#fff"></circle><path+ d="M36,17.92l-3.41-1q-.23-.69-.51-1.35l2-3.2A1.18,1.18,0,0,0,33.88,11L31.22,8.22a1.13,1.13,0,0,0-.81-.35,1.1,1.1,0,0,0-.59.14L26.65,9.79A12.73,12.73,0,0,0,24.85,9L24,5.46a1.14,1.14,0,0,0-1.1-.89l-3.85-.09a1.15,1.15,0,0,0-1.13.84L17,8.8a11.87,11.87,0,0,0-1.57.61L12.29,7.5a1.15,1.15,0,0,0-1.4.15L8.1,10.31a1.17,1.17,0,0,0-.21,1.4l1.74,3.1a14,14,0,0,0-.73,1.63l-3.44.81a1.14,1.14,0,0,0-.89,1.1L4.48,22.2a1.16,1.16,0,0,0,.84,1.13l3.31.94a12.89,12.89,0,0,0,.84,2.11l-1.7,2.73a1.16,1.16,0,0,0,.15,1.41l2.66,2.78a1.15,1.15,0,0,0,1.4.21l2.92-1.64a11.87,11.87,0,0,0,1.6.69l.77,3.27a1.14,1.14,0,0,0,1.1.89l3.85.09A1.16,1.16,0,0,0,23.35,36l.92-3.24A11.3,11.3,0,0,0,26.15,32L29,33.75a1.15,1.15,0,0,0,1.4-.14l2.78-2.67a1.14,1.14,0,0,0,.21-1.4l-1.67-3a12.14,12.14,0,0,0,.77-1.77L35.83,24a1.14,1.14,0,0,0,.89-1.1l.09-3.85A1.16,1.16,0,0,0,36,17.92ZM25.72,23.64l-3.84,1.78-2.38.87-3-1.46-1.35-2.51-.22-3.75,2.65-2.65h3.56l3.2,1.55,2.2,2.63Z"+ fill="#fff9ae"+ ></path><path+ d="M20.45,26.15a5.92,5.92,0,1,1,5.93-5.92A5.93,5.93,0,0,1,20.45,26.15Zm0-10.57a4.65,4.65,0,1,0,4.65,4.65A4.65,4.65,0,0,0,20.45,15.58Z"+ stroke="#000"+ stroke-miterlimit="10"+ ></path></svg>++ <h1 class="title">+ {{i18n "discourse_automation.title"}}+ </h1>++ {{#if showNewAutomation}}+ <DButton+ @label="discourse_automation.create"+ @icon="plus"+ @action={{action "newAutomation"}}+ class="new-automation"+ />+ {{/if}}+</LinkTo>++<hr />++{{outlet}}\ No newline at end of filediff --git a/plugins/automation/assets/javascripts/discourse/templates/components/form-error.hbs b/plugins/automation/assets/javascripts/discourse/templates/components/form-error.hbsnew file mode 100644index 00000000000..95a67e85083--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/templates/components/form-error.hbs@@ -0,0 +1,5 @@+{{#if error}}+ <div class="alert alert-error form-errors">+ {{html-safe error}}+ </div>+{{/if}}\ No newline at end of filediff --git a/plugins/automation/assets/javascripts/discourse/templates/components/topic-trigger.hbs b/plugins/automation/assets/javascripts/discourse/templates/components/topic-trigger.hbsnew file mode 100644index 00000000000..3c893a1284d--- /dev/null+++ b/plugins/automation/assets/javascripts/discourse/templates/components/topic-trigger.hbs@@ -0,0 +1,12 @@+<div class="control-group">+ <label class="control-label">+ {{i18n "discourse_automation.triggerables.topic.topic_id.label"}}+ </label>++ <div class="controls">+ <Input+ @value={{metadata.topic_id}}+ {{on "input" (action (mut metadata.topic_id) value="target.value")}}+ />+ </div>+</div>\ No newline at end of filediff --git a/plugins/automation/assets/stylesheets/common/discourse-automation.scss b/plugins/automation/assets/stylesheets/common/discourse-automation.scssnew file mode 100644index 00000000000..7ac22c3f026--- /dev/null+++ b/plugins/automation/assets/stylesheets/common/discourse-automation.scss@@ -0,0 +1,313 @@+.discourse-automation {+ .automations {+ .relative-date {+ font-size: $font-down-1;+ }++ td[role="button"] {+ cursor: pointer;+ }+ }+}++.discourse-automation-title {+ display: flex;+ align-items: center;+ height: 40px;++ .title {+ margin: 0 0 0 0.5em;+ font-weight: 700;+ font-size: $font-up-3;+ }++ .new-automation {+ margin-left: auto;+ }+}++.enabled-automation {+ color: var(--success);+}++.disabled-automation {+ color: var(--danger);+}++.discourse-automation-form {+ .scriptables,+ .triggerables {+ .select-kit-body {+ max-height: 250px;+ }+ }++ .alert {+ padding: 1em;+ background: var(--primary-very-low);+ border-left-style: solid;+ border-left-width: 5px;++ &.alert-info {+ border-left-color: var(--tertiary-low);+ }++ &.alert-warning {+ border-left-color: var(--highlight);+ background: var(--highlight-low);+ }++ &.alert-error {+ border-left-color: var(--danger);+ background: var(--danger-low);+ }++ p {+ margin: 0;+ }+ }++ .form-horizontal {+ .control-label {+ margin: 0.25em 0.25em 0.25em 0;+ text-align: left;+ width: 180px;+ line-height: 27px;+ }++ .controls {+ margin-left: 185px;+ }++ .boolean-field {+ .controls {+ display: flex;+ }+ }+ }++ .automation-presentation {+ border-left: 5px solid var(--primary-very-low);+ padding: 0.5em;++ .automation-name {+ font-size: $font-up-2;+ }++ .automation-doc {+ margin: 0;+ }+ }++ .automation-presentation + .control-group {+ margin-top: 2em;+ }++ .scripts-list {+ width: 210px;++ .select-kit-header {+ background: var(--secondary);+ border: 1px solid var(--primary-medium);+ border-radius: 0;++ &:hover {+ color: var(--primary);+ }+ }+ }++ .script-doc {+ background: var(--primary-very-low);+ border-left: 3px solid var(--primary-low);+ }++ .form-section {+ .title {+ padding-bottom: 0.5em;+ margin-bottom: 1em;+ border-bottom: 1px solid var(--primary-low);+ }++ .input-large,+ .select-kit,+ .d-date-time-input {+ width: 300px;++ .select-kit,+ input[type="text"] {+ width: auto;+ }+ }++ .period-field {+ line-height: 34px;++ .controls {+ display: flex;+ }++ .select-kit {+ width: 150px;+ margin-left: 6px;++ .select-kit-header {+ height: 34px;+ }+ }++ input {+ width: 100px;+ max-height: 34px;+ margin: 0 0 0 6px;+ }+ }++ .d-date-time-input {+ border-color: var(--primary-medium);+ }+ }++ .control-group {+ .control-description {+ color: var(--primary-medium);+ width: 100%;+ margin: 0;+ padding: 0.25em 0;+ }++ &.automation-enabled {+ display: flex;+ align-items: center;+ justify-content: flex-start;+ padding: 1em;++ .ember-checkbox {+ margin: 0 0 0 1em;+ padding: 0;+ }++ .control-label.disabled {+ color: var(--danger);+ }+ }+ }++ .controls-row {+ display: flex;++ input {+ margin-bottom: 0;+ }+ }++ .field-wrapper {+ display: flex;+ flex-direction: column;+ }++ .text-field {+ .ember-text-field {+ width: 300px;+ }+ }++ .message-field {+ textarea {+ width: 300px;+ height: 200px;+ }+ }++ .next-trigger {+ padding: 1em;++ p {+ margin: 0;+ padding: 0 0 0.5em 0;+ }+ }++ .pms-field {+ .actions {+ display: flex;+ justify-content: flex-end;+ align-items: center;++ &.header {+ justify-content: space-between;+ margin: 1em 0;+ }+ }++ .pm-field {+ margin-bottom: 1em;++ .control-group {+ display: flex;+ flex-direction: column;+ .control-label {+ width: 100%;+ }+ .controls {+ margin: 0;+ }+ }++ .d-editor,+ .d-editor-container {+ display: flex;+ flex: 1;+ justify-content: space-between;++ .d-editor-input {+ min-height: 200px;+ }+ }+ }++ .d-editor-textarea-wrapper {+ box-sizing: border-box;+ min-width: 300px;+ }++ .pm-field:not(:last-child) {+ margin-bottom: 1em;+ }+ .pm-title {+ width: 100%;+ }+ .pm-textarea {+ width: 100%;+ box-sizing: border-box;+ height: 200px;+ }++ .no-pm {+ border: 1px solid var(--tertiary);+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 1em;+ margin: 1em 0;+ flex-direction: column;+ }+ }+}++.placeholders-list {+ display: flex;+ align-items: center;+ flex-wrap: wrap;++ .placeholder-item {+ border-radius: 3px;+ font-size: $font-down-2;+ margin: 0.5em 0.5em 0 0;+ }+}++details[open] > summary:first-of-type ~ .btn-checked,+details.open > summary:first-of-type ~ .btn-checked {+ display: inline-flex;+}diff --git a/plugins/automation/config/locales/client.ar.yml b/plugins/automation/config/locales/client.ar.ymlnew file mode 100644index 00000000000..10a1b9f3bdf--- /dev/null+++ b/plugins/automation/config/locales/client.ar.yml@@ -0,0 +1,368 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ar:+ js:+ discourse_automation:+ title: الأتمتة+ create: إنشاء+ update: تحديث+ select_script: حدِّد برنامجًا نصيًا+ select_trigger: حدِّد مشغلًا+ confirm_automation_reset: سيؤدي هذا الإجراء إلى إعادة تعيين البرنامج النصي وتشغيل الخيارات، وسيتم حفظ الحالة الجديدة، هل تريد المتابعة؟+ confirm_automation_trigger: سيؤدي هذا الإجراء إلى تشغيل الأتمتة، هل تريد المتابعة؟+ no_automation_yet: لم تُنشئ أي أتمتة حتى الآن.+ edit_automation:+ trigger_section:+ forced: يتم فرض هذا المشغِّل بواسطة البرنامج النصي.+ next_pending_automation: "سيتم تشغيل الأتمتة التالية في: %{date}"+ trigger_now: "التشغيل الآن"+ title: متى/ماذا...+ fields_section:+ title: خيارات البرنامج النصي+ destroy_automation:+ confirm: "هل تريد بالتأكيد حذف `%{name}`؟"+ fields:+ key_value:+ label:+ zero: تعديل التكوين (%{count})+ one: تعديل التكوين (%{count})+ two: تعديل التكوين (%{count})+ few: تعديل التكوين (%{count})+ many: تعديل التكوين (%{count})+ other: تعديل التكوين (%{count})+ user:+ label: المستخدم+ pm:+ title:+ label: العنوان+ raw:+ label: النص+ pms:+ confirm_remove_pm: "هل تريد بالتأكيد إزالة هذه الرسالة الشخصية؟"+ placeholder_title: عنوان الرسالة الشخصية+ add_pm: إضافة رسالة شخصية+ no_pm_created: لم تُنشئ أي رسالة شخصية بعد. سيتم إرسال الرسائل الشخصية بعد تشغيل الأتمتة.+ title:+ label: العنوان+ raw:+ label: النص+ delay:+ label: التأخير (بالدقائق)+ prefers_encrypt:+ label: يشفِّر الرسائل الشخصية إذا كانت متاحة+ group:+ label: المجموعة+ text:+ label: النص+ triggerables:+ not_found: تعذَّر العثور على المشغِّل `%{trigger}` للأتمتة `%{automation}`، تأكَّد من تثبيت المكوِّن الإضافي ذي الصلة+ user_badge_granted:+ fields:+ badge:+ label: شارة+ only_first_grant:+ label: على المنحة الأولى فقط+ stalled_topic:+ durations:+ PT1H: "ساعة واحدة"+ P1D: "يوم واحد"+ P1W: "أسبوع واحد"+ P2W: "أسبوعان"+ P1M: "شهر واحد"+ P3M: "ثلاثة أشهر"+ P6M: "ستة أشهر"+ P1Y: "عام واحد"+ fields:+ categories:+ label: يقتصر على الفئات+ tags:+ label: يقتصر على الوسوم+ stalled_after:+ label: توقفت بعد+ recurring:+ every: كل+ frequencies:+ minute: دقيقة+ hour: ساعة+ day: يوم+ weekday: يوم من أيام الأسبوع+ week: أسبوع+ month: شهر+ year: عام+ fields:+ recurrence:+ label: التكرار+ start_date:+ label: تاريخ البدء+ stalled_wiki:+ durations:+ PT1H: "ساعة واحدة"+ P1D: "يوم واحد"+ P1W: "أسبوع واحد"+ P2W: "أسبوعان"+ P1M: "شهر واحد"+ P3M: "ثلاثة أشهر"+ P6M: "ستة أشهر"+ P1Y: "عام واحد"+ fields:+ restricted_category:+ label: مقيَّد إلى الفئة+ stalled_after:+ label: تأخير المشغِّل+ description: يحدِّد التأخير بين تعديل Wiki الأخير ومشغِّل الأتمتة+ retriggered_after:+ label: التأخير في إعادة التشغيل+ description: يحدِّد التأخير بين المشغِّل الأول والمشغِّل التالي، إذا لم يتم تعديل Wiki بعد أول مشغِّل+ user_added_to_group:+ fields:+ joined_group:+ label: مجموعة متتبَّعة+ user_removed_from_group:+ fields:+ left_group:+ label: مجموعة متتبَّعة+ user_promoted:+ fields:+ restricted_group:+ label: التقييد إلى المجموعة+ trust_level_transition:+ label: نقل مستوى الثقة+ trust_levels:+ ALL: "كل مستويات الثقة"+ TL01: "مستوى الثقة 0 إلى المستوى الثقة 1"+ TL12: "مستوى الثقة 1 إلى المستوى الثقة 2"+ TL23: "مستوى الثقة 2 إلى المستوى الثقة 3"+ TL34: "مستوى الثقة 3 إلى المستوى الثقة 4"+ point_in_time:+ fields:+ execute_at:+ label: التنفيذ في+ topic:+ fields:+ restricted_topic:+ label: معرِّف الموضوع+ post_created_edited:+ fields:+ action_type:+ label: نوع الإجراء+ description: "اختياري، تقييد التشغيل إلى الأحداث التي تم إنشاؤها أو تحريرها فقط"+ valid_trust_levels:+ label: مستويات الثقة الصالحة+ description: سيتم التشغيل فقط إذا تم إنشاء المنشور بواسطة مستخدم في مستويات الثقة هذه، ويتم تعيينه افتراضيًا على أي مستوى ثقة+ restricted_category:+ label: الفئة+ description: اختياري، لن يتم تشغيله إلا إذا كان موضوع المشاركة ضمن هذه الفئة+ restricted_group:+ label: مجموعة+ description: اختياري، لن يتم تشغيله إلا إذا كان موضوع المشاركة عبارة عن رسالة خاصة في البريد الوارد لهذه المجموعة+ ignore_group_members:+ label: تجاهل أعضاء المجموعة+ description: تخطي المشغِّل إذا كان المرسل عضوًا في المجموعة المحدَّدة أعلاه+ ignore_automated:+ label: تجاهل الرسائل الآلية+ description: تخطي المشغِّل إذا كان لدى المرسل بريد إلكتروني غير صحيح أو كان من مصدرٍ آلي. لا ينطبق ذلك إلا على المنشورات التي تم إنشاؤها عبر البريد الإلكتروني+ first_post_only:+ label: المنشور الأول فقط+ description: لن يتم تشغيله إلا إذا كان المنشور هو أول منشور أنشأه المستخدم+ first_topic_only:+ label: الموضوع الأول فقط+ description: لن يتم تشغيله إلا إذا كان الموضوع هو أول موضوع أنشأه المستخدم+ created: تم إنشاؤها+ edited: تم تحريرها+ category_created_edited:+ fields:+ restricted_category:+ label: الفئة الرئيسية+ description: اختياري، يسمح بتقييد تنفيذ المشغِّل لهذه الفئة+ pm_created:+ fields:+ restricted_user:+ label: المستخدمون+ description: لن يتم تشغيله إلا للرسائل الخاصة المُرسَلة إلى هذا المستخدم+ restricted_group:+ label: مجموعة+ description: لن يتم تشغيله إلا للرسائل الخاصة المُرسَلة إلى هذه المجموعة+ ignore_staff:+ label: تجاهل فريق العمل+ description: تخطي المشغِّل إذا كان المُرسل مستخدمًا من فريق العمل+ ignore_group_members:+ label: تجاهل أعضاء المجموعة+ description: تخطي المشغِّل إذا كان المرسل عضوًا في المجموعة المحدَّدة أعلاه+ ignore_automated:+ label: تجاهل الرسائل الآلية+ description: تخطي المشغِّل إذا كان لدى المرسل بريد إلكتروني غير صحيح أو كان من مصدرٍ آلي. لا ينطبق ذلك إلا على الرسائل الخاصة التي تم إنشاؤها عبر البريد الإلكتروني+ valid_trust_levels:+ label: مستويات الثقة الصالحة+ description: سيتم التشغيل فقط إذا تم إنشاء المنشور بواسطة مستخدم في مستويات الثقة هذه، ويتم تعيينه افتراضيًا على أي مستوى ثقة+ after_post_cook:+ fields:+ valid_trust_levels:+ label: مستويات الثقة الصالحة+ description: سيتم التشغيل فقط إذا تم إنشاء المنشور بواسطة مستخدم في مستويات الثقة هذه، ويتم تعيينه افتراضيًا على أي مستوى ثقة+ restricted_category:+ label: الفئة+ description: اختياري، لن يتم تشغيله إلا إذا كان موضوع المشاركة ضمن هذه الفئة+ restricted_tags:+ label: الوسوم+ description: اختياري، لن يتم تشغيله إلا إذا كان المنشور يحتوي على أي هذه الوسوم+ scriptables:+ not_found: تعذَّر العثور على البرنامج النصي `%{script}` للأتمتة `%{automation}`، تأكَّد من تثبيت المكوِّن الإضافي ذي الصلة+ zapier_webhook:+ fields:+ webhook_url:+ label: عنوان URL لخطاف الويب+ description: "يتوقع عنوان URL صالحًا لخطاف ويب Zapier؛ على سبيل المثال: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: مرة واحدة+ description: يستجيب مرة واحدة فقط لكل موضوع+ word_answer_list:+ label: قائمة أزواج الكلمات/الإجابات+ answering_user:+ label: المستخدم المجيب+ description: يتم تعيينه افتراضيًا إلى مستخدم النظام+ auto_tag_topic:+ fields:+ tags:+ label: الوسوم+ description: قائمة الوسوم لإضافتها إلى الموضوع.+ post:+ fields:+ creator:+ label: المُنشئ+ topic:+ label: معرِّف الموضوع+ post:+ label: محتوى المنشور+ group_category_notification_default:+ fields:+ group:+ label: المجموعة+ notification_level:+ label: مستوى الإشعارات+ update_existing_members:+ label: تحديث الأعضاء الحاليين+ description: يحدِّث مستوى الإشعارات لأعضاء المجموعة الحاليين+ user_global_notice:+ fields:+ level:+ label: المستوى+ notice:+ label: الإخطار+ description: يقبل HTML، لا تملأ هذا بإدخال غير موثوق فيه!+ levels:+ warning: تحذير+ info: المعلومات+ success: تم بنجاح+ error: خطأ+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: اسم الشارة+ group:+ label: مجموعة+ description: المجموعة المستهدفة. ستتم إضافة المستخدمين الذين لديهم الشارة المحدَّدة إلى هذه المجموعة+ update_user_title_and_flair:+ label: تحديث عنوان المستخدم والطابع+ description: اختياري، تحديث عنوان المستخدم والطابع+ remove_members_without_badge:+ label: إزالة الأعضاء الحاليين دون شارة+ description: اختياري، إزالة أعضاء المجموعة الحاليين دون الشارة المحدَّدة+ badge:+ label: شارة+ description: تحديد الشارة+ suspend_user_by_email:+ fields:+ suspend_until:+ label: التعليق حتى (الإعداد الافتراضي)+ reason:+ label: السبب (الإعداد الافتراضي)+ actor:+ label: المستخدم+ description: "المستخدم المسؤول عن التعليق (الإعداد الافتراضي: النظام)"+ pin_topic:+ fields:+ pinnable_topic:+ label: معرِّف الموضوع+ pinned_globally:+ label: مثبَّت بشكلٍ عام+ pinned_until:+ label: مثبَّت حتى+ banner_topic:+ fields:+ topic_id:+ label: معرِّف الموضوع+ banner_until:+ label: التحويل إلى لافتة حتى+ user:+ label: المستخدم+ description: "المستخدم الذي يُنشئ البانر (الإعداد الافتراضي: النظام)"+ flag_post_on_words:+ fields:+ words:+ label: الكلمات المتحقَّق منها+ topic_required_words:+ fields:+ words:+ label: قائمة الكلمات المطلوبة+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: اسم مجموعة المشاركين+ giftee_assignment_messages:+ label: الرسائل إلى مُرسل الهدية+ send_pms:+ add_a_pm_btn:+ label: إضافة رسالة شخصية+ fields:+ receiver:+ label: مستقبل الرسالة الشخصية+ sendable_pms:+ label: الرسائل الشخصية+ sender:+ label: مُرسل الرسائل الشخصية+ close_topic:+ fields:+ topic:+ label: معرِّف الموضوع+ message:+ label: الرسالة الختامية+ description: "رسالة اختيارية لإظهارها في سجل \"تم إغلاق الموضوع\""+ user:+ label: المستخدم+ description: "المستخدم الذي يغلق الموضوع (الافتراضي: النظام)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "اسم الحقل المخصَّص للمستخدم"+ models:+ script:+ name:+ label: البرنامج النصي+ trigger:+ name:+ label: المشغِّل+ automation:+ name:+ label: الاسم+ trigger:+ label: المشغِّل+ script:+ label: البرنامج النصي+ version:+ label: الإصدار+ enabled:+ label: مفعَّل+ disabled:+ label: متوقف+ placeholders:+ label: العناصر النائبة+ last_updated_at:+ label: آخر تحديث+ last_updated_by:+ label: تم التحديث بواسطةdiff --git a/plugins/automation/config/locales/client.be.yml b/plugins/automation/config/locales/client.be.ymlnew file mode 100644index 00000000000..2ea77a0d350--- /dev/null+++ b/plugins/automation/config/locales/client.be.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++be:diff --git a/plugins/automation/config/locales/client.bg.yml b/plugins/automation/config/locales/client.bg.ymlnew file mode 100644index 00000000000..52333529d3c--- /dev/null+++ b/plugins/automation/config/locales/client.bg.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++bg:diff --git a/plugins/automation/config/locales/client.bs_BA.yml b/plugins/automation/config/locales/client.bs_BA.ymlnew file mode 100644index 00000000000..828a7e65af8--- /dev/null+++ b/plugins/automation/config/locales/client.bs_BA.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++bs_BA:diff --git a/plugins/automation/config/locales/client.ca.yml b/plugins/automation/config/locales/client.ca.ymlnew file mode 100644index 00000000000..ec737bc1a5b--- /dev/null+++ b/plugins/automation/config/locales/client.ca.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ca:diff --git a/plugins/automation/config/locales/client.cs.yml b/plugins/automation/config/locales/client.cs.ymlnew file mode 100644index 00000000000..041b2f0bd05--- /dev/null+++ b/plugins/automation/config/locales/client.cs.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++cs:diff --git a/plugins/automation/config/locales/client.da.yml b/plugins/automation/config/locales/client.da.ymlnew file mode 100644index 00000000000..c00f07bd561--- /dev/null+++ b/plugins/automation/config/locales/client.da.yml@@ -0,0 +1,257 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++da:+ js:+ discourse_automation:+ title: Automatisering+ create: Opret+ update: Opdater+ select_script: Vælg et script+ select_trigger: Vælg en udløser+ no_automation_yet: Du har ikke oprettet nogen automatisering endnu.+ edit_automation:+ trigger_section:+ trigger_now: "Udløs nu"+ title: Hvornår/hvad...+ fields_section:+ title: Script indstillinger+ destroy_automation:+ confirm: "Er du sikker på, at du vil slette `%{name}`?"+ fields:+ user:+ label: Bruger+ pm:+ title:+ label: Titel+ pms:+ confirm_remove_pm: "Er du sikker på, at du vil fjerne denne PM?"+ placeholder_title: PM titel+ add_pm: Tilføj PM+ no_pm_created: Du har ikke oprettet nogen PM endnu. PM'er vil blive sendt, når din automatisering er udløst.+ title:+ label: Titel+ delay:+ label: Forsinkelse (minutter)+ prefers_encrypt:+ label: Krypterer PM hvis tilgængelig+ group:+ label: Gruppe+ text:+ label: Tekst+ triggerables:+ user_badge_granted:+ fields:+ badge:+ label: Emblem+ stalled_topic:+ durations:+ PT1H: "En time"+ P1D: "En dag"+ P1W: "En uge"+ P2W: "To uger"+ P1M: "En måned"+ P3M: "Tre måneder"+ P6M: "Seks måneder"+ P1Y: "Et år"+ fields:+ categories:+ label: Begrænset til kategorier+ tags:+ label: Begrænset til mærker+ stalled_after:+ label: Gået i stå efter+ recurring:+ every: Hver+ frequencies:+ minute: minut+ hour: time+ day: dag+ weekday: hverdag+ week: uge+ month: måned+ year: år+ fields:+ start_date:+ label: Start dato+ stalled_wiki:+ durations:+ PT1H: "En time"+ P1D: "En dag"+ P1W: "En uge"+ P2W: "To uger"+ P1M: "En måned"+ P3M: "Tre måneder"+ P6M: "Seks måneder"+ P1Y: "Et år"+ fields:+ restricted_category:+ label: Begrænset til kategori+ stalled_after:+ label: Udløserforsinkelse+ user_added_to_group:+ fields:+ joined_group:+ label: Sporet gruppe+ user_removed_from_group:+ fields:+ left_group:+ label: Sporet gruppe+ user_promoted:+ fields:+ restricted_group:+ label: Begræns til gruppe+ trust_level_transition:+ label: Overgang til tillidsniveau+ trust_levels:+ ALL: "Alle tillidsniveauer"+ TL01: "TL0 til TL1"+ TL12: "TL1 til TL2"+ TL23: "TL2 til TL3"+ TL34: "TL3 til TL4"+ topic:+ fields:+ restricted_topic:+ label: Emne ID+ post_created_edited:+ fields:+ action_type:+ label: Handlingstype+ valid_trust_levels:+ label: Gyldige tillidsniveauer+ restricted_category:+ label: Kategori+ restricted_group:+ label: Gruppe+ created: Skabt+ edited: Redigeret+ category_created_edited:+ fields:+ restricted_category:+ label: Overordnet Kategori+ pm_created:+ fields:+ restricted_group:+ label: Gruppe+ valid_trust_levels:+ label: Gyldige tillidsniveauer+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Gyldige tillidsniveauer+ restricted_category:+ label: Kategori+ restricted_tags:+ label: Mærker+ scriptables:+ zapier_webhook:+ fields:+ webhook_url:+ label: Webhook URL+ auto_responder:+ fields:+ once:+ label: En Gang+ auto_tag_topic:+ fields:+ tags:+ label: Mærker+ post:+ fields:+ topic:+ label: Emne ID+ group_category_notification_default:+ fields:+ group:+ label: Gruppe+ notification_level:+ label: Notifikationsniveau+ update_existing_members:+ label: Opdater eksisterende medlemmer+ description: Opdaterer meddelelsesniveauet for eksisterende gruppemedlemmer+ user_global_notice:+ fields:+ level:+ label: Niveau+ notice:+ label: Bemærk+ levels:+ warning: Advarsel+ info: Info+ success: Succes+ error: Fejl+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Emblem Navn+ group:+ label: Gruppe+ badge:+ label: Emblem+ suspend_user_by_email:+ fields:+ actor:+ label: Bruger+ pin_topic:+ fields:+ pinnable_topic:+ label: Emne ID+ pinned_globally:+ label: Fastgjort globalt+ pinned_until:+ label: Fastgjort indtil+ banner_topic:+ fields:+ topic_id:+ label: Emne ID+ user:+ label: Bruger+ description: "Brugeren, der opretter banneret (standard: system)"+ topic_required_words:+ fields:+ words:+ label: Liste over påkrævede ord+ send_pms:+ add_a_pm_btn:+ label: Tilføj en PM+ fields:+ sendable_pms:+ label: PM'er+ close_topic:+ fields:+ topic:+ label: Emne ID+ message:+ label: Lukkebesked+ user:+ label: Bruger+ description: "Brugeren, der lukker emnet (standard: system)"+ models:+ script:+ name:+ label: Script+ trigger:+ name:+ label: Udløser+ automation:+ name:+ label: Navn+ trigger:+ label: Aftrækkeren+ script:+ label: Script+ version:+ label: Version+ enabled:+ label: Aktiveret+ disabled:+ label: Deaktiveret+ placeholders:+ label: Pladsholdere+ last_updated_at:+ label: Sidst opdateret+ last_updated_by:+ label: Opdateret afdiff --git a/plugins/automation/config/locales/client.de.yml b/plugins/automation/config/locales/client.de.ymlnew file mode 100644index 00000000000..ff6ebfc6afa--- /dev/null+++ b/plugins/automation/config/locales/client.de.yml@@ -0,0 +1,378 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++de:+ js:+ discourse_automation:+ title: Automatisierung+ create: Erstellen+ update: Aktualisieren+ select_script: Skript auswählen+ select_trigger: Auslöser auswählen+ confirm_automation_reset: Diese Aktion setzt die Skript- und Auslöseroptionen zurück, der neue Zustand wird gespeichert. Willst du fortfahren?+ confirm_automation_trigger: Diese Aktion löst die Automatisierung aus. Willst du fortfahren?+ no_automation_yet: Du hast noch keine Automatisierung erstellt.+ edit_automation:+ trigger_section:+ forced: Dieser Auslöser wird vom Skript erzwungen.+ next_pending_automation: "Die nächste Automatisierung wird ausgelöst am: %{date}"+ trigger_now: "Jetzt auslösen"+ title: Wann/Was …+ fields_section:+ title: Skriptoptionen+ destroy_automation:+ confirm: "Bist du sicher, dass du `%{name}` löschen willst?"+ fields:+ key_value:+ label:+ one: Konfiguration bearbeiten (%{count})+ other: Konfiguration bearbeiten (%{count})+ user:+ label: Benutzer+ pm:+ title:+ label: Titel+ raw:+ label: Body+ pms:+ confirm_remove_pm: "Bist du sicher, dass du diese PN entfernen möchtest?"+ placeholder_title: PN-Titel+ add_pm: PN hinzufügen+ no_pm_created: Du hast noch keine PN erstellt. PN werden verschickt, sobald deine Automatisierung ausgelöst wird.+ title:+ label: Titel+ raw:+ label: Body+ delay:+ label: Verzögerung (Minuten)+ prefers_encrypt:+ label: Verschlüsselt PN, falls verfügbar+ group:+ label: Gruppe+ text:+ label: Text+ triggerables:+ not_found: Konnte den Auslöser `%{trigger}` für die Automatisierung `%{automation}` nicht finden. Stelle sicher, dass das zugehörige Plug-in installiert ist+ user_badge_granted:+ fields:+ badge:+ label: Abzeichen+ only_first_grant:+ label: Nur bei erster Vergabe+ stalled_topic:+ durations:+ PT1H: "Eine Stunde"+ P1D: "Ein Tag"+ P1W: "Eine Woche"+ P2W: "Zwei Wochen"+ P1M: "Ein Monat"+ P3M: "Drei Monate"+ P6M: "Sechs Monate"+ P1Y: "Ein Jahr"+ fields:+ categories:+ label: Beschränkt auf Kategorien+ tags:+ label: Beschränkt auf Tags+ stalled_after:+ label: Festgefahren nach+ recurring:+ every: Jede(n/s)+ frequencies:+ minute: Minute+ hour: Stunde+ day: Tag+ weekday: Wochentag+ week: Woche+ month: Monat+ year: Jahr+ fields:+ recurrence:+ label: Wiederholung+ start_date:+ label: Startdatum+ stalled_wiki:+ durations:+ PT1H: "Eine Stunde"+ P1D: "Ein Tag"+ P1W: "Eine Woche"+ P2W: "Zwei Wochen"+ P1M: "Ein Monat"+ P3M: "Drei Monate"+ P6M: "Sechs Monate"+ P1Y: "Ein Jahr"+ fields:+ restricted_category:+ label: Auf Kategorie beschränkt+ stalled_after:+ label: Auslöseverzögerung+ description: Definiert die Verzögerung zwischen der letzten Wiki-Bearbeitung und dem Auslöser der Automatisierung+ retriggered_after:+ label: Verzögerung der erneuten Auslösung+ description: Definiert die Verzögerung zwischen dem ersten Auslöser und dem nächsten Auslöser, falls das Wiki nach dem ersten Auslöser noch nicht bearbeitet wurde+ user_added_to_group:+ fields:+ joined_group:+ label: Verfolgte Gruppe+ user_removed_from_group:+ fields:+ left_group:+ label: Verfolgte Gruppe+ user_promoted:+ fields:+ restricted_group:+ label: Auf Gruppe beschränken+ trust_level_transition:+ label: Vertrauensstufenübergang+ trust_levels:+ ALL: "Alle Vertrauensstufen"+ TL01: "VS0 auf VS1"+ TL12: "VS1 auf VS2"+ TL23: "VS2 auf VS3"+ TL34: "VS3 auf VS4"+ point_in_time:+ fields:+ execute_at:+ label: Ausführen um+ topic:+ fields:+ restricted_topic:+ label: Themen-ID+ post_created_edited:+ fields:+ action_type:+ label: Aktionstyp+ description: "Optional, beschränke die Auslösung auf erstellte oder bearbeitete Ereignisse"+ valid_trust_levels:+ label: Gültige Vertrauensstufen+ description: Wird nur ausgelöst, wenn ein Beitrag von einem Benutzer mit diesen Vertrauensstufen erstellt wird, standardmäßig eine beliebige Vertrauensstufe+ restricted_category:+ label: Kategorie+ description: Optional. Wird nur ausgelöst, wenn das Thema des Beitrags in dieser Kategorie ist+ restricted_group:+ label: Gruppe+ description: Optional. Wird nur ausgelöst, wenn das Thema des Beitrags eine private Nachricht im Posteingang dieser Gruppe ist+ ignore_group_members:+ label: Gruppenmitglieder ignorieren+ description: Überspringe den Auslöser, wenn der Absender ein Mitglied der oben angegebenen Gruppe ist+ ignore_automated:+ label: Automatisierte Nachrichten ignorieren+ description: Überspringe den Auslöser, wenn der Absender eine Noreply-E-Mail-Adresse nutzt oder die Nachricht von einer automatischen Quelle stammt. Gilt nur für Beiträge, die per E-Mail erstellt wurden+ first_post_only:+ label: Nur erster Beitrag+ description: Wird nur ausgelöst, wenn der Beitrag der erste Beitrag ist, den ein Benutzer erstellt hat+ first_topic_only:+ label: Nur erstes Thema+ description: Wird nur ausgelöst, wenn das Thema das erste Thema ist, das ein Benutzer erstellt hat+ created: Erstellt+ edited: Bearbeitet+ user_updated:+ fields:+ user_profile:+ label: Benutzerprofilfelder+ description: Wird nur ausgelöst, wenn der Benutzer alle diese Felder ausgefüllt hat+ custom_fields:+ label: Benutzerdefinierte Felder+ description: Wird nur ausgelöst, wenn der Benutzer alle diese Felder ausgefüllt hat+ once_per_user:+ label: Einmal pro Benutzer+ description: Wird nur einmal pro Benutzer ausgelöst+ category_created_edited:+ fields:+ restricted_category:+ label: Übergeordnete Kategorie+ description: Optional, ermöglicht es, die Ausführung des Auslösers auf diese Kategorie zu beschränken+ pm_created:+ fields:+ restricted_user:+ label: Benutzer+ description: Wird nur für PN ausgelöst, die an diesen Benutzer gesendet werden+ restricted_group:+ label: Gruppe+ description: Wird nur für PN ausgelöst, die an diese Gruppe gesendet werden+ ignore_staff:+ label: Teammitglieder ignorieren+ description: Den Auslöser überspringen, falls der Absender ein Teammitglied ist+ ignore_group_members:+ label: Gruppenmitglieder ignorieren+ description: Überspringe den Auslöser, wenn der Absender ein Mitglied der oben angegebenen Gruppe ist+ ignore_automated:+ label: Automatisierte Nachrichten ignorieren+ description: Überspringe den Auslöser, wenn der Absender eine Noreply-E-Mail-Adresse nutzt oder die Nachricht von einer automatischen Quelle stammt. Gilt nur für PN, die per E-Mail erstellt wurden+ valid_trust_levels:+ label: Gültige Vertrauensstufen+ description: Wird nur ausgelöst, wenn ein Beitrag von einem Benutzer mit diesen Vertrauensstufen erstellt wird, standardmäßig eine beliebige Vertrauensstufe+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Gültige Vertrauensstufen+ description: Wird nur ausgelöst, wenn ein Beitrag von einem Benutzer mit diesen Vertrauensstufen erstellt wird, standardmäßig eine beliebige Vertrauensstufe+ restricted_category:+ label: Kategorie+ description: Optional. Wird nur ausgelöst, wenn das Thema des Beitrags in dieser Kategorie ist+ restricted_tags:+ label: Tags+ description: Optional. Wird nur ausgelöst, wenn der Beitrag eines dieser Schlagwörter enthält+ scriptables:+ not_found: Konnte das Skript `%{script}` für die Automatisierung `%{automation}` nicht finden. Stelle sicher, dass das zugehörige Plug-in installiert ist+ zapier_webhook:+ fields:+ webhook_url:+ label: Webhook-URL+ description: "Erwartet eine gültige Zapier-Webhook-URL, z. B.: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: Einmal+ description: Antwortet nur einmal pro Thema+ word_answer_list:+ label: Liste von Wort/Antwort-Paaren+ description: "Definiert eine Liste von Schlüssel/Wert-Gruppen, wobei `key` der gesuchte Begriff und `value` der Text der Antwort ist. `key` kann leer gelassen werden, um unabhängig vom Inhalt auf alle Auslöser zu reagieren. Beachte, dass `value` `{{key}}` als Platzhalter akzeptiert, der in der Antwort durch den Wert von `key` ersetzt wird. Beachte weiterhin, dass `key` als Regex ausgewertet wird und Sonderzeichen wie `.` maskiert werden müssen, wenn du tatsächlich einen Punkt meinst, z. B.: `\\.`"+ answering_user:+ label: Antwortender Benutzer+ description: Standardmäßig Systembenutzer+ auto_tag_topic:+ fields:+ tags:+ label: Schlagwörter+ description: Liste der Schlagwörter, die dem Thema hinzugefügt werden sollen.+ post:+ fields:+ creator:+ label: Ersteller+ post_creator_context: Der Ersteller des Beitrags+ updated_user_context: Der aktualisierte Benutzer+ topic:+ label: Themen-ID+ post:+ label: Beitragsinhalt+ group_category_notification_default:+ fields:+ group:+ label: Gruppe+ notification_level:+ label: Benachrichtigungsstufe+ update_existing_members:+ label: Bestehende Mitglieder aktualisieren+ description: Aktualisiert die Benachrichtigungsstufe für bestehende Gruppenmitglieder+ user_global_notice:+ fields:+ level:+ label: Level+ notice:+ label: Hinweis+ description: Akzeptiert HTML. Gib nur vertrauenswürdige Inhalte ein!+ levels:+ warning: Warnung+ info: Info+ success: Erfolg+ error: Fehler+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Abzeichenname+ group:+ label: Gruppe+ description: Zielgruppe. Benutzer mit dem angegebenen Abzeichen werden dieser Gruppe hinzugefügt+ update_user_title_and_flair:+ label: Benutzertitel und Flair aktualisieren+ description: Optional. Benutzertitel und Flair aktualisieren+ remove_members_without_badge:+ label: Bestehende Mitglieder ohne Abzeichen entfernen+ description: Optional. Bestehende Gruppenmitglieder ohne das angegebene Abzeichen entfernen+ badge:+ label: Abzeichen+ description: Abzeichen auswählen+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Aussetzen bis (Standard)+ reason:+ label: Grund (Standard)+ actor:+ label: Benutzer+ description: "Der für die Aussetzung verantwortliche Benutzer (Standard: System)"+ pin_topic:+ fields:+ pinnable_topic:+ label: Themen-ID+ pinned_globally:+ label: Global angeheftet+ pinned_until:+ label: Angeheftet bis+ banner_topic:+ fields:+ topic_id:+ label: Themen-ID+ banner_until:+ label: Banner machen bis+ user:+ label: Benutzer+ description: "Der Benutzer, der das Banner erstellt (Standard: System)"+ flag_post_on_words:+ fields:+ words:+ label: Geprüfte Wörter+ topic_required_words:+ fields:+ words:+ label: Liste der erforderlichen Wörter+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Gruppenname der Teilnehmer+ giftee_assignment_messages:+ label: An den Schenkenden gesendete Nachrichten+ send_pms:+ add_a_pm_btn:+ label: PN hinzufügen+ fields:+ receiver:+ label: PN-Empfänger+ sendable_pms:+ label: PN+ sender:+ label: PN-Absender+ close_topic:+ fields:+ topic:+ label: Themen-ID+ message:+ label: Nachricht bzgl. Schließung+ description: "Optionale Nachricht, die im Eintrag „Thema geschlossen“ angezeigt wird"+ user:+ label: Benutzer+ description: "Der Benutzer, der das Thema schließt (Standard: System)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "Name des benutzerdefinierten Benutzerfelds"+ models:+ script:+ name:+ label: Skript+ trigger:+ name:+ label: Auslöser+ automation:+ name:+ label: Name+ trigger:+ label: Auslöser+ script:+ label: Skript+ version:+ label: Version+ enabled:+ label: Aktiviert+ disabled:+ label: Deaktiviert+ placeholders:+ label: Platzhalter+ last_updated_at:+ label: Letzte Aktualisierung+ last_updated_by:+ label: Aktualisiert vondiff --git a/plugins/automation/config/locales/client.el.yml b/plugins/automation/config/locales/client.el.ymlnew file mode 100644index 00000000000..d872d0ecc40--- /dev/null+++ b/plugins/automation/config/locales/client.el.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++el:diff --git a/plugins/automation/config/locales/client.en.yml b/plugins/automation/config/locales/client.en.ymlnew file mode 100644index 00000000000..27d7c793205--- /dev/null+++ b/plugins/automation/config/locales/client.en.yml@@ -0,0 +1,374 @@+en:+ js:+ discourse_automation:+ title: Automation+ create: Create+ update: Update+ select_script: Select a script+ select_trigger: Select a trigger+ confirm_automation_reset: This action will reset script and trigger options, new state will be saved, do you want to proceed?+ confirm_automation_trigger: This action will trigger the automation, do you want to proceed?+ no_automation_yet: You haven’t created any automation yet.+ edit_automation:+ trigger_section:+ forced: This trigger is forced by script.+ next_pending_automation: "Next automation will trigger at: %{date}"+ trigger_now: "Trigger now"+ title: When/What...+ fields_section:+ title: Script options+ destroy_automation:+ confirm: "Are you sure you want to delete `%{name}`?"+ fields:+ key_value:+ label_without_count: "Configure"+ label_with_count:+ one: "Edit Configuration (%{count})"+ other: "Edit Configuration (%{count})"+ user:+ label: User+ pm:+ title:+ label: Title+ raw:+ label: Body+ pms:+ confirm_remove_pm: "Are you sure you want to remove this PM?"+ placeholder_title: PM title+ add_pm: Add PM+ no_pm_created: You haven’t created any PM yet. PMs will be sent once your automation is triggered.+ title:+ label: Title+ raw:+ label: Body+ delay:+ label: Delay (minutes)+ prefers_encrypt:+ label: Encrypts PM if available+ group:+ label: Group+ text:+ label: Text+ triggerables:+ not_found: Couldn’t find trigger `%{trigger}` for automation `%{automation}`, ensure the associated plugin is installed+ user_badge_granted:+ fields:+ badge:+ label: Badge+ only_first_grant:+ label: Only on first grant+ stalled_topic:+ durations:+ PT1H: "One hour"+ P1D: "One day"+ P1W: "One week"+ P2W: "Two weeks"+ P1M: "One month"+ P3M: "Three months"+ P6M: "Six months"+ P1Y: "One year"+ fields:+ categories:+ label: Limited to categories+ tags:+ label: Limited to tags+ stalled_after:+ label: Stalled after+ recurring:+ every: Every+ frequencies:+ minute: minute+ hour: hour+ day: day+ weekday: weekday+ week: week+ month: month+ year: year+ fields:+ recurrence:+ label: Recurrence+ start_date:+ label: Start date+ stalled_wiki:+ durations:+ PT1H: "One hour"+ P1D: "One day"+ P1W: "One week"+ P2W: "Two weeks"+ P1M: "One month"+ P3M: "Three months"+ P6M: "Six months"+ P1Y: "One year"+ fields:+ restricted_category:+ label: Restricted to category+ stalled_after:+ label: Trigger delay+ description: Defines delay between last wiki edit and automation’s trigger+ retriggered_after:+ label: Re-trigger delay+ description: Defines delay between first trigger and next trigger, if wiki has still not been edited after first trigger+ user_added_to_group:+ fields:+ joined_group:+ label: Tracked group+ user_removed_from_group:+ fields:+ left_group:+ label: Tracked group+ user_promoted:+ fields:+ restricted_group:+ label: Restrict to group+ trust_level_transition:+ label: Trust level transition+ trust_levels:+ ALL: "All trust levels"+ TL01: "TL0 to TL1"+ TL12: "TL1 to TL2"+ TL23: "TL2 to TL3"+ TL34: "TL3 to TL4"+ point_in_time:+ fields:+ execute_at:+ label: Execute at+ topic:+ fields:+ restricted_topic:+ label: Topic ID+ post_created_edited:+ fields:+ action_type:+ label: Action type+ description: "Optional, limit triggering to only created or edited events"+ valid_trust_levels:+ label: Valid trust levels+ description: Will trigger only if post is created by user in these trust levels, defaults to any trust level+ restricted_category:+ label: Category+ description: Optional, will trigger only if the post's topic is in this category+ restricted_group:+ label: Group+ description: Optional, will trigger only if the post's topic is a private message in this group's inbox+ ignore_group_members:+ label: Ignore group members+ description: Skip the trigger if sender is a member of the Group specified above+ ignore_automated:+ label: Ignore automated+ description: Skip the trigger if the sender has a noreply email or is from an automated source. Only applies to posts created via email+ first_post_only:+ label: First post only+ description: Will trigger only if the post is the first post a user created+ first_topic_only:+ label: First topic only+ description: Will trigger only if the topic is the first topic a user created+ created: Created+ edited: Edited+ user_updated:+ fields:+ user_profile:+ label: User profile fields+ description: Will trigger only if the user has filled all these fields+ custom_fields:+ label: User custom fields+ description: Will trigger only if the user has filled all these fields+ once_per_user:+ label: Once per user+ description: Will trigger only once per user+ category_created_edited:+ fields:+ restricted_category:+ label: Parent Category+ description: Optional, allows to limit trigger execution to this category+ pm_created:+ fields:+ restricted_user:+ label: Users+ description: Will trigger only for PMs sent to this user+ restricted_group:+ label: Group+ description: Will trigger only for PMs sent to this group+ ignore_staff:+ label: Ignore staff+ description: Skip the trigger if sender is a staff user+ ignore_group_members:+ label: Ignore group members+ description: Skip the trigger if sender is a member of the Group specified above+ ignore_automated:+ label: Ignore automated+ description: Skip the trigger if the sender has a noreply email or is from an automated source. Only applies to PMs created via email+ valid_trust_levels:+ label: Valid trust levels+ description: Will trigger only if post is created by user in these trust levels, defaults to any trust level+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Valid trust levels+ description: Will trigger only if post is created by user in these trust levels, defaults to any trust level+ restricted_category:+ label: Category+ description: Optional, will trigger only if the post's topic is in this category+ restricted_tags:+ label: Tags+ description: Optional, will trigger only if the post has any of these tags+ scriptables:+ not_found: Couldn’t find script `%{script}` for automation `%{automation}`, ensure the associated plugin is installed+ zapier_webhook:+ fields:+ webhook_url:+ label: Webhook URL+ description: "Expects a valid Zapier webhook URL, eg: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: Once+ description: Only responds once by topic+ word_answer_list:+ label: List of word/answer pairs+ description: "Defines a list of key/value groups, where the `key` is the searched term, and `value` the text of the reply. The `key` can be left blank to respond to all triggers, regardless of content. Note that `value` accepts `{{key}}` as a placeholder to be replaced by the value of `key` in the reply. Note that `key` will be evaluated as a regex, and special chars like `.` should be escaped if you actually mean a dot, eg: `\\.`"+ answering_user:+ label: Answering user+ description: Defaults to System user+ auto_tag_topic:+ fields:+ tags:+ label: Tags+ description: List of tags to add to the topic.+ post:+ fields:+ creator:+ label: Creator+ post_creator_context: The creator of the post+ updated_user_context: The updated user+ topic:+ label: Topic ID+ post:+ label: Post content+ group_category_notification_default:+ fields:+ group:+ label: Group+ notification_level:+ label: Notification level+ update_existing_members:+ label: Update existing members+ description: Updates the notification level for existing group members+ user_global_notice:+ fields:+ level:+ label: Level+ notice:+ label: Notice+ description: Accepts HTML, do not fill this with untrusted input!+ levels:+ warning: Warning+ info: Info+ success: Success+ error: Error+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Badge Name+ group:+ label: Group+ description: Target group. Users with the specified badge will be added to this group+ update_user_title_and_flair:+ label: Update user title and flair+ description: Optional, Update user title and flair+ remove_members_without_badge:+ label: Remove existing members without badge+ description: Optional, Remove existing group members without the specified badge+ badge:+ label: Badge+ description: Select badge+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Suspend until (default)+ reason:+ label: Reason (default)+ actor:+ label: User+ description: "The user responsible for the suspension (default: system)"+ pin_topic:+ fields:+ pinnable_topic:+ label: Topic ID+ pinned_globally:+ label: Pinned globally+ pinned_until:+ label: Pinned until+ banner_topic:+ fields:+ topic_id:+ label: Topic ID+ banner_until:+ label: Make banner until+ user:+ label: User+ description: "The user creating the banner (default: system)"+ flag_post_on_words:+ fields:+ words:+ label: Checked words+ topic_required_words:+ fields:+ words:+ label: Required words list+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Group name of participants+ giftee_assignment_messages:+ label: Messages sent to gifter+ send_pms:+ add_a_pm_btn:+ label: Add a PM+ fields:+ receiver:+ label: PM receiver+ sendable_pms:+ label: PMs+ sender:+ label: PMs sender+ close_topic:+ fields:+ topic:+ label: Topic ID+ message:+ label: Closing message+ description: "Optional message to show on the Topic Closed record"+ user:+ label: User+ description: "The user closing the topic (default: system)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "User Custom Field name"++ models:+ script:+ name:+ label: Script+ trigger:+ name:+ label: Trigger+ automation:+ name:+ label: Name+ trigger:+ label: Trigger+ script:+ label: Script+ version:+ label: Version+ enabled:+ label: Enabled+ disabled:+ label: Disabled+ placeholders:+ label: Placeholders+ last_updated_at:+ label: Last update+ last_updated_by:+ label: Updated bydiff --git a/plugins/automation/config/locales/client.en_GB.yml b/plugins/automation/config/locales/client.en_GB.ymlnew file mode 100644index 00000000000..2d4fa180ec7--- /dev/null+++ b/plugins/automation/config/locales/client.en_GB.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++en_GB:diff --git a/plugins/automation/config/locales/client.es.yml b/plugins/automation/config/locales/client.es.ymlnew file mode 100644index 00000000000..c88e64ad11e--- /dev/null+++ b/plugins/automation/config/locales/client.es.yml@@ -0,0 +1,364 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++es:+ js:+ discourse_automation:+ title: Automatización+ create: Crear+ update: Actualizar+ select_script: Selecciona un script+ select_trigger: Selecciona un activador+ confirm_automation_reset: Esta acción restablecerá las opciones del script y del activador, y se guardará el nuevo estado. ¿Quieres continuar?+ confirm_automation_trigger: Esta acción activará la automatización. ¿Quieres continuar?+ no_automation_yet: Todavía no has creado ninguna automatización.+ edit_automation:+ trigger_section:+ forced: Este activador está forzado por script.+ next_pending_automation: "La siguiente automatización se activará el: %{date}"+ trigger_now: "Activar ahora"+ title: Cuándo/qué…+ fields_section:+ title: Opciones del script+ destroy_automation:+ confirm: "¿Seguro que quieres eliminar «%{name}»?"+ fields:+ key_value:+ label:+ one: Editar configuración (%{count})+ other: Editar configuración (%{count})+ user:+ label: Usuario+ pm:+ title:+ label: Título+ raw:+ label: Cuerpo+ pms:+ confirm_remove_pm: "¿Seguro que quieres eliminar este MP?"+ placeholder_title: Título del mensaje+ add_pm: Añadir mensaje+ no_pm_created: Todavía no has creado ningún MP. Los MP se enviarán una vez que se active tu automatización.+ title:+ label: Título+ raw:+ label: Cuerpo+ delay:+ label: Retardo (en minutos)+ prefers_encrypt:+ label: Cifra el MP cuando sea posible+ group:+ label: Grupo+ text:+ label: Texto+ triggerables:+ not_found: No se ha podido encontrar el activador «%{trigger}» para la automatización «%{automation}», asegúrate de que el plugin asociado está instalado+ user_badge_granted:+ fields:+ badge:+ label: Insignia+ only_first_grant:+ label: Solo en la primera concesión+ stalled_topic:+ durations:+ PT1H: "Una hora"+ P1D: "Un día"+ P1W: "Una semana"+ P2W: "Dos semanas"+ P1M: "Un mes"+ P3M: "Tres meses"+ P6M: "Seis meses"+ P1Y: "Un año"+ fields:+ categories:+ label: Limitado a las categorías+ tags:+ label: Limitado a las etiquetas+ stalled_after:+ label: Estancado tras+ recurring:+ every: Cada+ frequencies:+ minute: minuto+ hour: hora+ day: día+ weekday: día laborable (lunes a viernes)+ week: semana+ month: mes+ year: año+ fields:+ recurrence:+ label: Frecuencia+ start_date:+ label: Fecha de inicio+ stalled_wiki:+ durations:+ PT1H: "Una hora"+ P1D: "Un día"+ P1W: "Una semana"+ P2W: "Dos semanas"+ P1M: "Un mes"+ P3M: "Tres meses"+ P6M: "Seis meses"+ P1Y: "Un año"+ fields:+ restricted_category:+ label: Restringido a la categoría+ stalled_after:+ label: Retardo de activación+ description: Define el retraso entre la última edición del wiki y la activación de la automatización+ retriggered_after:+ label: Retardo antes de volver a activar+ description: Define el retraso entre la primera activación y la siguiente, si la wiki todavía no ha sido editada desde la primera activación+ user_added_to_group:+ fields:+ joined_group:+ label: Grupo rastreado+ user_removed_from_group:+ fields:+ left_group:+ label: Grupo rastreado+ user_promoted:+ fields:+ restricted_group:+ label: Restringir al grupo+ trust_level_transition:+ label: Transición a nivel de confianza+ trust_levels:+ ALL: "Todos los niveles de confianza"+ TL01: "nivel 0 a nivel 1"+ TL12: "nivel 1 a nivel 2"+ TL23: "nivel 2 a nivel 3"+ TL34: "nivel 3 a nivel 4"+ point_in_time:+ fields:+ execute_at:+ label: Ejecutar en+ topic:+ fields:+ restricted_topic:+ label: ID del tema+ post_created_edited:+ fields:+ action_type:+ label: Tipo de acción+ description: "Opcional, limite la activación solo a eventos creados o editados"+ valid_trust_levels:+ label: Niveles de confianza válidos+ description: Se activará solo si la publicación es creada por un usuario en estos niveles de confianza. Por defecto, cualquier nivel de confianza+ restricted_category:+ label: Categoría+ description: Opcional, solo se activará si el tema de la publicación está en esta categoría+ restricted_group:+ label: Grupo+ description: Opcional, solo se activará si el tema de la publicación es un mensaje privado en la bandeja de entrada de este grupo+ ignore_group_members:+ label: Ignorar a los miembros del grupo+ description: Omitir el activador si el remitente es un miembro del Grupo especificado anteriormente+ ignore_automated:+ label: Ignorar la automatización+ description: Omite el activador si el remitente tiene un correo electrónico de no respuesta o procede de una fuente automatizada. Solo se aplica a las publicaciones creadas por correo electrónico+ first_post_only:+ label: Solo la primera publicación+ description: Se activará solo si la publicación es la primera que creó un usuario.+ first_topic_only:+ label: Solo el primer tema+ description: Se activará solo si el tema es el primer tema que creó un usuario+ created: Creado+ edited: Editado+ category_created_edited:+ fields:+ restricted_category:+ label: Categoría principal+ description: Opcional, permite limitar la ejecución del activador a esta categoría+ pm_created:+ fields:+ restricted_user:+ label: Usuarios+ description: Se activará solo para los MP enviados a este usuario+ restricted_group:+ label: Grupo+ description: Se activará solo para los MP enviados a este grupo+ ignore_staff:+ label: Ignorar personal+ description: Omitir la activación si el remitente es un usuario del personal+ ignore_group_members:+ label: Ignorar a los miembros del grupo+ description: Omitir el activador si el remitente es un miembro del Grupo especificado anteriormente+ ignore_automated:+ label: Ignorar la automatización+ description: Omite el activador si el remitente tiene un correo electrónico de no respuesta o procede de una fuente automatizada. Solo se aplica a los MP creados por correo electrónico+ valid_trust_levels:+ label: Niveles de confianza válidos+ description: Se activará solo si la publicación es creada por un usuario en estos niveles de confianza. Por defecto, cualquier nivel de confianza+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Niveles de confianza válidos+ description: Se activará solo si la publicación es creada por un usuario en estos niveles de confianza. Por defecto, cualquier nivel de confianza+ restricted_category:+ label: Categoría+ description: Opcional, solo se activará si el tema de la publicación está en esta categoría+ restricted_tags:+ label: Etiquetas+ description: Opcional, solo se activará si la publicación tiene alguna de estas etiquetas+ scriptables:+ not_found: No se ha podido encontrar el script «%{script}» para la automatización «%{automation}», asegúrate de que el plugin asociado está instalado+ zapier_webhook:+ fields:+ webhook_url:+ label: URL del webhook+ description: "Espera una URL válida del webhook de Zapier, por ejemplo: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: Una vez+ description: Solo responde una vez por tema+ word_answer_list:+ label: Lista de pares de palabras/respuestas+ answering_user:+ label: Usuario que responde+ description: Por defecto, usuario del sistema+ auto_tag_topic:+ fields:+ tags:+ label: Etiquetas+ description: Lista de etiquetas para añadir al tema.+ post:+ fields:+ creator:+ label: Creador+ topic:+ label: ID del tema+ post:+ label: Contenido de la publicación+ group_category_notification_default:+ fields:+ group:+ label: Grupo+ notification_level:+ label: Nivel de notificación+ update_existing_members:+ label: Actualizar miembros existentes+ description: Actualiza el nivel de notificación de los miembros del grupo existentes+ user_global_notice:+ fields:+ level:+ label: Nivel+ notice:+ label: Aviso+ description: Acepta HTML, ¡no incluyas contenido inseguro o de terceros!+ levels:+ warning: Advertencia+ info: Información+ success: Éxito+ error: Error+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Nombre de la insignia+ group:+ label: Grupo+ description: Grupo objetivo. Los usuarios con la insignia especificada se añadirán a este grupo+ update_user_title_and_flair:+ label: Actualizar el título y el estilo del usuario+ description: Opcional, actualizar el título y el estilo del usuario+ remove_members_without_badge:+ label: Eliminar miembros existentes sin insignia+ description: Opcional, eliminar miembros del grupo existentes sin la insignia especificada+ badge:+ label: Insignia+ description: Seleccionar insignia+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Suspender hasta (por defecto)+ reason:+ label: Motivo (por defecto)+ actor:+ label: Usuario+ description: "Usuario responsable de la suspensión (por defecto: system)"+ pin_topic:+ fields:+ pinnable_topic:+ label: ID del tema+ pinned_globally:+ label: Fijado globalmente+ pinned_until:+ label: Fijado hasta+ banner_topic:+ fields:+ topic_id:+ label: ID del tema+ banner_until:+ label: Hacer banner hasta+ user:+ label: Usuario+ description: "Usuario que crea el banner (por defecto: system)"+ flag_post_on_words:+ fields:+ words:+ label: Palabras revisadas+ topic_required_words:+ fields:+ words:+ label: Lista de palabras necesarias+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Nombre del grupo de participantes+ giftee_assignment_messages:+ label: Mensajes enviados a quien regala+ send_pms:+ add_a_pm_btn:+ label: Añadir un MP+ fields:+ receiver:+ label: Destinatario del MP+ sendable_pms:+ label: MPs+ sender:+ label: Remitente del MP+ close_topic:+ fields:+ topic:+ label: ID del tema+ message:+ label: Mensaje de cierre+ description: "Mensaje opcional para mostrar en el indicador al cerrar el tema"+ user:+ label: Usuario+ description: "Usuario que cierra el tema (por defecto: system)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "Nombre del campo personalizado del usuario"+ models:+ script:+ name:+ label: Script+ trigger:+ name:+ label: Activador+ automation:+ name:+ label: Nombre+ trigger:+ label: Activador+ script:+ label: Script+ version:+ label: Versión+ enabled:+ label: Activado+ disabled:+ label: Desactivado+ placeholders:+ label: Marcadores de posición+ last_updated_at:+ label: Última actualización+ last_updated_by:+ label: Actualizado pordiff --git a/plugins/automation/config/locales/client.et.yml b/plugins/automation/config/locales/client.et.ymlnew file mode 100644index 00000000000..0ea0b6d554b--- /dev/null+++ b/plugins/automation/config/locales/client.et.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++et:diff --git a/plugins/automation/config/locales/client.fa_IR.yml b/plugins/automation/config/locales/client.fa_IR.ymlnew file mode 100644index 00000000000..bfce4169e22--- /dev/null+++ b/plugins/automation/config/locales/client.fa_IR.yml@@ -0,0 +1,187 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++fa_IR:+ js:+ discourse_automation:+ title: اتوماسیون+ create: ایجاد+ update: بهروزرسانی+ destroy_automation:+ confirm: "آیا مطمئنید هستید که میخواهید «%{name}» را حذف کنید؟"+ fields:+ user:+ label: کاربر+ pm:+ title:+ label: عنوان+ raw:+ label: بدنه+ pms:+ title:+ label: عنوان+ raw:+ label: بدنه+ delay:+ label: تاخیر (دقیقه)+ group:+ label: گروه+ text:+ label: متن+ triggerables:+ user_badge_granted:+ fields:+ badge:+ label: نشان+ stalled_topic:+ durations:+ PT1H: "یک ساعت"+ P1D: "یک روز"+ P1W: "یک هفته"+ P2W: "دو هفته"+ P1M: "یک ماه"+ P3M: "سه ماه"+ P6M: "شش ماه"+ P1Y: "یک سال"+ fields:+ categories:+ label: محدود شده به دستهبندیها+ tags:+ label: محدود شده به برچسبها+ recurring:+ every: هر+ frequencies:+ minute: دقیقه+ hour: ساعت+ day: روز+ weekday: روز هفته+ week: هفته+ month: ماه+ year: سال+ fields:+ start_date:+ label: تاریخ شروع+ stalled_wiki:+ durations:+ PT1H: "یک ساعت"+ P1D: "یک روز"+ P1W: "یک هفته"+ P2W: "دو هفته"+ P1M: "یک ماه"+ P3M: "سه ماه"+ P6M: "شش ماه"+ P1Y: "یک سال"+ fields:+ restricted_category:+ label: محدود به دستهبندی+ topic:+ fields:+ restricted_topic:+ label: شناسه موضوع+ post_created_edited:+ fields:+ action_type:+ label: نوع عمل+ restricted_category:+ label: دستهبندی+ restricted_group:+ label: گروه+ created: ایجاد شده+ edited: ویرایش شده+ pm_created:+ fields:+ restricted_group:+ label: گروه+ after_post_cook:+ fields:+ restricted_category:+ label: دستهبندی+ restricted_tags:+ label: برچسبها+ scriptables:+ auto_responder:+ fields:+ once:+ label: یک بار+ description: فقط یک بار بر اساس موضوع پاسخ میدهد+ auto_tag_topic:+ fields:+ tags:+ label: برچسبها+ post:+ fields:+ creator:+ label: ایجاد کننده+ topic:+ label: شناسه موضوع+ post:+ label: محتوای نوشته+ group_category_notification_default:+ fields:+ group:+ label: گروه+ user_global_notice:+ fields:+ level:+ label: سطح+ levels:+ warning: هشدار+ info: اطلاعات+ success: موفقیت+ error: خطا+ user_group_membership_through_badge:+ fields:+ group:+ label: گروه+ badge:+ label: نشان+ suspend_user_by_email:+ fields:+ reason:+ label: دلیل (پیشفرض)+ actor:+ label: کاربر+ pin_topic:+ fields:+ pinnable_topic:+ label: شناسه موضوع+ pinned_until:+ label: سنجاق شده تا+ banner_topic:+ fields:+ topic_id:+ label: شناسه موضوع+ user:+ label: کاربر+ close_topic:+ fields:+ topic:+ label: شناسه موضوع+ user:+ label: کاربر+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "نام فیلد سفارشی کاربر"+ models:+ script:+ name:+ label: اسکریپت+ automation:+ name:+ label: نام+ script:+ label: اسکریپت+ version:+ label: نسخه+ enabled:+ label: فعال شد+ disabled:+ label: غیرفعال شد+ last_updated_at:+ label: آخرین بهروزرسانی+ last_updated_by:+ label: بهروز شده توسطdiff --git a/plugins/automation/config/locales/client.fi.yml b/plugins/automation/config/locales/client.fi.ymlnew file mode 100644index 00000000000..fabdc6e938e--- /dev/null+++ b/plugins/automation/config/locales/client.fi.yml@@ -0,0 +1,364 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++fi:+ js:+ discourse_automation:+ title: Automaatio+ create: Luo+ update: Päivitä+ select_script: Valitse skripti+ select_trigger: Valitse triggeri+ confirm_automation_reset: Tämä toiminto nollaa skripti- ja triggeriasetukset, uusi tila tallennetaan. Haluatko jatkaa?+ confirm_automation_trigger: Tämä toiminto käynnistää automaation, haluatko jatkaa?+ no_automation_yet: Et ole vielä luonut automaatioita.+ edit_automation:+ trigger_section:+ forced: Tämä triggeri on skriptin pakottama.+ next_pending_automation: "Seuraava automaatio käynnistyy: %{date}"+ trigger_now: "Käynnistä nyt"+ title: Milloin/mitä...+ fields_section:+ title: Skriptiasetukset+ destroy_automation:+ confirm: "Haluatko varmasti poistaa kohteen \"%{name}\"?"+ fields:+ key_value:+ label:+ one: Muokkaa määritystä (%{count})+ other: Muokkaa määritystä (%{count})+ user:+ label: Käyttäjä+ pm:+ title:+ label: Otsikko+ raw:+ label: Teksti+ pms:+ confirm_remove_pm: "Haluatko varmasti poistaa tämän yksityisviestin?"+ placeholder_title: Yksityisviestin otsikko+ add_pm: Lisää yksityisviesti+ no_pm_created: Et ole vielä luonut yksityisviestejä. Yksityisviestit lähetetään, kun automaatio käynnistyy.+ title:+ label: Otsikko+ raw:+ label: Teksti+ delay:+ label: Viive (minuutteina)+ prefers_encrypt:+ label: Salaa yksityisviestin, jos käytettävissä+ group:+ label: Ryhmä+ text:+ label: Teksti+ triggerables:+ not_found: Triggeriä %{trigger} automaatiolle %{automation} ei löytynyt. Varmista, että siihen liittyvä lisäosa on asennettuna.+ user_badge_granted:+ fields:+ badge:+ label: Kunniamerkki+ only_first_grant:+ label: Vain ensimmäisellä myöntämiskerralla+ stalled_topic:+ durations:+ PT1H: "Yksi tunti"+ P1D: "Yksi päivä"+ P1W: "Yksi viikko"+ P2W: "Kaksi viikkoa"+ P1M: "Yksi kuukausi"+ P3M: "Kolme kuukautta"+ P6M: "Kuusi kuukautta"+ P1Y: "Yksi vuosi"+ fields:+ categories:+ label: Rajoitettu alueisiin+ tags:+ label: Rajoitettu tunnisteisiin+ stalled_after:+ label: Pysähtyi jälkeen+ recurring:+ every: Joka+ frequencies:+ minute: minuutti+ hour: tunti+ day: päivä+ weekday: arkipäivä+ week: viikko+ month: kuukausi+ year: vuosi+ fields:+ recurrence:+ label: Toistuminen+ start_date:+ label: Alkamispäivä+ stalled_wiki:+ durations:+ PT1H: "Yksi tunti"+ P1D: "Yksi päivä"+ P1W: "Yksi viikko"+ P2W: "Kaksi viikkoa"+ P1M: "Yksi kuukausi"+ P3M: "Kolme kuukautta"+ P6M: "Kuusi kuukautta"+ P1Y: "Yksi vuosi"+ fields:+ restricted_category:+ label: Rajoitettu alueeseen+ stalled_after:+ label: Triggerin viive+ description: Määrittää viiveen viimeisimmän wiki-muokkauksen ja automaation triggerin välillä+ retriggered_after:+ label: Käynnistä viive uudelleen+ description: Määrittää viiveen ensimmäisen ja seuraavan triggerin välillä, jos wikiä ei ole vieläkään muokattu ensimmäisen triggerin jälkeen+ user_added_to_group:+ fields:+ joined_group:+ label: Seurattu ryhmä+ user_removed_from_group:+ fields:+ left_group:+ label: Seurattu ryhmä+ user_promoted:+ fields:+ restricted_group:+ label: Rajoita ryhmään+ trust_level_transition:+ label: Luottamustasosiirtymä+ trust_levels:+ ALL: "Kaikki luottamustasot"+ TL01: "LT0 → LT1"+ TL12: "LT1 → LT2"+ TL23: "LT2 → LT3"+ TL34: "LT3 → LT4"+ point_in_time:+ fields:+ execute_at:+ label: Suorita+ topic:+ fields:+ restricted_topic:+ label: Ketjun tunnus+ post_created_edited:+ fields:+ action_type:+ label: Toiminnon tyyppi+ description: "Valinnainen, rajaa käynnistyksen vain luomis- tai muokkaustapahtumiin"+ valid_trust_levels:+ label: Kelvolliset luottamustasot+ description: Käynnistyy vain, jos viestin on luonut käyttäjä, jonka luottamustaso on jokin näistä, oletusarvo on mikä tahansa luottamustaso+ restricted_category:+ label: Alue+ description: Valinnainen, käynnistyy vain, jos viestin ketju on tällä alueella+ restricted_group:+ label: Ryhmä+ description: Valinnainen, käynnistyy vain, jos viestin ketju on yksityisviesti tämän ryhmän postilaatikossa+ ignore_group_members:+ label: Ohita ryhmän jäsenet+ description: Ohita triggeri, jos lähettäjä on edellä määritellyn ryhmän jäsen+ ignore_automated:+ label: Ohita automaattiset+ description: Ohita triggeri, jos lähettäjällä on sähköpostiosoite, joka ei ota vastaan vastauksia, tai se on automatisoidusta lähteestä. Koskee vain sähköpostitse luotuja viestejä.+ first_post_only:+ label: Vain ensimmäinen viesti+ description: Käynnistyy vain, jos viesti on ensimmäinen käyttäjän luoma viesti+ first_topic_only:+ label: Vain ensimmäinen ketju+ description: Käynnistyy vain, jos ketju on ensimmäinen käyttäjän luoma ketju+ created: Luotu+ edited: Muokattu+ category_created_edited:+ fields:+ restricted_category:+ label: Ylätason alue+ description: Valinnainen, mahdollistaa triggerin suorittamisen rajoittamisen tähän alueeseen+ pm_created:+ fields:+ restricted_user:+ label: Käyttäjät+ description: Käynnistyy vain tälle käyttäjälle lähetetyille yksityisviesteille+ restricted_group:+ label: Ryhmä+ description: Käynnistyy vain tälle ryhmälle lähetetyille yksityisviesteille+ ignore_staff:+ label: Ohita henkilökunta+ description: Ohita triggeri, jos lähettäjä on henkilökunnan käyttäjä+ ignore_group_members:+ label: Ohita ryhmän jäsenet+ description: Ohita triggeri, jos lähettäjä on edellä määritellyn ryhmän jäsen+ ignore_automated:+ label: Ohita automaattiset+ description: Ohita triggeri, jos lähettäjällä on sähköpostiosoite, joka ei ota vastaan vastauksia, tai se on automatisoidusta lähteestä. Koskee vain sähköpostitse luotuja yksityisviestejä.+ valid_trust_levels:+ label: Kelvolliset luottamustasot+ description: Käynnistyy vain, jos viestin on luonut käyttäjä, jonka luottamustaso on jokin näistä; oletusarvo on mikä tahansa luottamustaso+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Kelvolliset luottamustasot+ description: Käynnistyy vain, jos viestin on luonut käyttäjä, jonka luottamustaso on jokin näistä; oletusarvo on mikä tahansa luottamustaso+ restricted_category:+ label: Alue+ description: Valinnainen, käynnistyy vain, jos viestin ketju on tällä alueella+ restricted_tags:+ label: Tunnisteet+ description: Valinnainen, käynnistyy vain, jos viestillä on jokin näistä tunnisteista+ scriptables:+ not_found: Skriptiä %{script} automaatiolle %{automation} ei löytynyt. Varmista, että siihen liittyvä lisäosa on asennettuna.+ zapier_webhook:+ fields:+ webhook_url:+ label: Webhookin URL-osoite+ description: "Odottaa kelvollista Zapierin webhook-URL-osoitetta, esim. https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: Kerran+ description: Vastaa vain kerran ketjua kohden+ word_answer_list:+ label: Sana ja vastaus -parien luettelo+ answering_user:+ label: Vastaava käyttäjä+ description: Oletuksena järjestelmäkäyttäjä+ auto_tag_topic:+ fields:+ tags:+ label: Tunnisteet+ description: Luettelo ketjuun lisättävistä tunnisteista.+ post:+ fields:+ creator:+ label: Luoja+ topic:+ label: Ketjun tunnus+ post:+ label: Viestin sisältö+ group_category_notification_default:+ fields:+ group:+ label: Ryhmä+ notification_level:+ label: Ilmoitustaso+ update_existing_members:+ label: Päivitä nykyiset jäsenet+ description: Päivittää ryhmän nykyisten jäsenten ilmoitustason+ user_global_notice:+ fields:+ level:+ label: Taso+ notice:+ label: Ilmoitus+ description: Hyväksyy HTML:n, älä täytä tätä epäluotettavalla syötteellä!+ levels:+ warning: Varoitus+ info: Info+ success: Onnistuminen+ error: Virhe+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Kunniamerkin nimi+ group:+ label: Ryhmä+ description: Kohderyhmä. Käyttäjät, joilla on määritetty kunniamerkki, lisätään tähän ryhmään+ update_user_title_and_flair:+ label: Päivitä käyttäjän nimike ja flair+ description: Valinnainen, päivitä käyttäjän nimike ja flair+ remove_members_without_badge:+ label: Poista olemassa olevat jäsenet ilman kunniamerkkiä+ description: Valinnainen, poista olemassa olevat ryhmän jäsenet ilman määritettyä kunniamerkkiä+ badge:+ label: Kunniamerkki+ description: Valitse kunniaerkki+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Keskeytä asti (oletus)+ reason:+ label: Syy (oletus)+ actor:+ label: Käyttäjä+ description: "Keskeytyksestä vastaava käyttäjä (oletus: järjestelmä)"+ pin_topic:+ fields:+ pinnable_topic:+ label: Ketjun tunnus+ pinned_globally:+ label: Kiinnitetty yleisesti+ pinned_until:+ label: Kiinnitetty asti+ banner_topic:+ fields:+ topic_id:+ label: Ketjun tunnus+ banner_until:+ label: Tee banneriksi asti+ user:+ label: Käyttäjä+ description: "Bannerin luova käyttäjä (oletus: järjestelmä)"+ flag_post_on_words:+ fields:+ words:+ label: Tarkistetut sanat+ topic_required_words:+ fields:+ words:+ label: Pakollisten sanojen luettelo+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Osallistujien ryhmän nimi+ giftee_assignment_messages:+ label: Viestit lähetetty lahjanantajalle+ send_pms:+ add_a_pm_btn:+ label: Lisää yksityisviesti+ fields:+ receiver:+ label: Yksityisviestin vastaanottaja+ sendable_pms:+ label: Yksityisviestit+ sender:+ label: Yksityisviestien lähettäjä+ close_topic:+ fields:+ topic:+ label: Ketjun tunnus+ message:+ label: Sulkemisviesti+ description: "Valinnainen viesti, joka näytetään ketju suljettu -tietueessa"+ user:+ label: Käyttäjä+ description: "Ketjun sulkeva käyttäjä (oletus: järjestelmä)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "Käyttäjän mukautetun kentän nimi"+ models:+ script:+ name:+ label: Skripti+ trigger:+ name:+ label: Triggeri+ automation:+ name:+ label: Nimi+ trigger:+ label: Triggeri+ script:+ label: Skripti+ version:+ label: Versio+ enabled:+ label: Käytössä+ disabled:+ label: Ei käytössä+ placeholders:+ label: Paikkamerkit+ last_updated_at:+ label: Viimeisin päivitys+ last_updated_by:+ label: Päivittänytdiff --git a/plugins/automation/config/locales/client.fr.yml b/plugins/automation/config/locales/client.fr.ymlnew file mode 100644index 00000000000..f9d66f2cc11--- /dev/null+++ b/plugins/automation/config/locales/client.fr.yml@@ -0,0 +1,364 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++fr:+ js:+ discourse_automation:+ title: Automatisation+ create: Créer+ update: Actualiser+ select_script: Sélectionner un script+ select_trigger: Sélectionner un déclencheur+ confirm_automation_reset: Cette action réinitialisera les options de script et de déclencheur, le nouvel état sera enregistré, voulez-vous continuer ?+ confirm_automation_trigger: Cette action déclenchera l'automatisation, voulez-vous continuer ?+ no_automation_yet: Vous n'avez pas encore créé d'automatisation.+ edit_automation:+ trigger_section:+ forced: Ce déclencheur est forcé par le script.+ next_pending_automation: "La prochaine automatisation se déclenchera le : %{date}"+ trigger_now: "Déclencher maintenant"+ title: Quand/quoi…+ fields_section:+ title: Options de script+ destroy_automation:+ confirm: "Voulez-vous vraiment supprimer « %{name} » ?"+ fields:+ key_value:+ label:+ one: Modifier la configuration (%{count})+ other: Modifier la configuration (%{count})+ user:+ label: Utilisateur+ pm:+ title:+ label: Titre+ raw:+ label: Corps+ pms:+ confirm_remove_pm: "Voulez-vous vraiment supprimer ce MP ?"+ placeholder_title: Titre du MP+ add_pm: Ajouter un MP+ no_pm_created: Vous n'avez pas encore créé de MP. Les MP seront envoyés une fois votre automatisation déclenchée.+ title:+ label: Titre+ raw:+ label: Corps+ delay:+ label: Délai (minutes)+ prefers_encrypt:+ label: Chiffrer le MP si disponible+ group:+ label: Groupe+ text:+ label: Texte+ triggerables:+ not_found: Impossible de trouver le déclencheur « %{trigger} » pour l'automatisation « %{automation} », assurez-vous que l'extension associée est installée+ user_badge_granted:+ fields:+ badge:+ label: Badge+ only_first_grant:+ label: Uniquement lors de la première autorisation+ stalled_topic:+ durations:+ PT1H: "Une heure"+ P1D: "Un jour"+ P1W: "Une semaine"+ P2W: "Deux semaines"+ P1M: "Un mois"+ P3M: "Trois mois"+ P6M: "Six mois"+ P1Y: "Un an"+ fields:+ categories:+ label: Limité aux catégories+ tags:+ label: Limité aux étiquettes+ stalled_after:+ label: Bloqué après+ recurring:+ every: Chaque+ frequencies:+ minute: minute+ hour: heure+ day: jour+ weekday: jour de la semaine+ week: semaine+ month: mois+ year: année+ fields:+ recurrence:+ label: Récurrence+ start_date:+ label: Date de début+ stalled_wiki:+ durations:+ PT1H: "Une heure"+ P1D: "Un jour"+ P1W: "Une semaine"+ P2W: "Deux semaines"+ P1M: "Un mois"+ P3M: "Trois mois"+ P6M: "Six mois"+ P1Y: "Un an"+ fields:+ restricted_category:+ label: Limité à la catégorie+ stalled_after:+ label: Délai de déclenchement+ description: Définit le délai entre la dernière modification du wiki et le déclenchement de l'automatisation+ retriggered_after:+ label: Délai de redéclenchement+ description: Définit le délai entre le premier déclencheur et le déclencheur suivant, si le wiki n'a toujours pas été modifié après le premier déclencheur+ user_added_to_group:+ fields:+ joined_group:+ label: Groupe suivi+ user_removed_from_group:+ fields:+ left_group:+ label: Groupe suivi+ user_promoted:+ fields:+ restricted_group:+ label: Restreindre au groupe+ trust_level_transition:+ label: Transition de niveau de confiance+ trust_levels:+ ALL: "Tous les niveaux de confiance"+ TL01: "TL0 à TL1"+ TL12: "TL1 à TL2"+ TL23: "TL2 à TL3"+ TL34: "TL3 à TL4"+ point_in_time:+ fields:+ execute_at:+ label: Exécuter à+ topic:+ fields:+ restricted_topic:+ label: ID de sujet+ post_created_edited:+ fields:+ action_type:+ label: Type d'action+ description: "Facultatif, limitez le déclenchement aux seuls événements créés ou modifiés"+ valid_trust_levels:+ label: Niveaux de confiance valides+ description: Se déclenchera uniquement si la publication est créée par l'utilisateur dans ces niveaux de confiance. Cette valeur est fixée par défaut sur tous les niveaux de confiance+ restricted_category:+ label: Catégorie+ description: Facultatif, ne se déclenchera que si le sujet de la publication se trouve dans cette catégorie+ restricted_group:+ label: Groupe+ description: Facultatif, se déclenchera uniquement si le sujet de la publication est un message privé dans la boîte de réception de ce groupe+ ignore_group_members:+ label: Ignorer les membres du groupe+ description: Ignorer le déclencheur si l'expéditeur est membre du groupe spécifié ci-dessus+ ignore_automated:+ label: Ignorer l'automatisation+ description: Ignorer le déclencheur si l'expéditeur a un e-mail de non-réponse ou provient d'une source automatique. Ne s'applique qu'aux messages créés par e-mail+ first_post_only:+ label: Premier message uniquement+ description: Se déclenchera uniquement si la publication est la première publication créée par un utilisateur+ first_topic_only:+ label: Premier sujet uniquement+ description: Se déclenchera uniquement si le sujet est le premier sujet créé par un utilisateur+ created: Créé+ edited: Édité+ category_created_edited:+ fields:+ restricted_category:+ label: Catégorie parente+ description: Facultatif, permet de limiter l'exécution du déclencheur à cette catégorie+ pm_created:+ fields:+ restricted_user:+ label: Utilisateurs+ description: Se déclenchera uniquement pour les MP envoyés à cet utilisateur+ restricted_group:+ label: Groupe+ description: Se déclenchera uniquement pour les MP envoyés à ce groupe+ ignore_staff:+ label: Ignorer le responsable+ description: Ignorer le déclencheur si l'expéditeur est un responsable+ ignore_group_members:+ label: Ignorer les membres du groupe+ description: Ignorer le déclencheur si l'expéditeur est membre du groupe spécifié ci-dessus+ ignore_automated:+ label: Ignorer l'automatisation+ description: Ignorer le déclencheur si l'expéditeur a un e-mail de non-réponse ou provient d'une source automatique. Ne s'applique qu'aux MP créés par e-mail+ valid_trust_levels:+ label: Niveaux de confiance valides+ description: Se déclenchera uniquement si la publication est créée par l'utilisateur dans ces niveaux de confiance. Cette valeur est fixée par défaut sur tous les niveaux de confiance+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Niveaux de confiance valides+ description: Se déclenchera uniquement si la publication est créée par l'utilisateur dans ces niveaux de confiance. Cette valeur est fixée par défaut sur tous les niveaux de confiance+ restricted_category:+ label: Catégorie+ description: Facultatif, ne se déclenchera que si le sujet de la publication se trouve dans cette catégorie+ restricted_tags:+ label: Étiquettes+ description: Facultatif, ne se déclenchera que si la publication contient l'une de ces étiquettes+ scriptables:+ not_found: Impossible de trouver le script « %{script} » pour l'automatisation « %{automation} », assurez-vous que l'extension associée est installée+ zapier_webhook:+ fields:+ webhook_url:+ label: URL du webhook+ description: "Attend une URL de webhook Zapier valide, par exemple : https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: Une fois+ description: Ne répond qu'une seule fois par sujet+ word_answer_list:+ label: Liste des paires mot/réponse+ answering_user:+ label: Utilisateur qui répond+ description: Par défaut, utilisateur système+ auto_tag_topic:+ fields:+ tags:+ label: Étiquettes+ description: Liste des étiquettes à ajouter au sujet.+ post:+ fields:+ creator:+ label: Créateur+ topic:+ label: ID de sujet+ post:+ label: Contenu du message+ group_category_notification_default:+ fields:+ group:+ label: Groupe+ notification_level:+ label: Niveau de notification+ update_existing_members:+ label: Mettre à jour les membres existants+ description: Met à jour le niveau de notification pour les membres du groupe existant+ user_global_notice:+ fields:+ level:+ label: Niveau+ notice:+ label: Avis+ description: Accepte le HTML, ne le remplissez pas avec une entrée non fiable !+ levels:+ warning: Avertissement+ info: Informations+ success: Succès+ error: Erreur+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Nom du badge+ group:+ label: Groupe+ description: Groupe ciblé. Les utilisateurs ayant le badge spécifié seront ajoutés à ce groupe+ update_user_title_and_flair:+ label: Mettre à jour le titre et le style de l'utilisateur+ description: Facultatif, mettre à jour le titre et le style de l'utilisateur+ remove_members_without_badge:+ label: Supprimer les membres existants sans badge+ description: Facultatif, supprimer les membres du groupe existants sans le badge spécifié.+ badge:+ label: Badge+ description: Sélectionner un badge+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Suspendre jusqu'à (par défaut)+ reason:+ label: Motif (par défaut)+ actor:+ label: Utilisateur+ description: "L'utilisateur responsable de la suspension (par défaut : système)"+ pin_topic:+ fields:+ pinnable_topic:+ label: ID de sujet+ pinned_globally:+ label: Épinglé globalement+ pinned_until:+ label: Épinglé jusqu'à+ banner_topic:+ fields:+ topic_id:+ label: ID de sujet+ banner_until:+ label: Faire une bannière jusqu'au+ user:+ label: Utilisateur+ description: "L'utilisateur qui crée la bannière (par défaut : système)"+ flag_post_on_words:+ fields:+ words:+ label: Mots vérifiés+ topic_required_words:+ fields:+ words:+ label: Liste des mots requis+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Nom du groupe de participants+ giftee_assignment_messages:+ label: Messages envoyés au donateur+ send_pms:+ add_a_pm_btn:+ label: Ajouter un MP+ fields:+ receiver:+ label: Récepteur du MP+ sendable_pms:+ label: MP+ sender:+ label: Expéditeur du MP+ close_topic:+ fields:+ topic:+ label: ID de sujet+ message:+ label: Message de fermeture+ description: "Message facultatif à afficher dans l'enregistrement Sujet fermé"+ user:+ label: Utilisateur+ description: "L'utilisateur qui ferme le sujet (par défaut : système)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "Nom du champ personnalisé de l'utilisateur"+ models:+ script:+ name:+ label: Script+ trigger:+ name:+ label: Déclencheur+ automation:+ name:+ label: Nom+ trigger:+ label: Déclencheur+ script:+ label: Script+ version:+ label: Version+ enabled:+ label: Activé+ disabled:+ label: Désactivé+ placeholders:+ label: Espaces réservés+ last_updated_at:+ label: Dernière mise à jour+ last_updated_by:+ label: Mis à jour pardiff --git a/plugins/automation/config/locales/client.gl.yml b/plugins/automation/config/locales/client.gl.ymlnew file mode 100644index 00000000000..fb911ce1635--- /dev/null+++ b/plugins/automation/config/locales/client.gl.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++gl:diff --git a/plugins/automation/config/locales/client.he.yml b/plugins/automation/config/locales/client.he.ymlnew file mode 100644index 00000000000..a5d2d53a9d1--- /dev/null+++ b/plugins/automation/config/locales/client.he.yml@@ -0,0 +1,362 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++he:+ js:+ discourse_automation:+ title: אוטומציה+ create: יצירה+ update: עדכון+ select_script: בחירת סקריפט+ select_trigger: בחירת גורם מפעיל+ confirm_automation_trigger: פעולה זו תקפיץ את האוטומציה, להמשיך?+ no_automation_yet: לא יצרת אף אוטומציה עדיין.+ edit_automation:+ trigger_section:+ forced: הקפצה זו נאכפת על ידי סקריפט.+ next_pending_automation: "האוטומציה הבאה תוקפץ ב־: %{date}"+ trigger_now: "להקפיץ כעת"+ title: מתי/מה…+ fields_section:+ title: אפשרויות סקריפט+ destroy_automation:+ confirm: "למחוק את `%{name}`?"+ fields:+ key_value:+ label:+ one: עריכת הגדרה (%{count})+ two: עריכת הגדרות (%{count})+ many: עריכת הגדרות (%{count})+ other: עריכת הגדרות (%{count})+ user:+ label: משתמש+ pm:+ title:+ label: כותרת+ raw:+ label: גוף+ pms:+ confirm_remove_pm: "להסיר את ההודעה הפרטית הזאת?"+ placeholder_title: כותרת ההודעה הפרטית+ add_pm: הוספת הודעה פרטית+ title:+ label: כותרת+ raw:+ label: גוף+ delay:+ label: השהיה (דקות)+ prefers_encrypt:+ label: מצפין הודעות פרטיות אם זמין+ group:+ label: קבוצה+ text:+ label: טקסט+ triggerables:+ not_found: לא ניתן למצוא את גורם ההקפצה `%{trigger}` לאוטומציה `%{automation}`, יש לוודא שהתוסף המשויך מותקן+ user_badge_granted:+ fields:+ badge:+ label: עיטור+ only_first_grant:+ label: רק עם ההענקה הראשונה+ stalled_topic:+ durations:+ PT1H: "שעה"+ P1D: "יום"+ P1W: "שבוע"+ P2W: "שבועיים"+ P1M: "חודש"+ P3M: "שלושה חודשים"+ P6M: "שישה חודשים"+ P1Y: "שנה"+ fields:+ categories:+ label: מוגבל לקטגוריות+ tags:+ label: מוגבל לתגיות+ recurring:+ every: כל+ frequencies:+ minute: דקה+ hour: שעה+ day: יום+ weekday: יום חול+ week: שבוע+ month: חודש+ year: שנה+ fields:+ recurrence:+ label: חזרתיות+ start_date:+ label: תאריך התחלה+ stalled_wiki:+ durations:+ PT1H: "שעה"+ P1D: "יום"+ P1W: "שבוע"+ P2W: "שבועיים"+ P1M: "חודש"+ P3M: "שלושה חודשים"+ P6M: "שישה חודשים"+ P1Y: "שנה"+ fields:+ restricted_category:+ label: מוגבל לקטגוריה+ stalled_after:+ label: השהיית הזנקה+ description: הגדרת השהייה בין עריכת הוויקי האחרונה והזנקת האוטומציה+ retriggered_after:+ label: השהיית הזנקה חוזרת+ user_added_to_group:+ fields:+ joined_group:+ label: קבוצה במעקב+ user_removed_from_group:+ fields:+ left_group:+ label: קבוצה במעקב+ user_promoted:+ fields:+ restricted_group:+ label: הגבלה לקבוצה+ trust_level_transition:+ label: מעבר בין דרגות אמון+ trust_levels:+ ALL: "כל דרגות האמון"+ TL01: "דרגת אמון 0 ל־1"+ TL12: "דרגת אמון 1 ל־2"+ TL23: "דרגת אמון 2 ל־3"+ TL34: "דרגת אמון 3 ל־4"+ point_in_time:+ fields:+ execute_at:+ label: לבצע ב־+ topic:+ fields:+ restricted_topic:+ label: מזהה נושא+ post_created_edited:+ fields:+ action_type:+ label: סוג פעולה+ description: "כרשות, הגבלת ההקפצה לאירועים שנוצרו או נערכו בלבד"+ valid_trust_levels:+ label: דרגות אמון תקפות+ description: יוקפץ רק אם הפוסט נוצר על ידי משתמש בדרגות האמון האלו, ברירת המחדל היא כל דרגת אמון+ restricted_category:+ label: קטגוריה+ description: הגדרת רשות, להזניק רק אם נושא הפוסט בקטגוריה הזאת+ restricted_group:+ label: קבוצה+ description: הגדרת רשות, להזניק רק אם נושא הפוסט הוא הודעה פרטית בתיבת הדואר הנכנס של הקבוצה הזאת+ ignore_group_members:+ label: התעלמות מחברי הקבוצה+ description: לדלג על ההזנקה אם המוען הוא חבר בקבוצה שצוינה לעיל+ ignore_automated:+ label: התעלמות מאוטומטי+ description: לדלג על ההזנקה אם לשולח יש כתובת דוא״ל noreply (לא להגיב) או שהוא ממקור אוטומטי. חל רק על פוסטים שנוצרו דרך דוא״ל+ first_post_only:+ label: פוסט ראשון בלבד+ description: יוקפץ רק אם הפוסט הוא הפוסט הראשון שיצר המשתמש+ first_topic_only:+ label: נושא ראשון בלבד+ description: יוקפץ רק אם הנושא הוא הנושא הראשון שיצר המשתמש+ created: נוצרו+ edited: נערכו+ user_updated:+ fields:+ user_profile:+ label: שדות פרופיל המשתמש+ description: יוזנק רק אם המשתמש מילא את השדות האלו+ custom_fields:+ label: להשתמש בשדות מותאמים אישית+ description: יוזנק רק אם המשתמש מילא את השדות האלו+ once_per_user:+ label: פעם אחת לכל משתמש+ description: יוזנק רק פעם אחת לכל משתמש+ category_created_edited:+ fields:+ restricted_category:+ label: קטגוריית הורה+ description: רשות, מאפשר להגביל הפעלות בקטגוריה הזאת+ pm_created:+ fields:+ restricted_user:+ label: משתמשים+ description: יוזנק רק עבור הודעות פרטיות שנשלחות למשתמש הזה+ restricted_group:+ label: קבוצה+ description: יוזנק רק עבור הודעות פרטיות שנשלחות לקבוצה הזאת+ ignore_staff:+ label: התעלמות מהסגל+ description: לדלג על גורם ההפעלה אם זה משתמש מהסגל+ ignore_group_members:+ label: התעלמות מחברי הקבוצה+ description: לדלג על ההזנקה אם המוען הוא חבר קבוצה שצוינה לעיל+ ignore_automated:+ label: התעלמות מאוטומטי+ description: לדלג על ההזנקה אם לשולח יש כתובת דוא״ל noreply (לא להגיב) או שהוא ממקור אוטומטי. חל רק על הודעות פרטיות שנוצרו דרך דוא״ל+ valid_trust_levels:+ label: דרגות אמון תקפות+ description: יוקפץ רק אם הפוסט נוצר על ידי משתמש בדרגות האמון האלו, ברירת המחדל היא כל דרגת אמון+ after_post_cook:+ fields:+ valid_trust_levels:+ label: דרגות אמון תקפות+ description: יוקפץ רק אם הפוסט נוצר על ידי משתמש בדרגות האמון האלו, ברירת המחדל היא כל דרגת אמון+ restricted_category:+ label: קטגוריה+ description: הגדרת רשות, להזניק רק אם נושא הפוסט בקטגוריה הזאת+ restricted_tags:+ label: תגיות+ description: הגדרת רשות, להזניק רק אם לפוסט יש את אחת התגיות הבאות+ scriptables:+ not_found: לא ניתן למצוא את הסקריפט `%{script}` לאוטומציה `%{automation}`, יש לוודא שהתוסף המשויך מותקן+ zapier_webhook:+ fields:+ webhook_url:+ label: כתובת התליה+ description: "אמורה להיות כתובת התליה תקפה של Zapier, למשל: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: פעם אחת+ description: מגיב פעם אחת בלבד בכל נושא+ word_answer_list:+ label: רשימה של צמדי מילה/תשובה+ description: "מגדיר רשימה של קבוצות מפתח/ערך כאשר `מפתח` הוא הערך אחריו מחפשים, ו`ערך` הוא טקסט התגובה. את ה`מפתח` אפשר להשאיר ריק כדי להגיב לכל ההזנקות ללא תלות בתוכן. נא לשים לב ש`ערך` מקבל `{{key}}` בתור ממלא מקום להחלפת הערך של ה`מפתח` בתגובה. נא לשים לב ש`מפתח` יפוענח כביטוי רגולרי, ותווים מיוחדים כגון `.` דורשים החרגה אם הכוונה שלך הייתה נקודה, למשל: `\\.`"+ answering_user:+ label: משתמש שענה+ description: ברירת המחדל היא משתמש המערכת+ auto_tag_topic:+ fields:+ tags:+ label: תגיות+ description: רשימת תגיות להוספה לנושא.+ post:+ fields:+ creator:+ label: יוצר+ post_creator_context: יוצר הפוסט+ updated_user_context: המשתמש שעודכן+ topic:+ label: מזהה נושא+ post:+ label: תוכן הפוסט+ group_category_notification_default:+ fields:+ group:+ label: קבוצה+ notification_level:+ label: רמת התראה+ update_existing_members:+ label: עדכון חברים קיימים+ description: מעדכן את רמת ההתראות עבור חברי קבוצה קיימים+ user_global_notice:+ fields:+ level:+ label: דרגה+ notice:+ label: הודעה+ description: מקבל HTML, לא למלא את זה בקלט מפוקפק!+ levels:+ warning: אזהרה+ info: מידע+ success: הצלחה+ error: שגיאה+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: שם העיטור+ group:+ label: קבוצה+ description: קבוצת יעד. משתמשים עם העיטור שצוין יתווספו לקבוצה הזאת.+ update_user_title_and_flair:+ label: עדכון כותרת וסמלון המשתמש+ description: רשות, עדכון כותרת וסמלון המשתמש+ remove_members_without_badge:+ label: הסרת חברים קיימים ללא עיטור+ description: כרשות, להסיר חברי קבוצה קיימים בלי עיטורים מסוימים+ badge:+ label: עיטור+ description: בחירת עיטור+ suspend_user_by_email:+ fields:+ suspend_until:+ label: להשעות עד (ברירת מחדל)+ reason:+ label: סיבה (ברירת מחדל)+ actor:+ label: משתמש+ description: "המשתמש האחראי להשעיה (ברירת מחדל: מערכת)"+ pin_topic:+ fields:+ pinnable_topic:+ label: מזהה נושא+ pinned_globally:+ label: נעוץ גלובלית+ pinned_until:+ label: נעוץ עד+ banner_topic:+ fields:+ topic_id:+ label: מזהה נושא+ banner_until:+ label: להציב ככרזה עד+ user:+ label: משתמש+ description: "המשתמש יוצר את הכרזה (ברירת מחדל: מערכת)"+ flag_post_on_words:+ fields:+ words:+ label: מילים שנבדקות+ topic_required_words:+ fields:+ words:+ label: רשימת מילים נדרשות+ send_pms:+ add_a_pm_btn:+ label: הוספת הודעה פרטית+ close_topic:+ fields:+ topic:+ label: מזהה נושא+ message:+ label: הודעת סגירה+ description: "הודעת רשות שתופיע ברשומת סגירת הנושא"+ user:+ label: משתמש+ description: "המשתמש שסגר את הנושא (ברירת מחדל: מערכת)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "שם שדה מותאם אישית של משתמש"+ models:+ script:+ name:+ label: סקריפט+ trigger:+ name:+ label: גורם מפעיל+ automation:+ name:+ label: שם+ trigger:+ label: גורם מפעיל+ script:+ label: סקריפט+ version:+ label: גירסה+ enabled:+ label: מופעל+ disabled:+ label: מושבת+ placeholders:+ label: ממלאי מקום+ last_updated_at:+ label: עדכון אחרון+ last_updated_by:+ label: עודכן על ידיdiff --git a/plugins/automation/config/locales/client.hr.yml b/plugins/automation/config/locales/client.hr.ymlnew file mode 100644index 00000000000..93343ce6e19--- /dev/null+++ b/plugins/automation/config/locales/client.hr.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++hr:diff --git a/plugins/automation/config/locales/client.hu.yml b/plugins/automation/config/locales/client.hu.ymlnew file mode 100644index 00000000000..625fe8d60a7--- /dev/null+++ b/plugins/automation/config/locales/client.hu.yml@@ -0,0 +1,227 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++hu:+ js:+ discourse_automation:+ title: Automatizálás+ create: Létrehozás+ update: Frissítés+ select_script: Válasszon egy parancsfájlt+ select_trigger: Válasszon egy aktiválót+ confirm_automation_reset: Ez a művelet visszaállítja a parancsfájlt és az aktiválási beállításokat, az új állapot mentésre kerül. Folytatja?+ confirm_automation_trigger: Ez a művelet aktiválja az automatizálást, folytatja?+ no_automation_yet: Még nem hozott létre automatizálást.+ edit_automation:+ trigger_section:+ forced: Ez az aktiválót a parancsfájl kényszeríti ki.+ next_pending_automation: "A következő automatizálás ekkor aktiválódik: %{date}"+ trigger_now: "Aktiválás most"+ title: Mikor/mi…+ fields_section:+ title: Parancsfájl beállításai+ destroy_automation:+ confirm: "Biztos, hogy törli: „%{name}\"?"+ fields:+ user:+ label: Felhasználó+ pm:+ title:+ label: Cím+ raw:+ label: Törzs+ pms:+ confirm_remove_pm: "Biztos, hogy eltávolítja ezt a PÜ-t?"+ placeholder_title: PÜ címe+ add_pm: PÜ hozzáadása+ no_pm_created: Még nem hozott létre PÜ-t. A PÜ-k az automatizálás aktiválása után lesznek elküldve.+ title:+ label: Cím+ raw:+ label: Törzs+ delay:+ label: Késleltetés (perc)+ prefers_encrypt:+ label: PÜ titkosítása, ha elérhető+ group:+ label: Csoport+ text:+ label: Szöveg+ triggerables:+ not_found: Nem találta a(z) `%{trigger}` kiváltóját a(z) `%{automation}` automatizáláshoz, győződjön meg róla, hogy a kapcsolódó bővítmény telepítve van-e.+ user_badge_granted:+ fields:+ badge:+ label: Jelvény+ only_first_grant:+ label: Csak az első megadás esetén+ stalled_topic:+ durations:+ PT1H: "Egy óra"+ P1D: "Egy nap"+ P1W: "Egy hét"+ P2W: "Két hét"+ P1M: "Egy hónap"+ P3M: "Három hónap"+ P6M: "Hat hónap"+ P1Y: "Egy év"+ fields:+ categories:+ label: Kategóriákra korlátozva+ tags:+ label: Címkékre korlátozva+ stalled_after:+ label: Ennyi idő után elakadt+ recurring:+ every: Minden+ frequencies:+ minute: percben+ hour: órában+ day: napon+ weekday: hétköznapon+ week: héten+ month: hónapban+ year: évben+ fields:+ recurrence:+ label: Ismétlődés+ start_date:+ label: Kezdő dátum+ stalled_wiki:+ durations:+ PT1H: "Egy óra"+ P1D: "Egy nap"+ P1W: "Egy hét"+ P2W: "Két hét"+ P1M: "Egy hónap"+ P3M: "Három hónap"+ P6M: "Hat hónap"+ P1Y: "Egy év"+ fields:+ stalled_after:+ label: Aktiváló késleltetése+ description: Meghatározza a késleltetést az utolsó wikiszerkesztés és az automatizálás aktiválása között.+ retriggered_after:+ label: Késleltetés újraaktiválása+ description: Meghatározza az első és a következő aktiválás közötti késleltetést, ha a wiki még mindig nem lett szerkesztve az első aktiválás után+ user_added_to_group:+ fields:+ joined_group:+ label: Nyomon követett csoport+ user_removed_from_group:+ fields:+ left_group:+ label: Nyomon követett csoport+ user_promoted:+ fields:+ restricted_group:+ label: Csoportra korlátozás+ trust_level_transition:+ label: Bizalmi szint átmenete+ trust_levels:+ ALL: "Összes bizalmi szintnél"+ TL01: "BSZ0 → BSZ1"+ TL12: "BSZ1 → BSZ2"+ TL23: "BSZ2 → BSZ3"+ TL34: "BSZ3 → BSZ4"+ topic:+ fields:+ restricted_topic:+ label: Témaazonosító+ post_created_edited:+ fields:+ valid_trust_levels:+ label: Érvényes bizalmi szintek+ restricted_category:+ label: Kategória+ restricted_group:+ label: Csoport+ pm_created:+ fields:+ restricted_group:+ label: Csoport+ ignore_staff:+ label: Stáb figyelmen kívül hagyása+ description: Az aktiválás kihagyása, ha a küldő stábtag+ valid_trust_levels:+ label: Érvényes bizalmi szintek+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Érvényes bizalmi szintek+ restricted_category:+ label: Kategória+ restricted_tags:+ label: Címkék+ scriptables:+ zapier_webhook:+ fields:+ webhook_url:+ label: Webhook webcíme+ auto_responder:+ fields:+ word_answer_list:+ label: Szó/válasz párok listája+ answering_user:+ label: Válaszoló felhasználó+ description: Alapértelmezetten a rendszerfelhasználó+ auto_tag_topic:+ fields:+ tags:+ label: Címkék+ post:+ fields:+ topic:+ label: Témaazonosító+ group_category_notification_default:+ fields:+ group:+ label: Csoport+ user_global_notice:+ fields:+ level:+ label: Szint+ notice:+ label: Értesítés+ description: Elfogad HTML-t, ne töltse ki nem megbízható bevitellel!+ levels:+ warning: Figyelmeztetés+ info: Információ+ success: Siker+ error: Hiba+ user_group_membership_through_badge:+ fields:+ group:+ label: Csoport+ badge:+ label: Jelvény+ suspend_user_by_email:+ fields:+ reason:+ label: Ok (alapértelmezett)+ actor:+ label: Felhasználó+ description: "A felfüggesztésért felelős felhasználó (alapértelmezett: rendszer)"+ pin_topic:+ fields:+ pinnable_topic:+ label: Témaazonosító+ pinned_globally:+ label: Globálisan kitűzve+ pinned_until:+ label: Kitűzve eddig+ banner_topic:+ fields:+ topic_id:+ label: Témaazonosító+ user:+ label: Felhasználó+ close_topic:+ fields:+ topic:+ label: Témaazonosító+ user:+ label: Felhasználódiff --git a/plugins/automation/config/locales/client.hy.yml b/plugins/automation/config/locales/client.hy.ymlnew file mode 100644index 00000000000..cb18f64d356--- /dev/null+++ b/plugins/automation/config/locales/client.hy.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++hy:diff --git a/plugins/automation/config/locales/client.id.yml b/plugins/automation/config/locales/client.id.ymlnew file mode 100644index 00000000000..596e36b2e13--- /dev/null+++ b/plugins/automation/config/locales/client.id.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++id:diff --git a/plugins/automation/config/locales/client.it.yml b/plugins/automation/config/locales/client.it.ymlnew file mode 100644index 00000000000..675ea87ab88--- /dev/null+++ b/plugins/automation/config/locales/client.it.yml@@ -0,0 +1,364 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++it:+ js:+ discourse_automation:+ title: Automazione+ create: Crea+ update: Aggiorna+ select_script: Seleziona uno script+ select_trigger: Seleziona evento di attivazione+ confirm_automation_reset: Questa azione ripristinerà script e le opzioni di attivazione, il nuovo stato verrà salvato, vuoi procedere?+ confirm_automation_trigger: Questa azione attiverà l'automazione, vuoi procedere?+ no_automation_yet: Non hai ancora creato alcuna automazione.+ edit_automation:+ trigger_section:+ forced: Questa azione di attivazione è forzata dallo script.+ next_pending_automation: "La prossima automazione si attiverà il: %{date}"+ trigger_now: "Attiva ora"+ title: Quando/Cosa...+ fields_section:+ title: Opzioni dello script+ destroy_automation:+ confirm: "Vuoi davvero eliminare `%{name}`?"+ fields:+ key_value:+ label:+ one: Modifica configurazione (%{count})+ other: Modifica configurazione (%{count})+ user:+ label: Utente+ pm:+ title:+ label: Titolo+ raw:+ label: Corpo+ pms:+ confirm_remove_pm: "Vuoi davvero rimuovere questo MP?"+ placeholder_title: Titolo MP+ add_pm: Aggiungi MP+ no_pm_created: Non hai ancora creato alcun MP. I messaggi personali saranno inviati una volta attivata l'automazione.+ title:+ label: Titolo+ raw:+ label: Corpo+ delay:+ label: Ritardo (minuti)+ prefers_encrypt:+ label: Applica crittografia ai MP se disponibile+ group:+ label: Gruppo+ text:+ label: Testo+ triggerables:+ not_found: Impossibile trovare azione di attivazione `%{trigger}` per l'automazione `%{automation}`, verifica che il plugin associato sia installato+ user_badge_granted:+ fields:+ badge:+ label: Distintivo+ only_first_grant:+ label: Solo alla prima concessione+ stalled_topic:+ durations:+ PT1H: "Un'ora"+ P1D: "Un giorno"+ P1W: "Una settimana"+ P2W: "Due settimane"+ P1M: "Un mese"+ P3M: "Tre mesi"+ P6M: "Sei mesi"+ P1Y: "Un anno"+ fields:+ categories:+ label: Limitato alle categorie+ tags:+ label: Limitato ai tag+ stalled_after:+ label: Bloccato dopo+ recurring:+ every: Sempre+ frequencies:+ minute: minuto+ hour: ora+ day: giorno+ weekday: giorno feriale+ week: settimana+ month: mese+ year: anno+ fields:+ recurrence:+ label: Ricorrenza+ start_date:+ label: Data iniziale+ stalled_wiki:+ durations:+ PT1H: "Un'ora"+ P1D: "Un giorno"+ P1W: "Una settimana"+ P2W: "Due settimane"+ P1M: "Un mese"+ P3M: "Tre mesi"+ P6M: "Sei mesi"+ P1Y: "Un anno"+ fields:+ restricted_category:+ label: Limitato alla categoria+ stalled_after:+ label: Ritardo di attivazione+ description: Definisce il ritardo tra l'ultima modifica wiki e l'attivazione dell'automazione+ retriggered_after:+ label: Ritardo di riattivazione+ description: Definisce il ritardo tra la prima attivazione e la successiva, se wiki non è stato ancora modificato dopo la prima attivazione+ user_added_to_group:+ fields:+ joined_group:+ label: Gruppo tracciato+ user_removed_from_group:+ fields:+ left_group:+ label: Gruppo tracciato+ user_promoted:+ fields:+ restricted_group:+ label: Limita al gruppo+ trust_level_transition:+ label: Transizione del livello di attendibilità (TL)+ trust_levels:+ ALL: "Tutti i livelli di attendibilità"+ TL01: "Da TL0 a TL1"+ TL12: "Da TL1 a TL2"+ TL23: "Da TL2 a TL3"+ TL34: "Da TL3 a TL4"+ point_in_time:+ fields:+ execute_at:+ label: Esegui alle+ topic:+ fields:+ restricted_topic:+ label: ID argomento+ post_created_edited:+ fields:+ action_type:+ label: Tipo di azione+ description: "Facoltativo, limitare l'attivazione solo agli eventi creati o modificati"+ valid_trust_levels:+ label: Livelli di attendibilità validi+ description: L'attivazione avverrà solo se il messaggio viene creato da utenti in questi livelli di attendibilità, il valore predefinito è qualsiasi livello di attendibilità+ restricted_category:+ label: Categoria+ description: Facoltativo, verrà attivato solo se l'argomento del post rientra in questa categoria+ restricted_group:+ label: Gruppo+ description: Facoltativo, verrà attivato solo se l'argomento del post è un messaggio privato nella posta in arrivo di questo gruppo+ ignore_group_members:+ label: Ignora i membri del gruppo+ description: Salta l'attivazione se il mittente è un membro del gruppo specificato sopra+ ignore_automated:+ label: Ignora automatizzati+ description: Salta l'attivazione se il mittente ha un'e-mail che non accetta risposte o che proviene da una fonte automatizzata. Si applica solo ai messaggi creati via e-mail+ first_post_only:+ label: Solo il primo messaggio+ description: Si attiverà solo se il messaggio è il primo messaggio creato da un utente+ first_topic_only:+ label: Solo il primo argomento+ description: Si attiverà solo se l'argomento è il primo creato da un utente+ created: Creati+ edited: Modificati+ category_created_edited:+ fields:+ restricted_category:+ label: Categoria principale+ description: Facoltativo, consente di limitare l'attivazione di questa categoria+ pm_created:+ fields:+ restricted_user:+ label: Utenti+ description: Si attiverà solo per i MP inviati a questo utente+ restricted_group:+ label: Gruppo+ description: Si attiverà solo per i MP inviati a questo gruppo+ ignore_staff:+ label: Ignora staff+ description: Salta l'attivazione se il mittente è un utente dello staff+ ignore_group_members:+ label: Ignora i membri del gruppo+ description: Salta l'attivazione se il mittente è un membro del gruppo specificato sopra+ ignore_automated:+ label: Ignora automatizzati+ description: Salta l'attivazione se il mittente ha un'e-mail che non accetta risposte o che proviene da una fonte automatizzata. Si applica solo ai MP creati via e-mail+ valid_trust_levels:+ label: Livelli di attendibilità validi+ description: L'attivazione avverrà solo se il messaggio viene creato da utenti in questi livelli di attendibilità, il valore predefinito è qualsiasi livello di attendibilità+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Livelli di attendibilità validi+ description: L'attivazione avverrà solo se il messaggio viene creato da utenti in questi livelli di attendibilità, il valore predefinito è qualsiasi livello di attendibilità+ restricted_category:+ label: Categoria+ description: Facoltativo, verrà attivato solo se l'argomento del post rientra in questa categoria+ restricted_tags:+ label: Tag+ description: Facoltativo, si attiverà solo se il messaggio ha una di queste etichette+ scriptables:+ not_found: Impossibile trovare lo script `%{script}` per l'automazione `%{automation}`, verifica che il plugin associato sia installato+ zapier_webhook:+ fields:+ webhook_url:+ label: URL webhook+ description: "Richiede un URL webhook Zapier valido, ad esempio: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: Una volta+ description: Risponde solo una volta per argomento+ word_answer_list:+ label: Elenco di coppie parole/risposte+ answering_user:+ label: Utente che risponde+ description: Ripristina impostazione predefinita Utente di sistema+ auto_tag_topic:+ fields:+ tags:+ label: Etichette+ description: Elenco di etichette da aggiungere all'argomento.+ post:+ fields:+ creator:+ label: Autore+ topic:+ label: ID argomento+ post:+ label: Contenuto messaggio+ group_category_notification_default:+ fields:+ group:+ label: Gruppo+ notification_level:+ label: Livello di notifica+ update_existing_members:+ label: Aggiorna i membri esistenti+ description: Aggiorna il livello di notifica per i membri del gruppo esistenti+ user_global_notice:+ fields:+ level:+ label: Livello+ notice:+ label: Avviso+ description: Accetta HTML, non riempire questo campo con contenuti non attendibili!+ levels:+ warning: Avvertenza+ info: Informazioni+ success: Riuscito+ error: Errore+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Nome del distintivo+ group:+ label: Gruppo+ description: Gruppo di destinazione. Gli utenti con il distintivo specificato saranno aggiunti a questo gruppo.+ update_user_title_and_flair:+ label: Aggiorna il titolo e lo stile dell'utente+ description: Facoltativo, aggiorna il titolo e lo stile dell'utente+ remove_members_without_badge:+ label: Rimuovi i membri esistenti senza distintivo+ description: Facoltativo, rimuovi i membri del gruppo esistenti senza il distintivo specificato+ badge:+ label: Distintivo+ description: Seleziona il distintivo+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Sospendi fino a (predefinito)+ reason:+ label: Motivo (predefinito)+ actor:+ label: Utente+ description: "Utente responsabile della sospensione (valore predefinito: sistema)"+ pin_topic:+ fields:+ pinnable_topic:+ label: ID argomento+ pinned_globally:+ label: Fissato a livello globale+ pinned_until:+ label: Fissato fino a+ banner_topic:+ fields:+ topic_id:+ label: ID argomento+ banner_until:+ label: Crea banner fino a+ user:+ label: Utente+ description: "Utente che crea il banner (valore predefinito: sistema)"+ flag_post_on_words:+ fields:+ words:+ label: Parole controllate+ topic_required_words:+ fields:+ words:+ label: Elenco delle parole richieste+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Nome del gruppo di partecipanti+ giftee_assignment_messages:+ label: Messaggi inviati al donatore+ send_pms:+ add_a_pm_btn:+ label: Aggiungi un MP+ fields:+ receiver:+ label: Destinatario MP+ sendable_pms:+ label: MP+ sender:+ label: Mittente MP+ close_topic:+ fields:+ topic:+ label: ID argomento+ message:+ label: Messaggio di chiusura+ description: "Messaggio opzionale da mostrare nel registro Argomento chiuso"+ user:+ label: Utente+ description: "Utente che chiude l'argomento (valore predefinito: sistema)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "Nome campo personalizzato utente"+ models:+ script:+ name:+ label: Script+ trigger:+ name:+ label: Azione di attivazione+ automation:+ name:+ label: Nome+ trigger:+ label: Azione di attivazione+ script:+ label: Script+ version:+ label: Versione+ enabled:+ label: Abilitato+ disabled:+ label: Disabilitato+ placeholders:+ label: Segnaposto+ last_updated_at:+ label: Ultimo aggiornamento+ last_updated_by:+ label: Aggiornato dadiff --git a/plugins/automation/config/locales/client.ja.yml b/plugins/automation/config/locales/client.ja.ymlnew file mode 100644index 00000000000..d698389d40e--- /dev/null+++ b/plugins/automation/config/locales/client.ja.yml@@ -0,0 +1,363 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ja:+ js:+ discourse_automation:+ title: 自動化+ create: 作成+ update: 更新+ select_script: スクリプトを選択+ select_trigger: トリガーを選択+ confirm_automation_reset: この操作により、スクリプトとトリガーのオプションがリセットされ、新しい状態が保存されます。続行しますか?+ confirm_automation_trigger: この操作により、自動化がトリガーされます。続行しますか?+ no_automation_yet: 自動化はまだ作成されていません。+ edit_automation:+ trigger_section:+ forced: このトリガーはスクリプトで強制されています。+ next_pending_automation: "次の自動化がトリガーされるタイミング: %{date}"+ trigger_now: "今すぐトリガー"+ title: いつ/何を...+ fields_section:+ title: スクリプトのオプション+ destroy_automation:+ confirm: "`%{name}` を削除してもよろしいですか?"+ fields:+ key_value:+ label:+ other: 構成の編集 (%{count})+ user:+ label: ユーザー+ pm:+ title:+ label: タイトル+ raw:+ label: 本文+ pms:+ confirm_remove_pm: "この PM を削除してもよろしいですか?"+ placeholder_title: PM のタイトル+ add_pm: PM を追加+ no_pm_created: まだ PM を作成していません。PM は自動化がトリガーされると送信されます。+ title:+ label: タイトル+ raw:+ label: 本文+ delay:+ label: 遅延(分)+ prefers_encrypt:+ label: 可能な場合は PM を暗号化する+ group:+ label: グループ+ text:+ label: テキスト+ triggerables:+ not_found: 自動化 `%{automation}` のトリガー `%{trigger}` が見つかりませんでした。関連するプラグインがインストールされていることを確認してください。+ user_badge_granted:+ fields:+ badge:+ label: バッジ+ only_first_grant:+ label: 初回付与時のみ+ stalled_topic:+ durations:+ PT1H: "1 時間"+ P1D: "1 日"+ P1W: "1 週間"+ P2W: "2 週間"+ P1M: "1 か月"+ P3M: "3 か月"+ P6M: "6 か月"+ P1Y: "1 年"+ fields:+ categories:+ label: カテゴリ限定+ tags:+ label: タグ限定+ stalled_after:+ label: 次の後失速+ recurring:+ every: 毎+ frequencies:+ minute: 分+ hour: 時間+ day: 日+ weekday: 平日+ week: 週+ month: 月+ year: 年+ fields:+ recurrence:+ label: 繰り返し+ start_date:+ label: 開始日+ stalled_wiki:+ durations:+ PT1H: "1 時間"+ P1D: "1 日"+ P1W: "1 週間"+ P2W: "2 週間"+ P1M: "1 か月"+ P3M: "3 か月"+ P6M: "6 か月"+ P1Y: "1 年"+ fields:+ restricted_category:+ label: カテゴリに限定+ stalled_after:+ label: トリガー遅延+ description: 最後のウィキ編集と自動化のトリガーの間の遅延を定義します+ retriggered_after:+ label: 再トリガー遅延+ description: 最初のトリガーの後にまだWikiが編集されていない場合に、最初のトリガーと次のトリガーの間の遅延を定義します。+ user_added_to_group:+ fields:+ joined_group:+ label: 追跡中のグループ+ user_removed_from_group:+ fields:+ left_group:+ label: 追跡中のグループ+ user_promoted:+ fields:+ restricted_group:+ label: グループに限定+ trust_level_transition:+ label: 信頼レベルの移行+ trust_levels:+ ALL: "すべての信頼レベル"+ TL01: "TL0 から TL1"+ TL12: "TL1 から TL2"+ TL23: "TL2 から TL3"+ TL34: "TL3 から TL4"+ point_in_time:+ fields:+ execute_at:+ label: 実行時間+ topic:+ fields:+ restricted_topic:+ label: トピック ID+ post_created_edited:+ fields:+ action_type:+ label: アクションのタイプ+ description: "オプション。トリガーを作成または編集されたイベントのみに制限します"+ valid_trust_levels:+ label: 有効な信頼レベル+ description: 投稿がこれらの信頼レベルのユーザーによって作成された場合にのみトリガーされます。デフォルトはすべての信頼レベルです。+ restricted_category:+ label: カテゴリ+ description: オプション。投稿のトピックがこのカテゴリにある場合にのみトリガーされます。+ restricted_group:+ label: グループ+ description: オプション。投稿のトピックがこのグループの受信トレイにあるプライベートメッセージである場合にのみトリガーされます。+ ignore_group_members:+ label: グループメンバーを無視+ description: 送信者が上記に指定されたグループのメンバーである場合はトリガーをスキップします。+ ignore_automated:+ label: 自動送信元を無視+ description: 送信者のメールが noreply メールである場合、または自動送信元から送信されたものである場合はスキップします。メールで作成された投稿にのみ適用されます。+ first_post_only:+ label: 最初の投稿のみ+ description: 投稿がユーザーが作成した最初の投稿である場合にのみトリガーされます。+ first_topic_only:+ label: 最初のトピックのみ+ description: トピックがユーザーが作成した最初のトピックである場合にのみトリガーされます。+ created: 作成+ edited: 編集+ category_created_edited:+ fields:+ restricted_category:+ label: 親カテゴリ+ description: オプション。トリガーの実行をこのカテゴリに限定できます+ pm_created:+ fields:+ restricted_user:+ label: ユーザー+ description: このユーザーに送信された PM に対してのみトリガーされます。+ restricted_group:+ label: グループ+ description: このグループに送信された PM に対してのみトリガーされます+ ignore_staff:+ label: スタッフを無視する+ description: 送信者がスタッフユーザーである場合は、トリガーをスキップします+ ignore_group_members:+ label: グループメンバーを無視+ description: 送信者が上記に指定されたグループのメンバーである場合はトリガーをスキップします。+ ignore_automated:+ label: 自動送信元を無視+ description: 送信者のメールが noreply メールである場合、または自動送信元から送信されたものである場合はスキップします。メールで作成された PM にのみ適用されます。+ valid_trust_levels:+ label: 有効な信頼レベル+ description: 投稿がこれらの信頼レベルのユーザーによって作成された場合にのみトリガーされます。デフォルトはすべての信頼レベルです。+ after_post_cook:+ fields:+ valid_trust_levels:+ label: 有効な信頼レベル+ description: 投稿がこれらの信頼レベルのユーザーによって作成された場合にのみトリガーされます。デフォルトはすべての信頼レベルです。+ restricted_category:+ label: カテゴリ+ description: オプション。投稿のトピックがこのカテゴリにある場合にのみトリガーされます。+ restricted_tags:+ label: タグ+ description: オプション。投稿にこれらのいずれかのタグが設定されている場合にのみトリガーされます。+ scriptables:+ not_found: 自動化 `%{automation}` のスクリプト `%{script}` が見つかりませんでした。関連するプラグインがインストールされていることを確認してください。+ zapier_webhook:+ fields:+ webhook_url:+ label: Webhook URL+ description: "有効な Zpier webhook URL が必要です。例: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: 1 回+ description: トピックごとに 1 回だけ応答します+ word_answer_list:+ label: 単語/回答ペアのリスト+ answering_user:+ label: 回答するユーザー+ description: デフォルトでシステムユーザー+ auto_tag_topic:+ fields:+ tags:+ label: タグ+ description: トピックに追加するタグのリスト。+ post:+ fields:+ creator:+ label: 作成者+ topic:+ label: トピック ID+ post:+ label: 投稿内容+ group_category_notification_default:+ fields:+ group:+ label: グループ+ notification_level:+ label: 通知レベル+ update_existing_members:+ label: 既存のメンバーを更新する+ description: 既存のグループメンバーの通知レベルを更新します+ user_global_notice:+ fields:+ level:+ label: レベル+ notice:+ label: お知らせ+ description: HTML を使用できます。信頼できない入力を入力しないでください!+ levels:+ warning: 警告+ info: 情報+ success: 成功+ error: エラー+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: バッジ名+ group:+ label: グループ+ description: ターゲットグループ。指定されたバッジを持つユーザーがこのグループに追加されます。+ update_user_title_and_flair:+ label: ユーザーのタイトルとフレアを更新+ description: オプション。ユーザーのタイトルとフレアを更新します。+ remove_members_without_badge:+ label: バッジのない既存のメンバーを削除+ description: オプション。指定されたバッジのない既存のグループメンバーを削除します。+ badge:+ label: バッジ+ description: バッジの選択+ suspend_user_by_email:+ fields:+ suspend_until:+ label: 凍結期間(デフォルト)+ reason:+ label: 理由(デフォルト)+ actor:+ label: ユーザー+ description: "凍結を管理するユーザー(デフォルト: システム)"+ pin_topic:+ fields:+ pinnable_topic:+ label: トピック ID+ pinned_globally:+ label: グローバルに固定+ pinned_until:+ label: 固定期間+ banner_topic:+ fields:+ topic_id:+ label: トピック ID+ banner_until:+ label: バナー設定期間+ user:+ label: ユーザー+ description: "バナーを作成するユーザー(デフォルト: システム)"+ flag_post_on_words:+ fields:+ words:+ label: チェックした単語+ topic_required_words:+ fields:+ words:+ label: 必要な単語リスト+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: 参加者のグループ名+ giftee_assignment_messages:+ label: 贈り主に送信されるメッセージ+ send_pms:+ add_a_pm_btn:+ label: PM を追加する+ fields:+ receiver:+ label: PM 受信者+ sendable_pms:+ label: PM+ sender:+ label: PM 送信者+ close_topic:+ fields:+ topic:+ label: トピック ID+ message:+ label: 閉鎖メッセージ+ description: "トピック閉鎖レコードに表示されるオプションのメッセージ"+ user:+ label: ユーザー+ description: "トピックを閉鎖するユーザー(デフォルト: システム)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "ユーザーカスタムフィールド名"+ models:+ script:+ name:+ label: スクリプト+ trigger:+ name:+ label: トリガー+ automation:+ name:+ label: 名前+ trigger:+ label: トリガー+ script:+ label: スクリプト+ version:+ label: バージョン+ enabled:+ label: 有効+ disabled:+ label: 無効+ placeholders:+ label: プレースホルダー+ last_updated_at:+ label: 最終更新+ last_updated_by:+ label: 更新者diff --git a/plugins/automation/config/locales/client.ko.yml b/plugins/automation/config/locales/client.ko.ymlnew file mode 100644index 00000000000..18dd77fd3ec--- /dev/null+++ b/plugins/automation/config/locales/client.ko.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ko:diff --git a/plugins/automation/config/locales/client.lt.yml b/plugins/automation/config/locales/client.lt.ymlnew file mode 100644index 00000000000..16bb19758dc--- /dev/null+++ b/plugins/automation/config/locales/client.lt.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++lt:diff --git a/plugins/automation/config/locales/client.lv.yml b/plugins/automation/config/locales/client.lv.ymlnew file mode 100644index 00000000000..59e0ef6f4ed--- /dev/null+++ b/plugins/automation/config/locales/client.lv.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++lv:diff --git a/plugins/automation/config/locales/client.nb_NO.yml b/plugins/automation/config/locales/client.nb_NO.ymlnew file mode 100644index 00000000000..2e2224d1472--- /dev/null+++ b/plugins/automation/config/locales/client.nb_NO.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++nb_NO:diff --git a/plugins/automation/config/locales/client.nl.yml b/plugins/automation/config/locales/client.nl.ymlnew file mode 100644index 00000000000..41886fd9dad--- /dev/null+++ b/plugins/automation/config/locales/client.nl.yml@@ -0,0 +1,364 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++nl:+ js:+ discourse_automation:+ title: Automatisering+ create: Maken+ update: Bijwerken+ select_script: Selecteer een script+ select_trigger: Selecteer een trigger+ confirm_automation_reset: Deze actie reset script- en triggeropties, de nieuwe toestand wordt opgeslagen. Wil je doorgaan?+ confirm_automation_trigger: Deze actie activeert de automatisering, wil je doorgaan?+ no_automation_yet: Je hebt nog geen automatiseringen gemaakt.+ edit_automation:+ trigger_section:+ forced: Deze trigger wordt geforceerd door een script.+ next_pending_automation: "De volgende automatisering wordt geactiveerd op: %{date}"+ trigger_now: "Nu triggeren"+ title: Wanneer/wat...+ fields_section:+ title: Scriptopties+ destroy_automation:+ confirm: "Weet je zeker dat je '%{name}' wilt verwijderen?"+ fields:+ key_value:+ label:+ one: Configuratie bewerken (%{count})+ other: Configuratie bewerken (%{count})+ user:+ label: Gebruiker+ pm:+ title:+ label: Titel+ raw:+ label: Tekst+ pms:+ confirm_remove_pm: "Weet je zeker dat je dit PB wilt verwijderen?"+ placeholder_title: PB-titel+ add_pm: PB toevoegen+ no_pm_created: Je hebt nog geen PB gemaakt. PB's worden gestuurd wanneer je automatisering is geactiveerd.+ title:+ label: Titel+ raw:+ label: Tekst+ delay:+ label: Vertraging (minuten)+ prefers_encrypt:+ label: Versleutelt PB indien beschikbaar+ group:+ label: Groep+ text:+ label: Tekst+ triggerables:+ not_found: Kon trigger '%{trigger}' voor automatisering '%{automation}' niet vinden, controleer of de bijbehorende plug-in is geïnstalleerd+ user_badge_granted:+ fields:+ badge:+ label: Badge+ only_first_grant:+ label: Alleen bij eerste toekenning+ stalled_topic:+ durations:+ PT1H: "Eén uur"+ P1D: "Eén dag"+ P1W: "Eén week"+ P2W: "Twee weken"+ P1M: "Eén maand"+ P3M: "Drie maanden"+ P6M: "Zes maanden"+ P1Y: "Eén jaar"+ fields:+ categories:+ label: Beperkt tot categorieën+ tags:+ label: Beperkt tot tags+ stalled_after:+ label: Stilgevallen na+ recurring:+ every: Elk(e)+ frequencies:+ minute: minuut+ hour: uur+ day: dag+ weekday: weekdag+ week: week+ month: maand+ year: jaar+ fields:+ recurrence:+ label: Herhaling+ start_date:+ label: Begindatum+ stalled_wiki:+ durations:+ PT1H: "Eén uur"+ P1D: "Eén dag"+ P1W: "Eén week"+ P2W: "Twee weken"+ P1M: "Eén maand"+ P3M: "Drie maanden"+ P6M: "Zes maanden"+ P1Y: "Eén jaar"+ fields:+ restricted_category:+ label: Beperkt tot categorie+ stalled_after:+ label: Triggervertraging+ description: Definieert de vertraging tussen de laatste wikibewerking en de automatiseringstrigger+ retriggered_after:+ label: Hertriggervertraging+ description: Definieert de vertraging tussen de eerste en de volgende trigger, als de wiki na de eerste trigger nog steeds niet is bewerkt+ user_added_to_group:+ fields:+ joined_group:+ label: Gevolgde groep+ user_removed_from_group:+ fields:+ left_group:+ label: Gevolgde groep+ user_promoted:+ fields:+ restricted_group:+ label: Beperken tot groep+ trust_level_transition:+ label: Overgang vertrouwensniveau+ trust_levels:+ ALL: "Alle vertrouwensniveaus"+ TL01: "TL0 naar TL1"+ TL12: "TL1 naar TL2"+ TL23: "TL2 naar TL3"+ TL34: "TL3 naar TL4"+ point_in_time:+ fields:+ execute_at:+ label: Uitvoeren om+ topic:+ fields:+ restricted_topic:+ label: Topic-ID+ post_created_edited:+ fields:+ action_type:+ label: Actietype+ description: "Optioneel, beperk triggering tot alleen gemaakte of bewerkte gebeurtenissen"+ valid_trust_levels:+ label: Geldige vertrouwensniveaus+ description: Wordt alleen getriggerd als een bericht wordt gemaakt door een gebruiker met deze vertrouwensniveaus. Standaard ingesteld op elk vertrouwensniveau+ restricted_category:+ label: Categorie+ description: Optioneel, wordt alleen geactiveerd als het topic van het bericht in deze categorie valt+ restricted_group:+ label: Groep+ description: Optioneel, wordt alleen geactiveerd als het topic van het bericht een privébericht is in de inbox van deze groep+ ignore_group_members:+ label: Groepsleden negeren+ description: Sla de trigger over als de afzender lid is van de hierboven opgegeven groep+ ignore_automated:+ label: Geautomatiseerd negeren+ description: Sla de trigger over als de afzender een noreply-e-mailadres heeft of een geautomatiseerde bron is. Alleen van toepassing op berichten die via e-mail zijn gemaakt+ first_post_only:+ label: Alleen eerste bericht+ description: Wordt alleen geactiveerd als het bericht het eerste bericht is dat een gebruiker heeft gemaakt+ first_topic_only:+ label: Alleen eerste topic+ description: Wordt alleen geactiveerd als het topic het eerste topic is dat een gebruiker heeft gemaakt+ created: Gemaakt+ edited: Bewerkt+ category_created_edited:+ fields:+ restricted_category:+ label: Bovenliggende categorie+ description: Optioneel, maakt het mogelijk om de uitvoering van triggers te beperken tot deze categorie+ pm_created:+ fields:+ restricted_user:+ label: Gebruikers+ description: Wordt alleen geactiveerd voor PB's die naar deze gebruiker worden verzonden+ restricted_group:+ label: Groep+ description: Wordt alleen geactiveerd voor PB's die naar deze groep worden verzonden+ ignore_staff:+ label: Medewerkers negeren+ description: Sla de trigger over als de afzender een medewerker is+ ignore_group_members:+ label: Groepsleden negeren+ description: Sla de trigger over als de afzender lid is van de hierboven opgegeven groep+ ignore_automated:+ label: Geautomatiseerd negeren+ description: Sla de trigger over als de afzender een noreply-e-mailadres heeft of een geautomatiseerde bron is. Alleen van toepassing op PB's die via e-mail zijn gemaakt+ valid_trust_levels:+ label: Geldige vertrouwensniveaus+ description: Wordt alleen getriggerd als een bericht wordt gemaakt door een gebruiker met deze vertrouwensniveaus. Standaard ingesteld op elk vertrouwensniveau+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Geldige vertrouwensniveaus+ description: Wordt alleen getriggerd als een bericht wordt gemaakt door een gebruiker met deze vertrouwensniveaus. Standaard ingesteld op elk vertrouwensniveau+ restricted_category:+ label: Categorie+ description: Optioneel, wordt alleen geactiveerd als het topic van het bericht in deze categorie valt+ restricted_tags:+ label: Tags+ description: Optioneel, wordt alleen geactiveerd als het bericht een van deze tags heeft+ scriptables:+ not_found: Kon script '%{script}' voor automatisering '%{automation}' niet vinden, controleer of de bijbehorende plug-in is geïnstalleerd+ zapier_webhook:+ fields:+ webhook_url:+ label: Webhook-URL+ description: "Verwacht een geldige Zapier-webhook-URL, bijvoorbeeld: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: Eenmaal+ description: Reageert slechts één keer per topic+ word_answer_list:+ label: Lijst van woord-antwoordparen+ answering_user:+ label: Antwoordende gebruiker+ description: Standaard ingesteld op Systeemgebruiker+ auto_tag_topic:+ fields:+ tags:+ label: Tags+ description: Lijst van tags om toe te voegen aan de topic.+ post:+ fields:+ creator:+ label: Maker+ topic:+ label: Topic-ID+ post:+ label: Berichtinhoud+ group_category_notification_default:+ fields:+ group:+ label: Groep+ notification_level:+ label: Meldingsniveau+ update_existing_members:+ label: Bestaande leden bijwerken+ description: Werkt het meldingsniveau bij voor bestaande groepsleden+ user_global_notice:+ fields:+ level:+ label: Niveau+ notice:+ label: Kennisgeving+ description: Accepteert HTML, vul dit niet met niet-vertrouwde invoer!+ levels:+ warning: Waarschuwing+ info: Informatie+ success: Geslaagd+ error: Fout+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Badgenaam+ group:+ label: Groep+ description: Doelgroep. Gebruikers met de opgegeven badge worden aan deze groep toegevoegd.+ update_user_title_and_flair:+ label: Gebruikerstitel en flair bijwerken+ description: 'Optioneel: werk de gebruikerstitel en flair bij'+ remove_members_without_badge:+ label: Bestaande leden zonder badge verwijderen+ description: 'Optioneel: verwijder bestaande groepsleden zonder de opgegeven badge'+ badge:+ label: Badge+ description: Selecteer badge+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Schorsen tot (standaard)+ reason:+ label: Reden (standaard)+ actor:+ label: Gebruiker+ description: "De gebruiker die verantwoordelijk is voor de schorsing (standaard: systeem)"+ pin_topic:+ fields:+ pinnable_topic:+ label: Topic-ID+ pinned_globally:+ label: Globaal vastgemaakt+ pinned_until:+ label: Vastgemaakt tot+ banner_topic:+ fields:+ topic_id:+ label: Topic-ID+ banner_until:+ label: Banner maken tot+ user:+ label: Gebruiker+ description: "De gebruiker die de banner maakt (standaard: systeem)"+ flag_post_on_words:+ fields:+ words:+ label: Gecontroleerde woorden+ topic_required_words:+ fields:+ words:+ label: Lijst van vereiste woorden+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Groepsnaam van deelnemers+ giftee_assignment_messages:+ label: Berichten gestuurd naar gever+ send_pms:+ add_a_pm_btn:+ label: Voeg een PB toe+ fields:+ receiver:+ label: PB-ontvanger+ sendable_pms:+ label: PB's+ sender:+ label: Afzender PB's+ close_topic:+ fields:+ topic:+ label: Topic-ID+ message:+ label: Sluitingsbericht+ description: "Optioneel bericht om weer te geven in het record Topic gesloten"+ user:+ label: Gebruiker+ description: "De gebruiker die het topic sluit (standaard: systeem)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "Naam aangepast gebruikersveld"+ models:+ script:+ name:+ label: Script+ trigger:+ name:+ label: Trigger+ automation:+ name:+ label: Naam+ trigger:+ label: Trigger+ script:+ label: Script+ version:+ label: Versie+ enabled:+ label: Ingeschakeld+ disabled:+ label: Uitgeschakeld+ placeholders:+ label: Plaatshouders+ last_updated_at:+ label: Laatst bijgewerkt+ last_updated_by:+ label: Bijgewerkt doordiff --git a/plugins/automation/config/locales/client.pl_PL.yml b/plugins/automation/config/locales/client.pl_PL.ymlnew file mode 100644index 00000000000..d9464ce7a5c--- /dev/null+++ b/plugins/automation/config/locales/client.pl_PL.yml@@ -0,0 +1,239 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++pl_PL:+ js:+ discourse_automation:+ title: Automatyzacja+ create: Utwórz+ update: Aktualizuj+ select_script: Wybierz skrypt+ select_trigger: Wybierz wyzwalacz+ confirm_automation_reset: Ta czynność spowoduje zresetowanie opcji skryptu i wyzwalacza, nowy stan zostanie zapisany, czy chcesz kontynuować?+ confirm_automation_trigger: Ta czynność uruchomi automatyzację, czy chcesz kontynuować?+ no_automation_yet: Nie utworzyłeś jeszcze żadnej automatyzacji.+ edit_automation:+ trigger_section:+ forced: Ten wyzwalacz jest wymuszany przez skrypt.+ next_pending_automation: "Następna automatyzacja uruchomi się: %{date}"+ trigger_now: "Uruchom teraz"+ title: Kiedy/Co...+ fields_section:+ title: Opcje skryptu+ destroy_automation:+ confirm: "Czy na pewno chcesz usunąć `%{name}`?"+ fields:+ user:+ label: Użytkownik+ pm:+ title:+ label: Tytuł+ pms:+ confirm_remove_pm: "Czy na pewno chcesz usunąć tę wiadomość prywatną?"+ placeholder_title: Tytuł PW+ add_pm: Dodaj PW+ title:+ label: Tytuł+ group:+ label: Grupa+ text:+ label: Tekst+ triggerables:+ user_badge_granted:+ fields:+ badge:+ label: Odznaka+ stalled_topic:+ durations:+ PT1H: "Jedna godzina"+ P1D: "Jeden dzień"+ P1W: "Jeden tydzień"+ P2W: "Dwa tygodnie"+ P1M: "Jeden miesiąc"+ P3M: "Trzy miesiące"+ P6M: "Sześć miesięcy"+ P1Y: "Jeden rok"+ recurring:+ every: Co+ frequencies:+ minute: minuta+ hour: godzina+ day: dzień+ weekday: dzień powszedni+ week: tydzień+ month: miesiąc+ year: rok+ fields:+ start_date:+ label: Data rozpoczęcia+ stalled_wiki:+ durations:+ PT1H: "Jedna godzina"+ P1D: "Jeden dzień"+ P1W: "Jeden tydzień"+ P2W: "Dwa tygodnie"+ P1M: "Jeden miesiąc"+ P3M: "Trzy miesiące"+ P6M: "Sześć miesięcy"+ P1Y: "Jeden rok"+ user_added_to_group:+ fields:+ joined_group:+ label: Śledzona grupa+ user_removed_from_group:+ fields:+ left_group:+ label: Śledzona grupa+ user_promoted:+ fields:+ restricted_group:+ label: Ogranicz do grupy+ trust_levels:+ ALL: "Wszystkie poziomy zaufania"+ TL01: "TL0 do TL1"+ TL12: "TL1 do TL2"+ TL23: "TL2 do TL3"+ TL34: "TL3 do TL4"+ point_in_time:+ fields:+ execute_at:+ label: Wykonaj o+ topic:+ fields:+ restricted_topic:+ label: ID tematu+ post_created_edited:+ fields:+ action_type:+ label: Typ akcji+ valid_trust_levels:+ label: Prawidłowe poziomy zaufania+ restricted_category:+ label: Kategoria+ restricted_group:+ label: Grupa+ created: Utworzony+ edited: Edytowany+ category_created_edited:+ fields:+ restricted_category:+ label: Kategoria nadrzędna+ pm_created:+ fields:+ restricted_group:+ label: Grupa+ ignore_staff:+ label: Ignoruj personel+ valid_trust_levels:+ label: Prawidłowe poziomy zaufania+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Prawidłowe poziomy zaufania+ restricted_category:+ label: Kategoria+ restricted_tags:+ label: Tagi+ scriptables:+ zapier_webhook:+ fields:+ webhook_url:+ label: URL webhooka+ auto_responder:+ fields:+ once:+ label: Raz+ answering_user:+ label: Odpowiada użytkownikowi+ auto_tag_topic:+ fields:+ tags:+ label: Tagi+ post:+ fields:+ creator:+ label: Twórca+ topic:+ label: ID tematu+ post:+ label: Treść postu+ group_category_notification_default:+ fields:+ group:+ label: Grupa+ notification_level:+ label: Poziom powiadomienia+ update_existing_members:+ label: Zaktualizuj istniejących członków+ user_global_notice:+ fields:+ level:+ label: Poziom+ levels:+ warning: Ostrzeżenie+ info: Informacja+ success: Sukces+ error: Błąd+ user_group_membership_through_badge:+ fields:+ group:+ label: Grupa+ badge:+ label: Odznaka+ suspend_user_by_email:+ fields:+ reason:+ label: Powód (domyślny)+ actor:+ label: Użytkownik+ pin_topic:+ fields:+ pinnable_topic:+ label: ID tematu+ pinned_globally:+ label: Przypięty globalnie+ pinned_until:+ label: Przypięty do+ banner_topic:+ fields:+ topic_id:+ label: ID tematu+ user:+ label: Użytkownik+ close_topic:+ fields:+ topic:+ label: ID tematu+ message:+ label: Wiadomość zamykająca+ description: "Opcjonalny komunikat do wyświetlenia w rekordzie Zamknięty Temat"+ user:+ label: Użytkownik+ description: "Użytkownik zamykający temat (domyślnie: system)"+ models:+ script:+ name:+ label: Skrypt+ trigger:+ name:+ label: Wyzwalacz+ automation:+ name:+ label: Nazwa+ trigger:+ label: Wyzwalacz+ script:+ label: Skrypt+ version:+ label: Wersja+ enabled:+ label: Włączony+ disabled:+ label: Wyłączony+ last_updated_at:+ label: Ostatnia aktualizacja+ last_updated_by:+ label: Zaktualizowany przezdiff --git a/plugins/automation/config/locales/client.pt.yml b/plugins/automation/config/locales/client.pt.ymlnew file mode 100644index 00000000000..298ba523c1d--- /dev/null+++ b/plugins/automation/config/locales/client.pt.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++pt:diff --git a/plugins/automation/config/locales/client.pt_BR.yml b/plugins/automation/config/locales/client.pt_BR.ymlnew file mode 100644index 00000000000..77c09571867--- /dev/null+++ b/plugins/automation/config/locales/client.pt_BR.yml@@ -0,0 +1,364 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++pt_BR:+ js:+ discourse_automation:+ title: Automação+ create: Criar+ update: Atualizar+ select_script: Selecione um script+ select_trigger: Selecione um acionador+ confirm_automation_reset: Esta ação redefinirá as opções de script e de acionamento, o novo estado será salvo, deseja continuar?+ confirm_automation_trigger: Esta ação acionará a automação, deseja continuar?+ no_automation_yet: Você ainda não criou nenhuma automação.+ edit_automation:+ trigger_section:+ forced: Este acionador é forçado por script.+ next_pending_automation: "A próxima automação será acionada em: %{date}"+ trigger_now: "Acionar agora"+ title: Quando/O quê...+ fields_section:+ title: Opções de script+ destroy_automation:+ confirm: "Tem certeza de que deseja excluir `%{name}`?"+ fields:+ key_value:+ label:+ one: Editar configuração (%{count})+ other: Editar configurações (%{count})+ user:+ label: Usuário+ pm:+ title:+ label: Título+ raw:+ label: Corpo+ pms:+ confirm_remove_pm: "Tem certeza de que deseja excluir esta PM?"+ placeholder_title: Título da PM+ add_pm: Adicionar PM+ no_pm_created: Você ainda não criou nenhuma MP. PMs serão enviadas assim que sua automação for acionada.+ title:+ label: Título+ raw:+ label: Corpo+ delay:+ label: Atraso (minutos)+ prefers_encrypt:+ label: Criptografa PM, se disponível+ group:+ label: Grupo+ text:+ label: Texto+ triggerables:+ not_found: Não foi possível encontrar o acionador `%{trigger}` para automação `%{automation}`, verifique se o plugin associado está instalado+ user_badge_granted:+ fields:+ badge:+ label: Emblema+ only_first_grant:+ label: Somente na primeira concessão+ stalled_topic:+ durations:+ PT1H: "Uma hora"+ P1D: "Um dia"+ P1W: "Uma semana"+ P2W: "Duas semanas"+ P1M: "Um mês"+ P3M: "Três meses"+ P6M: "Seis meses"+ P1Y: "Um ano"+ fields:+ categories:+ label: Limitado a categorias+ tags:+ label: Limitado a tags+ stalled_after:+ label: Parado depois+ recurring:+ every: Cada+ frequencies:+ minute: minuto+ hour: hora+ day: dia+ weekday: dia da semana+ week: semana+ month: mês+ year: ano+ fields:+ recurrence:+ label: Recorrência+ start_date:+ label: Data de início+ stalled_wiki:+ durations:+ PT1H: "Uma hora"+ P1D: "Um dia"+ P1W: "Uma semana"+ P2W: "Duas semanas"+ P1M: "Um mês"+ P3M: "Três meses"+ P6M: "Seis meses"+ P1Y: "Um ano"+ fields:+ restricted_category:+ label: Restrito(a) à categoria+ stalled_after:+ label: Atraso do acionador+ description: Define o atraso entre a última edição do wiki e o acionador da automação+ retriggered_after:+ label: Atraso do reacionador+ description: Define o atraso entre o primeiro acionador e o próximo acionador, se o wiki ainda não foi editado após o primeiro acionador+ user_added_to_group:+ fields:+ joined_group:+ label: Grupo rastreado+ user_removed_from_group:+ fields:+ left_group:+ label: Grupo rastreado+ user_promoted:+ fields:+ restricted_group:+ label: Restringir ao grupo+ trust_level_transition:+ label: Transição do nível de confiança+ trust_levels:+ ALL: "Todos os níveis de confiança"+ TL01: "TL0 a TL1"+ TL12: "TL1 a TL2"+ TL23: "TL2 a TL3"+ TL34: "TL3 a TL4"+ point_in_time:+ fields:+ execute_at:+ label: Executar em+ topic:+ fields:+ restricted_topic:+ label: ID do tópico+ post_created_edited:+ fields:+ action_type:+ label: Tipo de ação+ description: "Opcional, acionamento de limite apenas para eventos criados ou editados"+ valid_trust_levels:+ label: Níveis de confiança válidos+ description: Será acionado apenas se a postagem for criada pelo usuário nesses níveis de confiança, o padrão é qualquer nível de confiança+ restricted_category:+ label: Categoria+ description: Opcional, ativa apenas se o tópico da postagem estiver nesta categoria+ restricted_group:+ label: Grupo+ description: Opcional, será ativado apenas se o tópico da postagem for uma mensagem privada na caixa de mensagens deste grupo+ ignore_group_members:+ label: Ignorar membros de grupo+ description: Ignorar o gatilho se o remetente for um membro do Grupo especificado acima+ ignore_automated:+ label: Ignorar automatizado+ description: Ignore o gatilho se o remetente tiver um e-mail sem resposta ou for de uma fonte automatizada. Aplica-se apenas a postagens criadas por e-mail.+ first_post_only:+ label: Apenas primeira postagem+ description: Ativa apenas se a postagem for a primeira postagem criada pelo(a) usuário(a)+ first_topic_only:+ label: Apenas primeiro tópico+ description: Ativa apenas se o tópico for o primeiro tópico criado pelo(a) usuário(a)+ created: Criado(a)+ edited: Editado(a)+ category_created_edited:+ fields:+ restricted_category:+ label: Categoria pai+ description: Opcional, permite limitar a execução do acionador a esta categoria+ pm_created:+ fields:+ restricted_user:+ label: Usuários(as)+ description: Ativa apenas para MPs enviadas a este(a) usuário(a)+ restricted_group:+ label: Grupo+ description: Ativa apenas para MPs enviadas a este grupo+ ignore_staff:+ label: Ignorar equipe+ description: Ignore o acionador se o remetente for um usuário da equipe+ ignore_group_members:+ label: Ignorar membros de grupo+ description: Ignorar o gatilho se o remetente for um membro do Grupo especificado acima+ ignore_automated:+ label: Ignorar automatizado+ description: Ignore o gatilho se o remetente tiver um e-mail sem resposta ou for de uma fonte automatizada. Aplica-se apenas a MPs criadas por e-mail.+ valid_trust_levels:+ label: Níveis de confiança válidos+ description: Será acionado apenas se a postagem for criada pelo(a) usuário(a) nesses níveis de confiança, o padrão é qualquer nível de confiança+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Níveis de confiança válidos+ description: Será acionado apenas se a postagem for criada pelo usuário nesses níveis de confiança, o padrão é qualquer nível de confiança+ restricted_category:+ label: Categoria+ description: Opcional, ativa apenas se o tópico da postagem estiver nesta categoria+ restricted_tags:+ label: Tags+ description: Opcional, ativa apenas se a postagem tiver alguma destas etiquetas+ scriptables:+ not_found: Não foi possível encontrar o script `%{script}` para automação `%{automation}`, verifique se o plugin associado está instalado+ zapier_webhook:+ fields:+ webhook_url:+ label: URL do webhook+ description: "Espera uma URL de webhook válido do Zapier, por exemplo: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: Uma vez+ description: Responde apenas uma vez por tópico+ word_answer_list:+ label: Lista de pares palavra/resposta+ answering_user:+ label: Respondendo ao usuário+ description: Padrões para o usuário do Sistema+ auto_tag_topic:+ fields:+ tags:+ label: Tags+ description: Lista de tags para adicionar ao tópico.+ post:+ fields:+ creator:+ label: Criador+ topic:+ label: ID do tópico+ post:+ label: Publicar conteúdo+ group_category_notification_default:+ fields:+ group:+ label: Grupo+ notification_level:+ label: Nível de notificação+ update_existing_members:+ label: Atualizar membros existentes+ description: Atualiza o nível de notificação para membros de grupos existentes+ user_global_notice:+ fields:+ level:+ label: Nível+ notice:+ label: Aviso+ description: Aceita HTML, não preencha isso com entrada não confiável!+ levels:+ warning: Atenção+ info: Informações+ success: Sucesso+ error: Erro+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Nome do emblema+ group:+ label: Grupo+ description: Grupo de destino. Os(as) usuários(as) com o emblema especificado serão adicionados(as) a este grupo+ update_user_title_and_flair:+ label: Atualizar estilo e título do(a) usuário(a)+ description: Opcional, atualizar estilo e título do(a) usuário(a)+ remove_members_without_badge:+ label: Remover membros existentes sem emblema+ description: Opcional, remover membros do grupo existentes sem o emblema especificado+ badge:+ label: Emblema+ description: Selecionar emblema+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Suspender até (padrão)+ reason:+ label: Motivo (padrão)+ actor:+ label: Usuário+ description: "O usuário responsável pela suspensão (padrão: sistema)"+ pin_topic:+ fields:+ pinnable_topic:+ label: ID do tópico+ pinned_globally:+ label: Fixado globalmente+ pinned_until:+ label: Fixado até+ banner_topic:+ fields:+ topic_id:+ label: ID do tópico+ banner_until:+ label: Criar banner até+ user:+ label: Usuário+ description: "O usuário que cria o banner (padrão: sistema)"+ flag_post_on_words:+ fields:+ words:+ label: Palavras verificadas+ topic_required_words:+ fields:+ words:+ label: Lista de palavras obrigatórias+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Nome do grupo de participantes+ giftee_assignment_messages:+ label: Mensagens enviadas ao presenteador+ send_pms:+ add_a_pm_btn:+ label: Adicionar uma PM+ fields:+ receiver:+ label: Receptor da PM+ sendable_pms:+ label: PMs+ sender:+ label: Remetente de PMs+ close_topic:+ fields:+ topic:+ label: ID do tópico+ message:+ label: Mensagem de encerramento+ description: "Mensagem opcional para ser exibida no registro Tópico Fechado"+ user:+ label: Usuário+ description: "O usuário que fecha o tópico (padrão: sistema)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "Nome do campo personalizado do usuário"+ models:+ script:+ name:+ label: Script+ trigger:+ name:+ label: Acionador+ automation:+ name:+ label: Nome+ trigger:+ label: Acionador+ script:+ label: Script+ version:+ label: Versão+ enabled:+ label: Habilitado+ disabled:+ label: Desabilitado+ placeholders:+ label: Espaços reservados+ last_updated_at:+ label: Última atualização+ last_updated_by:+ label: Atualizado pordiff --git a/plugins/automation/config/locales/client.ro.yml b/plugins/automation/config/locales/client.ro.ymlnew file mode 100644index 00000000000..08a77f812ee--- /dev/null+++ b/plugins/automation/config/locales/client.ro.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ro:diff --git a/plugins/automation/config/locales/client.ru.yml b/plugins/automation/config/locales/client.ru.ymlnew file mode 100644index 00000000000..26f7d8b84c9--- /dev/null+++ b/plugins/automation/config/locales/client.ru.yml@@ -0,0 +1,366 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ru:+ js:+ discourse_automation:+ title: Автоматизация+ create: Создать+ update: Обновить+ select_script: Выберите скрипт+ select_trigger: Выберите триггер+ confirm_automation_reset: Параметры скрипта и триггера будут сброшены. Новое состояние будет сохранено. Продолжить?+ confirm_automation_trigger: Будет запущена автоматизация. Продолжить?+ no_automation_yet: Вы еще не создали автоматизаций.+ edit_automation:+ trigger_section:+ forced: Этот триггер вызван скриптом.+ next_pending_automation: "Следующая автоматизация сработает %{date}"+ trigger_now: "Запустить сейчас"+ title: Когда и что…+ fields_section:+ title: Параметры скрипта+ destroy_automation:+ confirm: "Действительно удалить `%{name}`?"+ fields:+ key_value:+ label:+ one: Изменить конфигурацию (%{count})+ few: Изменить конфигурацию (%{count})+ many: Изменить конфигурацию (%{count})+ other: Изменить конфигурацию (%{count})+ user:+ label: Пользователь+ pm:+ title:+ label: Название+ raw:+ label: Тело сообщения+ pms:+ confirm_remove_pm: "Действительно удалить это ЛС?"+ placeholder_title: Название ЛС+ add_pm: Добавить ЛС+ no_pm_created: Вы еще не создали личных сообщений. ЛС будут отправлены после запуска автоматизации.+ title:+ label: Название+ raw:+ label: Тело сообщения+ delay:+ label: Задержка (в минутах)+ prefers_encrypt:+ label: Шифрует ЛС, если это возможно+ group:+ label: Группа+ text:+ label: Текст+ triggerables:+ not_found: Не удалось найти триггер `%{trigger}` для автоматизации `%{automation}`. Проверьте, установлен ли соответствующий плагин.+ user_badge_granted:+ fields:+ badge:+ label: Награда+ only_first_grant:+ label: Только при первой выдаче+ stalled_topic:+ durations:+ PT1H: "Один час"+ P1D: "Один день"+ P1W: "Одна неделя"+ P2W: "Две недели"+ P1M: "Один месяц"+ P3M: "Три месяца"+ P6M: "Шесть месяцев"+ P1Y: "Один год"+ fields:+ categories:+ label: Ограничено по категориям+ tags:+ label: Ограничено по тегам+ stalled_after:+ label: Считать неактивной через+ recurring:+ every: Кажд.+ frequencies:+ minute: минуту+ hour: час+ day: день+ weekday: будний день+ week: неделю+ month: месяц+ year: год+ fields:+ recurrence:+ label: Повторение+ start_date:+ label: Дата начала+ stalled_wiki:+ durations:+ PT1H: "Один час"+ P1D: "Один день"+ P1W: "Одна неделя"+ P2W: "Две недели"+ P1M: "Один месяц"+ P3M: "Три месяца"+ P6M: "Шесть месяцев"+ P1Y: "Один год"+ fields:+ restricted_category:+ label: Ограничено по категории+ stalled_after:+ label: Задержка запуска+ description: Задержка между последним редактированием вики-записи и запуском автоматизации+ retriggered_after:+ label: Задержка повторного запуска+ description: Задержка между первым и следующим срабатыванием, если вики-запись не редактировалась после первого срабатывания+ user_added_to_group:+ fields:+ joined_group:+ label: Отслеживаемая группа+ user_removed_from_group:+ fields:+ left_group:+ label: Отслеживаемая группа+ user_promoted:+ fields:+ restricted_group:+ label: Ограничить по группе+ trust_level_transition:+ label: Смена уровня доверия+ trust_levels:+ ALL: "Все уровни доверия"+ TL01: "УД0 — УД1"+ TL12: "УД1 — УД2"+ TL23: "УД2 — УД3"+ TL34: "УД3 — УД4"+ point_in_time:+ fields:+ execute_at:+ label: Время выполнения+ topic:+ fields:+ restricted_topic:+ label: Идентификатор темы+ post_created_edited:+ fields:+ action_type:+ label: Тип действия+ description: "Необязательно; ограничить срабатывание только созданными или измененными событиями"+ valid_trust_levels:+ label: Допустимые уровни доверия+ description: Сработает, только если запись создана пользователем на указанных уровнях доверия. По умолчанию — любой уровень.+ restricted_category:+ label: Категория+ description: Необязательно, срабатывает только в случае, если тема публикации находится в этой категории+ restricted_group:+ label: Группа+ description: Необязательно, срабатывает только в случае, если тема публикации является личным сообщением в папке «Входящие» этой группы+ ignore_group_members:+ label: Игнорировать участников группы+ description: Пропустить триггер, если отправитель является участником указанной выше группы+ ignore_automated:+ label: Игнорировать автоматические+ description: Пропустить триггер, если отправитель использует адрес эл. почты без возможности ответа (noreply) или письмо получено из источника автоматической рассылки. Применяется только к публикациям, созданным по электронной почте+ first_post_only:+ label: Только первая публикация+ description: Срабатывает только в том случае, если это первая публикация пользователя+ first_topic_only:+ label: Только первая тема+ description: Срабатывает только в том случае, если это первая тема пользователя+ created: Создано+ edited: Изменено+ category_created_edited:+ fields:+ restricted_category:+ label: Родительская категория+ description: Необязательно; позволяет ограничить срабатывание триггера указанной категорией+ pm_created:+ fields:+ restricted_user:+ label: Пользователи+ description: Сработает только для личных сообщений, отправленных этому пользователю+ restricted_group:+ label: Группа+ description: Сработает только для личных сообщений, отправленных в эту группу+ ignore_staff:+ label: Игнорировать персонал+ description: Пропустить триггер, если отправитель является сотрудником+ ignore_group_members:+ label: Игнорировать участников группы+ description: Пропустить триггер, если отправитель является участником указанной выше группы+ ignore_automated:+ label: Игнорировать автоматические+ description: Пропустить триггер, если отправитель использует адрес эл. почты без возможности ответа (noreply) или письмо получено из источника автоматической рассылки. Применяется только к личным сообщениям, созданным по электронной почте+ valid_trust_levels:+ label: Допустимые уровни доверия+ description: Сработает, только если запись создана пользователем на указанных уровнях доверия. По умолчанию — любой уровень.+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Допустимые уровни доверия+ description: Сработает, только если запись создана пользователем на указанных уровнях доверия. По умолчанию — любой уровень.+ restricted_category:+ label: Категория+ description: Необязательно, срабатывает только в том случае, если тема публикации находится в этой категории+ restricted_tags:+ label: Теги+ description: Необязательно, срабатывает только в том случае, если публикация содержит любой из этих тегов+ scriptables:+ not_found: Не удалось найти скрипт `%{script}` для автоматизации `%{automation}`. Проверьте, установлен ли соответствующий плагин.+ zapier_webhook:+ fields:+ webhook_url:+ label: URL вебхука+ description: "Требуется действительный URL вебхука Zapier, например: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: Один раз+ description: Отвечает только один раз на тему+ word_answer_list:+ label: Список пар «слово — ответ»+ answering_user:+ label: Отвечающий пользователь+ description: Пользователь по умолчанию — система+ auto_tag_topic:+ fields:+ tags:+ label: Теги+ description: Список тегов для добавления в тему.+ post:+ fields:+ creator:+ label: Автор+ topic:+ label: Идентификатор темы+ post:+ label: Контент записи+ group_category_notification_default:+ fields:+ group:+ label: Группа+ notification_level:+ label: Уровень уведомлений+ update_existing_members:+ label: Обновить существующих участников+ description: Обновляет уровень уведомлений для существующих участников группы+ user_global_notice:+ fields:+ level:+ label: Уровень+ notice:+ label: Уведомление+ description: Принимает HTML — не вводите небезопасные данные!+ levels:+ warning: Предупреждение+ info: Информация+ success: Выполнено+ error: Ошибка+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Название награды+ group:+ label: Группа+ description: Целевая группа. Пользователи с указанной наградой будут добавлены в эту группу+ update_user_title_and_flair:+ label: Обновить название и значок пользователя+ description: Необязательно, обновить название и значок пользователя+ remove_members_without_badge:+ label: Удалить существующих участников без награды+ description: Необязательно, удалить существующих участников группы без указанной награды+ badge:+ label: Награда+ description: Выбрать награду+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Заморозить до (по умолчанию)+ reason:+ label: Причина (по умолчанию)+ actor:+ label: Пользователь+ description: "Пользователь, ответственный за заморозку (по умолчанию — система)"+ pin_topic:+ fields:+ pinnable_topic:+ label: Идентификатор темы+ pinned_globally:+ label: Закреплено глобально+ pinned_until:+ label: Закреплено до+ banner_topic:+ fields:+ topic_id:+ label: Идентификатор темы+ banner_until:+ label: Сделать баннером до+ user:+ label: Пользователь+ description: "Пользователь, создающий баннер (по умолчанию — система)"+ flag_post_on_words:+ fields:+ words:+ label: Проверенные слова+ topic_required_words:+ fields:+ words:+ label: Список обязательных слов+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Название группы участников+ giftee_assignment_messages:+ label: Сообщения, отправленные дарителю+ send_pms:+ add_a_pm_btn:+ label: Добавить ЛС+ fields:+ receiver:+ label: Получатель ЛС+ sendable_pms:+ label: ЛС+ sender:+ label: Отправитель ЛС+ close_topic:+ fields:+ topic:+ label: Идентификатор темы+ message:+ label: Сообщение о закрытии+ description: "Необязательное сообщение для показа при закрытии темы"+ user:+ label: Пользователь+ description: "Пользователь, закрывающий тему (по умолчанию — система)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "Название настраиваемого поля пользователя"+ models:+ script:+ name:+ label: Скрипт+ trigger:+ name:+ label: Триггер+ automation:+ name:+ label: Название+ trigger:+ label: Триггер+ script:+ label: Скрипт+ version:+ label: Версия+ enabled:+ label: Включено+ disabled:+ label: Отключено+ placeholders:+ label: Заполнители+ last_updated_at:+ label: Последнее обновление+ last_updated_by:+ label: Кем обновленоdiff --git a/plugins/automation/config/locales/client.sk.yml b/plugins/automation/config/locales/client.sk.ymlnew file mode 100644index 00000000000..6f815624081--- /dev/null+++ b/plugins/automation/config/locales/client.sk.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sk:diff --git a/plugins/automation/config/locales/client.sl.yml b/plugins/automation/config/locales/client.sl.ymlnew file mode 100644index 00000000000..23489a48b1f--- /dev/null+++ b/plugins/automation/config/locales/client.sl.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sl:diff --git a/plugins/automation/config/locales/client.sq.yml b/plugins/automation/config/locales/client.sq.ymlnew file mode 100644index 00000000000..7f051b7a7cf--- /dev/null+++ b/plugins/automation/config/locales/client.sq.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sq:diff --git a/plugins/automation/config/locales/client.sr.yml b/plugins/automation/config/locales/client.sr.ymlnew file mode 100644index 00000000000..88d63d6ae1a--- /dev/null+++ b/plugins/automation/config/locales/client.sr.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sr:diff --git a/plugins/automation/config/locales/client.sv.yml b/plugins/automation/config/locales/client.sv.ymlnew file mode 100644index 00000000000..4d43d383052--- /dev/null+++ b/plugins/automation/config/locales/client.sv.yml@@ -0,0 +1,303 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sv:+ js:+ discourse_automation:+ title: Automatisering+ create: Skapa+ update: Uppdatera+ select_script: Välj ett skript+ select_trigger: Välj en utlösare+ confirm_automation_reset: Den här åtgärden återställer skriptet och utlösningsalternativen, det nya tillståndet sparas, vill du fortsätta?+ confirm_automation_trigger: Denna åtgärd kommer att utlösa automatisering, vill du fortsätta?+ no_automation_yet: Du har inte skapat någon automatisering ännu.+ edit_automation:+ trigger_section:+ forced: Denna utlösare tvingas av skript.+ next_pending_automation: "Nästa automatisering kommer att utlösas vid: %{date}"+ trigger_now: "Utlös nu"+ title: När/Vad...+ fields_section:+ title: Skriptalternativ+ destroy_automation:+ confirm: "Är du säker på att du vill ta bort `%{name}`?"+ fields:+ user:+ label: Användare+ pm:+ title:+ label: Titel+ raw:+ label: Kropp+ pms:+ confirm_remove_pm: "Är du säker på att du vill ta bort detta PM?"+ placeholder_title: PM-titel+ add_pm: Lägg till PM+ no_pm_created: Du har inte skapat någon PM än. PM kommer att skickas när din automatisering utlöses.+ title:+ label: Titel+ raw:+ label: Kropp+ delay:+ label: Fördröjning (minuter)+ prefers_encrypt:+ label: Krypterar PM om tillgängligt+ group:+ label: Grupp+ text:+ label: Text+ triggerables:+ not_found: Kunde inte hitta utlösaren `%{trigger}` för automatisering `%{automation}`, se till att det tillhörande insticksprogrammet är installerat.+ user_badge_granted:+ fields:+ badge:+ label: Märke+ only_first_grant:+ label: Endast vid första beviljan+ stalled_topic:+ durations:+ PT1H: "En timme"+ P1D: "En dag"+ P1W: "En vecka"+ P2W: "Två veckor"+ P1M: "En månad"+ P3M: "Tre månader"+ P6M: "Sex månader"+ P1Y: "Ett år"+ fields:+ categories:+ label: Begränsat till kategorier+ tags:+ label: Begränsat till taggar+ stalled_after:+ label: Stannade efter+ recurring:+ every: Varje+ frequencies:+ minute: minut+ hour: timme+ day: dag+ weekday: veckodag+ week: vecka+ month: månad+ year: år+ fields:+ recurrence:+ label: Upprepning+ start_date:+ label: Startdatum+ stalled_wiki:+ durations:+ PT1H: "En timme"+ P1D: "En dag"+ P1W: "En vecka"+ P2W: "Två veckor"+ P1M: "En månad"+ P3M: "Tre månader"+ P6M: "Sex månader"+ P1Y: "Ett år"+ fields:+ stalled_after:+ label: Utlösningsfördröjning+ description: Definierar fördröjning mellan senaste wiki-redigering och automatisk utlösare+ retriggered_after:+ label: Återaktivera fördröjning+ description: Definierar fördröjning mellan första utlösaren och nästa utlösare, om wiki fortfarande inte har redigerats efter första utlösaren+ user_added_to_group:+ fields:+ joined_group:+ label: Spårad grupp+ user_removed_from_group:+ fields:+ left_group:+ label: Spårad grupp+ user_promoted:+ fields:+ restricted_group:+ label: Begränsa till grupp+ trust_level_transition:+ label: Byte av tillits nivå+ trust_levels:+ ALL: "Alla förtroendenivåer"+ TL01: "TL0 till TL1"+ TL12: "TL1 till TL2"+ TL23: "TL2 till TL3"+ TL34: "TL3 till TL4"+ point_in_time:+ fields:+ execute_at:+ label: Utför vid+ topic:+ fields:+ restricted_topic:+ label: Ämnes-ID+ post_created_edited:+ fields:+ valid_trust_levels:+ label: Giltiga förtroendenivåer+ description: Kommer att utlösa endast om inlägg skapas av användare i dessa förtroendenivåer, standard är alla förtroendenivåer+ restricted_category:+ label: Kategori+ restricted_group:+ label: Grupp+ category_created_edited:+ fields:+ restricted_category:+ description: Valfritt, tillåter att begränsa utlösarens körning till denna kategori+ pm_created:+ fields:+ restricted_group:+ label: Grupp+ ignore_staff:+ label: Ignorera personal+ description: Hoppa över utlösaren om avsändaren är en medarbetare+ valid_trust_levels:+ label: Giltiga förtroendenivåer+ description: Kommer att utlösas endast om inlägg skapas av användare inom dessa förtroendenivåer, standard är samtliga förtroendenivåer+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Giltiga förtroendenivåer+ description: Kommer att utlösa endast om inlägg skapas av användare i dessa förtroendenivåer, standard är alla förtroendenivåer+ restricted_category:+ label: Kategori+ restricted_tags:+ label: Taggar+ scriptables:+ not_found: Kunde inte hitta skript `%{script}` för automatisering `%{automation}`, se till att den tillhörande pluginen är installerad+ zapier_webhook:+ fields:+ webhook_url:+ label: Webhook-URL+ description: "Förväntar sig en giltig Zapier-webhook-URL, t.ex. https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ word_answer_list:+ label: Lista över ord/svarspar+ answering_user:+ label: Svarande användare+ description: Standard är systemanvändaren+ auto_tag_topic:+ fields:+ tags:+ label: Taggar+ post:+ fields:+ topic:+ label: Ämnes-ID+ group_category_notification_default:+ fields:+ group:+ label: Grupp+ user_global_notice:+ fields:+ level:+ label: Nivå+ notice:+ label: Notis+ description: Accepterar HTML, fyll inte detta med opålitlig inmatning!+ levels:+ warning: Varning+ info: Information+ success: Framgång+ error: Fel+ user_group_membership_through_badge:+ fields:+ group:+ label: Grupp+ badge:+ label: Märke+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Stäng av tills (standard)+ reason:+ label: Orsak (standard)+ actor:+ label: Användare+ description: "Användaren som är ansvarig för avstängningen (standard: system)"+ pin_topic:+ fields:+ pinnable_topic:+ label: Ämnes-ID+ pinned_globally:+ label: Fäst globalt+ pinned_until:+ label: Fäst tills+ banner_topic:+ fields:+ topic_id:+ label: Ämnes-ID+ banner_until:+ label: Skapa banner tills+ user:+ label: Användare+ description: "Användaren som skapar bannern (standard: system)"+ flag_post_on_words:+ fields:+ words:+ label: Kontrollerade ord+ topic_required_words:+ fields:+ words:+ label: Lista över obligatoriska ord+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Deltagarnas gruppnamn+ giftee_assignment_messages:+ label: Meddelanden skickade till givare+ send_pms:+ add_a_pm_btn:+ label: Lägg till PM+ fields:+ receiver:+ label: PM-mottagare+ sendable_pms:+ label: PM+ sender:+ label: Avsändare för PM+ close_topic:+ fields:+ topic:+ label: Ämnes-ID+ message:+ label: Avslutningsmeddelande+ description: "Valfritt meddelande att visa på tråden stängd post"+ user:+ label: Användare+ description: "Användaren som stänger ämnet (standard: system)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "Användaranpassat fältnamn"+ models:+ script:+ name:+ label: Skript+ trigger:+ name:+ label: Utlösare+ automation:+ name:+ label: Namn+ trigger:+ label: Utlösare+ script:+ label: Skript+ version:+ label: Version+ enabled:+ label: Aktiverad+ disabled:+ label: Inaktiverad+ placeholders:+ label: Platshållare+ last_updated_at:+ label: Senaste uppdatering+ last_updated_by:+ label: Uppdaterad avdiff --git a/plugins/automation/config/locales/client.sw.yml b/plugins/automation/config/locales/client.sw.ymlnew file mode 100644index 00000000000..0d7cdd075bf--- /dev/null+++ b/plugins/automation/config/locales/client.sw.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sw:diff --git a/plugins/automation/config/locales/client.te.yml b/plugins/automation/config/locales/client.te.ymlnew file mode 100644index 00000000000..03967bdbb07--- /dev/null+++ b/plugins/automation/config/locales/client.te.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++te:diff --git a/plugins/automation/config/locales/client.th.yml b/plugins/automation/config/locales/client.th.ymlnew file mode 100644index 00000000000..7de85ff91c4--- /dev/null+++ b/plugins/automation/config/locales/client.th.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++th:diff --git a/plugins/automation/config/locales/client.tr_TR.yml b/plugins/automation/config/locales/client.tr_TR.ymlnew file mode 100644index 00000000000..91dce8820f5--- /dev/null+++ b/plugins/automation/config/locales/client.tr_TR.yml@@ -0,0 +1,364 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++tr_TR:+ js:+ discourse_automation:+ title: Otomasyon+ create: Oluştur+ update: Güncelle+ select_script: Komut dosyası seçin+ select_trigger: Tetikleyici seçin+ confirm_automation_reset: Bu eylem komut dosyası ve tetikleyici seçeneklerini sıfırlar, yeni durum kaydedilir, devam etmek istiyor musunuz?+ confirm_automation_trigger: Bu eylem otomasyonu tetikler, devam etmek istiyor musunuz?+ no_automation_yet: Henüz otomasyon oluşturmadınız.+ edit_automation:+ trigger_section:+ forced: Bu tetikleyici komut dosyası ile zorlanır.+ next_pending_automation: "Bir sonraki otomasyon şu saatte tetiklenecek: %{date}"+ trigger_now: "Şimdi tetikle"+ title: Ne zaman/Ne...+ fields_section:+ title: Komut dosyası seçenekleri+ destroy_automation:+ confirm: "Şunu silmek istediğinizden emin misiniz: \"%{name}\"?"+ fields:+ key_value:+ label:+ one: Yapılandırmayı Düzenle (%{count})+ other: Yapılandırmayı Düzenle (%{count})+ user:+ label: Kullanıcı+ pm:+ title:+ label: Başlık+ raw:+ label: Gövde+ pms:+ confirm_remove_pm: "Bu özel mesajı kaldırmak istediğinizden emin misiniz?"+ placeholder_title: Özel mesaj başlığı+ add_pm: Özel mesaj ekle+ no_pm_created: Henüz özel mesaj oluşturmadınız. Otomasyonunuz tetiklendiğinde özel mesajlar gönderilecek.+ title:+ label: Başlık+ raw:+ label: Gövde+ delay:+ label: Gecikme (dakika)+ prefers_encrypt:+ label: Mümkünse özel mesajı şifreler+ group:+ label: Grup+ text:+ label: Metin+ triggerables:+ not_found: '"%{automation}" otomasyonu için "%{trigger}" tetikleyicisi bulunamadı, ilişkili eklentinin yüklü olduğundan emin olun'+ user_badge_granted:+ fields:+ badge:+ label: Rozet+ only_first_grant:+ label: Sadece ilk izinde+ stalled_topic:+ durations:+ PT1H: "Bir saat"+ P1D: "Bir gün"+ P1W: "Bir hafta"+ P2W: "İki hafta"+ P1M: "Bir ay"+ P3M: "Üç ay"+ P6M: "Altı ay"+ P1Y: "Bir yıl"+ fields:+ categories:+ label: Kategorilerle sınırlı+ tags:+ label: Etiketlerle sınırlı+ stalled_after:+ label: 'Şundan sonra durdu:'+ recurring:+ every: Her+ frequencies:+ minute: dakika+ hour: saat+ day: gün+ weekday: hafta içi günü+ week: hafta+ month: ay+ year: yıl+ fields:+ recurrence:+ label: Tekrarlama+ start_date:+ label: Başlangıç tarihi+ stalled_wiki:+ durations:+ PT1H: "Bir saat"+ P1D: "Bir gün"+ P1W: "Bir hafta"+ P2W: "İki hafta"+ P1M: "Bir ay"+ P3M: "Üç ay"+ P6M: "Altı ay"+ P1Y: "Bir yıl"+ fields:+ restricted_category:+ label: Kategori ile sınırlı+ stalled_after:+ label: Tetikleyici gecikmesi+ description: Son viki düzenlemesi ile otomasyonun tetiklenmesi arasındaki gecikmeyi tanımlar+ retriggered_after:+ label: Yeniden tetikleyici gecikmesi+ description: İlk tetiklemeden sonra viki hala düzenlenmemişse ilk tetikleyici ile sonraki tetikleyici arasındaki gecikmeyi tanımlar+ user_added_to_group:+ fields:+ joined_group:+ label: İzlenen grup+ user_removed_from_group:+ fields:+ left_group:+ label: İzlenen grup+ user_promoted:+ fields:+ restricted_group:+ label: Grupla sınırla+ trust_level_transition:+ label: Güven seviyesi geçişi+ trust_levels:+ ALL: "Tüm güven seviyeleri"+ TL01: "GS0 - GS1"+ TL12: "GS1 - GS2"+ TL23: "GS2 - GS3"+ TL34: "GS3 - GS4"+ point_in_time:+ fields:+ execute_at:+ label: 'Şurada yürüt:'+ topic:+ fields:+ restricted_topic:+ label: Konu Kimliği+ post_created_edited:+ fields:+ action_type:+ label: Eylem türü+ description: "İsteğe bağlı, tetiklemeyi yalnızca oluşturulan veya düzenlenen etkinliklerle sınırlandırın"+ valid_trust_levels:+ label: Geçerli güven seviyeleri+ description: Yalnızca gönderi bu güven seviyelerindeki bir kullanıcı tarafından oluşturulduğunda tetiklenir, varsayılan olarak herhangi bir güven seviyesidir+ restricted_category:+ label: Kategori+ description: İsteğe bağlı, yalnızca gönderinin konusu bu kategorideyse tetiklenir+ restricted_group:+ label: Grup+ description: İsteğe bağlı, yalnızca gönderinin konusu bu grubun gelen kutusundaki bir özel mesajsa tetiklenir+ ignore_group_members:+ label: Grup üyelerini yok say+ description: Gönderen yukarıda belirtilen Grubun bir üyesiyse tetikleyiciyi atla+ ignore_automated:+ label: Otomatikleştirmeyi yok say+ description: Gönderenin noreply e-postası varsa veya otomatik bir kaynaktan geliyorsa tetikleyiciyi atla. Yalnızca e-posta yoluyla oluşturulan gönderiler için geçerlidir+ first_post_only:+ label: Sadece ilk gönderi+ description: Yalnızca gönderi bir kullanıcının oluşturduğu ilk gönderiyse tetiklenir+ first_topic_only:+ label: Yalnızca ilk konu+ description: Yalnızca konu bir kullanıcının oluşturduğu ilk konuysa tetiklenir+ created: Oluşturuldu+ edited: Düzenlendi+ category_created_edited:+ fields:+ restricted_category:+ label: Ana Kategori+ description: İsteğe bağlı, tetikleyici yürütmeyi bu kategoriyle sınırlandırmaya izin verir+ pm_created:+ fields:+ restricted_user:+ label: Kullanıcılar+ description: Yalnızca bu kullanıcıya gönderilen kişisel mesajlar için tetiklenir+ restricted_group:+ label: Grup+ description: Yalnızca bu gruba gönderilen kişisel mesajlar için tetiklenir+ ignore_staff:+ label: Personeli yok say+ description: Gönderen bir personel kullanıcısıysa tetikleyiciyi atla+ ignore_group_members:+ label: Grup üyelerini yok say+ description: Gönderen yukarıda belirtilen Grubun bir üyesiyse tetikleyiciyi atla+ ignore_automated:+ label: Otomatikleştirmeyi yok say+ description: Gönderenin noreply e-postası varsa veya otomatik bir kaynaktan geliyorsa tetikleyiciyi atla. Yalnızca e-posta yoluyla oluşturulan kişisel mesajlar için geçerlidir+ valid_trust_levels:+ label: Geçerli güven seviyeleri+ description: Yalnızca gönderi bu güven seviyelerindeki bir kullanıcı tarafından oluşturulduğunda tetiklenir, varsayılan olarak herhangi bir güven seviyesidir+ after_post_cook:+ fields:+ valid_trust_levels:+ label: Geçerli güven seviyeleri+ description: Yalnızca gönderi bu güven seviyelerindeki bir kullanıcı tarafından oluşturulduğunda tetiklenir, varsayılan olarak herhangi bir güven seviyesidir+ restricted_category:+ label: Kategori+ description: İsteğe bağlı, yalnızca gönderinin konusu bu kategorideyse tetiklenir+ restricted_tags:+ label: Etiketler+ description: 'İsteğe bağlı, yalnızca gönderide şu etiketlerden herhangi biri varsa tetiklenir:'+ scriptables:+ not_found: '"%{automation}" otomasyonu için "%{script}" komut dosyası bulunamadı, ilişkili eklentinin yüklü olduğundan emin olun'+ zapier_webhook:+ fields:+ webhook_url:+ label: Web kancası URL'si+ description: "Geçerli bir Zapier web kancası URL'si bekler, ör.: https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: Bir kez+ description: Konuya göre yalnızca bir kez yanıt verir+ word_answer_list:+ label: Kelime/yanıt çiftlerinin listesi+ answering_user:+ label: Yanıtlayan kullanıcı+ description: Varsayılan olarak Sistem kullanıcısını ayarlar+ auto_tag_topic:+ fields:+ tags:+ label: Etiketler+ description: Konuya eklenecek etiketlerin listesi.+ post:+ fields:+ creator:+ label: Oluşturucu+ topic:+ label: Konu Kimliği+ post:+ label: Gönderi içeriği+ group_category_notification_default:+ fields:+ group:+ label: Grup+ notification_level:+ label: Bildirim seviyesi+ update_existing_members:+ label: Mevcut üyeleri güncelleyin+ description: Mevcut grup üyeleri için bildirim seviyesini günceller+ user_global_notice:+ fields:+ level:+ label: Seviye+ notice:+ label: Bildiri+ description: HTML kabul eder, bunu güvenilmeyen girdi ile doldurmayın!+ levels:+ warning: Uyarı+ info: Bilgi+ success: Başarılı+ error: Hata+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: Rozet Adı+ group:+ label: Grup+ description: Hedef grup. Belirtilen rozete sahip kullanıcılar bu gruba eklenir+ update_user_title_and_flair:+ label: Kullanıcı unvanını ve yeteneğini güncelle+ description: İsteğe bağlı, Kullanıcı unvanını ve yeteneğini güncelle+ remove_members_without_badge:+ label: Rozeti olmayan mevcut üyeleri kaldır+ description: İsteğe bağlı, Belirtilen rozete sahip olmayan mevcut grup üyelerini kaldır+ badge:+ label: Rozet+ description: Rozet seç+ suspend_user_by_email:+ fields:+ suspend_until:+ label: Şu tarihe kadar askıya al (varsayılan)+ reason:+ label: Sebep (varsayılan)+ actor:+ label: Kullanıcı+ description: "Askıya alma işleminden sorumlu kullanıcı (varsayılan: sistem)"+ pin_topic:+ fields:+ pinnable_topic:+ label: Konu Kimliği+ pinned_globally:+ label: Küresel olarak sabitlendi+ pinned_until:+ label: 'Şu tarihe kadar sabitlendi:'+ banner_topic:+ fields:+ topic_id:+ label: Konu Kimliği+ banner_until:+ label: 'Şu tarihe kadar banner yap:'+ user:+ label: Kullanıcı+ description: "Banner'ı oluşturan kullanıcı (varsayılan: sistem)"+ flag_post_on_words:+ fields:+ words:+ label: Kontrol edilen kelimeler+ topic_required_words:+ fields:+ words:+ label: Gerekli kelimeler listesi+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: Katılımcıların grup adı+ giftee_assignment_messages:+ label: Hediye eden kişiye gönderilen mesajlar+ send_pms:+ add_a_pm_btn:+ label: Özel mesaj ekle+ fields:+ receiver:+ label: Özel mesaj alıcısı+ sendable_pms:+ label: Özel mesajlar+ sender:+ label: Özel mesajı gönderen+ close_topic:+ fields:+ topic:+ label: Konu Kimliği+ message:+ label: Kapanış mesajı+ description: "Konu Kapatıldı kaydında gösterilecek isteğe bağlı mesaj"+ user:+ label: Kullanıcı+ description: "Konuyu kapatan kullanıcı (varsayılan: sistem)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "Kullanıcı Özel Alan adı"+ models:+ script:+ name:+ label: Komut dosyası+ trigger:+ name:+ label: Tetikleyici+ automation:+ name:+ label: İsim+ trigger:+ label: Tetikleyici+ script:+ label: Komut dosyası+ version:+ label: Sürüm+ enabled:+ label: Etkin+ disabled:+ label: Devre Dışı+ placeholders:+ label: Yer Tutucular+ last_updated_at:+ label: Son güncelleme+ last_updated_by:+ label: Güncelleyendiff --git a/plugins/automation/config/locales/client.uk.yml b/plugins/automation/config/locales/client.uk.ymlnew file mode 100644index 00000000000..f1390545d1d--- /dev/null+++ b/plugins/automation/config/locales/client.uk.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++uk:diff --git a/plugins/automation/config/locales/client.ur.yml b/plugins/automation/config/locales/client.ur.ymlnew file mode 100644index 00000000000..b4a9c21ee2f--- /dev/null+++ b/plugins/automation/config/locales/client.ur.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ur:diff --git a/plugins/automation/config/locales/client.vi.yml b/plugins/automation/config/locales/client.vi.ymlnew file mode 100644index 00000000000..f629dcf5329--- /dev/null+++ b/plugins/automation/config/locales/client.vi.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++vi:diff --git a/plugins/automation/config/locales/client.zh_CN.yml b/plugins/automation/config/locales/client.zh_CN.ymlnew file mode 100644index 00000000000..2c4a320bc61--- /dev/null+++ b/plugins/automation/config/locales/client.zh_CN.yml@@ -0,0 +1,363 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++zh_CN:+ js:+ discourse_automation:+ title: 自动化+ create: 创建+ update: 更新+ select_script: 选择脚本+ select_trigger: 选择触发器+ confirm_automation_reset: 此操作将重置脚本和触发器选项,新状态将被保存,要继续吗?+ confirm_automation_trigger: 此操作将触发自动化,要继续吗?+ no_automation_yet: 您尚未创建任何自动化。+ edit_automation:+ trigger_section:+ forced: 此触发器由脚本强制执行。+ next_pending_automation: "下一次自动化将在 %{date} 触发"+ trigger_now: "立即触发"+ title: 何时/什么…+ fields_section:+ title: 脚本选项+ destroy_automation:+ confirm: "确定要删除 `%{name}` 吗?"+ fields:+ key_value:+ label:+ other: 编辑配置 (%{count})+ user:+ label: 用户+ pm:+ title:+ label: 标题+ raw:+ label: 正文+ pms:+ confirm_remove_pm: "确定要移除此 PM 吗?"+ placeholder_title: PM 标题+ add_pm: 添加 PM+ no_pm_created: 您尚未创建任何 PM。触发自动化后,即会发送 PM。+ title:+ label: 标题+ raw:+ label: 正文+ delay:+ label: 延迟(分钟)+ prefers_encrypt:+ label: 加密 PM(如果可用)+ group:+ label: 群组+ text:+ label: 文本+ triggerables:+ not_found: 找不到用于自动化 `%{automation}` 的触发器 `%{trigger}`,请确保相关插件已安装+ user_badge_granted:+ fields:+ badge:+ label: 徽章+ only_first_grant:+ label: 仅在第一次授予时+ stalled_topic:+ durations:+ PT1H: "一小时"+ P1D: "一天"+ P1W: "一周"+ P2W: "两周"+ P1M: "一个月"+ P3M: "三个月"+ P6M: "六个月"+ P1Y: "一年"+ fields:+ categories:+ label: 限制为类别+ tags:+ label: 限制为标签+ stalled_after:+ label: 此时长后停止+ recurring:+ every: 每+ frequencies:+ minute: 分钟+ hour: 小时+ day: 天+ weekday: 工作日+ week: 周+ month: 月+ year: 年+ fields:+ recurrence:+ label: 重复+ start_date:+ label: 开始日期+ stalled_wiki:+ durations:+ PT1H: "一小时"+ P1D: "一天"+ P1W: "一周"+ P2W: "两周"+ P1M: "一个月"+ P3M: "三个月"+ P6M: "六个月"+ P1Y: "一年"+ fields:+ restricted_category:+ label: 限制为类别+ stalled_after:+ label: 触发延迟+ description: 定义上次 Wiki 编辑和自动化触发器之间的延迟+ retriggered_after:+ label: 重新触发延迟+ description: 定义第一个触发器和下一个触发器之间的延迟(如果在第一个触发器后 Wiki 仍未被编辑)+ user_added_to_group:+ fields:+ joined_group:+ label: 跟踪的群组+ user_removed_from_group:+ fields:+ left_group:+ label: 跟踪的群组+ user_promoted:+ fields:+ restricted_group:+ label: 限制为群组+ trust_level_transition:+ label: 信任级别转换+ trust_levels:+ ALL: "所有信任级别"+ TL01: "TL0 到 TL1"+ TL12: "TL1 到 TL2"+ TL23: "TL2 到 TL3"+ TL34: "TL3 到 TL4"+ point_in_time:+ fields:+ execute_at:+ label: 执行时间+ topic:+ fields:+ restricted_topic:+ label: 话题 ID+ post_created_edited:+ fields:+ action_type:+ label: 操作类型+ description: "可选,仅限创建或编辑事件触发"+ valid_trust_levels:+ label: 有效信任级别+ description: 仅当这些信任级别的用户创建帖子时才会触发,默认为任意信任级别+ restricted_category:+ label: 类别+ description: 可选,仅当帖子所属话题属于此类别时才会触发+ restricted_group:+ label: 群组+ description: 可选,仅当帖子所属话题是此群组收件箱中的私信时才会触发+ ignore_group_members:+ label: 忽略群组成员+ description: 如果发出者是上面指定的群组的成员,则跳过触发器+ ignore_automated:+ label: 忽略机器人发出的帖子+ description: 如果发出者的电子邮件地址包含 noreply 或来自机器人来源,则跳过触发器。仅适用于通过电子邮件创建的帖子+ first_post_only:+ label: 仅第一个帖子+ description: 仅当该帖子是用户创建的第一个帖子时才会触发+ first_topic_only:+ label: 仅第一个话题+ description: 仅当该话题是用户创建的第一个话题时才会触发+ created: 创建+ edited: 编辑+ category_created_edited:+ fields:+ restricted_category:+ label: 父类别+ description: 可选,允许将触发器执行限制为此类别+ pm_created:+ fields:+ restricted_user:+ label: 用户+ description: 仅对发送给此用户的私信触发+ restricted_group:+ label: 群组+ description: 仅对发送给此群组的私信触发+ ignore_staff:+ label: 忽略管理人员+ description: 如果发出者是管理人员用户,则跳过触发器+ ignore_group_members:+ label: 忽略群组成员+ description: 如果发出者是上面指定的群组的成员,则跳过触发器+ ignore_automated:+ label: 忽略机器人发出的帖子+ description: 如果发出者的电子邮件地址包含 noreply 或来自机器人来源,则跳过触发器。仅适用于通过电子邮件创建的私信+ valid_trust_levels:+ label: 有效信任级别+ description: 仅当这些信任级别的用户创建帖子时才会触发,默认为任意信任级别+ after_post_cook:+ fields:+ valid_trust_levels:+ label: 有效信任级别+ description: 仅当这些信任级别的用户创建帖子时才会触发,默认为任意信任级别+ restricted_category:+ label: 类别+ description: 可选,仅当帖子所属话题属于此类别时才会触发+ restricted_tags:+ label: 标签+ description: 可选,仅当帖子具有以下任意标签时才会触发+ scriptables:+ not_found: 找不到用于自动化 `%{automation}` 的脚本 `%{script}`,请确保相关插件已安装+ zapier_webhook:+ fields:+ webhook_url:+ label: 网络钩子 URL+ description: "需要一个有效的 Zapier 网络钩子 URL,例如:https://hooks.zapier.com/hooks/catch/xxx/yyy/"+ auto_responder:+ fields:+ once:+ label: 一次+ description: 仅按话题回复一次+ word_answer_list:+ label: 字词/答案对列表+ answering_user:+ label: 回答用户+ description: 默认为系统用户+ auto_tag_topic:+ fields:+ tags:+ label: 标签+ description: 要添加到话题的标签列表。+ post:+ fields:+ creator:+ label: 创建者+ topic:+ label: 话题 ID+ post:+ label: 帖子内容+ group_category_notification_default:+ fields:+ group:+ label: 群组+ notification_level:+ label: 通知级别+ update_existing_members:+ label: 更新现有成员+ description: 更新现有群组成员的通知级别+ user_global_notice:+ fields:+ level:+ label: 级别+ notice:+ label: 通知+ description: 接受 HTML,不要使用不可信的输入进行填充!+ levels:+ warning: 警告+ info: 信息+ success: 成功+ error: 错误+ user_group_membership_through_badge:+ fields:+ badge_name:+ label: 徽章名称+ group:+ label: 群组+ description: 目标群组。具有指定徽章的用户将被添加到此群组+ update_user_title_and_flair:+ label: 更新用户头衔和资质+ description: 可选,更新用户头衔和资质+ remove_members_without_badge:+ label: 移除没有徽章的现有成员+ description: 可选,移除群组中没有指定徽章的现有成员+ badge:+ label: 徽章+ description: 选择徽章+ suspend_user_by_email:+ fields:+ suspend_until:+ label: 暂停至(默认)+ reason:+ label: 原因(默认)+ actor:+ label: 用户+ description: "负责暂停的用户(默认设置:系统)"+ pin_topic:+ fields:+ pinnable_topic:+ label: 话题 ID+ pinned_globally:+ label: 全局置顶+ pinned_until:+ label: 置顶至+ banner_topic:+ fields:+ topic_id:+ label: 话题 ID+ banner_until:+ label: 设置为横幅至+ user:+ label: 用户+ description: "创建横幅的用户(默认设置:系统)"+ flag_post_on_words:+ fields:+ words:+ label: 选中的字词+ topic_required_words:+ fields:+ words:+ label: 必选字词列表+ gift_exchange:+ fields:+ gift_exchangers_group:+ label: 参加者的群组名称+ giftee_assignment_messages:+ label: 发送给赠送者的消息+ send_pms:+ add_a_pm_btn:+ label: 添加 PM+ fields:+ receiver:+ label: PM 接收者+ sendable_pms:+ label: PM+ sender:+ label: PM 发送者+ close_topic:+ fields:+ topic:+ label: 话题 ID+ message:+ label: 关闭消息+ description: "要在“话题已关闭”记录上显示的可选消息"+ user:+ label: 用户+ description: "关闭话题的用户(默认设置:系统)"+ add_user_to_group_through_custom_field:+ fields:+ custom_field_name:+ label: "用户自定义字段名称"+ models:+ script:+ name:+ label: 脚本+ trigger:+ name:+ label: 触发器+ automation:+ name:+ label: 名称+ trigger:+ label: 触发器+ script:+ label: 脚本+ version:+ label: 版本+ enabled:+ label: 已启用+ disabled:+ label: 已禁用+ placeholders:+ label: 占位符+ last_updated_at:+ label: 最后更新+ last_updated_by:+ label: 更新者diff --git a/plugins/automation/config/locales/client.zh_TW.yml b/plugins/automation/config/locales/client.zh_TW.ymlnew file mode 100644index 00000000000..7e15fab0018--- /dev/null+++ b/plugins/automation/config/locales/client.zh_TW.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++zh_TW:diff --git a/plugins/automation/config/locales/server.ar.yml b/plugins/automation/config/locales/server.ar.ymlnew file mode 100644index 00000000000..1594548d9a0--- /dev/null+++ b/plugins/automation/config/locales/server.ar.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ar:+ site_settings:+ discourse_automation_enabled: "تفعيل المكوِّن الإضافي discourse-automation"+ discourse_automation:+ models:+ fields:+ required_field: يجب ملء الحقل `%{name}` في `%{target}:%{target_name}`.+ invalid_field: مكوِّن الحقل `%{component}` غير قابل للاستخدام في `%{target}:%{target_name}.`+ invalid_metadata: بيانات الحقل `%{field}` غير صالحة أو المكوِّن `%{component}` غير معروف.+ triggerables:+ user_badge_granted:+ title: تم منح شارة المستخدم+ doc: يشغِّل الأتمتة عند منح المستخدم شارة.+ user_first_logged_in:+ title: تسجيل المستخدم الدخول لأول مرة+ doc: يشغِّل الأتمتة عندما يسجِّل أحد المستخدمين الدخول لأول مرة.+ stalled_topic:+ title: موضوع متوقف+ doc: يشغِّل الأتمتة عندما لا يتلقى الموضوع ردًا جديدًا من مالك الموضوع لفترة زمنية محدَّدة. يوصى بتوسيع نطاق هذا المشغِّل إلى وسم/فئة لأن عدد الموضوعات المتأثرة يمكن أن يكون مرتفعًا جدًا. كإجراء أمني، تم تحديد عدد الموضوعات المتأثرة بـ 250 موضوعًا.+ api_call:+ title: استدعاء API+ description: إنشاء طلب منشور لتشغيل الأتمتة+ doc: ينبغي إجراء طلب المنشور إلى `/automations/:id/trigger.json` باستخدام مفتاح API عام.+ category_created_edited:+ title: تم إنشاء/تحرير الفئة+ description: يتم تشغيل الأتمتة عند إنشاء أو تعديل منشور+ recurring:+ title: متكرر+ point_in_time:+ title: النقطة الزمنية+ description: عند الوصول إلى التاريخ، سيتم تشغيل الأتمتة.+ user_added_to_group:+ title: تمت إضافة المستخدم إلى المجموعة+ description: عند إضافة مستخدم إلى المجموعة المحدَّدة، سيتم تشغيل الأتمتة.+ user_removed_from_group:+ title: تمت إزالة المستخدم من المجموعة+ description: عند إزالة مستخدم من المجموعة المحدَّدة، سيتم تشغيل الأتمتة.+ user_promoted:+ title: تمت ترقية المستخدم+ description: عند ترقية مستخدم من مستوى ثقة إلى آخر+ transition_placeholder: "من %{from_level_name} إلى %{to_level_name}"+ stalled_wiki:+ title: Wiki متوقفة+ description: عندما تظل Wiki دون تعديل لفترة أطول من المحدَّدة، سيتم تشغيل الأتمتة+ post_created_edited:+ title: تم إنشاء/تعديل المنشور+ description: عند تعديل أو إنشاء منشور صالح، سيتم تشغيل الأتمتة+ pm_created:+ title: تم إنشاء رسالة شخصية+ description: عند إنشاء رسالة شخصية صالحة، سيتم تشغيل الأتمتة+ topic:+ title: الموضوع+ description: سيتم استخدام البرنامج النصي المرتبط مع الموضوع المحدَّد فقط، وهذا مفيد للبرامج النصية التي تجري التحقق على سبيل المثال+ after_post_cook:+ title: بعد معالجة المنشور+ description: عند معالجة محتوى المنشور، سيتم تشغيل الأتمتة+ scriptables:+ post:+ title: إنشاء منشور+ description: إنشاء منشور في الموضوع المحدَّد+ flag_post_on_words:+ title: الإبلاغ عن منشور حسب كلمات معيَّنة+ description: يُبلغ عن المنشور إذا احتوى على كلمات معيَّنة+ flag_message: "يحتوي المنشور على كلمات غير مسموح بها: %{words}"+ doc: سيتم الإبلاغ عن المنشورات التي تحتوي على كل الكلمات المحدَّدة وإخفاؤها. يُرجى ملاحظة أنه عند تحديد عدة كلمات مفصولة بفاصلة، سيتم استخدامها كمركَّب (يجب أن تكون كل الكلمات موجودة).+ zapier_webhook:+ title: خطاف ويب Zapier+ description: يستدعي Zap في سياق استخدام المشغِّل كنص+ auto_responder:+ title: المستجيب التلقائي+ description: ينشر ردًا على منشور يتضمَّن كلمات رئيسية محدَّدة+ auto_tag_topic:+ title: التوسيم التلقائي للموضوع+ description: يضيف الوسوم تلقائيًا إلى الموضوع+ pin_topic:+ title: تثبيت الموضوع+ description: يثبِّت موضوعًا محدَّدًا في تاريخ معيَّن+ banner_topic:+ title: إنشاء موضوع من بانر+ description: تحويل الموضوع إلى بانر+ gift_exchange:+ title: تبادل الهدايا+ description: يسمح بإقران مستخدمي المجموعة بشكلٍ مجهول لإرسال هدية لبعضهم البعض.+ doc: يتطلب تبادل الهدايا وجود مجموعة حالية تضم 3 مستخدمين على الأقل. سيتم إقران كل مستخدم في المجموعة بمُرسل هدايا واحد ومستقبل هدايا واحد في التاريخ المختار.+ send_pms:+ title: إرسال رسائل شخصية+ description: يسمح بإرسال الرسائل الشخصية (ربما يتأخر).+ doc: يسمح بإرسال عدة رسائل شخصية إلى المستخدم. وتقبل كل رسالة شخصية التأخير.+ suspend_user_by_email:+ title: تعليق المستخدم باستخدام البريد الإلكتروني+ user_global_notice:+ title: الإشعار العام للمستخدم+ description: يسمح بعرض إشعار عام للمستخدم+ user_group_membership_through_badge:+ title: عضوية مجموعة المستخدمين من خلال الشارة+ description: تعديل عضوية مجموعة المستخدمين حسب الشارة+ suspend_user_by_email_with_api_call:+ doc: عند تشغيل `suspend_user_by_email` باستخدام استدعاء API، تتوقع نقطة النهاية وجود `email` صالح في المعلمات المُرسلة. يمكن أيضًا استخدام `reasons` و`suspend_until (ISO 8601 format)` لتجاوز قيم الحقول الافتراضية.+ user_global_notice_with_stalled_topic:+ doc: عند التشغيل عبر موضوع المتوقف، سيتلقى مالك الموضوع الإشعار العام.+ user_global_notice_with_first_accepted_solution:+ doc: يتلقى مؤلف الحل الإشعار العام عند تشغيل الأتمتة من خلال أول حل تم قبوله.+ send_pms_with_api_call:+ doc: عند استخدام البرنامج النصي `send pms` مع المشغِّل `api call`، سيتم استخدام معلمة `usernames` لطلبك لملء قائمة المستلمين.+ topic_required_words:+ title: الكلمات المطلوبة للموضوع+ description: يسمح بتحديد قائمة الكلمات المطلوبة لموضوعٍ ما، ويجب استخدام واحدة على الأقل في كل منشور.+ doc: تتطلب الكلمات المطلوبة للموضوع موضوعًا. عند تعديل المنشور أو إنشائه، سيتم التحقق من المنشور مقابل قائمة الكلمات، ولا بد من وجود واحدة على الأقل.+ errors:+ must_include_word: "يجب أن تتضمَّن المشاركة واحدة من تلك الكلمات على الأقل: %{words}"+ close_topic:+ title: إغلاق الموضوع+ description: يغلق الموضوع برسالة ختامية اختيارية+ append_last_edited_by:+ title: إلحاق "آخر تعديل بواسطة"+ description: يضيف تفاصيل "آخر تعديل بواسطة" للمنشور إلى أسفل المحتوى الذي تمت معالجته.+ text: "آخر تعديل بواسطة @%{username} %{date_time}"+ append_last_checked_by:+ title: إلحاق "آخر تحقق بواسطة"+ description: يضيف تفاصيل "آخر تحقق بواسطة" للمنشور إلى أسفل المحتوى الذي تمت معالجته.+ text: "آخر تحقق بواسطة @%{username} %{date_time}"+ summary: التحقق من المستند+ details: "التحقق من المستند: "+ button_text: تم+ add_user_to_group_through_custom_field:+ title: "إضافة مستخدم إلى المجموعة عبر الحقل المخصَّص للمستخدمين"+ group_category_notification_default:+ title: "الإعداد الافتراضي لإشعارات فئة المجموعة"+ description: "يضبط مستوى الإشعارات الافتراضي للفئة لأعضاء المجموعة"diff --git a/plugins/automation/config/locales/server.be.yml b/plugins/automation/config/locales/server.be.ymlnew file mode 100644index 00000000000..2ea77a0d350--- /dev/null+++ b/plugins/automation/config/locales/server.be.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++be:diff --git a/plugins/automation/config/locales/server.bg.yml b/plugins/automation/config/locales/server.bg.ymlnew file mode 100644index 00000000000..52333529d3c--- /dev/null+++ b/plugins/automation/config/locales/server.bg.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++bg:diff --git a/plugins/automation/config/locales/server.bs_BA.yml b/plugins/automation/config/locales/server.bs_BA.ymlnew file mode 100644index 00000000000..828a7e65af8--- /dev/null+++ b/plugins/automation/config/locales/server.bs_BA.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++bs_BA:diff --git a/plugins/automation/config/locales/server.ca.yml b/plugins/automation/config/locales/server.ca.ymlnew file mode 100644index 00000000000..ec737bc1a5b--- /dev/null+++ b/plugins/automation/config/locales/server.ca.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ca:diff --git a/plugins/automation/config/locales/server.cs.yml b/plugins/automation/config/locales/server.cs.ymlnew file mode 100644index 00000000000..041b2f0bd05--- /dev/null+++ b/plugins/automation/config/locales/server.cs.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++cs:diff --git a/plugins/automation/config/locales/server.da.yml b/plugins/automation/config/locales/server.da.ymlnew file mode 100644index 00000000000..3671b65615b--- /dev/null+++ b/plugins/automation/config/locales/server.da.yml@@ -0,0 +1,30 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++da:+ site_settings:+ discourse_automation_enabled: "Aktiver discourse-automation plugin"+ discourse_automation:+ triggerables:+ api_call:+ title: API-kald+ category_created_edited:+ title: Kategori oprettet/redigeret+ user_added_to_group:+ title: Bruger tilføjet til gruppe+ user_removed_from_group:+ title: Bruger fjernet fra gruppe+ topic:+ title: Emne+ scriptables:+ post:+ title: Opret et indlæg+ zapier_webhook:+ title: Zapier webhook+ pin_topic:+ title: Fastgør emne+ close_topic:+ title: Luk Emnediff --git a/plugins/automation/config/locales/server.de.yml b/plugins/automation/config/locales/server.de.ymlnew file mode 100644index 00000000000..1a3cbc66b3c--- /dev/null+++ b/plugins/automation/config/locales/server.de.yml@@ -0,0 +1,140 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++de:+ site_settings:+ discourse_automation_enabled: "discourse-automation-Plug-in aktivieren"+ discourse_automation:+ models:+ fields:+ required_field: Feld `%{name}` muss bei `%{target}:%{target_name}` ausgefüllt sein.+ invalid_field: Die Komponente `%{component}` des Feldes kann nicht bei `%{target}:%{target_name}` verwendet werden.+ invalid_metadata: Daten für `%{field}` sind ungültig oder Komponente `%{component}` ist unbekannt.+ triggerables:+ errors:+ custom_fields_or_user_profile_required: "Zumindest eines von „custom_fields“ oder „user_profile“ muss angegeben werden."+ user_badge_granted:+ title: Benutzer-Abzeichen gewährt+ doc: Löst eine Automatisierung aus, wenn einem Benutzer ein Abzeichen gewährt wird.+ user_first_logged_in:+ title: Benutzer hat sich erstmals angemeldet+ doc: Löst eine Automatisierung aus, wenn sich ein Benutzer zum ersten Mal anmeldet.+ stalled_topic:+ title: Festgefahrenes Thema+ doc: Löst eine Automatisierung aus, wenn das Thema für einen bestimmten Zeitraum keine neue Antwort vom Themeninhaber erhalten hat. Es wird empfohlen, diesen Auslöser auf ein Tag/eine Kategorie zu beschränken, da die Anzahl der betroffenen Themen sehr hoch sein kann. Als Sicherheitsmaßnahme ist die Anzahl der betroffenen Themen auf 250 begrenzt.+ api_call:+ title: API-Aufruf+ description: Erstellen einer POST-Anfrage, um eine Automatisierung auszulösen+ doc: Die POST-Anfrage muss an `/automations/:id/trigger.json` mit einem globalen API-Schlüssel gestellt werden.+ category_created_edited:+ title: Kategorie erstellt/bearbeitet+ description: Wenn eine Kategorie erstellt oder bearbeitet wird, wird die Automatisierung ausgelöst+ recurring:+ title: Wiederkehrend+ point_in_time:+ title: Zeitpunkt+ description: Wenn das Datum erreicht ist, wird die Automatisierung ausgelöst+ user_added_to_group:+ title: Benutzer zu Gruppe hinzugefügt+ description: Wenn ein Benutzer zur angegebenen Gruppe hinzugefügt wird, wird die Automatisierung ausgelöst+ user_removed_from_group:+ title: Benutzer aus Gruppe entfernt+ description: Wenn ein Benutzer aus der angegebenen Gruppe entfernt wird, wird die Automatisierung ausgelöst+ user_promoted:+ title: Benutzer befördert+ description: Wenn ein Benutzer von einer Vertrauensstufe zu einer anderen befördert wird+ transition_placeholder: "von %{from_level_name} auf %{to_level_name}"+ stalled_wiki:+ title: Festgefahrenes Wiki+ description: Wenn ein Wiki für einen längeren als den definierten Zeitraum nicht bearbeitet wurde, wird die Automatisierung ausgelöst+ post_created_edited:+ title: Beitrag erstellt/bearbeitet+ description: Wenn ein gültiger Beitrag bearbeitet oder erstellt wird, wird die Automatisierung ausgelöst+ pm_created:+ title: Persönliche Nachricht erstellt+ description: Wenn eine gültige PN erstellt wird, wird die Automatisierung ausgelöst+ topic:+ title: Thema+ description: Das zugehörige Skript wird nur für das angegebene Thema verwendet. Dies ist beispielsweise für Skripts nützlich, die eine Validierung durchführen+ after_post_cook:+ title: Nach Beitragsfinalisierung+ description: Wenn ein Beitragsinhalt finalisiert wird, wird die Automatisierung ausgelöst+ user_updated:+ title: Nach Benutzeraktualisierung+ description: Wenn ein Benutzer irgendeine Information aktualisiert, wird die Automatisierung ausgelöst+ scriptables:+ post:+ title: Beitrag erstellen+ description: Einen Beitrag zu einem bestimmten Thema erstellen+ flag_post_on_words:+ title: Beitrag wegen Wörtern markieren+ description: Markiert einen Beitrag, falls er bestimmte Wörter enthält+ flag_message: "Beitrag enthält unzulässige Wörter: %{words}"+ doc: Ein Beitrag, der alle angegebenen Wörter auf einmal enthält, wird markiert und ausgeblendet. Beachte, dass die Angabe mehrerer Wörter, die durch ein Komma getrennt sind, als Verbindung behandelt wird (jedes Wort muss vorhanden sein).+ zapier_webhook:+ title: Zapier-Webhook+ description: Ruft einen Zap mit dem Kontext eines Auslösers als Body auf+ auto_responder:+ title: Auto-Responder+ description: Antwortet auf einen Beitrag, der bestimmte Schlüsselwörter enthält+ auto_tag_topic:+ title: Thema automatisch mit Schlagwort markieren+ description: Schlagwörter automatisch zu einem Thema hinzufügen+ pin_topic:+ title: Thema anheften+ description: Heftet ein bestimmtes Thema zu einem bestimmten Datum an+ banner_topic:+ title: Bannerthema erstellen+ description: Ein Thema in ein Banner verwandeln+ gift_exchange:+ title: Austausch von Geschenken+ description: Ermöglicht das anonyme Paaren von Benutzern einer Gruppe, um sich gegenseitig ein Geschenk zu senden.+ doc: Der Austausch von Geschenken erfordert eine bestehende Gruppe mit mindestens 3 Benutzern. Zum gewählten Datum wird jeder Benutzer der Gruppe mit einem Schenkenden und einem Beschenkten gepaart.+ send_pms:+ title: PN senden+ description: Ermöglicht das Senden von PN (möglicherweise verzögert).+ doc: Ermöglicht es, mehrere PN an einen Benutzer zu senden. Jede PN akzeptiert eine Verzögerung.+ suspend_user_by_email:+ title: Benutzer nach E-Mail-Adresse sperren+ user_global_notice:+ title: Globaler Hinweis für Benutzer+ description: Ermöglicht die Anzeige eines globalen Hinweises für einen Benutzer+ user_group_membership_through_badge:+ title: Benutzergruppenmitgliedschaft über Abzeichen+ description: Benutzergruppenmitgliedschaft anhand eines Abzeichens ändern+ suspend_user_by_email_with_api_call:+ doc: Beim Auslösen von `suspend_user_by_email` mit einem API-Aufruf erwartet der Endpunkt, dass eine gültige `email` in den gesendeten Parametern vorhanden ist. `reasons` und `suspend_until (ISO 8601 format)` können auch verwendet werden, um Standardfeldwerte zu überschreiben.+ user_global_notice_with_stalled_topic:+ doc: Wenn dies durch ein festgefahrenes Thema ausgelöst wird, erhält der Themeninhaber den globalen Hinweis.+ user_global_notice_with_first_accepted_solution:+ doc: Bei Auslösung durch die erste akzeptierte Lösung erhält der Lösungsautor die globale Benachrichtigung.+ send_pms_with_api_call:+ doc: Bei Verwendung des Skripts `send pms` mit dem Auslöser `api call` wird der Parameter `usernames` aus deiner Anfrage verwendet, um die Empfängerliste auszufüllen.+ topic_required_words:+ title: Für das Thema erforderliche Wörter+ description: Ermöglicht es, eine Liste von Wörtern zu definieren, die für ein Thema erforderlich sind, von denen mindestens eines in jedem Beitrag verwendet werden muss.+ doc: '„Für das Thema erforderliche Wörter“ erfordert ein Thema. Wenn ein Beitrag bearbeitet/erstellt wird, wird der Beitrag anhand der Wortliste validiert. Mindestens ein Wort muss vorhanden sein.'+ errors:+ must_include_word: "Beitrag muss mindestens eines dieser Wörter enthalten: %{words}"+ close_topic:+ title: Thema schließen+ description: Schließt ein Thema mit einer optionalen Schließungsnachricht+ append_last_edited_by:+ title: '„Zuletzt bearbeitet von“ anhängen'+ description: Fügt die „Zuletzt bearbeitet von“-Details des Beitrags am Ende des finalisierten Inhalts hinzu.+ text: "Zuletzt bearbeitet von @%{username} %{date_time}"+ append_last_checked_by:+ title: '„Zuletzt überprüft von“ anhängen'+ description: Fügt die „Zuletzt überprüft von“-Details des Beitrags am Ende des finalisierten Inhalts hinzu.+ text: "Zuletzt überprüft von @%{username} %{date_time}"+ summary: Dokument überprüfen+ details: "Überprüfung des Dokuments durchführen: "+ button_text: Fertig+ add_user_to_group_through_custom_field:+ title: "Benutzer über benutzerdefiniertes Benutzerfeld zur Gruppe hinzufügen"+ group_category_notification_default:+ title: "Gruppenkategorie-Benachrichtigungsstandard"+ description: "Die Standardbenachrichtigungsstufe einer Kategorie für Mitglieder einer Gruppe festlegen"diff --git a/plugins/automation/config/locales/server.el.yml b/plugins/automation/config/locales/server.el.ymlnew file mode 100644index 00000000000..d872d0ecc40--- /dev/null+++ b/plugins/automation/config/locales/server.el.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++el:diff --git a/plugins/automation/config/locales/server.en.yml b/plugins/automation/config/locales/server.en.ymlnew file mode 100644index 00000000000..220b1a04796--- /dev/null+++ b/plugins/automation/config/locales/server.en.yml@@ -0,0 +1,134 @@+en:+ site_settings:+ discourse_automation_enabled: "Enable discourse-automation plugin"+ discourse_automation:+ models:+ fields:+ required_field: Field `%{name}` must be filled on `%{target}:%{target_name}`.+ invalid_field: Field’s component `%{component}` is not usable on `%{target}:%{target_name}.`+ invalid_metadata: Data for `%{field}` is invalid or component `%{component}` is unknown.+ triggerables:+ errors:+ custom_fields_or_user_profile_required: "At least one of 'custom_fields' or 'user_profile' must be provided."+ user_badge_granted:+ title: User badge granted+ doc: Triggers an automation when a user is granted a badge.+ user_first_logged_in:+ title: User first logged in+ doc: Triggers an automation when a user logs in for the first time.+ stalled_topic:+ title: Stalled topic+ doc: Triggers an automation when the topic has not received a new reply from topic owner for a specified period of time. It is recommended to scope this trigger to a tag/category as the number of topics impacted can be very high. As a safety measure, the number of impacted topics is capped at 250.+ api_call:+ title: API call+ description: Making a POST request to trigger an automation+ doc: The POST request should be made to `/automations/:id/trigger.json` with a global API key.+ category_created_edited:+ title: Category created/edited+ description: When a category is created or edited the automation will be triggered+ recurring:+ title: Recurring+ point_in_time:+ title: Point in time+ description: When the date is reached the automation will be triggered+ user_added_to_group:+ title: User added to group+ description: When a user is added to the specified group the automation will be triggered+ user_removed_from_group:+ title: User removed from group+ description: When a user is removed from the specified group the automation will be triggered+ user_promoted:+ title: User promoted+ description: When a user is promoted from one trust level to another+ transition_placeholder: "from %{from_level_name} to %{to_level_name}"+ stalled_wiki:+ title: Stalled wiki+ description: When a wiki has not been edited for a period longer than the one defined, the automation will be triggered+ post_created_edited:+ title: Post created/edited+ description: When a valid post is edited or created the automation will be triggered+ pm_created:+ title: Personal message created+ description: When a valid PM is created the automation will be triggered+ topic:+ title: Topic+ description: The associated script will only be used on the specified topic, this is usefull for scripts doing validation for example+ after_post_cook:+ title: After post cook+ description: When a post content is cooked the automation will be triggered+ user_updated:+ title: After user update+ description: When a user updates any information the automation will be triggered+ scriptables:+ post:+ title: Create a post+ description: Create a post on a specified topic+ flag_post_on_words:+ title: Flag post on words+ description: Flags a post if it contains specified words+ flag_message: "Post contains disallowed words: %{words}"+ doc: Post containing all given words at once will be flagged and hidden. Note that defining multiple words delimited by a comma will be used as compound (each word has to be present).+ zapier_webhook:+ title: Zapier webhook+ description: Calls a zap with the context of a trigger as body+ auto_responder:+ title: Auto Responder+ description: Posts a reply to a post including specified keywords+ auto_tag_topic:+ title: Auto Tag Topic+ description: Automatically add tags to a topic+ pin_topic:+ title: Pin Topic+ description: Pins a specified topic at a given date+ banner_topic:+ title: Make banner topic+ description: Make a topic into a banner+ gift_exchange:+ title: Gift exchange+ description: Allows to anonymously pair users of a group to send each other a gift.+ doc: Gift exchange requires an existing group with at least 3 users. At the chosen date each users of the group will be paired with one gifter and one giftee.+ send_pms:+ title: Send pms+ description: Allows to send PMs (possibly delayed).+ doc: Allows to send multiple pms to a user. Each PM accepts a delay.+ suspend_user_by_email:+ title: Suspend user by email+ user_global_notice:+ title: User global notice+ description: Allows to display a global notice for a user+ user_group_membership_through_badge:+ title: User Group Membership through Badge+ description: Modify user group membership based on a badge+ suspend_user_by_email_with_api_call:+ doc: When triggering `suspend_user_by_email` with an api call, the endpoint expects a valid `email` to be present in the params sent. `reasons` and `suspend_until (ISO 8601 format)` can also be used to override default fields values.+ user_global_notice_with_stalled_topic:+ doc: When triggered through stalled topic, the topic owner will receive the global notice.+ user_global_notice_with_first_accepted_solution:+ doc: When triggered through first accepted solution, the solution author will receive the global notice.+ send_pms_with_api_call:+ doc: When using `send pms` script with `api call` trigger, the `usernames` param of your request will be used to fill the receivers list.+ topic_required_words:+ title: Topic required words+ description: Allows to define a list of words required on a topic, at least one should be used in each post.+ doc: Topic required words requires a topic. When a post is edited/created, the post will be validated against the list of words, at least one must be present.+ errors:+ must_include_word: "Post must include at least one of these words: %{words}"+ close_topic:+ title: Close Topic+ description: Closes a topic with an optional closing message+ append_last_edited_by:+ title: Append last edited by+ description: Adds the 'last edited by' details of the post to cooked content's bottom.+ text: "Last edited by @%{username} %{date_time}"+ append_last_checked_by:+ title: Append last checked by+ description: Adds the 'last checked by' details of the post cooked content's bottom.+ text: "Last checked by @%{username} %{date_time}"+ summary: Check document+ details: "Perform check on document: "+ button_text: Done+ add_user_to_group_through_custom_field:+ title: "Add user to group through User Custom Field"+ group_category_notification_default:+ title: "Group Category Notification Default"+ description: "Set the default notification level of a category for members of a group"diff --git a/plugins/automation/config/locales/server.en_GB.yml b/plugins/automation/config/locales/server.en_GB.ymlnew file mode 100644index 00000000000..2d4fa180ec7--- /dev/null+++ b/plugins/automation/config/locales/server.en_GB.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++en_GB:diff --git a/plugins/automation/config/locales/server.es.yml b/plugins/automation/config/locales/server.es.ymlnew file mode 100644index 00000000000..80b001aacd2--- /dev/null+++ b/plugins/automation/config/locales/server.es.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++es:+ site_settings:+ discourse_automation_enabled: "Activar el plugin discourse-automation"+ discourse_automation:+ models:+ fields:+ required_field: El campo «%{name}» debe rellenarse en «%{target}:%{target_name}».+ invalid_field: El componente del campo «%{component}» no es utilizable en «%{target}:%{target_name}».+ invalid_metadata: Los datos de «%{field}» no son válidos o el componente «%{component}» es desconocido.+ triggerables:+ user_badge_granted:+ title: Credencial de usuario concedida+ doc: Activa una automatización cuando un usuario recibe una insignia.+ user_first_logged_in:+ title: Usuario que inició sesión por primera vez+ doc: Activa una automatización cuando un usuario se conecta por primera vez.+ stalled_topic:+ title: Tema estancado+ doc: Activa una automatización cuando el autor del tema no responde tras un periodo de tiempo especificado. Recomendamos limitarlo por etiqueta o categoría, ya que si no el número de temas impactados puede ser muy elevado. Como medida de seguridad, no podrá impactar a más de 250 temas.+ api_call:+ title: Llamada a la API+ description: Hacer una petición POST para activar una automatización+ doc: La petición POST debe hacerse a «/automations/:id/trigger.json» con una clave de API global.+ category_created_edited:+ title: Categoría creada/editada+ description: Cuando se cree o edite una categoría se activará la automatización+ recurring:+ title: Periódico+ point_in_time:+ title: Fecha y hora+ description: Cuando se alcance la fecha, se activará la automatización+ user_added_to_group:+ title: Usuario añadido a un grupo+ description: Cuando un usuario sea añadido al grupo especificado, se activará la automatización+ user_removed_from_group:+ title: Usuario eliminado del grupo+ description: Cuando un usuario sea eliminado del grupo especificado, se activará la automatización+ user_promoted:+ title: Usuario sube de nivel de confianza+ description: Cuando un usuario sube de un nivel de confianza a otro+ transition_placeholder: "de %{from_level_name} a %{to_level_name}"+ stalled_wiki:+ title: Wiki estancada+ description: Cuando un wiki no haya sido editado durante un periodo superior al definido, se activará la automatización+ post_created_edited:+ title: Publicación creada o editada+ description: Cuando se edita o se crea una publicación válida, se activa la automatización+ pm_created:+ title: Mensaje personal creado+ description: Cuando se cree un MP válido se activará la automatización+ topic:+ title: Tema+ description: El script asociado solo se utilizará en el tema especificado. Por ejemplo, esto es útil para los scripts que hacen validaciones+ after_post_cook:+ title: Después de cocinar la publicación+ description: Cuando se cocine el contenido de una publicación se activará la automatización+ scriptables:+ post:+ title: Crear una publicación+ description: Crear una publicación sobre un tema específico+ flag_post_on_words:+ title: Denunciar publicación según su contenido+ description: Denuncia una publicación si contiene las palabras especificadas+ flag_message: "La publicación contiene palabras no permitidas: %{words}"+ doc: Las publicaciones que contengan todas las palabras a la vez serán denunciadas y ocultadas. Ten en cuenta que si defines varias palabras separadas por coma, todas ellas deberán estar presentes.+ zapier_webhook:+ title: Webhook de Zapier+ description: Llama a un zap con el contexto de un activador como cuerpo+ auto_responder:+ title: Respuesta automática+ description: Responde a un mensaje que incluya las palabras clave especificadas+ auto_tag_topic:+ title: Etiquetar automáticamente tea+ description: Añadir etiquetas automáticamente a un tema+ pin_topic:+ title: Fijar tema+ description: Fija un tema específico en una fecha determinada+ banner_topic:+ title: Hacer tema de encabezado+ description: Convertir un tema en un encabezado+ gift_exchange:+ title: Amigo invisible+ description: Permite emparejar de forma anónima a los usuarios de un grupo para que se envíen un regalo entre ellos.+ doc: El amigo invisible (intercambio de regalos) requiere un grupo existente con al menos 3 usuarios. En la fecha elegida, se emparejará a cada usuario con una persona a la que regalar (y otra distinta que le regalará).+ send_pms:+ title: Enviar mensajes privados+ description: Permite enviar MPs (posiblemente con retardo).+ doc: Permite enviar varios pms a un usuario. Cada PM acepta un retardo.+ suspend_user_by_email:+ title: Suspender usuario con un correo electrónico+ user_global_notice:+ title: Aviso global para un usuario+ description: Permite mostrarle un aviso global a un usuario+ user_group_membership_through_badge:+ title: Pertenencia a grupos de usuarios mediante una insignia+ description: Modificar la pertenencia a un grupo de usuarios en función de una insignia+ suspend_user_by_email_with_api_call:+ doc: Al activar «suspend_user_by_email» con una llamada API, se espera que haya un «email» válido en los parámetros enviados. También se pueden utilizar «reasons» y «suspend_until (formato ISO 8601)» para anular los valores de los campos por defecto.+ user_global_notice_with_stalled_topic:+ doc: Cuando se active a través de un tema estancado, el autor del tema recibirá el aviso global+ user_global_notice_with_first_accepted_solution:+ doc: Cuando se active a través de la primera solución aceptada, el autor de la solución recibirá el aviso global.+ send_pms_with_api_call:+ doc: Si utilizas el script «send pms» con el activador «api call», el parámetro «usernames» de tu solicitud se utilizará para rellenar la lista de destinatarios.+ topic_required_words:+ title: Palabras requeridas en un tema+ description: Permite definir una lista de palabras requeridas en un tema, al menos una debe ser utilizada en cada publicación.+ doc: Palabras requeridas en un tema necesita un tema. Cuando se cree o edite una publicación, se verificará que incluya al menos una de las palabras requeridas.+ errors:+ must_include_word: "La publicación debe contener al menos una de las siguientes palabras: %{words}"+ close_topic:+ title: Cerrar tema+ description: Cierra un tema y permite opcionalmente incluir un mensaje+ append_last_edited_by:+ title: Anexar la última edición realizada por+ description: Añade los datos de «last edited by» de la publicación en la parte inferior del contenido cocinado.+ text: "Editado por última vez por @%{username} %{date_time}"+ append_last_checked_by:+ title: Anexar la última comprobación realizada por+ description: Añade los datos de «last checked by» de la parte inferior del contenido cocinado de la publicación.+ text: "Comprobado por última vez por @%{username} %{date_time}"+ summary: Comprobar documento+ details: "Realiza la comprobación del documento: "+ button_text: Hecho+ add_user_to_group_through_custom_field:+ title: "Añadir un usuario al grupo a través del campo personalizado de usuario"+ group_category_notification_default:+ title: "Notificación de categoría de grupo predeterminada"+ description: "Establecer el nivel de notificación por defecto de una categoría para los miembros de un grupo"diff --git a/plugins/automation/config/locales/server.et.yml b/plugins/automation/config/locales/server.et.ymlnew file mode 100644index 00000000000..0ea0b6d554b--- /dev/null+++ b/plugins/automation/config/locales/server.et.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++et:diff --git a/plugins/automation/config/locales/server.fa_IR.yml b/plugins/automation/config/locales/server.fa_IR.ymlnew file mode 100644index 00000000000..72c192a995e--- /dev/null+++ b/plugins/automation/config/locales/server.fa_IR.yml@@ -0,0 +1,23 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++fa_IR:+ discourse_automation:+ triggerables:+ user_badge_granted:+ title: نشان کاربر اعطا شده+ topic:+ title: موضوع+ scriptables:+ post:+ title: ایجاد نوشته+ description: یک نوشته را در موضوع مشخص ایجاد کنید+ append_last_edited_by:+ text: "آخرین ویرایش توسط @%{username} %{date_time}"+ append_last_checked_by:+ text: "آخرین بررسی توسط @%{username} %{date_time}"+ add_user_to_group_through_custom_field:+ title: "افزودن کاربر به گروه از طریق فیلد سفارشی کاربر"diff --git a/plugins/automation/config/locales/server.fi.yml b/plugins/automation/config/locales/server.fi.ymlnew file mode 100644index 00000000000..18d3541673e--- /dev/null+++ b/plugins/automation/config/locales/server.fi.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++fi:+ site_settings:+ discourse_automation_enabled: "Ota discourse-automation-lisäosa käyttöön"+ discourse_automation:+ models:+ fields:+ required_field: Kenttä "%{name}" on täytettävä kohdassa "%{target}:%{target_name}".+ invalid_field: Kentän komponenttia "%{component}" ei voi käyttää kohteessa "%{target}:%{target_name}".+ invalid_metadata: Kentän "%{field}" tiedot ovat virheellisiä, tai komponentti "%{component}" on tuntematon.+ triggerables:+ user_badge_granted:+ title: Käyttäjän kunniamerkki myönnetty+ doc: Käynnistää automaation, kun käyttäjälle myönnetään kunniamerkki.+ user_first_logged_in:+ title: Käyttäjä kirjautui sisään ensimmäisen kerran+ doc: Käynnistää automaation, kun käyttäjä kirjautuu sisään ensimmäisen kerran.+ stalled_topic:+ title: Pysähtynyt ketju+ doc: Käynnistää automaation, kun ketju ei ole saanut uutta vastausta ketjun omistajalta tiettynä aikana. Suosittelemme, että tämä triggeri kohdistetaan tunnisteeseen tai alueeseen, koska niiden ketjujen määrä, joihin se vaikuttaa, saattaa olla erittäin suuri. Turvallisuussyistä ketjujen määrä, johon tämä vaikuttaa, on rajoitettu 250:een.+ api_call:+ title: API-kutsu+ description: POST-pyynnön tekeminen automaation käynnistämiseksi+ doc: POST-pyyntö tulisi lähettää osoitteeseen "/automations/:id/trigger.json" yleisellä API-avaimella.+ category_created_edited:+ title: Alue luotu/aluetta muokattu+ description: Kun aluetta muokataan tai sellainen luodaan, automaatio käynnistyy+ recurring:+ title: Toistuva+ point_in_time:+ title: Ajankohta+ description: Kun päivämäärä on saavutettu, automaatio käynnistyy+ user_added_to_group:+ title: Käyttäjä lisätty ryhmään+ description: Kun käyttäjä lisätään määritettyyn ryhmään, automaatio käynnistyy+ user_removed_from_group:+ title: Käyttäjä poistettu ryhmästä+ description: Kun käyttäjä poistetaan määritetystä ryhmästä, automaatio käynnistyy+ user_promoted:+ title: Käyttäjä ylennetty+ description: Kun käyttäjä ylennetään luottamustasolta toiselle+ transition_placeholder: "tasolta %{from_level_name} tasolle %{to_level_name}"+ stalled_wiki:+ title: Pysähtynyt wiki+ description: Kun wikiä ei ole muokattu määritettyä ajanjaksoa pidempään, automaatio käynnistyy+ post_created_edited:+ title: Viesti luotu tai viestiä muokattu+ description: Kun kelvollista viestiä muokataan tai sellainen luodaan, automaatio käynnistyy+ pm_created:+ title: Yksityisviesti luotu+ description: Kun kelvollinen yksityisviesti luodaan, automaatio käynnistyy+ topic:+ title: Ketju+ description: Tähän liittyvää skriptiä käytetään vain tietyssä ketjussa; tämä on hyödyllistä esimerkiksi validointia suorittavissa skripteissä+ after_post_cook:+ title: Viestin kirjoittamisen jälkeen+ description: Kun viestin sisältö luodaan, automaatio käynnistyy+ scriptables:+ post:+ title: Luo viesti+ description: Luo viesti tietyssä ketjussa+ flag_post_on_words:+ title: Liputa viesti sanojen perusteella+ description: Liputtaa viestin, jos se sisältää tiettyjä sanoja+ flag_message: "Viesti sisältää kiellettyjä sanoja: %{words}"+ doc: Viesti, joka sisältää kaikki annetut sanat kerralla, liputetaan ja piilotetaan. Huomaa, että useita pilkulla eroteltuja sanoja käytetään yhdistelmänä (jokaisen sanan täytyy esiintyä).+ zapier_webhook:+ title: Zapierin webhook+ description: Kutsuu zapin, tekstinä on triggerin konteksti+ auto_responder:+ title: Automaattinen vastaus+ description: Lähettää vastauksen viestiin, joka sisältää tietyt avainsanat+ auto_tag_topic:+ title: Ketjun automaattinen merkintä+ description: Lisää tunnisteita ketjuun automaattisesti+ pin_topic:+ title: Kiinnitä aihe+ description: Kiinnittää tietyn aiheen tiettynä päivänä+ banner_topic:+ title: Aseta banneriketjuksi+ description: Tee ketjusta bannerin+ gift_exchange:+ title: Lahjojen vaihto+ description: Sallii anonyymin käyttäjäparin ryhmästä lähettää toisilleen lahjan.+ doc: Lahjojen vaihto vaatii olemassa olevan ryhmän, jossa on vähintään 3 käyttäjää. Valittuna päivänä jokaiselle ryhmän käyttäjälle valitaan pariksi yksi lahjanantaja ja yksi lahjansaaja.+ send_pms:+ title: Lähetä yksityisviestejä+ description: Sallii yksityisviestien lähettämisen (mahdollisesti viiveellä).+ doc: Mahdollistaa useiden yksityisviestien lähettämisen käyttäjälle. Kussakin yksityisviestissä voi olla viive.+ suspend_user_by_email:+ title: Hyllytä käyttäjä sähköpostitse+ user_global_notice:+ title: Käyttäjän yleinen ilmoitus+ description: Mahdollistaa yleisen ilmoituksen näyttämisen käyttäjälle+ user_group_membership_through_badge:+ title: Käyttäjäryhmän jäsenyys kunniamerkin kautta+ description: Muokkaa käyttäjäryhmän jäsenyyttä kunniamerkin perusteella+ suspend_user_by_email_with_api_call:+ doc: Kun "suspend_user_by_email" käynnistetään API-kutsulla, päätepiste odottaa, että lähetettyihin parametreihin sisältyy kelvollinen "email". Parametreja "reasons" ja "suspend_until (ISO 8601 -muoto)" voidaan myös käyttää oletusarvoisten kenttien arvojen ohittamiseen.+ user_global_notice_with_stalled_topic:+ doc: Kun tämä käynnistetään pysähtyneen ketjun kautta, ketjun omistaja saa yleisen ilmoituksen.+ user_global_notice_with_first_accepted_solution:+ doc: Kun tämä käynnistetään ensimmäisen hyväksytyn ratkaisun kautta, ratkaisun kirjoittaja saa yleisen ilmoituksen.+ send_pms_with_api_call:+ doc: Kun "send pms" -skriptiä käytetään "api call" -triggerin kanssa, pyyntösi "usernames"-parametria käytetään vastaanottajaluettelon täyttämiseen.+ topic_required_words:+ title: Ketjun pakolliset sanat+ description: Mahdollistaa ketjussa vaadittavien sanojen luettelon määrittämisen, ainakin yhtä niistä tulisi käyttää jokaisessa viestissä.+ doc: Ketjun pakolliset sanat edellyttävät ketjun. Kun viesti luodaan tai viestiä muokataan, viesti validoidaan luettelon avulla, ja ainakin yhden sanan on esiinnyttävä.+ errors:+ must_include_word: "Viestin täytyy sisältää vähintään yksi seuraavista sanoista: %{words}"+ close_topic:+ title: Sulje ketju+ description: Sulkee ketjun valinnaisella sulkemisviestillä+ append_last_edited_by:+ title: Lisää viimeisimmän muokkaajan tiedot+ description: Lisää viestien viimeisen muokkaajan tiedot sisällön alaosaan.+ text: "Viimeksi muokannut @%{username} %{date_time}"+ append_last_checked_by:+ title: Lisää viimeisimmän tarkistajan tiedot+ description: Lisää viestien viimeisen tarkistajan tiedot sisällön alaosaan.+ text: "Viimeksi tarkistanut @%{username} %{date_time}"+ summary: Tarkista asiakirja+ details: "Suorita tarkistus asiakirjalle: "+ button_text: Valmis+ add_user_to_group_through_custom_field:+ title: "Lisää käyttäjä ryhmään käyttäjän mukautetun kentän kautta"+ group_category_notification_default:+ title: "Ryhmän alueen ilmoitusoletus"+ description: "Aseta alueen oletusarvoinen ilmoitustaso ryhmän jäsenille"diff --git a/plugins/automation/config/locales/server.fr.yml b/plugins/automation/config/locales/server.fr.ymlnew file mode 100644index 00000000000..d45f698ca12--- /dev/null+++ b/plugins/automation/config/locales/server.fr.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++fr:+ site_settings:+ discourse_automation_enabled: "Activer l'extension discourse-automation"+ discourse_automation:+ models:+ fields:+ required_field: Le champ « %{name} » doit être rempli sur « %{target}:%{target_name} ».+ invalid_field: Le composant du champ « %{component} » n'est pas utilisable sur « %{target}:%{target_name} ».+ invalid_metadata: Les données pour « %{field} » ne sont pas valides ou le composant « %{component} » est inconnu.+ triggerables:+ user_badge_granted:+ title: Badge d'utilisateur accordé+ doc: Déclenche une automatisation lorsqu'un utilisateur reçoit un badge.+ user_first_logged_in:+ title: Utilisateur connecté pour la première fois+ doc: Déclenche une automatisation lorsqu'un utilisateur se connecte pour la première fois.+ stalled_topic:+ title: Sujet bloqué+ doc: Déclenche une automatisation lorsque le sujet n'a pas reçu de nouvelle réponse du propriétaire du sujet pendant une période de temps spécifiée. Il est recommandé d'étendre ce déclencheur à une étiquette/catégorie, car le nombre de sujets impactés peut être très élevé. Par mesure de sécurité, le nombre de sujets impactés est plafonné à 250.+ api_call:+ title: Appel d'API+ description: Faire une requête POST pour déclencher une automatisation+ doc: La requête POST doit être envoyée à « /automations/:id/trigger.json » avec une clé API globale.+ category_created_edited:+ title: Catégorie créée/modifiée+ description: Lorsqu'une catégorie est créée ou modifiée, l'automatisation sera déclenchée+ recurring:+ title: Récurrent+ point_in_time:+ title: Point dans le temps+ description: Lorsque la date est atteinte, l'automatisation est déclenchée.+ user_added_to_group:+ title: Utilisateur ajouté au groupe+ description: Lorsqu'un utilisateur est ajouté au groupe spécifié, l'automatisation est déclenchée+ user_removed_from_group:+ title: Utilisateur supprimé du groupe+ description: Lorsqu'un utilisateur est supprimé du groupe spécifié, l'automatisation est déclenchée+ user_promoted:+ title: Utilisateur promu+ description: Lorsqu'un utilisateur est promu à un niveau de confiance supérieur+ transition_placeholder: "de %{from_level_name} à %{to_level_name}"+ stalled_wiki:+ title: Wiki bloqué+ description: Lorsqu'un wiki n'a pas été édité pendant une période supérieure à celle définie, l'automatisation sera déclenchée+ post_created_edited:+ title: Message créé/modifié+ description: Lorsqu'un message valide est modifié ou créé, l'automatisation est déclenchée+ pm_created:+ title: Message privé créé+ description: Lorsqu'un MP valide est créé, l'automatisation est déclenchée+ topic:+ title: Sujet+ description: Le script associé ne sera utilisé que sur le sujet spécifié, ceci est utile pour les scripts utilisation la validation par exemple+ after_post_cook:+ title: Après la préparation du message+ description: Lorsqu'un contenu de publication est préparé, l'automatisation est déclenchée+ scriptables:+ post:+ title: Créer un message+ description: Créer un message sur un sujet spécifique+ flag_post_on_words:+ title: Signaler un message en fonction des mots+ description: Signale un message s'il contient des mots spécifiés+ flag_message: "Le message contient des mots interdits : %{words}"+ doc: Les messages contenant tous les mots donnés à la fois seront signalés et masqués. Notez que la définition de plusieurs mots délimités par une virgule sera utilisée comme un ensemble (chaque mot doit être présent).+ zapier_webhook:+ title: Webhook Zapier+ description: Appelle un zap avec le contexte d'un déclencheur comme corps+ auto_responder:+ title: Répondeur automatique+ description: Publie une réponse à un message incluant des mots-clés spécifiés+ auto_tag_topic:+ title: Marquage automatique du sujet+ description: Ajouter automatiquement des étiquettes à un sujet+ pin_topic:+ title: Épingler le sujet+ description: Épingle un sujet spécifié à une date donnée+ banner_topic:+ title: Créer un sujet en bannière+ description: Transformer un sujet en bannière+ gift_exchange:+ title: Échange de cadeaux+ description: Permet d'associer anonymement les utilisateurs d'un groupe pour qu'ils s'envoient des cadeaux.+ doc: L'échange de cadeaux nécessite un groupe existant avec au moins 3 utilisateurs. À la date choisie, chaque utilisateur du groupe sera jumelé avec un donateur et un bénéficiaire.+ send_pms:+ title: Envoyer des MP+ description: Permet d'envoyer des MP (éventuellement retardés).+ doc: Permet d'envoyer plusieurs MP à un utilisateur. Chaque MP accepte un délai.+ suspend_user_by_email:+ title: Suspendre l'utilisateur par e-mail+ user_global_notice:+ title: Avis global de l'utilisateur+ description: Permet d'afficher un avis global pour un utilisateur+ user_group_membership_through_badge:+ title: Adhésion à un groupe d'utilisateurs par le biais d'un badge+ description: Modifier l'appartenance à un groupe d'utilisateurs en fonction d'un badge+ suspend_user_by_email_with_api_call:+ doc: Lorsque vous déclenchez « suspend_user_by_email » avec un appel d'API, le terminal s'attend à ce qu'un « email » valide soit présent dans les paramètres envoyés. « reasons » et « suspend_until » (format ISO 8601) peuvent également être utilisés pour remplacer les valeurs des champs par défaut.+ user_global_notice_with_stalled_topic:+ doc: Lorsqu'il est déclenché par un sujet bloqué, le propriétaire du sujet recevra l'avis global.+ user_global_notice_with_first_accepted_solution:+ doc: En cas de déclenchement via la première solution acceptée, l'auteur de la solution recevra la notification globale.+ send_pms_with_api_call:+ doc: Lorsque vous utilisez le script « send pms » avec le déclencheur « api call », le paramètre « usernames » de votre requête sera utilisé pour remplir la liste des destinataires.+ topic_required_words:+ title: Mots requis pour le sujet+ description: Permet de définir une liste de mots obligatoires sur un sujet, au moins un mot doit être utilisé dans chaque message.+ doc: Les mots obligatoires du sujet nécessitent un sujet. Lorsqu'un message est édité/créé, le message sera validé par rapport à la liste de mots, au moins un mot doit y être présent.+ errors:+ must_include_word: "Le message doit inclure au moins un de ces mots : %{words}"+ close_topic:+ title: Fermer le sujet+ description: Ferme un sujet avec un message de fermeture facultatif+ append_last_edited_by:+ title: Ajouter la dernière modification par+ description: Ajoute les détails de la « dernière modification par » du message au bas du contenu préparé.+ text: "Dernière modification par @%{username} %{date_time}"+ append_last_checked_by:+ title: Ajouter la dernière vérification par+ description: Ajoute les détails de la « dernière vérification par » au bas du message après sa préparation.+ text: "Dernière vérification par @%{username} %{date_time}"+ summary: Vérifier le document+ details: "Effectuer une vérification du document : "+ button_text: Terminé+ add_user_to_group_through_custom_field:+ title: "Ajouter un utilisateur au groupe via le champ personnalisé de l'utilisateur"+ group_category_notification_default:+ title: "Notification de catégorie de groupe par défaut"+ description: "Définir le niveau de notification par défaut d'une catégorie pour les membres d'un groupe"diff --git a/plugins/automation/config/locales/server.gl.yml b/plugins/automation/config/locales/server.gl.ymlnew file mode 100644index 00000000000..fb911ce1635--- /dev/null+++ b/plugins/automation/config/locales/server.gl.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++gl:diff --git a/plugins/automation/config/locales/server.he.yml b/plugins/automation/config/locales/server.he.ymlnew file mode 100644index 00000000000..a40b0d23afd--- /dev/null+++ b/plugins/automation/config/locales/server.he.yml@@ -0,0 +1,107 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++he:+ site_settings:+ discourse_automation_enabled: "הפעלת תוסף discourse-automation"+ discourse_automation:+ triggerables:+ errors:+ custom_fields_or_user_profile_required: "יש לציין לפחות אחת מבין האפשרויות ‚custom_fields’ (שדות מותאמים אישית) או ‚user_profile’ (פרופיל משתמש)."+ user_badge_granted:+ title: עיטור משתמש הוענק+ doc: מקפיץ אוטומציה כשמוענק עיטור למשתמש.+ user_first_logged_in:+ title: כניסת המשתמש לראשונה+ doc: מפעיל אוטומציה עם כניסת משתמש לראשונה+ stalled_topic:+ title: נושא מעוכב+ api_call:+ title: קריאת API+ category_created_edited:+ title: הקטגוריה נוצרה/נערכה+ description: כאשר קטגוריה נוצרת או נערכת, האוטומציה תפעל+ recurring:+ title: מחזורי+ point_in_time:+ title: נקודה בזמן+ description: כאשר יגיע התאריך האוטומציה תוקפץ+ user_added_to_group:+ title: משתמש נוסף לקבוצה+ user_removed_from_group:+ title: משתמש הוסר מהקבוצה+ description: כאשר משתמש מוסר מהקבוצה שצוינה, האוטומציה תופעל+ user_promoted:+ title: משתמש קיבל קידום+ description: כאשר משתמש מקודם מדרגת אמון אחת לאחרת+ transition_placeholder: "מדרגה %{from_level_name} אל %{to_level_name}"+ post_created_edited:+ title: פוסט נוצר/נערך+ pm_created:+ title: נוצרה הודעה פרטית+ description: כאשר הודעה פרטית תקפה האוטומציה תוקפץ+ topic:+ title: נושא+ after_post_cook:+ title: אחרי בישול פוסט+ description: כאשר תוכן פוסט מבושל האוטומציה תופעל+ user_updated:+ title: לאחר עדכון המשתמש+ description: כאשר המשתמש מעדכן מידע האוטומציה תוזנק+ scriptables:+ post:+ title: יצירת פוסט+ description: יצירת פוסט בנושא מסוים+ flag_post_on_words:+ title: סימון פוסט בדגל על המילים+ description: מסמן פוסט בדגל אם מופיעות בו מילים מסוימות+ flag_message: "הפוסט מכיל מילים אסורות: %{words}"+ zapier_webhook:+ title: התליה של Zapier+ auto_responder:+ title: משיב אוטומטי+ auto_tag_topic:+ title: תיוג נושא אוטומטית+ description: להוסיף תגיות לנושא אוטומטית+ pin_topic:+ title: נעיצת נושא+ banner_topic:+ title: להציב ככרזה לנושא+ description: הפיכת נושא לכרזה+ gift_exchange:+ title: החלפת מתנות+ suspend_user_by_email:+ title: השהיית משתמש לפי דוא״ל+ user_global_notice:+ description: מאפשר להציג הודעה גלובלית למשתמש+ user_group_membership_through_badge:+ title: חברות משתמשים בקבוצות לפי עיטורים+ description: שינוי חברות בקבוצת משתמשים לפי עיטור+ user_global_notice_with_first_accepted_solution:+ doc: כאשר מוקפץ עקב הפתרון הראשון שהתקבל, הפותר יקבל התראה כללית.+ topic_required_words:+ title: מילים שנחוצות לנושא+ errors:+ must_include_word: "הפוסט חייב לכלול לפחות אחת מהמילים האלו: %{words}"+ close_topic:+ title: סגירת נושא+ description: סגירת הנושא עם הודעת סגירה כרשות+ append_last_edited_by:+ title: הוספת נערך לאחרונה על ידי+ description: מוסיף את פרטי העריכה האחרונה של הפוסט לתחתית התוכן המבושל.+ text: "נערך לאחרונה על ידי @%{username} ב־%{date_time}"+ append_last_checked_by:+ title: הוספת נבדק לאחרונה על ידי+ description: מוסיף את פרטי הבדיקה האחרונה של הפוסט לתחתית התוכן המבושל.+ text: "נבדק לאחרונה על ידי @%{username} ב־%{date_time}"+ summary: בדיקת מסמך+ details: "ביצוע בדיקה על המסמך: "+ button_text: בוצע+ add_user_to_group_through_custom_field:+ title: "הוספת משתמש לקבוצה באמצעות שדה מותאם אישית של משתמש"+ group_category_notification_default:+ title: "ברירת מחדל של התראה על קטגוריית קבוצה"+ description: "הגדרת רמת ברירת המחדל של התראה בקטגוריה עבור חברים בקבוצה"diff --git a/plugins/automation/config/locales/server.hr.yml b/plugins/automation/config/locales/server.hr.ymlnew file mode 100644index 00000000000..93343ce6e19--- /dev/null+++ b/plugins/automation/config/locales/server.hr.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++hr:diff --git a/plugins/automation/config/locales/server.hu.yml b/plugins/automation/config/locales/server.hu.ymlnew file mode 100644index 00000000000..5858dc2f7a8--- /dev/null+++ b/plugins/automation/config/locales/server.hu.yml@@ -0,0 +1,12 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++hu:+ discourse_automation:+ triggerables:+ user_removed_from_group:+ title: Felhasználó eltávolítva a csoportból+ description: Amikor egy felhasználót eltávolítanak a megadott csoportból, az automatizálás aktiválódikdiff --git a/plugins/automation/config/locales/server.hy.yml b/plugins/automation/config/locales/server.hy.ymlnew file mode 100644index 00000000000..cb18f64d356--- /dev/null+++ b/plugins/automation/config/locales/server.hy.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++hy:diff --git a/plugins/automation/config/locales/server.id.yml b/plugins/automation/config/locales/server.id.ymlnew file mode 100644index 00000000000..596e36b2e13--- /dev/null+++ b/plugins/automation/config/locales/server.id.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++id:diff --git a/plugins/automation/config/locales/server.it.yml b/plugins/automation/config/locales/server.it.ymlnew file mode 100644index 00000000000..b7d0e631c38--- /dev/null+++ b/plugins/automation/config/locales/server.it.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++it:+ site_settings:+ discourse_automation_enabled: "Abilita il plugin discourse-automation"+ discourse_automation:+ models:+ fields:+ required_field: Il campo `%{name}` deve essere compilato su `%{target}:%{target_name}`.+ invalid_field: Il componente del campo `%{component}` non è utilizzabile su `%{target}:%{target_name}.`+ invalid_metadata: I dati per `%{field}` non sono validi o il componente `%{component}` è sconosciuto.+ triggerables:+ user_badge_granted:+ title: Distintivo utente concesso+ doc: Attiva un'automazione quando a un utente viene riconosciuto un distintivo.+ user_first_logged_in:+ title: L'utente ha effettuato l'accesso per la prima volta+ doc: Attiva un'automazione quando un utente accede per la prima volta.+ stalled_topic:+ title: Argomento bloccato+ doc: Attiva un'automazione quando l'argomento non ha ricevuto una nuova risposta dal proprietario dell'argomento per un periodo di tempo specificato. Si consiglia di limitare questa azione di attivazione a un tag/categoria poiché il numero di argomenti interessati può essere molto elevato. Per motivi di sicurezza, il numero di argomenti interessati è limitato a 250.+ api_call:+ title: Chiamata API+ description: Effettuare una richiesta POST per attivare un'automazione+ doc: La richiesta POST deve essere inviata a `/automations/:id/trigger.json` con una chiave API globale.+ category_created_edited:+ title: Categoria creata/modificata+ description: Quando una categoria viene creata o modificata, verrà attivata l'automazione+ recurring:+ title: Ricorrente+ point_in_time:+ title: Momento di tempo+ description: Al raggiungimento della data l'automazione sarà attivata+ user_added_to_group:+ title: Utente aggiunto al gruppo+ description: Quando un utente viene aggiunto al gruppo specificato, l'automazione verrà attivata+ user_removed_from_group:+ title: Utente rimosso dal gruppo+ description: Quando un utente viene rimosso dal gruppo specificato, l'automazione verrà attivata+ user_promoted:+ title: Utente promosso+ description: Quando un utente viene promosso da un livello di attendibilità a un altro+ transition_placeholder: "da %{from_level_name} a %{to_level_name}"+ stalled_wiki:+ title: Wiki bloccato+ description: Quando un wiki non è stato modificato per un periodo più lungo di quello definito, l'automazione verrà attivata+ post_created_edited:+ title: Messaggio creato/modificato+ description: Quando un messaggio valido viene modificato o creato, l'automazione verrà attivata+ pm_created:+ title: Messaggio personale creato+ description: Quando un messaggio personale valido viene creato, l'automazione verrà attivata+ topic:+ title: Argomento+ description: Lo script associato verrà utilizzato solo sull'argomento specificato, questo è utile per gli script che eseguono la convalida, ad esempio+ after_post_cook:+ title: Dopo l'elaborazione del messaggio+ description: Quando il contenuto di un messaggio viene elaborato, l'automazione verrà attivata+ scriptables:+ post:+ title: Crea un messaggio+ description: Crea un messaggio su un argomento specificato+ flag_post_on_words:+ title: Contrassegna messaggio in base alle parole+ description: Contrassegna un messaggio se contiene parole specificate+ flag_message: "Il messaggio contiene parole non consentite: %{words}"+ doc: I messaggi contenenti tutte le parole indicate contemporaneamente saranno contrassegnati e nascosti. La definizione di più parole delimitate da una virgola verrà considerata come un elenco composto di parole (ogni parola deve essere presente).+ zapier_webhook:+ title: Webhook Zapier+ description: Chiama uno zap con il contesto di un'attivazione come corpo+ auto_responder:+ title: Risponditore automatico+ description: Pubblica una risposta a un messaggio includendo le parole chiave specificate+ auto_tag_topic:+ title: Etichetta automaticamente argomenti+ description: Aggiungi automaticamente etichette a un argomento+ pin_topic:+ title: Fissa argomento+ description: Fissa un argomento specificato in una determinata data+ banner_topic:+ title: Crea argomento banner+ description: Trasforma un argomento in un banner+ gift_exchange:+ title: Scambio di regali+ description: Consente a coppie di utenti anonimi di un gruppo di scambiarsi un regalo.+ doc: Lo scambio di regali richiede un gruppo con almeno 3 utenti. Alla data prescelta ogni utente del gruppo sarà abbinato a un donatore e a un destinatario di un regalo.+ send_pms:+ title: Invia MP+ description: Consente di inviare messaggi personali (con eventuale ritardo).+ doc: Consente di inviare più messaggi personali a un utente. Ogni PM può essere inviato con un ritardo.+ suspend_user_by_email:+ title: Sospendi utente per e-mail+ user_global_notice:+ title: Avviso globale agli utenti+ description: Consente di visualizzare un avviso globale per un utente+ user_group_membership_through_badge:+ title: Iscrizione al gruppo utenti tramite distintivo+ description: Modifica l'appartenenza al gruppo utenti in base a un distintivo+ suspend_user_by_email_with_api_call:+ doc: Quando si attiva `suspend_user_by_email` con una chiamata API, l'endpoint si aspetta un valore `email` valido nei parametri inviati. I parametri `reasons` e `suspend_until (formato ISO 8601)` possono anche essere usati per sovrascrivere i valori predefiniti dei campi.+ user_global_notice_with_stalled_topic:+ doc: Quando l'attivazione avviene tramite l'argomento bloccato, il proprietario dell'argomento riceverà l'avviso globale.+ user_global_notice_with_first_accepted_solution:+ doc: Quando attivato tramite la prima soluzione accettata, l'autore della soluzione riceverà l'avviso globale.+ send_pms_with_api_call:+ doc: Quando si utilizza lo script `send pms` con azione di attivazione `api call`, il parametro `usernames` della tua richiesta verrà utilizzato per riempire l'elenco dei destinatari.+ topic_required_words:+ title: Parole richieste per l'argomento+ description: Consente di definire un elenco di parole richieste su un argomento, almeno una delle quali deve essere utilizzata in ogni messaggio.+ doc: Le parole richieste per un argomento richiedono la definizione di un argomento. Quando un messaggio viene modificato/creato, esso sarà convalidato verificando che almeno una delle parole in elenco sia presente.+ errors:+ must_include_word: "Il messaggio deve includere almeno una di queste parole: %{words}"+ close_topic:+ title: Chiudi argomento+ description: Chiude un argomento con un messaggio di chiusura facoltativo+ append_last_edited_by:+ title: Aggiungi info ultima modifica di+ description: Aggiunge i dettagli di 'ultima modifica' del messaggio in coda al contenuto preparato.+ text: "Ultima modifica di @%{username} %{date_time}"+ append_last_checked_by:+ title: Aggiungi info ultimo controllo di+ description: Aggiunge i dettagli di 'ultimo controllo' del messaggio in coda al contenuto preparato.+ text: "Ultimo controllo di @%{username} %{date_time}"+ summary: Controlla documento+ details: "Esegue il controllo sul documento: "+ button_text: Fatto+ add_user_to_group_through_custom_field:+ title: "Aggiungi utente al gruppo tramite il campo personalizzato utente"+ group_category_notification_default:+ title: "Notifica predefinita per le categorie di gruppo"+ description: "Imposta il livello di notifica predefinito di una categoria per i membri di un gruppo"diff --git a/plugins/automation/config/locales/server.ja.yml b/plugins/automation/config/locales/server.ja.ymlnew file mode 100644index 00000000000..c7ba0e5ded9--- /dev/null+++ b/plugins/automation/config/locales/server.ja.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ja:+ site_settings:+ discourse_automation_enabled: "discourse-automation プラグインを有効にする"+ discourse_automation:+ models:+ fields:+ required_field: フィールド `%{name}` は `%{target}:%{target_name}` で入力する必要があります。+ invalid_field: フィールドのコンポーネント `%{component}` は `%{target}:%{target_name}` では使用できません。+ invalid_metadata: '`%{field}` のデータが無効であるか、コンポーネント `%{component}` が不明です。'+ triggerables:+ user_badge_granted:+ title: ユーザーバッチ付与+ doc: ユーザーがバッチを付与されると、自動化がトリガーされます。+ user_first_logged_in:+ title: ユーザーの初回ログイン+ doc: ユーザーが初めてログインするときに自動化をトリガーします。+ stalled_topic:+ title: トピックの失速+ doc: 特定の期間、トピックにトピック所有者からの新しい返信がない場合に自動化をトリガーします。影響を受けるトピック数が非常に高くなる可能性があるため、このトリガーの範囲をタグ/カテゴリに設定することをお勧めします。安全対策として、影響のあるトピック数は 250 に制限されています。+ api_call:+ title: API 呼び出し+ description: 自動化をトリガーする POST リクエストの作成+ doc: POST リクエストは、グローバル API キーを使用して `/automations/:id/trigger.json` に行う必要があります。+ category_created_edited:+ title: カテゴリの作成/編集+ description: カテゴリが作成または先週差あれると、自動化がトリガーされます+ recurring:+ title: 繰り返し+ point_in_time:+ title: 時点+ description: 日付に達すると、自動化がトリガーされます+ user_added_to_group:+ title: グループへのユーザーの追加+ description: ユーザーが特定のグループに追加されると、自動化がトリガーされます+ user_removed_from_group:+ title: グループからのユーザーの削除+ description: ユーザーが特定のグループから削除されると、自動化がトリガーされます+ user_promoted:+ title: ユーザー昇格+ description: ユーザーがある信頼レベルから別の信頼レベルに昇格したとき+ transition_placeholder: "%{from_level_name} から %{to_level_name}"+ stalled_wiki:+ title: Wiki の失速+ description: Wiki が所定の期間編集されていない場合、自動化がトリガーされます。+ post_created_edited:+ title: 投稿の作成/編集+ description: 有効な投稿が編集または作成されると、自動化がトリガーされます。+ pm_created:+ title: 個人メッセージの作成+ description: 有効な PM が作成されると、自動化がトリガーされます。+ topic:+ title: トピック+ description: 関連付けられたスクリプトは特定のトピックでのみ使用されます。これは、検証を行うスクリプトなどに役立ちます。+ after_post_cook:+ title: 投稿のクック処理後+ description: 投稿内容がクックされると、自動化がトリガーされます。+ scriptables:+ post:+ title: 投稿を作成する+ description: 指定されたトピックで投稿を作成します+ flag_post_on_words:+ title: 単語で投稿を通報する+ description: 投稿に指定された単語が含まれる場合に通報します+ flag_message: "投稿に許可されていない単語が含まれます: %{words}"+ doc: 特定の単語が一度にすべて含まれる投稿は通報され、非表示になります。複数の単語をカンマ区切りで定義すると、複合語として使用されることに注意してください(すべての語が存在する必要があります)。+ zapier_webhook:+ title: Zapier webhook+ description: トリガーのコンテキストを本体として zap を呼び出します+ auto_responder:+ title: 自動応答+ description: 指定されたキーワードを含む投稿に返信を投稿します+ auto_tag_topic:+ title: トピックにタグを自動設定+ description: トピックにタグを自動的に追加します+ pin_topic:+ title: トピックを固定+ description: 指定されたトピックを特定の日付に固定します+ banner_topic:+ title: バナーをトピックにする+ description: トピックをバナーにします+ gift_exchange:+ title: ギフト交換+ description: グループの 2 人のユーザーが匿名で互いにギフトを贈ることができます。+ doc: ギフト交換には、3 人以上のユーザーがいる既存のグループが必要です。選択した日に、一方がギフトを贈る側、もう一方がギフトを受ける側として、グループの各ユーザーがペアリングされます。+ send_pms:+ title: PM を送信する+ description: PM の送信を許可します(遅延の可能性があります)。+ doc: 複数の PM を 1 人のユーザーに送信できるようにします。各 PM は遅延を受け入れます。+ suspend_user_by_email:+ title: メールでユーザーを凍結する+ user_global_notice:+ title: ユーザーのグローバル通知+ description: ユーザーのグローバル通知を表示できるようにします+ user_group_membership_through_badge:+ title: バッジによるユーザーグループメンバーシップ+ description: バッジに基づいてユーザーグループのメンバーシップを変更します。+ suspend_user_by_email_with_api_call:+ doc: API 呼び出しで `suspend_user_by_email` をトリガーする場合、エンドポイントでは送信されたパラメーターに有効な `email` が存在することを必要としてます。デフォルトのフィールド値をオーバーライドするには、`reasons` と `suspend_until(ISO 8601 形式)` を使用することも可能です。+ user_global_notice_with_stalled_topic:+ doc: 失速したトピックからトリガーされると、トピック所有者はグローバル通知を受信します。+ user_global_notice_with_first_accepted_solution:+ doc: 最初に承諾されたソリューションからトリガーされると、ソリューション作成者はグローバル通知を受け取ります。+ send_pms_with_api_call:+ doc: '`api call` で `send pms` スクリプトを使用する場合、リクエストの `usernames` パラメーターが受信者リストの入力に使用されます。'+ topic_required_words:+ title: トピックの必須単語+ description: トピックに必要な単語のリストを定義できます。各投稿で少なくとも 1 つの単語が使用されている必要があります。+ doc: トピックの必須単語にはトピックが必要です。投稿が編集/作成されると、その投稿は単語のリストに対して検証されます。少なくとも 1 つの単語が存在する必要があります。+ errors:+ must_include_word: "投稿には、次の単語の少なくとも 1 つを含める必要があります: %{words}"+ close_topic:+ title: トピックを閉鎖+ description: オプションの閉鎖メッセージを添えてトピックを閉鎖します+ append_last_edited_by:+ title: 最終編集者を追加する+ description: '''最終編集者'' の詳細をクック済みコンテンツの下に追加します。'+ text: "最終編集者: %{username} %{date_time}"+ append_last_checked_by:+ title: 最終確認者を追加する+ description: '''最終確認者'' の詳細をクック済みコンテンツの下に追加します。'+ text: "最終確認者: @%{username} %{date_time}"+ summary: ドキュメントの確認+ details: "ドキュメントの確認を行います: "+ button_text: 完了+ add_user_to_group_through_custom_field:+ title: "ユーザーカスタムフィールドを介してグループにユーザーを追加する"+ group_category_notification_default:+ title: "グループカテゴリ通知のデフォルト"+ description: "グループのメンバーに対するカテゴリのデフォルトの通知レベルを設定します"diff --git a/plugins/automation/config/locales/server.ko.yml b/plugins/automation/config/locales/server.ko.ymlnew file mode 100644index 00000000000..18dd77fd3ec--- /dev/null+++ b/plugins/automation/config/locales/server.ko.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ko:diff --git a/plugins/automation/config/locales/server.lt.yml b/plugins/automation/config/locales/server.lt.ymlnew file mode 100644index 00000000000..16bb19758dc--- /dev/null+++ b/plugins/automation/config/locales/server.lt.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++lt:diff --git a/plugins/automation/config/locales/server.lv.yml b/plugins/automation/config/locales/server.lv.ymlnew file mode 100644index 00000000000..59e0ef6f4ed--- /dev/null+++ b/plugins/automation/config/locales/server.lv.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++lv:diff --git a/plugins/automation/config/locales/server.nb_NO.yml b/plugins/automation/config/locales/server.nb_NO.ymlnew file mode 100644index 00000000000..2e2224d1472--- /dev/null+++ b/plugins/automation/config/locales/server.nb_NO.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++nb_NO:diff --git a/plugins/automation/config/locales/server.nl.yml b/plugins/automation/config/locales/server.nl.ymlnew file mode 100644index 00000000000..c5f65b22954--- /dev/null+++ b/plugins/automation/config/locales/server.nl.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++nl:+ site_settings:+ discourse_automation_enabled: "Discourse-automatiseringsplug-in inschakelen"+ discourse_automation:+ models:+ fields:+ required_field: Veld '%{name}' moet worden ingevuld op '%{target}:%{target_name}'.+ invalid_field: Veldcomponent '%{component}' is niet bruikbaar op '%{target}:%{target_name}'.+ invalid_metadata: Gegevens voor '%{field}' zijn ongeldig of component '%{component}' is onbekend.+ triggerables:+ user_badge_granted:+ title: Gebruikersbadge toegekend+ doc: Triggert een automatisering als een gebruiker een badge krijgt.+ user_first_logged_in:+ title: Gebruiker voor het eerst ingelogd+ doc: Triggert een automatisering wanneer een gebruiker voor het eerst inlogt.+ stalled_topic:+ title: Stilgevallen topic+ doc: Triggert een automatisering wanneer het topic gedurende een bepaalde periode geen nieuw antwoord van de topiceigenaar heeft ontvangen. Het wordt aanbevolen om deze trigger in te stellen op een tag/categorie, aangezien het aantal getroffen topics erg hoog kan zijn. Uit veiligheidsoverwegingen is het aantal getroffen topics beperkt tot 250.+ api_call:+ title: API-aanroep+ description: Een POST-verzoek doen om een automatisering te triggeren+ doc: Het POST-verzoek moet worden gedaan aan '/automations/:id/trigger.json' met een globale API-sleutel.+ category_created_edited:+ title: Categorie gemaakt/bewerkt+ description: Wanneer een categorie wordt gemaakt of bewerkt, wordt de automatisering getriggerd+ recurring:+ title: Herhalend+ point_in_time:+ title: Tijdstip+ description: Wanneer de datum is bereikt, wordt de automatisering getriggerd+ user_added_to_group:+ title: Gebruiker toegevoegd aan groep+ description: Wanneer een gebruiker wordt toegevoegd aan de opgegeven groep, wordt de automatisering getriggerd+ user_removed_from_group:+ title: Gebruiker verwijderd uit groep+ description: Wanneer een gebruiker wordt verwijderd uit de opgegeven groep, wordt de automatisering getriggerd+ user_promoted:+ title: Gebruiker gepromoveerd+ description: Wanneer een gebruiker wordt gepromoveerd van het ene vertrouwensniveau naar het andere+ transition_placeholder: "van %{from_level_name} naar %{to_level_name}"+ stalled_wiki:+ title: Stilgevallen wiki+ description: Wanneer een wiki langer dan de gedefinieerde periode niet is bewerkt, wordt de automatisering getriggerd+ post_created_edited:+ title: Bericht gemaakt/bewerkt+ description: Wanneer een geldig bericht wordt bewerkt of gemaakt, wordt de automatisering getriggerd+ pm_created:+ title: Bericht gemaakt door medewerker+ description: Wanneer een geldig PB wordt gemaakt, wordt de automatisering getriggerd+ topic:+ title: Topic+ description: Het bijbehorende script wordt alleen gebruikt voor het opgegeven topic, dit is bijvoorbeeld handig voor scripts die validatie uitvoeren+ after_post_cook:+ title: Na finalisering bericht+ description: Wanneer de inhoud van een bericht wordt gefinaliseerd, wordt de automatisering getriggerd+ scriptables:+ post:+ title: Een bericht maken+ description: Maak een bericht over een bepaald topic+ flag_post_on_words:+ title: Bericht markeren bij woorden+ description: Markeert een bericht als het bepaalde woorden bevat+ flag_message: "Bericht bevat niet-toegestane woorden: %{words}"+ doc: Berichten die alle opgegeven woorden tegelijk bevatten, worden gemarkeerd en verborgen. Merk op dat het definiëren van meerdere woorden, gescheiden door een komma, wordt gebruikt als samenstelling (elk woord moet aanwezig zijn).+ zapier_webhook:+ title: Zapier-webhook+ description: Roept een zap aan met de context van een trigger als body+ auto_responder:+ title: Automatische beantwoorder+ description: Plaatst een antwoord op een bericht inclusief opgegeven trefwoorden+ auto_tag_topic:+ title: Topic automatisch taggen+ description: Voeg automatisch tags toe aan een topic+ pin_topic:+ title: Topic vastmaken+ description: Maakt een opgegeven topic vast op een bepaalde datum+ banner_topic:+ title: Bannertopic maken+ description: Maakt een banner van een topic+ gift_exchange:+ title: Cadeau-uitwisseling+ description: Maakt het mogelijk om gebruikers van een groep anoniem te koppelen om elkaar een cadeau te sturen.+ doc: Cadeau-uitwisseling vereist een bestaande groep met minimaal 3 gebruikers. Op de gekozen datum worden alle gebruikers van de groep gekoppeld aan één gever en één ontvanger.+ send_pms:+ title: PB's sturen+ description: Staat het sturen van PB's toe (mogelijk vertraagd).+ doc: Staat het sturen van meerdere PB's naar een gebruiker toe. Elk PB krijgt een vertraging.+ suspend_user_by_email:+ title: Gebruiker schorsen op e-mailadres+ user_global_notice:+ title: Algemene kennisgeving voor gebruiker+ description: Maakt het mogelijk om een globale kennisgeving weer te geven voor een gebruiker+ user_group_membership_through_badge:+ title: Lidmaatschap van gebruikersgroep via badge+ description: Wijzig het lidmaatschap van een gebruikersgroep op basis van een badge+ suspend_user_by_email_with_api_call:+ doc: Bij het triggeren van 'suspend_user_by_email' met een API-aanroep, verwacht het eindpunt dat er een geldige 'email' aanwezig is in de verzonden parameters. 'reasons' en 'suspend_until' (ISO 8601-notatie) kunnen ook worden gebruikt om standaardveldwaarden te overschrijven.+ user_global_notice_with_stalled_topic:+ doc: Indien getriggerd via stilgevallen topic, ontvangt de topiceigenaar de algemene melding.+ user_global_notice_with_first_accepted_solution:+ doc: Indien getriggerd via eerst geaccepteerde oplossing, ontvangt de auteur van de oplossing de algemene melding.+ send_pms_with_api_call:+ doc: Wanneer je het 'send pms'-script gebruikt met de 'api call'-trigger, wordt de parameter 'usernames' van je verzoek gebruikt om de lijst van ontvangers te vullen.+ topic_required_words:+ title: Topic vereist woorden+ description: Maakt het mogelijk om een lijst van vereiste woorden te definiëren voor een topic. In elk bericht moet er minimaal één worden gebruikt.+ doc: Topic vereist woorden. Wanneer een bericht wordt gemaakt/bewerkt, wordt het bericht gevalideerd aan de hand van de lijst van woorden, er moet er minimaal één aanwezig zijn.+ errors:+ must_include_word: "Bericht moet minimaal één van deze woorden bevatten: %{words}"+ close_topic:+ title: Topic sluiten+ description: Sluit een topic met een optioneel sluitingsbericht+ append_last_edited_by:+ title: Laatst bewerkt door toevoegen+ description: Voegt de 'laatst bewerkt door'-gegevens van het bericht toe onderaan de gefinaliseerde inhoud.+ text: "Laatst bewerkt door @%{username} %{date_time}"+ append_last_checked_by:+ title: Laatst gecontroleerd door toevoegen+ description: Voegt de 'laatst gecontroleerd door'-gegevens van het bericht toe onderaan de gefinaliseerde inhoud.+ text: "Laatst gecontroleerd door @%{username} %{date_time}"+ summary: Document controleren+ details: "Controle uitvoeren op document: "+ button_text: Gereed+ add_user_to_group_through_custom_field:+ title: "Gebruiker toevoegen aan groep via Aangepast veld"+ group_category_notification_default:+ title: "Standaard categoriemelding groep"+ description: "Stel het standaard meldingsniveau van een categorie in voor leden van een groep"diff --git a/plugins/automation/config/locales/server.pl_PL.yml b/plugins/automation/config/locales/server.pl_PL.ymlnew file mode 100644index 00000000000..a260c31c64c--- /dev/null+++ b/plugins/automation/config/locales/server.pl_PL.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++pl_PL:diff --git a/plugins/automation/config/locales/server.pt.yml b/plugins/automation/config/locales/server.pt.ymlnew file mode 100644index 00000000000..298ba523c1d--- /dev/null+++ b/plugins/automation/config/locales/server.pt.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++pt:diff --git a/plugins/automation/config/locales/server.pt_BR.yml b/plugins/automation/config/locales/server.pt_BR.ymlnew file mode 100644index 00000000000..b2bc4118ccb--- /dev/null+++ b/plugins/automation/config/locales/server.pt_BR.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++pt_BR:+ site_settings:+ discourse_automation_enabled: "Habilitar plugin discourse-automation"+ discourse_automation:+ models:+ fields:+ required_field: O campo `%{name}` deve ser preenchido em `%{target}:%{target_name}`.+ invalid_field: O componente do campo `%{component}` não pode ser usado em `%{target}:%{target_name}.`+ invalid_metadata: Os dados para `%{field}` são inválidos ou o componente `%{component}` é desconhecido.+ triggerables:+ user_badge_granted:+ title: Emblema de usuário concedido+ doc: Aciona uma automação quando um usuário recebe um emblema.+ user_first_logged_in:+ title: Usuário(a) logado(a) pela primeira vez+ doc: Aciona uma automação quando um(a) usuário(a) fizer login pela primeira vez.+ stalled_topic:+ title: Tópico parado+ doc: Aciona uma automação quando o tópico não recebe uma nova resposta do proprietário do tópico por um período de tempo especificado. É recomendável definir o escopo desse acionador para uma tag/categoria, pois o número de tópicos impactados pode ser muito alto. Como medida de segurança, o número de tópicos impactados é limitado a 250.+ api_call:+ title: Chamada de API+ description: Fazendo uma solicitação POSTAGEM para acionar uma automação+ doc: A solicitação POSTAGEM deve ser feita para `/automations/:id/trigger.json` com uma chave de API global.+ category_created_edited:+ title: Categoria criada/editada+ description: Quando uma categoria for criada ou editada, a automação será acionada+ recurring:+ title: Recorrente+ point_in_time:+ title: Ponto no tempo+ description: Quando a data for atingida, a automação será acionada+ user_added_to_group:+ title: Usuário adicionado ao grupo+ description: Quando um usuário é adicionado ao grupo especificado, a automação será acionada+ user_removed_from_group:+ title: Usuário removido do grupo+ description: Quando um usuário for removido do grupo especificado, a automação será acionada+ user_promoted:+ title: Usuário promovido+ description: Quando um usuário é promovido de um nível de confiança para outro+ transition_placeholder: "de %{from_level_name} a %{to_level_name}"+ stalled_wiki:+ title: Wiki parada+ description: Quando uma wiki não for editada por um período maior que o definido, a automação será acionada+ post_created_edited:+ title: Postagem criada/editada+ description: Quando uma postagem válida for editada ou criada, a automação será acionada+ pm_created:+ title: Mensagem pessoal criada+ description: Quando uma PM válida for criada, a automação será acionada+ topic:+ title: Tópico+ description: O script associado será usado apenas no tópico especificado, isso é útil para scripts fazendo validação, por exemplo+ after_post_cook:+ title: Depois da falsificação da postagem+ description: Quando o conteúdo de uma postagem for falsificado, a automação será acionada+ scriptables:+ post:+ title: Criar uma postagem+ description: Criar uma postagem em um tópico específico+ flag_post_on_words:+ title: Sinalizar postagem em palavras+ description: Sinaliza uma postagem se ela contiver palavras especificadas+ flag_message: "A postagem contém palavras não permitidas: %{words}"+ doc: A postagem contendo todas as palavras dadas de uma só vez será sinalizada e ocultada. Observe que definir várias palavras delimitadas por uma vírgula será usado como composto (cada palavra deve estar presente).+ zapier_webhook:+ title: Zapier webhook+ description: Chama um zap com o contexto de um acionador como corpo+ auto_responder:+ title: Respondente automático+ description: Publica uma resposta a uma postagem incluindo palavras-chave especificadas+ auto_tag_topic:+ title: Marcar tópico automaticamente+ description: Adiciona automaticamente tags a um tópico+ pin_topic:+ title: Fixar Tópico+ description: Fixa um tópico especificado em uma determinada data+ banner_topic:+ title: Criar tópico de banner+ description: Transforme um tópico em um banner+ gift_exchange:+ title: Troca de presentes+ description: Permite emparelhar anonimamente os usuários de um grupo para enviar um presente um ao outro.+ doc: A troca de presentes requer um grupo existente com pelo menos 3 usuários. Na data escolhida, cada usuário do grupo será pareado com um presenteador e um presenteado.+ send_pms:+ title: Enviar pms+ description: Permite o envio de PMs (possivelmente atrasados).+ doc: Permite enviar várias pms para um usuário. Cada PM aceita um atraso.+ suspend_user_by_email:+ title: Suspender usuário por e-mail+ user_global_notice:+ title: Aviso global do usuário+ description: Permite exibir um aviso global para um usuário+ user_group_membership_through_badge:+ title: Assinatura de grupo de usuário(a) sem emblema+ description: Modificar assinatura de grupo de usuário(a) com base no emblema+ suspend_user_by_email_with_api_call:+ doc: Ao acionar `suspend_user_by_email` com uma chamada de API, o endpoint espera que um `email` válido esteja presente nos parâmetros enviados. `reasons` e `suspend_until (formato ISO 8601)` também podem ser usados para substituir valores de campos padrão.+ user_global_notice_with_stalled_topic:+ doc: Quando acionado por meio de um tópico parado, o proprietário do tópico receberá o aviso global.+ user_global_notice_with_first_accepted_solution:+ doc: Quando acionado(a) através da primera solução aceita, o(a) autor(a) da solução receberá o aviso global.+ send_pms_with_api_call:+ doc: Ao usar o script `send pms` com o acionador `api call`, o parâmetro `usernames` da sua solicitação será usado para preencher a lista de receptores.+ topic_required_words:+ title: Palavras obrigatórias do tópico+ description: Permite definir uma lista de palavras obrigatórias em um tópico, pelo menos uma deve ser usada em cada postagem.+ doc: As palavras obrigatórias do tópico requerem um tópico. Quando uma postagem for editada/criada, a postagem será validada em relação à lista de palavras, pelo menos uma deve estar presente.+ errors:+ must_include_word: "A postagem deve incluir pelo menos uma destas palavras: %{words}"+ close_topic:+ title: Fechar Tópico+ description: Fecha um tópico com uma mensagem de fechamento opcional+ append_last_edited_by:+ title: Anexar última edição por+ description: Adiciona os detalhes de 'última edição por' da postagem na parte inferior do conteúdo preparado.+ text: "Última edição por @%{username} %{date_time}"+ append_last_checked_by:+ title: Anexar última verificação por+ description: Adiciona os detalhes de 'última verificação por' da postagem na parte inferior do conteúdo preparado.+ text: "Última verificação por @%{username} %{date_time}"+ summary: Verificar documento+ details: "Realizar verificação no documento: "+ button_text: Concluído+ add_user_to_group_through_custom_field:+ title: "Adicionar usuário ao grupo por meio do campo personalizado do usuário"+ group_category_notification_default:+ title: "Notificação de categoria de grupo por padrão"+ description: "Definir o nível de notificação padrão de uma categoria para membros de um grupo"diff --git a/plugins/automation/config/locales/server.ro.yml b/plugins/automation/config/locales/server.ro.ymlnew file mode 100644index 00000000000..08a77f812ee--- /dev/null+++ b/plugins/automation/config/locales/server.ro.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ro:diff --git a/plugins/automation/config/locales/server.ru.yml b/plugins/automation/config/locales/server.ru.ymlnew file mode 100644index 00000000000..fe28438f992--- /dev/null+++ b/plugins/automation/config/locales/server.ru.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ru:+ site_settings:+ discourse_automation_enabled: "Включить плагин «discourse-automation»"+ discourse_automation:+ models:+ fields:+ required_field: 'Поле `%{name}` должно быть заполнено: `%{target}:%{target_name}`.'+ invalid_field: 'Компонент поля `%{component}` не подходит: `%{target}:%{target_name}`.'+ invalid_metadata: Данные для поля `%{field}` недействительны или компонент `%{component}` неизвестен.+ triggerables:+ user_badge_granted:+ title: Выдана награда пользователя+ doc: Запускает автоматизацию, когда пользователю выдаётся награда.+ user_first_logged_in:+ title: Первый вход пользователя в систему+ doc: Запускает автоматизацию, когда пользователь впервые выполняет вход.+ stalled_topic:+ title: Неактивная тема+ doc: 'Запускает автоматизацию, если тема не получает новые ответы от автора в течение указанного времени. Рекомендуется ограничить этот триггер по тегу или категории: количество затронутых тем может быть очень большим. В качестве меры предосторожности максимальное количество затрагиваемых тем — 250.'+ api_call:+ title: Вызов API+ description: Выполнение POST-запроса для запуска автоматизации+ doc: POST-запрос должен быть сделан на `/automations/:id/trigger.json` с глобальным ключом API.+ category_created_edited:+ title: Категория создана (изменена)+ description: Автоматизация будет запущена при создании или изменении категории+ recurring:+ title: Повторение+ point_in_time:+ title: Момент времени+ description: Автоматизация будет запущена по достижении указанной даты+ user_added_to_group:+ title: Пользователь добавлен в группу+ description: Автоматизация будет запущена, когда в указанную группу будет добавлен пользователь+ user_removed_from_group:+ title: Пользователь удален из группы+ description: Автоматизация будет запущена, когда из указанной группы будет удален пользователь+ user_promoted:+ title: Пользователь повышен+ description: При повышении уровня доверия пользователя+ transition_placeholder: "с %{from_level_name} до %{to_level_name}"+ stalled_wiki:+ title: Неактивная вики-запись+ description: Автоматизация будет запущена, если вики-запись не редактировалась в течение указанного периода+ post_created_edited:+ title: Запись создана (отредактирована)+ description: Автоматизация будет запущена, когда будет отредактирована или создана соответствующая требованиям запись+ pm_created:+ title: Создано личное сообщение+ description: Автоматизация будет запущена, когда будет создано соответствующее требованиям ЛС+ topic:+ title: Тема+ description: Связанный скрипт будет использоваться только в указанной теме (например, это удобно для скриптов, выполняющих проверку)+ after_post_cook:+ title: После финализации записи+ description: Автоматизация будет запущена, когда будет финализирован контент записи+ scriptables:+ post:+ title: Создать запись+ description: Создать запись на указанную тему+ flag_post_on_words:+ title: Пожаловаться на запись по словам+ description: Пожаловаться на запись, если она содержит указанные слова+ flag_message: "Запись содержит запрещенные слова: %{words}"+ doc: Запись, содержащая сразу все указанные слова, получит жалобу и будет скрыта. Разделенные запятыми слова считаются составным условием (должно присутствовать каждое слово).+ zapier_webhook:+ title: Вебхук Zapier+ description: Вызывает зап с контекстом триггера в качестве тела сообщения+ auto_responder:+ title: Автоответчик+ description: Публикует ответ, если запись содержит указанные ключевые слова+ auto_tag_topic:+ title: Автодобавление тегов к темам+ description: Автоматически добавлять теги в тему+ pin_topic:+ title: Закрепить тему+ description: Закрепляет указанную тему в указанную дату+ banner_topic:+ title: Сделать баннером+ description: Преобразовать тему в баннер+ gift_exchange:+ title: Обмен подарками+ description: Позволяет анонимно связывать пользователей группы для отправки друг другу подарков.+ doc: Для обмена подарками нужна группа как минимум из трех пользователей. В указанную дату каждый пользователь группы будет связан с одним дарителем и одним дарящим.+ send_pms:+ title: Отправить ЛС+ description: Позволяет отправлять личные сообщения (можно с задержкой).+ doc: Позволяет отправлять пользователю несколько личных сообщений. Каждое ЛС может быть отправлено с задержкой.+ suspend_user_by_email:+ title: Заморозить пользователя по адресу эл. почты+ user_global_notice:+ title: Глобальное уведомление пользователей+ description: Позволяет отобразить пользователю глобальное уведомление+ user_group_membership_through_badge:+ title: Участие в группе пользователей на основе награды+ description: Изменить участие в группе пользователей на основе награды+ suspend_user_by_email_with_api_call:+ doc: При запуске `suspend_user_by_email` с помощью вызова API конечная точка ожидает, что в передаваемых параметрах будет присутствовать правильный адрес `email`. Причины `reasons` и время `suspend_until` (в формате ISO 8601) также могут быть использованы для переопределения значений по умолчанию.+ user_global_notice_with_stalled_topic:+ doc: При запуске по неактивной теме владелец темы получит глобальное уведомление.+ user_global_notice_with_first_accepted_solution:+ doc: При запуске по первому принятому решению автор решения получит глобальное уведомление.+ send_pms_with_api_call:+ doc: При использовании скрипта `send pms` с триггером `api call` параметр `usernames` запроса будет использоваться для заполнения списка получателей.+ topic_required_words:+ title: Обязательные слова для темы+ description: Список слов, которые должны быть в теме. В каждой записи должно использоваться как минимум одно слово.+ doc: 'Для обязательных слов нужно указать тему. Когда запись редактируется или создается, она проверяется на соответствие списку слов: должно присутствовать хотя бы одно из них.'+ errors:+ must_include_word: "Запись должна содержать как минимум одно из этих слов: %{words}"+ close_topic:+ title: Закрыть тему+ description: Закрывает тему; можно указать сообщение о закрытии+ append_last_edited_by:+ title: Добавить данные о последней правке+ description: Внизу финализированного контента добавляет сведения о том, кем запись последний раз редактировалась.+ text: "Последняя правка: @%{username} %{date_time}"+ append_last_checked_by:+ title: Добавить данные о последней проверке+ description: Внизу финализированного контента добавляет сведения о том, кем запись последний раз проверялась.+ text: "Последняя проверка: @%{username} %{date_time}"+ summary: Проверить документ+ details: "Выполнить проверку документа: "+ button_text: Готово+ add_user_to_group_through_custom_field:+ title: "Добавить пользователя в группу через настраиваемое поле пользователя"+ group_category_notification_default:+ title: "Уведомления по умолчанию для категории группы"+ description: "Уровень уведомлений по умолчанию в категории для участников группы."diff --git a/plugins/automation/config/locales/server.sk.yml b/plugins/automation/config/locales/server.sk.ymlnew file mode 100644index 00000000000..6f815624081--- /dev/null+++ b/plugins/automation/config/locales/server.sk.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sk:diff --git a/plugins/automation/config/locales/server.sl.yml b/plugins/automation/config/locales/server.sl.ymlnew file mode 100644index 00000000000..23489a48b1f--- /dev/null+++ b/plugins/automation/config/locales/server.sl.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sl:diff --git a/plugins/automation/config/locales/server.sq.yml b/plugins/automation/config/locales/server.sq.ymlnew file mode 100644index 00000000000..7f051b7a7cf--- /dev/null+++ b/plugins/automation/config/locales/server.sq.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sq:diff --git a/plugins/automation/config/locales/server.sr.yml b/plugins/automation/config/locales/server.sr.ymlnew file mode 100644index 00000000000..88d63d6ae1a--- /dev/null+++ b/plugins/automation/config/locales/server.sr.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sr:diff --git a/plugins/automation/config/locales/server.sv.yml b/plugins/automation/config/locales/server.sv.ymlnew file mode 100644index 00000000000..df950627733--- /dev/null+++ b/plugins/automation/config/locales/server.sv.yml@@ -0,0 +1,74 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sv:+ site_settings:+ discourse_automation_enabled: "Aktivera discourse-automation plugin"+ discourse_automation:+ triggerables:+ user_badge_granted:+ title: Användarmärke beviljat+ doc: Utlöser en automatisering när en användare tilldelas ett märke.+ api_call:+ title: API-anrop+ description: Gör en POST-förfrågan för att utlösa en automatisering+ doc: POST-förfrågan ska göras till `/automations/:id/trigger.json` med en global API-nyckel.+ recurring:+ title: Återkommande+ point_in_time:+ title: Tidpunkt+ description: När datumet har nåtts kommer automatiseringen att utlösas+ user_added_to_group:+ title: Användare tillagd i grupp+ description: När en användare läggs till i den angivna gruppen kommer automatiseringen att utlösas+ user_removed_from_group:+ title: Användare borttagen från gruppen+ description: När en användare tas bort från den angivna gruppen utlöses automatiseringen.+ user_promoted:+ title: Användare befordrad+ description: När en användare befordras från en förtroendenivå till en annan+ transition_placeholder: "från %{from_level_name} till %{to_level_name}"+ stalled_wiki:+ description: När en wiki inte har redigerats under en längre period än den som definierats, aktiveras automatiseringen.+ post_created_edited:+ title: Inlägg skapat/redigerat+ description: När ett giltigt inlägg redigeras eller skapas kommer automatiseringen att utlösas+ pm_created:+ title: Personligt meddelande skapat+ topic:+ title: Ämne+ scriptables:+ auto_responder:+ title: Automatiskt svar+ description: Skickar ett svar på ett inlägg inklusive specificerade nyckelord+ pin_topic:+ title: Fäst ämne+ description: Fäster ett angivet ämne vid ett visst datum+ banner_topic:+ title: Omvandla en banner till ett ämne+ description: Omvandla ett ämne till en banner+ send_pms:+ title: Skicka PM+ description: Tillåter att skicka PMs (eventuellt fördröjt).+ doc: Gör det möjligt att skicka flera PM till en användare. Varje PM accepterar en fördröjning.+ suspend_user_by_email:+ title: Stäng av användare via e-post+ topic_required_words:+ title: Obligatoriska ord för ämnet+ close_topic:+ title: Stäng ämne+ description: Stänger ett ämne med ett valfritt avslutningsmeddelande+ append_last_edited_by:+ title: Lägg till senast redigerad av+ text: "Senast redigerad av @%{username} %{date_time}"+ append_last_checked_by:+ title: Lägg till senast kontrollerad av+ text: "Senast kontrollerad av @%{username} %{date_time}"+ summary: Kontrollera dokument+ details: "Utför kontroll av dokument: "+ button_text: Klar+ add_user_to_group_through_custom_field:+ title: "Lägg till användare till grupp genom användaranpassat fält"diff --git a/plugins/automation/config/locales/server.sw.yml b/plugins/automation/config/locales/server.sw.ymlnew file mode 100644index 00000000000..0d7cdd075bf--- /dev/null+++ b/plugins/automation/config/locales/server.sw.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++sw:diff --git a/plugins/automation/config/locales/server.te.yml b/plugins/automation/config/locales/server.te.ymlnew file mode 100644index 00000000000..03967bdbb07--- /dev/null+++ b/plugins/automation/config/locales/server.te.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++te:diff --git a/plugins/automation/config/locales/server.th.yml b/plugins/automation/config/locales/server.th.ymlnew file mode 100644index 00000000000..7de85ff91c4--- /dev/null+++ b/plugins/automation/config/locales/server.th.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++th:diff --git a/plugins/automation/config/locales/server.tr_TR.yml b/plugins/automation/config/locales/server.tr_TR.ymlnew file mode 100644index 00000000000..5a76a498e3a--- /dev/null+++ b/plugins/automation/config/locales/server.tr_TR.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++tr_TR:+ site_settings:+ discourse_automation_enabled: "discourse-automation eklentisini etkinleştirin"+ discourse_automation:+ models:+ fields:+ required_field: '"%{name}" alanı "%{target}:%{target_name}" üzerinde doldurulmalıdır.'+ invalid_field: Alanın bileşeni "%{component}", "%{target}:%{target_name}" üzerinde kullanılamaz.+ invalid_metadata: '"%{field}" için veriler geçersiz veya "%{component}" bileşeni bilinmiyor.'+ triggerables:+ user_badge_granted:+ title: Kullanıcı rozeti verildi+ doc: Bir kullanıcıya rozet verildiğinde bir otomasyonu tetikler.+ user_first_logged_in:+ title: Kullanıcı ilk kez giriş yaptı+ doc: Bir kullanıcı ilk kez giriş yaptığında bir otomasyonu tetikler.+ stalled_topic:+ title: Durmuş konu+ doc: Konu, belirli bir süre boyunca konu sahibinden yeni bir yanıt almadığında bir otomasyonu tetikler. Etkilenen konu sayısı çok yüksek olabileceğinden, bu tetikleyicinin bir etiket/kategoriyi kapsaması önerilir. Bir güvenlik önlemi olarak, etkilenen konu sayısı 250 ile sınırlandırılmıştır.+ api_call:+ title: API çağrısı+ description: Bir otomasyonu tetiklemek için GÖNDERİ talebi yapma+ doc: GÖNDERİ talebi global bir API anahtarı ile "/automations/:id/trigger.json" adresine yapılmalıdır.+ category_created_edited:+ title: Kategori oluşturuldu/düzenlendi+ description: Bir kategori oluşturulduğunda veya düzenlendiğinde otomasyon tetiklenir+ recurring:+ title: Yinelenen+ point_in_time:+ title: Zaman içinde nokta+ description: Tarihe ulaşıldığında otomasyon tetiklenir+ user_added_to_group:+ title: Kullanıcı gruba eklendi+ description: Belirtilen gruba bir kullanıcı eklendiğinde otomasyon tetiklenir+ user_removed_from_group:+ title: Kullanıcı gruptan çıkarıldı+ description: Bir kullanıcı belirtilen gruptan çıkarıldığında otomasyon tetiklenir+ user_promoted:+ title: Kullanıcı yükseltildi+ description: Bir kullanıcı bir güven seviyesinden diğerine yükseldiğinde+ transition_placeholder: "%{from_level_name} seviyesinden %{to_level_name} seviyesine"+ stalled_wiki:+ title: Durmuş viki+ description: Bir viki tanımlanandan daha uzun bir süre boyunca düzenlenmediğinde otomasyon tetiklenir+ post_created_edited:+ title: Gönderi oluşturuldu/düzenlendi+ description: Geçerli bir gönderi düzenlendiğinde veya oluşturulduğunda otomasyon tetiklenir+ pm_created:+ title: Kişisel mesaj oluşturuldu+ description: Geçerli bir kişisel mesaj oluşturulduğunda otomasyon tetiklenir+ topic:+ title: Konu+ description: İlişkili komut dosyası yalnızca belirtilen konuda kullanılır, bu, örneğin doğrulama yapan komut dosyaları için kullanışlıdır+ after_post_cook:+ title: Gönderi finalize edildikten sonra+ description: Bir gönderi içeriği hazırlandığında otomasyon tetiklenir+ scriptables:+ post:+ title: Gönderi oluştur+ description: Belirli bir konuda gönderi oluşturun+ flag_post_on_words:+ title: Kelimeler üzerine gönderiye bayrak ekle+ description: Belirtilen kelimeleri içeriyorsa bir gönderiye bayrak ekler+ flag_message: "Gönderi izin verilmeyen kelimeler içeriyor: %{words}"+ doc: Verilen tüm kelimeleri aynı anda içeren gönderiye bayrak eklenir ve gönderi gizlenir. Virgülle ayrılan birden fazla kelime tanımlamanın birleşik olarak kullanılacağını unutmayın (her kelime mevcut olmalı).+ zapier_webhook:+ title: Zapier web kancası+ description: Gövde olarak bir tetikleyici bağlamıyla bir zap çağırır+ auto_responder:+ title: Otomatik Yanıtlayıcı+ description: Belirtilen anahtar kelimeleri içeren bir gönderiye yanıt gönderir+ auto_tag_topic:+ title: Konuyu Otomatik Etiketle+ description: Bir konuya otomatik olarak etiket ekleyin+ pin_topic:+ title: Konuyu Sabitle+ description: Belirli bir konuyu belirli bir tarihte sabitler+ banner_topic:+ title: Banner konusu yap+ description: Bir konuyu banner'a dönüştürün+ gift_exchange:+ title: Hediye değiş tokuşu+ description: Birbirlerine hediye göndermeleri için bir grubun kullanıcılarını anonim olarak eşleştirmeye izin verir.+ doc: Hediye değiş tokuşu en az 3 kullanıcısı olan mevcut bir grup gerektirir. Seçilen tarihte grubun her kullanıcısı bir hediye veren ve bir hediye alan ile eşleştirilir.+ send_pms:+ title: Özel mesaj gönder+ description: Özel mesaj gönderilmesine izin verir+ doc: Bir kullanıcıya birden fazla özel mesaj gönderilmesine izin verir. Her özel mesaj bir gecikme kabul eder.+ suspend_user_by_email:+ title: Kullanıcıyı e-posta ile askıya al+ user_global_notice:+ title: Kullanıcı küresel bildirimi+ description: Bir kullanıcı için genel bir bildirim görüntülemeye izin verir+ user_group_membership_through_badge:+ title: Rozet ile Kullanıcı Grubu Üyeliği+ description: Kullanıcı grubu üyeliğini rozete göre değiştir+ suspend_user_by_email_with_api_call:+ doc: Bir api çağrısı ile "suspend_user_by_email" tetiklendiğinde, uç nokta gönderilen parametreleri içinde geçerli bir "email" bulunmasını bekler. "reasons" ve "suspend_until (ISO 8601 format)" de varsayılan alan değerlerini geçersiz kılmak için kullanılabilir.+ user_global_notice_with_stalled_topic:+ doc: Durdurulan konu üzerinden tetiklendiğinde, konu sahibi genel bildirimi alır.+ user_global_notice_with_first_accepted_solution:+ doc: İlk kabul edilen çözüm aracılığıyla tetiklendiğinde, çözüm yazarı genel bildirimi alır.+ send_pms_with_api_call:+ doc: '"api call" tetikleyicisi ile "send pms" komut dosyasını kullanırken, alıcı listesini doldurmak için isteğinizin "usernames" parametresi kullanılır.'+ topic_required_words:+ title: Konu gerekli kelimeler+ description: Bir konuda gerekli olan kelimelerin bir listesini tanımlamaya izin verir, her gönderide en az bir tane kullanılmalıdır.+ doc: Konu gerekli kelimeler bir konu gerektirir. Bir gönderi düzenlendiğinde/oluşturulduğunda, gönderi kelime listesine göre doğrulanır, en az bir kelime bulunmalıdır.+ errors:+ must_include_word: "Gönderi bu kelimelerden en az birini içermelidir: %{words}"+ close_topic:+ title: Konuyu Kapat+ description: Bir konuyu isteğe bağlı bir kapanış mesajıyla kapatır+ append_last_edited_by:+ title: Son düzenleyeni ekle+ description: Gönderinin "son düzenleyen" bilgilerini pişmiş içeriğin altına ekler.+ text: "Son düzenleyen: @%{username} %{date_time}"+ append_last_checked_by:+ title: Son kontrol edeni ekle+ description: Pişmiş içeriğin alt kısmına "son kontrol eden" bilgilerini ekler.+ text: "Son kontrol eden: @%{username} %{date_time}"+ summary: Belgeyi kontrol et+ details: "Belge üzerinde kontrol gerçekleştirin: "+ button_text: Bitti+ add_user_to_group_through_custom_field:+ title: "Kullanıcı Özel Alanı aracılığıyla gruba kullanıcı ekleyin"+ group_category_notification_default:+ title: "Grup Kategorisi Bildirimi Varsayılan"+ description: "Bir grubun üyeleri için bir kategorinin varsayılan bildirim seviyesini ayarlayın"diff --git a/plugins/automation/config/locales/server.uk.yml b/plugins/automation/config/locales/server.uk.ymlnew file mode 100644index 00000000000..f1390545d1d--- /dev/null+++ b/plugins/automation/config/locales/server.uk.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++uk:diff --git a/plugins/automation/config/locales/server.ur.yml b/plugins/automation/config/locales/server.ur.ymlnew file mode 100644index 00000000000..b4a9c21ee2f--- /dev/null+++ b/plugins/automation/config/locales/server.ur.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++ur:diff --git a/plugins/automation/config/locales/server.vi.yml b/plugins/automation/config/locales/server.vi.ymlnew file mode 100644index 00000000000..f629dcf5329--- /dev/null+++ b/plugins/automation/config/locales/server.vi.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++vi:diff --git a/plugins/automation/config/locales/server.zh_CN.yml b/plugins/automation/config/locales/server.zh_CN.ymlnew file mode 100644index 00000000000..47273257eb2--- /dev/null+++ b/plugins/automation/config/locales/server.zh_CN.yml@@ -0,0 +1,135 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++zh_CN:+ site_settings:+ discourse_automation_enabled: "启用 discourse-automation 插件"+ discourse_automation:+ models:+ fields:+ required_field: 必须在 `%{target}:%{target_name}` 上填写字段 `%{name}`。+ invalid_field: 字段的组件 `%{component}` 在 `%{target}:%{target_name}` 上不可用。+ invalid_metadata: '`%{field}` 的数据无效或组件 `%{component}` 未知。'+ triggerables:+ user_badge_granted:+ title: 授予用户徽章+ doc: 当用户被授予徽章时触发自动化。+ user_first_logged_in:+ title: 用户首次登录+ doc: 当用户首次登录时触发自动化。+ stalled_topic:+ title: 停止话题+ doc: 当话题在指定时间段内未收到话题所有者的新回复时会触发自动化。建议将此触发器的范围限定为标签/类别,因为受影响的话题数量可能会非常多。作为一项安全措施,受影响话题的数量上限为 250 个。+ api_call:+ title: API 调用+ description: 发出 POST 请求来触发自动化+ doc: 应使用全局 API 密钥将 POST 请求发送到 `/automations/:id/trigger.json`。+ category_created_edited:+ title: 创建/编辑类别+ description: 创建或编辑类别时将触发自动化+ recurring:+ title: 重复+ point_in_time:+ title: 时间点+ description: 当达到某个日期时,触发自动化+ user_added_to_group:+ title: 用户被添加到群组+ description: 当用户被添加到指定群组时,触发自动化+ user_removed_from_group:+ title: 用户被从群组中移除+ description: 当用户被从指定群组中移除时,触发自动化+ user_promoted:+ title: 用户被提升+ description: 当用户被从一个信任级别提升到另一个信任级别时+ transition_placeholder: "从 %{from_level_name} 到 %{to_level_name}"+ stalled_wiki:+ title: 停止 Wiki+ description: 当 Wiki 未被编辑的时间超过定义的时间时,触发自动化+ post_created_edited:+ title: 帖子被创建/编辑+ description: 当有效的帖子被编辑或创建时,触发自动化+ pm_created:+ title: 个人消息被创建+ description: 当有效的 PM 被创建时,触发自动化+ topic:+ title: 话题+ description: 关联的脚本将仅用于指定的话题,这对于执行验证的脚本十分有用+ after_post_cook:+ title: 处理帖子后+ description: 当帖子内容被处理时,触发自动化+ scriptables:+ post:+ title: 创建帖子+ description: 在指定话题上创建帖子+ flag_post_on_words:+ title: 基于字词举报帖子+ description: 如果帖子包含指定字词,则举报它+ flag_message: "帖子包含不允许的字词:%{words}"+ doc: 同时包含所有给定字词的帖子将被举报和隐藏。请注意,定义由逗号分隔的多个字词将用作复合词(每个字词都必须存在)。+ zapier_webhook:+ title: Zapier 网络钩子+ description: 以触发器的上下文为正文调用 zap+ auto_responder:+ title: 自动回复器+ description: 对包含指定关键字的帖子发布回复+ auto_tag_topic:+ title: 自动为话题添加标签+ description: 自动为话题添加标签+ pin_topic:+ title: 置顶话题+ description: 在给定日期置顶指定话题+ banner_topic:+ title: 将横幅设置为话题+ description: 将话题设置成横幅+ gift_exchange:+ title: 礼物交换+ description: 允许以匿名方式配对群组中的用户以互相发送礼物。+ doc: 礼物交换需要一个至少包含 3 个用户的现有群组。在选定日期,该群组的每个用户都将与一名赠送者和一名受赠者配对。+ send_pms:+ title: 发送 PM+ description: 允许发送 PM(可能存在延迟)。+ doc: 允许向用户发送多条 PM。每条 PM 都接受延迟。+ suspend_user_by_email:+ title: 通过电子邮件暂停用户+ user_global_notice:+ title: 用户全局通知+ description: 允许为用户显示全局通知+ user_group_membership_through_badge:+ title: 通过徽章获得用户群组成员资格+ description: 根据徽章修改用户群组成员关系+ suspend_user_by_email_with_api_call:+ doc: 当使用 API 调用触发 `suspend_user_by_email` 时,端点期望发送的参数中存在有效的 `email`。`reasons` 和 `suspend_until (ISO 8601 format)` 也可以用于重写默认字段值。+ user_global_notice_with_stalled_topic:+ doc: 当通过停止的话题触发时,话题所有者将收到全局通知。+ user_global_notice_with_first_accepted_solution:+ doc: 通过第一个接受的解决方案触发时,解决方案作者将收到全局通知。+ send_pms_with_api_call:+ doc: 将 `send pms` 脚本与 `api call` 触发器结合使用时,您的请求的 `usernames` 参数将用于填充接收者列表。+ topic_required_words:+ title: 话题必选字词+ description: 允许定义话题所需的字词列表,每个帖子中至少应使用一个字词。+ doc: 话题必选字词需要一个话题。编辑/创建帖子时,将根据字词列表验证帖子,至少必须存在一个字词。+ errors:+ must_include_word: "帖子必须至少包含以下字词之一:%{words}"+ close_topic:+ title: 关闭话题+ description: 使用可选的关闭消息关闭话题+ append_last_edited_by:+ title: 追加最后编辑者+ description: 将帖子的“最后编辑者”详细信息添加到已处理内容的底部。+ text: "最后由 @%{username} 在 %{date_time} 编辑"+ append_last_checked_by:+ title: 追加最后检查者+ description: 将帖子的“最后检查者”详细信息添加到已处理内容的底部。+ text: "最后由 @%{username} 在 %{date_time} 检查"+ summary: 检查文档+ details: "对文档执行检查:"+ button_text: 已完成+ add_user_to_group_through_custom_field:+ title: "通过用户自定义字段将用户添加到群组"+ group_category_notification_default:+ title: "群组类别通知默认值"+ description: "为群组成员设置类别的默认通知级别"diff --git a/plugins/automation/config/locales/server.zh_TW.yml b/plugins/automation/config/locales/server.zh_TW.ymlnew file mode 100644index 00000000000..7e15fab0018--- /dev/null+++ b/plugins/automation/config/locales/server.zh_TW.yml@@ -0,0 +1,7 @@+# WARNING: Never edit this file.+# It will be overwritten when translations are pulled from Crowdin.+#+# To work with us on translations, join this project:+# https://translate.discourse.org/++zh_TW:diff --git a/plugins/automation/config/routes.rb b/plugins/automation/config/routes.rbnew file mode 100644index 00000000000..79185e91fb3--- /dev/null+++ b/plugins/automation/config/routes.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++DiscourseAutomation::Engine.routes.draw do+ scope format: :json, constraints: AdminConstraint.new do+ post "/automations/:id/trigger" => "automations#trigger"+ end++ scope format: :json do+ delete "/user-global-notices/:id" => "user_global_notices#destroy"+ put "/append-last-checked-by/:post_id" => "append_last_checked_by#post_checked"+ end++ scope "/admin/plugins/discourse-automation",+ as: "admin_discourse_automation",+ constraints: AdminConstraint.new do+ scope format: false do+ get "/" => "admin#index"+ get "/new" => "admin#new"+ get "/:id" => "admin#edit"+ end++ scope format: :json do+ get "/scriptables" => "admin_scriptables#index"+ get "/triggerables" => "admin_triggerables#index"+ get "/automations" => "admin_automations#index"+ get "/automations/:id" => "admin_automations#show"+ delete "/automations/:id" => "admin_automations#destroy"+ put "/automations/:id" => "admin_automations#update"+ post "/automations" => "admin_automations#create"+ end+ end+end++Discourse::Application.routes.draw { mount ::DiscourseAutomation::Engine, at: "/" }diff --git a/plugins/automation/config/settings.yml b/plugins/automation/config/settings.ymlnew file mode 100644index 00000000000..5097a67ec3e--- /dev/null+++ b/plugins/automation/config/settings.yml@@ -0,0 +1,4 @@+plugins:+ discourse_automation_enabled:+ default: false+ client: truediff --git a/plugins/automation/db/migrate/20190601000001_create_automations_table.rb b/plugins/automation/db/migrate/20190601000001_create_automations_table.rbnew file mode 100644index 00000000000..cb04c129152--- /dev/null+++ b/plugins/automation/db/migrate/20190601000001_create_automations_table.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++class CreateAutomationsTable < ActiveRecord::Migration[6.0]+ def change+ create_table :discourse_automation_automations do |t|+ t.string :name, null: false+ t.string :script, null: false+ t.boolean :enabled, null: false, default: true+ t.timestamps null: false+ end++ create_table :discourse_automation_fields do |t|+ t.integer :automation_id, null: false+ t.jsonb :metadata, null: false, default: {}+ t.string :component, null: false+ t.string :name, null: false+ t.timestamps null: false+ end++ create_table :discourse_automation_triggers do |t|+ t.integer :automation_id, null: false+ t.jsonb :metadata, null: false, default: {}+ t.string :name, null: false+ t.timestamps null: false+ end++ create_table :discourse_automation_pending_automations do |t|+ t.integer :automation_id, null: false+ t.datetime :execute_at, null: false+ t.timestamps null: false+ end+ end+enddiff --git a/plugins/automation/db/migrate/20210108134117_add_pending_pms_table.rb b/plugins/automation/db/migrate/20210108134117_add_pending_pms_table.rbnew file mode 100644index 00000000000..eb2efd886fc--- /dev/null+++ b/plugins/automation/db/migrate/20210108134117_add_pending_pms_table.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++class AddPendingPmsTable < ActiveRecord::Migration[6.0]+ def change+ create_table :discourse_automation_pending_pms do |t|+ t.string :target_usernames, array: true+ t.string :sender+ t.string :title+ t.string :raw+ t.integer :automation_id, null: false+ t.datetime :execute_at, null: false+ t.timestamps null: false+ end+ end+enddiff --git a/plugins/automation/db/migrate/20210512090204_add_timestamps_to_automations.rb b/plugins/automation/db/migrate/20210512090204_add_timestamps_to_automations.rbnew file mode 100644index 00000000000..0b46287e5bc--- /dev/null+++ b/plugins/automation/db/migrate/20210512090204_add_timestamps_to_automations.rb@@ -0,0 +1,16 @@+# frozen_string_literal: true++class AddTimestampsToAutomations < ActiveRecord::Migration[6.1]+ def change+ add_column :discourse_automation_automations, :last_updated_by_id, :integer, null: true++ DB.exec(<<~SQL, user_id: Discourse::SYSTEM_USER_ID)+ UPDATE discourse_automation_automations+ SET last_updated_by_id = :user_id+ SQL++ execute <<~SQL+ ALTER TABLE discourse_automation_automations ALTER COLUMN last_updated_by_id SET NOT NULL;+ SQL+ end+enddiff --git a/plugins/automation/db/migrate/20210517073211_add_stalled_wiki_custom_fields_index.rb b/plugins/automation/db/migrate/20210517073211_add_stalled_wiki_custom_fields_index.rbnew file mode 100644index 00000000000..91a5d11bcc7--- /dev/null+++ b/plugins/automation/db/migrate/20210517073211_add_stalled_wiki_custom_fields_index.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++class AddStalledWikiCustomFieldsIndex < ActiveRecord::Migration[6.1]+ def change+ add_index :post_custom_fields,+ :post_id,+ unique: true,+ name: "index_post_custom_fields_on_stalled_wiki_triggered_at",+ where: "name = 'stalled_wiki_triggered_at'"+ end+enddiff --git a/plugins/automation/db/migrate/20210528203310_post_migrate_gift_from_pm_to_pms.rb b/plugins/automation/db/migrate/20210528203310_post_migrate_gift_from_pm_to_pms.rbnew file mode 100644index 00000000000..4d3012a25de--- /dev/null+++ b/plugins/automation/db/migrate/20210528203310_post_migrate_gift_from_pm_to_pms.rb@@ -0,0 +1,40 @@+# frozen_string_literal: true++class PostMigrateGiftFromPmToPms < ActiveRecord::Migration[6.1]+ def up+ query = DB.query(<<~SQL, name: "giftee_assignment_message")+ SELECT id, metadata+ FROM discourse_automation_fields+ WHERE name = :name+ SQL++ return if query.empty?++ query.each do |field|+ next if !field.metadata++ pm = field.metadata+ metadata = {+ pms: [+ {+ title: pm["title"],+ raw: pm["body"],+ delay: pm["delay"] || 0,+ prefers_encrypt: pm["encrypt"] || true,+ },+ ],+ }++ DB.exec(+ <<~SQL,+ UPDATE discourse_automation_fields+ SET name = :name, component = 'pms', metadata = :metadata+ WHERE id = :field_id+ SQL+ field_id: field.id,+ name: "giftee_assignment_messages",+ metadata: metadata.to_json,+ )+ end+ end+enddiff --git a/plugins/automation/db/migrate/20210530122323_move_triggers_to_fields.rb b/plugins/automation/db/migrate/20210530122323_move_triggers_to_fields.rbnew file mode 100644index 00000000000..8622cd6ab07--- /dev/null+++ b/plugins/automation/db/migrate/20210530122323_move_triggers_to_fields.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true++class MoveTriggersToFields < ActiveRecord::Migration[6.1]+ def change+ add_column :discourse_automation_automations, :trigger, :string, null: true++ add_column :discourse_automation_fields, :target, :string, null: true++ DB.exec(<<~SQL)+ UPDATE discourse_automation_fields+ SET target = 'script'+ SQL+ end+enddiff --git a/plugins/automation/db/migrate/20210530122334_move_existing_triggers_to_fields.rb b/plugins/automation/db/migrate/20210530122334_move_existing_triggers_to_fields.rbnew file mode 100644index 00000000000..4bc194a969b--- /dev/null+++ b/plugins/automation/db/migrate/20210530122334_move_existing_triggers_to_fields.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++class MoveExistingTriggersToFields < ActiveRecord::Migration[6.1]+ def create_field(automation_id, component, name, metadata)+ DB.exec(+ <<~SQL,+ INSERT INTO discourse_automation_fields (automation_id, component, name, metadata, target, created_at, updated_at)+ VALUES (:automation_id, :component, :name, :metadata, 'trigger', :created_at, :created_at)+ SQL+ automation_id: automation_id,+ component: component,+ name: name,+ metadata: metadata.to_json,+ created_at: Time.zone.now,+ )+ end++ def change+ DB+ .query("SELECT name,automation_id,metadata FROM discourse_automation_triggers")+ .each do |trigger|+ trigger.name = "point_in_time" if trigger.name == "point-in-time"++ DB.exec(<<~SQL, automation_id: trigger.automation_id, trigger: trigger.name)+ UPDATE discourse_automation_automations+ SET trigger = :trigger+ WHERE id = :automation_id+ SQL++ trigger.metadata.each do |key, value|+ if key == "group_ids" && trigger.name == "user_added_to_group"+ create_field(trigger.automation_id, "group", "joined_group", { group_id: value })+ end++ if key == "execute_at" && trigger.name == "point_in_time"+ create_field(trigger.automation_id, "date", "execute_at", { date: value })+ end++ if key == "category_id" && trigger.name == "post_created_edited"+ create_field(+ trigger.automation_id,+ "category",+ "restricted_category",+ { category_id: value },+ )+ end++ if key == "topic" && trigger.name == "topic"+ create_field(trigger.automation_id, "topic", "restricted_topic", { topic_id: value })+ end+ end+ end++ execute <<~SQL+ DROP TABLE IF EXISTS discourse_automation_triggers;+ SQL+ end+enddiff --git a/plugins/automation/db/migrate/20210603135629_convert_date_component_to_date_time.rb b/plugins/automation/db/migrate/20210603135629_convert_date_component_to_date_time.rbnew file mode 100644index 00000000000..bddf558607a--- /dev/null+++ b/plugins/automation/db/migrate/20210603135629_convert_date_component_to_date_time.rb@@ -0,0 +1,16 @@+# frozen_string_literal: true++class ConvertDateComponentToDateTime < ActiveRecord::Migration[6.1]+ def change+ DB+ .query("SELECT id,metadata FROM discourse_automation_fields WHERE component = 'date'")+ .each do |field|+ metadata = { value: field.metadata["date"] }.to_json+ DB.exec(<<~SQL, field_id: field.id, metadata: metadata)+ UPDATE discourse_automation_fields+ SET metadata = :metadata, component = 'date_time'+ WHERE id = :field_id+ SQL+ end+ end+enddiff --git a/plugins/automation/db/migrate/20210702084757_force_value_for_every_fields.rb b/plugins/automation/db/migrate/20210702084757_force_value_for_every_fields.rbnew file mode 100644index 00000000000..2815ecc7965--- /dev/null+++ b/plugins/automation/db/migrate/20210702084757_force_value_for_every_fields.rb@@ -0,0 +1,28 @@+# frozen_string_literal: true++class ForceValueForEveryFields < ActiveRecord::Migration[6.1]+ def up+ mapping = {+ "group" => "group_id",+ "user" => "username",+ "pms" => "pms",+ "text" => "text",+ "text_list" => "list",+ "category" => "category_id",+ "tags" => "tags",+ }+ DiscourseAutomation::Field+ .where(component: mapping.keys)+ .find_each do |field|+ if mapping[field.component].present?+ metadata = field.metadata+ metadata["value"] = metadata.delete(mapping[field.component])+ field.update_column(:metadata, metadata)+ end+ end+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/automation/db/migrate/20210805204149_makes_automation_disabled_by_default.rb b/plugins/automation/db/migrate/20210805204149_makes_automation_disabled_by_default.rbnew file mode 100644index 00000000000..6e557c514fe--- /dev/null+++ b/plugins/automation/db/migrate/20210805204149_makes_automation_disabled_by_default.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class MakesAutomationDisabledByDefault < ActiveRecord::Migration[6.1]+ def change+ change_column_default :discourse_automation_automations, :enabled, false+ end+enddiff --git a/plugins/automation/db/migrate/20211015092047_adds_automation_ids_index_to_post_custom_fields.rb b/plugins/automation/db/migrate/20211015092047_adds_automation_ids_index_to_post_custom_fields.rbnew file mode 100644index 00000000000..070b33b3541--- /dev/null+++ b/plugins/automation/db/migrate/20211015092047_adds_automation_ids_index_to_post_custom_fields.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++class AddsAutomationIdsIndexToPostCustomFields < ActiveRecord::Migration[5.2]+ def change+ add_index :post_custom_fields,+ %i[post_id value],+ unique: true,+ where: "name = 'discourse_automation_ids'",+ name: :idx_post_custom_fields_discourse_automation_unique_id_partial+ end+enddiff --git a/plugins/automation/db/migrate/20211015092048_make_discourse_automation_id_an_array_on_topic_custom_fields.rb b/plugins/automation/db/migrate/20211015092048_make_discourse_automation_id_an_array_on_topic_custom_fields.rbnew file mode 100644index 00000000000..68ec769b2ff--- /dev/null+++ b/plugins/automation/db/migrate/20211015092048_make_discourse_automation_id_an_array_on_topic_custom_fields.rb@@ -0,0 +1,30 @@+# frozen_string_literal: true++class MakeDiscourseAutomationIdAnArrayOnTopicCustomFields < ActiveRecord::Migration[5.2]+ def change+ # there's no ON CONFLICT for UPDATE/SET,+ # so it's safer to remove possible duplicates first+ DB.exec(<<~SQL)+ DELETE FROM topic_custom_fields a+ USING topic_custom_fields b+ WHERE a.ctid != b.ctid+ AND a.value = b.value+ AND a.name = 'discourse_automation_id'+ AND b.name = 'discourse_automation_id'+ AND a.topic_id = b.topic_id+ AND a.id > b.id+ SQL++ DB.exec(<<~SQL)+ UPDATE topic_custom_fields+ SET name = 'discourse_automation_ids'+ WHERE name = 'discourse_automation_id'+ SQL++ add_index :topic_custom_fields,+ %i[topic_id value],+ unique: true,+ where: "name = 'discourse_automation_ids'",+ name: :idx_topic_custom_fields_discourse_automation_unique_id_partial+ end+enddiff --git a/plugins/automation/db/migrate/20211015092049_adds_automation_ids_index_to_user_custom_fields.rb b/plugins/automation/db/migrate/20211015092049_adds_automation_ids_index_to_user_custom_fields.rbnew file mode 100644index 00000000000..9a8bdf611d2--- /dev/null+++ b/plugins/automation/db/migrate/20211015092049_adds_automation_ids_index_to_user_custom_fields.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++class AddsAutomationIdsIndexToUserCustomFields < ActiveRecord::Migration[5.2]+ def change+ add_index :user_custom_fields,+ %i[user_id value],+ unique: true,+ where: "name = 'discourse_automation_ids'",+ name: :idx_user_custom_fields_discourse_automation_unique_id_partial+ end+enddiff --git a/plugins/automation/db/migrate/20211119103353_adds_discourse_automation_user_global_notice.rb b/plugins/automation/db/migrate/20211119103353_adds_discourse_automation_user_global_notice.rbnew file mode 100644index 00000000000..b14adcdf1fb--- /dev/null+++ b/plugins/automation/db/migrate/20211119103353_adds_discourse_automation_user_global_notice.rb@@ -0,0 +1,18 @@+# frozen_string_literal: true++class AddsDiscourseAutomationUserGlobalNotice < ActiveRecord::Migration[6.1]+ def change+ create_table :discourse_automation_user_global_notices do |t|+ t.integer :user_id, null: false+ t.text :notice, null: false+ t.string :identifier, null: false+ t.string :level, default: "info"+ t.timestamps null: false+ end++ add_index :discourse_automation_user_global_notices,+ %i[user_id identifier],+ unique: true,+ name: :idx_discourse_automation_user_global_notices+ end+enddiff --git a/plugins/automation/db/migrate/20220419124720_convert_recurrence_to_custom_field.rb b/plugins/automation/db/migrate/20220419124720_convert_recurrence_to_custom_field.rbnew file mode 100644index 00000000000..3a4ebe88513--- /dev/null+++ b/plugins/automation/db/migrate/20220419124720_convert_recurrence_to_custom_field.rb@@ -0,0 +1,29 @@+# frozen_string_literal: true++class ConvertRecurrenceToCustomField < ActiveRecord::Migration[6.1]+ def change+ DB+ .query("SELECT id,metadata FROM discourse_automation_fields WHERE name = 'recurrence'")+ .each do |field|+ old_value = field.metadata["value"]+ next unless old_value.is_a? String++ interval = 1+ frequency = old_value.sub("every_", "")++ if frequency == "other_week"+ interval = 2+ frequency = "week"+ end++ new_value = { interval: interval, frequency: frequency }+ metadata = { value: new_value }.to_json++ DB.exec(<<~SQL, field_id: field.id, metadata: metadata)+ UPDATE discourse_automation_fields+ SET metadata = :metadata, component = 'period'+ WHERE id = :field_id+ SQL+ end+ end+enddiff --git a/plugins/automation/db/migrate/20221006130454_add_auto_responder_triggered_ids_index.rb b/plugins/automation/db/migrate/20221006130454_add_auto_responder_triggered_ids_index.rbnew file mode 100644index 00000000000..8f36bdbfec7--- /dev/null+++ b/plugins/automation/db/migrate/20221006130454_add_auto_responder_triggered_ids_index.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++class AddAutoResponderTriggeredIdsIndex < ActiveRecord::Migration[7.0]+ def change+ add_index :topic_custom_fields,+ %i[topic_id value],+ unique: true,+ where: "name = 'auto_responder_triggered_ids'",+ name: :idx_topic_custom_fields_auto_responder_triggered_ids_partial+ end+enddiff --git a/plugins/automation/db/migrate/20230412120414_add_prefers_encrypt_field_to_pending_pms.rb b/plugins/automation/db/migrate/20230412120414_add_prefers_encrypt_field_to_pending_pms.rbnew file mode 100644index 00000000000..a0d1263c59c--- /dev/null+++ b/plugins/automation/db/migrate/20230412120414_add_prefers_encrypt_field_to_pending_pms.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true++class AddPrefersEncryptFieldToPendingPms < ActiveRecord::Migration[7.0]+ def change+ add_column :discourse_automation_pending_pms, :prefers_encrypt, :boolean, default: false++ execute <<~SQL+ UPDATE discourse_automation_pending_pms+ SET prefers_encrypt = false+ SQL++ change_column_null :discourse_automation_pending_pms, :prefers_encrypt, false+ end+enddiff --git a/plugins/automation/db/migrate/20231017175757_change_user_group_membership_through_badge_script_badge_name_field_to_badge.rb b/plugins/automation/db/migrate/20231017175757_change_user_group_membership_through_badge_script_badge_name_field_to_badge.rbnew file mode 100644index 00000000000..299096a7c4e--- /dev/null+++ b/plugins/automation/db/migrate/20231017175757_change_user_group_membership_through_badge_script_badge_name_field_to_badge.rb@@ -0,0 +1,32 @@+# frozen_string_literal: true++class ChangeUserGroupMembershipThroughBadgeScriptBadgeNameFieldToBadge < ActiveRecord::Migration[+ 7.0+]+ def change+ query = <<~SQL+ SELECT+ f.id,+ b.id AS badge_id+ FROM+ discourse_automation_fields f+ INNER JOIN discourse_automation_automations a ON a.id = f.automation_id+ INNER JOIN badges b ON b.name = TRIM(BOTH ' ' FROM f.metadata->>'value')+ WHERE+ f.name = 'badge_name'+ AND a.script = 'user_group_membership_through_badge'+ SQL++ DB+ .query(query)+ .each do |field|+ metadata = { value: field.badge_id }.to_json++ DB.exec(<<~SQL, field_id: field.id, metadata: metadata)+ UPDATE discourse_automation_fields+ SET metadata = :metadata, component = 'choices', name = 'badge'+ WHERE id = :field_id+ SQL+ end+ end+enddiff --git a/plugins/automation/db/migrate/20231022224833_update_custom_field_data.rb b/plugins/automation/db/migrate/20231022224833_update_custom_field_data.rbnew file mode 100644index 00000000000..975acca2bf4--- /dev/null+++ b/plugins/automation/db/migrate/20231022224833_update_custom_field_data.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++class UpdateCustomFieldData < ActiveRecord::Migration[7.0]+ def up+ DB.exec(<<~SQL)+ UPDATE discourse_automation_fields daf+ SET metadata = CONCAT('{"value":', REPLACE(daf.metadata ->> 'value', 'user_field_', ''), '}')::JSONB,+ component = 'custom_field'+ FROM discourse_automation_automations daa+ WHERE daa.id = daf.automation_id+ AND daa.trigger = 'recurring'+ AND daa.script = 'add_user_to_group_through_custom_field'+ AND daf.name = 'custom_field_name'+ AND daf.component = 'text'+ AND daf.metadata ->>'value' LIKE 'user_field_%'+ SQL++ DB.exec(<<~SQL)+ UPDATE discourse_automation_fields daf+ SET metadata = CONCAT('{"value":', (SELECT id FROM user_fields WHERE name = daf.metadata ->> 'value'), '}')::JSONB,+ component = 'custom_field'+ FROM discourse_automation_automations daa+ WHERE daa.id = daf.automation_id+ AND daa.trigger = 'user_first_logged_in'+ AND daa.script = 'add_user_to_group_through_custom_field'+ AND daf.component = 'text'+ AND daf.name = 'custom_field_name'+ SQL+ end++ def down+ DB.exec(<<~SQL)+ UPDATE discourse_automation_fields daf+ SET metadata = CONCAT('{"value": "user_field_', daf.metadata ->> 'value', '"}')::JSONB,+ component = 'text'+ FROM discourse_automation_automations daa+ WHERE daa.id = daf.automation_id+ AND daa.trigger = 'recurring'+ AND daa.script = 'add_user_to_group_through_custom_field'+ AND daf.component = 'custom_field'+ AND daf.name = 'custom_field_name'+ SQL++ DB.exec(<<~SQL)+ UPDATE discourse_automation_fields daf+ SET metadata = CONCAT('{"value": "', (SELECT name FROM user_fields WHERE id = (daf.metadata ->> 'value')::INTEGER), '"}')::JSONB,+ component = 'text'+ FROM discourse_automation_automations daa+ WHERE daa.id = daf.automation_id+ AND daa.trigger = 'user_first_logged_in'+ AND daa.script = 'add_user_to_group_through_custom_field'+ AND daf.component = 'custom_field'+ AND daf.name = 'custom_field_name'+ SQL+ end+enddiff --git a/plugins/automation/lib/discourse_automation/engine.rb b/plugins/automation/lib/discourse_automation/engine.rbnew file mode 100644index 00000000000..d20fc9debaa--- /dev/null+++ b/plugins/automation/lib/discourse_automation/engine.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module ::DiscourseAutomation+ class Engine < ::Rails::Engine+ engine_name PLUGIN_NAME+ isolate_namespace DiscourseAutomation+ end++ def self.filter_by_trigger(items, trigger)+ trigger = trigger&.to_sym++ indexed_items =+ items.each_with_object({}) do |item, acc|+ if item[:triggerable] == trigger || item[:triggerable].nil?+ acc[item[:name]] = item if acc[item[:name]].nil? || item[:triggerable] == trigger+ end+ end++ indexed_items.values+ end+enddiff --git a/plugins/automation/lib/discourse_automation/event_handlers.rb b/plugins/automation/lib/discourse_automation/event_handlers.rbnew file mode 100644index 00000000000..7e6b9dc849b--- /dev/null+++ b/plugins/automation/lib/discourse_automation/event_handlers.rb@@ -0,0 +1,278 @@+# frozen_string_literal: true++module DiscourseAutomation+ module EventHandlers+ def self.handle_post_created_edited(post, action)+ return if post.post_type != Post.types[:regular] || post.user_id < 0+ topic = post.topic+ return if topic.blank?++ name = DiscourseAutomation::Triggers::POST_CREATED_EDITED++ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each do |automation|+ first_post_only = automation.trigger_field("first_post_only")+ if first_post_only["value"]+ next if post.user.user_stat.post_count != 1+ end++ first_topic_only = automation.trigger_field("first_topic_only")+ if first_topic_only["value"]+ next if post.post_number != 1+ next if post.user.user_stat.topic_count != 1+ end++ valid_trust_levels = automation.trigger_field("valid_trust_levels")+ if valid_trust_levels["value"]+ next unless valid_trust_levels["value"].include?(post.user.trust_level)+ end++ restricted_category = automation.trigger_field("restricted_category")+ if restricted_category["value"]+ category_ids =+ if topic.category_id.blank?+ []+ else+ [topic.category_id, topic.category.parent_category_id]+ end+ next if !category_ids.include?(restricted_category["value"])+ end++ restricted_group_id = automation.trigger_field("restricted_group")["value"]+ if restricted_group_id.present?+ next if !topic.private_message?++ target_group_ids = topic.allowed_groups.pluck(:id)+ next if restricted_group_id != target_group_ids.first++ ignore_group_members = automation.trigger_field("ignore_group_members")+ next if ignore_group_members["value"] && post.user.in_any_groups?([restricted_group_id])+ end++ ignore_automated = automation.trigger_field("ignore_automated")+ next if ignore_automated["value"] && post.incoming_email&.is_auto_generated?++ action_type = automation.trigger_field("action_type")+ selected_action = action_type["value"]&.to_sym++ if selected_action+ next if selected_action == :created && action != :create+ next if selected_action == :edited && action != :edit+ end++ automation.trigger!("kind" => name, "action" => action, "post" => post)+ end+ end++ def self.handle_user_updated(user)+ return if user.id < 0++ name = DiscourseAutomation::Triggers::USER_UPDATED++ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each do |automation|+ once_per_user = automation.trigger_field("once_per_user")["value"]+ if once_per_user &&+ UserCustomField.exists?(name: DiscourseAutomation::CUSTOM_FIELD, user_id: user.id)+ next+ end++ required_custom_fields = automation.trigger_field("custom_fields")+ user_data = {}+ user_custom_fields_data = DB.query <<-SQL+ SELECT uf.name AS field_name, ucf.value AS field_value+ FROM user_fields uf+ JOIN user_custom_fields ucf ON CONCAT('user_field_', uf.id) = ucf.name+ WHERE ucf.user_id = #{user.id};+ SQL+ user_custom_fields_data =+ user_custom_fields_data.each_with_object({}) do |obj, hash|+ field_name = obj.field_name+ field_value = obj.field_value+ hash[field_name] = field_value+ end+ if required_custom_fields["value"]+ if required_custom_fields["value"].any? { |field|+ user_custom_fields_data[field].blank?+ }+ next+ end+ user_data[:custom_fields] = user_custom_fields_data+ end++ required_user_profile_fields = automation.trigger_field("user_profile")+ user_profile_data = UserProfile.find(user.id).attributes+ if required_user_profile_fields["value"]+ if required_user_profile_fields["value"].any? { |field|+ user_profile_data[field].blank?+ }+ next+ end+ user_data[:profile_data] = user_profile_data+ end++ automation.attach_custom_field(user)+ automation.trigger!("kind" => name, "user" => user, "user_data" => user_data)+ end+ end++ def self.handle_category_created_edited(category, action)+ name = DiscourseAutomation::Triggers::CATEGORY_CREATED_EDITED++ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each do |automation|+ restricted_category = automation.trigger_field("restricted_category")+ if restricted_category["value"].present?+ next if restricted_category["value"] != category.parent_category_id+ end++ automation.trigger!("kind" => name, "action" => action, "category" => category)+ end+ end++ def self.handle_pm_created(topic)+ return if topic.user_id < 0++ user = topic.user+ target_usernames = topic.allowed_users.pluck(:username) - [user.username]+ target_group_ids = topic.allowed_groups.pluck(:id)+ return if (target_usernames.length + target_group_ids.length) > 1++ name = DiscourseAutomation::Triggers::PM_CREATED++ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each do |automation|+ restricted_username = automation.trigger_field("restricted_user")["value"]+ next if restricted_username.present? && restricted_username != target_usernames.first++ restricted_group_id = automation.trigger_field("restricted_group")["value"]+ next if restricted_group_id.present? && restricted_group_id != target_group_ids.first++ ignore_staff = automation.trigger_field("ignore_staff")+ next if ignore_staff["value"] && user.staff?++ ignore_group_members = automation.trigger_field("ignore_group_members")+ next if ignore_group_members["value"] && user.in_any_groups?([restricted_group_id])++ ignore_automated = automation.trigger_field("ignore_automated")+ next if ignore_automated["value"] && topic.first_post.incoming_email&.is_auto_generated?++ valid_trust_levels = automation.trigger_field("valid_trust_levels")+ if valid_trust_levels["value"]+ next if !valid_trust_levels["value"].include?(user.trust_level)+ end++ automation.trigger!("kind" => name, "post" => topic.first_post)+ end+ end++ def self.handle_after_post_cook(post, cooked)+ return cooked if post.post_type != Post.types[:regular] || post.post_number > 1++ name = DiscourseAutomation::Triggers::AFTER_POST_COOK++ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each do |automation|+ valid_trust_levels = automation.trigger_field("valid_trust_levels")+ if valid_trust_levels["value"]+ next unless valid_trust_levels["value"].include?(post.user.trust_level)+ end++ restricted_category = automation.trigger_field("restricted_category")+ if restricted_category["value"]+ category_ids = [post.topic&.category&.parent_category&.id, post.topic&.category&.id]+ next if !category_ids.compact.include?(restricted_category["value"])+ end++ restricted_tags = automation.trigger_field("restricted_tags")+ if tag_names = restricted_tags["value"]+ found = false+ next if !post.topic++ post.topic.tags.each do |tag|+ found ||= tag_names.include?(tag.name)+ break if found+ end++ next if !found+ end++ if new_cooked = automation.trigger!("kind" => name, "post" => post, "cooked" => cooked)+ cooked = new_cooked+ end+ end++ cooked+ end++ def self.handle_user_promoted(user_id, new_trust_level, old_trust_level)+ trigger = DiscourseAutomation::Triggers::USER_PROMOTED+ user = User.find_by(id: user_id)+ return if user.blank?++ # don't want to do anything if the user is demoted. this should probably+ # be a separate event in core+ return if new_trust_level < old_trust_level++ DiscourseAutomation::Automation+ .where(trigger: trigger, enabled: true)+ .find_each do |automation|+ trust_level_code_all = DiscourseAutomation::USER_PROMOTED_TRUST_LEVEL_CHOICES.first[:id]++ restricted_group_id = automation.trigger_field("restricted_group")["value"]+ trust_level_transition = automation.trigger_field("trust_level_transition")["value"]+ trust_level_transition = trust_level_transition || trust_level_code_all++ if restricted_group_id.present? &&+ !GroupUser.exists?(user_id: user_id, group_id: restricted_group_id)+ next+ end++ transition_code = "TL#{old_trust_level}#{new_trust_level}"+ if trust_level_transition == trust_level_code_all ||+ trust_level_transition == transition_code+ automation.trigger!(+ "kind" => trigger,+ "usernames" => [user.username],+ "placeholders" => {+ "trust_level_transition" =>+ I18n.t(+ "discourse_automation.triggerables.user_promoted.transition_placeholder",+ from_level_name: TrustLevel.name(old_trust_level),+ to_level_name: TrustLevel.name(new_trust_level),+ ),+ },+ )+ end+ end+ end++ def self.handle_stalled_topic(post)+ return if post.topic.blank?+ return if post.user_id != post.topic.user_id++ DiscourseAutomation::Automation+ .where(trigger: DiscourseAutomation::Triggers::STALLED_TOPIC)+ .where(enabled: true)+ .find_each do |automation|+ fields = automation.serialized_fields++ categories = fields.dig("categories", "value")+ next if categories && !categories.include?(post.topic.category_id)++ tags = fields.dig("tags", "value")+ next if tags && (tags & post.topic.tags.map(&:name)).empty?++ DiscourseAutomation::UserGlobalNotice+ .where(identifier: automation.id)+ .where(user_id: post.user_id)+ .destroy_all+ end+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/post_extension.rb b/plugins/automation/lib/discourse_automation/post_extension.rbnew file mode 100644index 00000000000..1e15c2baaf9--- /dev/null+++ b/plugins/automation/lib/discourse_automation/post_extension.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++module DiscourseAutomation+ module PostExtension+ extend ActiveSupport::Concern++ prepended { validate :discourse_automation_topic_required_words }++ def discourse_automation_topic_required_words+ return if !SiteSetting.discourse_automation_enabled+ return if self.post_type == Post.types[:small_action]+ return if !topic+ return if topic.custom_fields[DiscourseAutomation::CUSTOM_FIELD].blank?++ topic.custom_fields[DiscourseAutomation::CUSTOM_FIELD].each do |automation_id|+ automation = DiscourseAutomation::Automation.find_by(id: automation_id)+ next if automation&.script != DiscourseAutomation::Scripts::TOPIC_REQUIRED_WORDS++ words = automation.fields.find_by(name: "words")&.metadata&.[]("value")+ next if words.blank?++ if words.none? { |word| raw.include?(word) }+ errors.add(+ :base,+ I18n.t(+ "discourse_automation.scriptables.topic_required_words.errors.must_include_word",+ words: words.join(", "),+ ),+ )+ end+ end+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scriptable.rb b/plugins/automation/lib/discourse_automation/scriptable.rbnew file mode 100644index 00000000000..617b53b02ab--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scriptable.rb@@ -0,0 +1,303 @@+# frozen_string_literal: true++module DiscourseAutomation+ class Scriptable+ attr_reader :fields,+ :name,+ :not_found,+ :forced_triggerable,+ :background,+ :automation,+ :placeholders++ @@plugin_triggerables ||= {}++ class << self+ def add_plugin_triggerable(triggerable, scriptable)+ @@plugin_triggerables[scriptable.to_sym] ||= []+ @@plugin_triggerables[scriptable.to_sym] << triggerable.to_sym+ end++ def plugin_triggerables+ @@plugin_triggerables+ end+ end++ def initialize(name, automation = nil)+ @name = name+ @version = 0+ @fields = []+ @placeholders = []+ @triggerables = (@@plugin_triggerables[name&.to_sym] || [])+ @script = proc {}+ @on_reset = proc {}+ @not_found = false+ @forced_triggerable = nil+ @background = false+ @automation = automation++ eval! if @name+ end++ def run_in_background+ @background = true+ end++ def id+ "script"+ end++ def scriptable?+ true+ end++ def triggerable?+ false+ end++ def eval!+ begin+ public_send("__scriptable_#{name.underscore}")+ rescue NoMethodError+ @not_found = true+ end++ self+ end++ def triggerable!(*args)+ if args.present?+ @forced_triggerable = { triggerable: args[0], state: args[1] }+ else+ @forced_triggerable+ end+ end++ def placeholder(name = nil, triggerable: nil, &block)+ if block_given?+ result = yield(@automation.serialized_fields, @automation)+ Array(result).each do |name|+ @placeholders << { name: name.to_sym, triggerable: triggerable&.to_sym }+ end+ elsif name+ @placeholders << { name: name.to_sym, triggerable: triggerable&.to_sym }+ end+ end++ def version(*args)+ if args.present?+ @version, = args+ else+ @version+ end+ end++ def permits_trigger?(triggerable)+ Array(triggerables.map(&:to_s)).include?(triggerable.to_s)+ end++ def triggerables(*args)+ if args.present?+ @triggerables.push(*args[0])+ else+ forced_triggerable ? [forced_triggerable[:triggerable]] : @triggerables+ end+ end++ def script(&block)+ if block_given?+ @script = block+ else+ @script+ end+ end++ def on_reset(&block)+ if block_given?+ @on_reset_block = block+ else+ @on_reset_block+ end+ end++ def field(name, component:, **options)+ @fields << {+ name: name,+ component: component,+ extra: {+ },+ accepts_placeholders: false,+ accepted_contexts: [],+ triggerable: nil,+ required: false,+ }.merge(options || {})+ end++ def components+ fields.map { |f| f[:component] }.uniq+ end++ def utils+ Utils+ end++ module Utils+ def self.fetch_report(name, args = {})+ report = Report.find(name, args)++ return if !report++ return if !report.modes.include?(:table)++ ordered_columns = report.labels.map { |l| l[:property] }++ table = +"\n"+ table << "|" + report.labels.map { |l| l[:title] }.join("|") + "|\n"+ table << "|" + report.labels.count.times.map { "-" }.join("|") + "|\n"+ if report.data.count > 0+ report.data.each do |data|+ table << "|#{ordered_columns.map { |col| data[col] }.join("|")}|\n"+ end+ else+ table << "|" + report.labels.count.times.map { " " }.join("|") + "|\n"+ end+ table+ end++ def self.apply_placeholders(input, map = {})+ input = input.dup+ map[:site_title] = SiteSetting.title++ input = apply_report_placeholder(input)++ map.each { |key, value| input = input.gsub("%%#{key.upcase}%%", value.to_s) }++ input = Mustache.render(input, map).to_s+ end++ REPORT_REGEX = /%%REPORT=(.*?)%%/+ def self.apply_report_placeholder(input = "")+ input.gsub(REPORT_REGEX) do |pattern|+ match = pattern.match(REPORT_REGEX)+ if match+ params = match[1].match(/^(.*?)(?:\s(.*))?$/)++ args = { filters: {} }+ if params[2]+ params[2]+ .split(" ")+ .each do |param|+ key, value = param.split("=")+ if %w[start_date end_date].include?(key)+ args[key.to_sym] = begin+ Date.parse(value)+ rescue StandardError+ nil+ end+ else+ args[:filters][key.to_sym] = value+ end+ end+ end++ fetch_report(params[1].downcase, args) || ""+ end+ end+ end++ def self.send_pm(+ pm,+ sender: Discourse.system_user.username,+ delay: nil,+ automation_id: nil,+ prefers_encrypt: true+ )+ pm = pm.symbolize_keys+ prefers_encrypt = prefers_encrypt && !!defined?(EncryptedPostCreator)++ if delay && delay.to_i > 0 && automation_id+ pm[:execute_at] = delay.to_i.minutes.from_now+ pm[:sender] = sender+ pm[:automation_id] = automation_id+ pm[:prefers_encrypt] = prefers_encrypt+ DiscourseAutomation::PendingPm.create!(pm)+ else+ sender = User.find_by(username: sender)+ if !sender+ Rails.logger.warn "[discourse-automation] Did not send PM #{pm[:title]} - sender does not exist: `#{sender}`"+ return+ end++ pm[:target_usernames] = Array.wrap(pm[:target_usernames])+ pm[:target_group_names] = Array.wrap(pm[:target_group_names])+ pm[:target_emails] = Array.wrap(pm[:target_emails])++ if pm[:target_usernames].empty? && pm[:target_group_names].empty? &&+ pm[:target_emails].empty?+ Rails.logger.warn "[discourse-automation] Did not send PM - no target usernames, groups or emails"+ return+ end++ non_existing_targets = []++ if pm[:target_usernames].present?+ existing_target_usernames = User.where(username: pm[:target_usernames]).pluck(:username)+ if existing_target_usernames.length != pm[:target_usernames].length+ non_existing_targets += pm[:target_usernames] - existing_target_usernames+ pm[:target_usernames] = existing_target_usernames+ end+ end++ if pm[:target_group_names].present?+ existing_target_groups = Group.where(name: pm[:target_group_names]).pluck(:name)+ if existing_target_groups.length != pm[:target_group_names].length+ non_existing_targets += pm[:target_group_names] - existing_target_groups+ pm[:target_group_names] = existing_target_groups+ end+ end++ if pm[:target_emails].present?+ valid_emails = pm[:target_emails].select { |email| Email.is_valid?(email) }+ if valid_emails.length != pm[:target_emails].length+ non_existing_targets += pm[:target_emails] - valid_emails+ pm[:target_emails] = valid_emails+ end+ end++ post_created = false+ pm = pm.merge(archetype: Archetype.private_message)+ pm[:target_usernames] = pm[:target_usernames].join(",")+ pm[:target_group_names] = pm[:target_group_names].join(",")+ pm[:target_emails] = pm[:target_emails].join(",")++ if pm[:target_usernames].blank? && pm[:target_group_names].blank? &&+ pm[:target_emails].blank?+ Rails.logger.warn "[discourse-automation] Did not send PM #{pm[:title]} - no valid targets exist"+ return+ elsif non_existing_targets.any?+ Rails.logger.warn "[discourse-automation] Did not send PM #{pm[:title]} to all users - some do not exist: `#{non_existing_targets.join(",")}`"+ end++ post_created = EncryptedPostCreator.new(sender, pm).create if prefers_encrypt++ PostCreator.new(sender, pm).create! if !post_created+ end+ end+ end++ def self.add(identifier, &block)+ @all_scriptables = nil+ define_method("__scriptable_#{identifier}", &block)+ end++ def self.remove(identifier)+ @all_scriptables = nil+ undef_method("__scriptable_#{identifier}")+ end++ def self.all+ @all_scriptables ||=+ DiscourseAutomation::Scriptable.instance_methods(false).grep(/^__scriptable_/)+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts.rb b/plugins/automation/lib/discourse_automation/scripts.rbnew file mode 100644index 00000000000..944ab47aca8--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++module DiscourseAutomation+ module Scripts+ ADD_USER_TO_GROUP_THROUGH_CUSTOM_FIELD = "add_user_to_group_through_custom_field"+ APPEND_LAST_CHECKED_BY = "append_last_checked_by"+ APPEND_LAST_EDITED_BY = "append_last_edited_by"+ AUTO_RESPONDER = "auto_responder"+ AUTO_TAG_TOPIC = "auto_tag_topic"+ BANNER_TOPIC = "banner_topic"+ CLOSE_TOPIC = "close_topic"+ FLAG_POST_ON_WORDS = "flag_post_on_words"+ GIFT_EXCHANGE = "gift_exchange"+ GROUP_CATEGORY_NOTIFICATION_DEFAULT = "group_category_notification_default"+ PIN_TOPIC = "pin_topic"+ POST = "post"+ SEND_PMS = "send_pms"+ SUSPEND_USER_BY_EMAIL = "suspend_user_by_email"+ TOPIC_REQUIRED_WORDS = "topic_required_words"+ USER_GLOBAL_NOTICE = "user_global_notice"+ USER_GROUP_MEMBERSHIP_THROUGH_BADGE = "user_group_membership_through_badge"+ ZAPIER_WEBHOOK = "zapier_webhook"+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/add_user_to_group_through_custom_field.rb b/plugins/automation/lib/discourse_automation/scripts/add_user_to_group_through_custom_field.rbnew file mode 100644index 00000000000..9d077665bde--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/add_user_to_group_through_custom_field.rb@@ -0,0 +1,74 @@+# frozen_string_literal: true++# This script takes the name of a User Custom Field containing a group name.+# On each run, it ensures that each user belongs to the group name given by that UCF (NOTE: group full_name, not name).+#+# In other words, it designates a certain User Custom Field to act as+# a "pointer" to a group that the user should belong to, and adds users as needed.++DiscourseAutomation::Scriptable.add(+ DiscourseAutomation::Scripts::ADD_USER_TO_GROUP_THROUGH_CUSTOM_FIELD,+) do+ field :custom_field_name, component: :custom_field, required: true++ version 1++ triggerables %i[recurring user_first_logged_in]++ script do |trigger, fields|+ custom_field_name = fields.dig("custom_field_name", "value")++ case trigger["kind"]+ when DiscourseAutomation::Triggers::API_CALL, DiscourseAutomation::Triggers::RECURRING+ query =+ DB.query(<<-SQL, prefix: ::User::USER_FIELD_PREFIX, custom_field_name: custom_field_name)+ SELECT u.id as user_id, g.id as group_id+ FROM users u+ JOIN user_custom_fields ucf+ ON u.id = ucf.user_id+ AND ucf.name = CONCAT(:prefix, :custom_field_name)+ JOIN groups g+ on g.full_name ilike ucf.value+ FULL OUTER JOIN group_users gu+ ON gu.user_id = u.id+ AND gu.group_id = g.id+ WHERE gu.id is null+ AND u.active = true+ ORDER BY 1, 2+ SQL++ groups_by_id = {}++ User+ .where(id: query.map(&:user_id))+ .order(:id)+ .zip(query) do |user, query_row|+ group_id = query_row.group_id+ group = groups_by_id[group_id] ||= Group.find(group_id)++ group.add(user)+ GroupActionLogger.new(Discourse.system_user, group).log_add_user_to_group(user)+ end+ when DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN+ group_name =+ DB.query_single(+ <<-SQL,+ SELECT value+ FROM user_custom_fields ucf+ WHERE ucf.user_id = :user_id AND ucf.name = CONCAT(:prefix, :custom_field_name)+ SQL+ prefix: ::User::USER_FIELD_PREFIX,+ custom_field_name: custom_field_name,+ user_id: trigger["user"].id,+ ).first+ next if !group_name++ group = Group.find_by(full_name: group_name)+ next if !group++ user = trigger["user"]+ group.add(user)+ GroupActionLogger.new(Discourse.system_user, group).log_add_user_to_group(user)+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/append_last_checked_by.rb b/plugins/automation/lib/discourse_automation/scripts/append_last_checked_by.rbnew file mode 100644index 00000000000..c218c9647bd--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/append_last_checked_by.rb@@ -0,0 +1,49 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::APPEND_LAST_CHECKED_BY) do+ version 1++ triggerables [:after_post_cook]++ script do |context|+ post = context["post"]+ topic = post.topic++ cooked = context["cooked"]+ doc = Loofah.fragment(cooked)+ node = doc.css("blockquote.discourse-automation").first++ if node.blank?+ node = doc.document.create_element("blockquote")+ node["class"] = "discourse-automation"+ doc.add_child(node)+ end++ username = topic.custom_fields[DiscourseAutomation::TOPIC_LAST_CHECKED_BY]+ checked_at = topic.custom_fields[DiscourseAutomation::TOPIC_LAST_CHECKED_AT]++ if username.present? && checked_at.present?+ checked_at = DateTime.parse(checked_at)++ date_time =+ "[date=#{checked_at.to_date} time=#{checked_at.strftime("%H:%M:%S")} timezone=UTC]"+ node.inner_html +=+ PrettyText.cook(+ I18n.t(+ "discourse_automation.scriptables.append_last_checked_by.text",+ username: username,+ date_time: date_time,+ ),+ ).html_safe+ end++ summary_tag =+ "<summary>#{I18n.t("discourse_automation.scriptables.append_last_checked_by.summary")}</summary>"+ button_tag =+ "<input type=\"button\" value=\"#{I18n.t("discourse_automation.scriptables.append_last_checked_by.button_text")}\" class=\"btn btn-checked\" />"+ node.inner_html +=+ "<details>#{summary_tag}#{I18n.t("discourse_automation.scriptables.append_last_checked_by.details")}#{button_tag}</details>"++ doc.try(:to_html)+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/append_last_edited_by.rb b/plugins/automation/lib/discourse_automation/scripts/append_last_edited_by.rbnew file mode 100644index 00000000000..2f4ae4823d0--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/append_last_edited_by.rb@@ -0,0 +1,36 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::APPEND_LAST_EDITED_BY) do+ version 1++ triggerables [:after_post_cook]++ script do |context|+ post = context["post"]+ post_revision = post.revisions.where("user_id > 0").last+ username = post_revision&.user&.username || post.username+ updated_at = post_revision&.updated_at || post.updated_at++ cooked = context["cooked"]+ doc = Loofah.fragment(cooked)++ node = doc.css("blockquote.discourse-automation").first+ if node.blank?+ node = doc.document.create_element("blockquote")+ node["class"] = "discourse-automation"+ doc.add_child(node)+ end++ date_time = "[date=#{updated_at.to_date} time=#{updated_at.strftime("%H:%M:%S")} timezone=UTC]"+ node.inner_html +=+ PrettyText.cook(+ I18n.t(+ "discourse_automation.scriptables.append_last_edited_by.text",+ username: username,+ date_time: date_time,+ ),+ ).html_safe++ doc.try(:to_html)+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/auto_responder.rb b/plugins/automation/lib/discourse_automation/scripts/auto_responder.rbnew file mode 100644index 00000000000..4a3a910cea6--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/auto_responder.rb@@ -0,0 +1,85 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::AUTO_RESPONDER) do+ field :word_answer_list, component: :"key-value", accepts_placeholders: true+ field :answering_user, component: :user+ field :once, component: :boolean++ version 1++ triggerables %i[post_created_edited pm_created]++ placeholder :sender_username+ placeholder :word++ script do |context, fields, automation|+ key = DiscourseAutomation::AUTO_RESPONDER_TRIGGERED_IDS++ answering_username = fields.dig("answering_user", "value") || Discourse.system_user.username+ placeholders = { sender_username: answering_username }+ post = context["post"]+ next if !post.topic++ next if fields.dig("once", "value") && post.topic.custom_fields[key]&.include?(automation.id)++ answers = Set.new+ word_answer_list_json = fields.dig("word_answer_list", "value")+ next if word_answer_list_json.blank?++ word_answer_list = JSON.parse(word_answer_list_json)+ next if word_answer_list.blank?++ word_answer_list.each do |word_answer_pair|+ if word_answer_pair["key"].blank?+ answers.add(word_answer_pair)+ next+ end++ if post.is_first_post?+ if match = post.topic.title.match(/\b(#{word_answer_pair["key"]})\b/i)+ word_answer_pair["key"] = match.captures.first+ answers.add(word_answer_pair)+ next+ end+ end++ if match = post.raw.match(/\b(#{word_answer_pair["key"]})\b/i)+ word_answer_pair["key"] = match.captures.first+ answers.add(word_answer_pair)+ end+ end++ next if answers.blank?++ answering_user = User.find_by(username: answering_username)+ next if post.user == answering_user++ replies =+ post+ .replies+ .where(user_id: answering_user.id, deleted_at: nil)+ .secured(Guardian.new(post.user))++ next if replies.present?++ answers =+ answers+ .to_a+ .map do |answer|+ utils.apply_placeholders(answer["value"], placeholders.merge(key: answer["key"]))+ end+ .join("\n\n")++ value = (Array(post.topic.custom_fields[key]) << automation.id).compact.uniq+ post.topic.custom_fields[key] = value+ post.topic.save_custom_fields++ PostCreator.create!(+ answering_user,+ topic_id: post.topic.id,+ reply_to_post_number: post.post_number,+ raw: answers,+ skip_validations: true,+ )+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/auto_tag_topic.rb b/plugins/automation/lib/discourse_automation/scripts/auto_tag_topic.rbnew file mode 100644index 00000000000..d216033b455--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/auto_tag_topic.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::AUTO_TAG_TOPIC) do+ field :tags, component: :tags, required: true++ version 1++ triggerables %i[post_created_edited pm_created]++ script do |context, fields|+ post = context["post"]++ next if !post.is_first_post?+ next if !post.topic+ next unless topic = Topic.find_by(id: post.topic.id)++ tags = fields.dig("tags", "value")++ DiscourseTagging.tag_topic_by_names(topic, Guardian.new(post.user), tags, append: true)+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/banner_topic.rb b/plugins/automation/lib/discourse_automation/scripts/banner_topic.rbnew file mode 100644index 00000000000..18c921395c2--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/banner_topic.rb@@ -0,0 +1,23 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::BANNER_TOPIC) do+ field :topic_id, component: :text, required: true+ field :banner_until, component: :date_time+ field :user, component: :user++ version 1++ triggerables [:point_in_time]++ script do |_, fields|+ next unless topic_id = fields.dig("topic_id", "value")+ next unless topic = Topic.find_by(id: topic_id)++ banner_until = fields.dig("banner_until", "value") || nil++ username = fields.dig("user", "value") || Discourse.system_user.username+ next unless user = User.find_by(username: username)++ topic.make_banner!(user, banner_until)+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/close_topic.rb b/plugins/automation/lib/discourse_automation/scripts/close_topic.rbnew file mode 100644index 00000000000..7471d6db101--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/close_topic.rb@@ -0,0 +1,37 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::CLOSE_TOPIC) do+ field :topic, component: :text, required: true, triggerable: :point_in_time+ field :message, component: :text+ field :user, component: :user++ version 1++ triggerables %i[point_in_time stalled_wiki]++ script do |context, fields|+ message = fields.dig("message", "value")+ username = fields.dig("user", "value") || Discourse.system_user.username++ topic_id = fields.dig("topic", "value") || context.dig("topic", "id")+ next unless topic_id+ next unless topic = Topic.find_by(id: topic_id)++ user = User.find_by_username(username)+ next unless user+ next unless Guardian.new(user).can_moderate?(topic)++ topic.update_status("closed", true, user)++ if message.present?+ topic_closed_post = topic.posts.where(action_code: "closed.enabled").last+ topic_closed_post.raw = message++ # FIXME: when there is proper error handling and logging in automation,+ # remove this and allow validations to take place+ topic_closed_post.skip_validation = true++ topic_closed_post.save!+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/flag_post_on_words.rb b/plugins/automation/lib/discourse_automation/scripts/flag_post_on_words.rbnew file mode 100644index 00000000000..f8448efd856--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/flag_post_on_words.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::FLAG_POST_ON_WORDS) do+ field :words, component: :text_list, required: true++ version 1++ triggerables %i[post_created_edited]++ script do |trigger, fields|+ post = trigger["post"]++ Array(fields.dig("words", "value")).each do |list|+ words = list.split(",")+ count = words.inject(0) { |acc, word| post.raw.match?(/#{word}/i) ? acc + 1 : acc }+ next if count < words.length++ has_trust_level = post.user.has_trust_level?(TrustLevel[2])+ trusted_user =+ has_trust_level ||+ ReviewableFlaggedPost.where(+ status: Reviewable.statuses[:rejected],+ target_created_by: post.user,+ ).exists?+ next if trusted_user++ message =+ I18n.t("discourse_automation.scriptables.flag_post_on_words.flag_message", words: list)+ PostActionCreator.new(+ Discourse.system_user,+ post,+ PostActionType.types[:spam],+ message: message,+ queue_for_review: true,+ ).perform+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/gift_exchange.rb b/plugins/automation/lib/discourse_automation/scripts/gift_exchange.rbnew file mode 100644index 00000000000..a37989963ba--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/gift_exchange.rb@@ -0,0 +1,72 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::GIFT_EXCHANGE) do+ placeholder :year+ placeholder :giftee_username+ placeholder :gifter_username++ field :giftee_assignment_messages, component: :pms, accepts_placeholders: true, required: true+ field :gift_exchangers_group, component: :group, required: true++ version 17++ triggerables %i[point_in_time]++ script do |_, fields, automation|+ now = Time.zone.now+ group_id = fields.dig("gift_exchangers_group", "value")++ unless group = Group.find_by(id: group_id)+ Rails.logger.warn "[discourse-automation] Couldn’t find group with id #{group_id}"+ next+ end++ cf_name = "#{group.name}-gifts-were-exchanged-#{automation.id}-#{version}-#{now.year}"+ if group.custom_fields[cf_name].present?+ Rails.logger.warn "[discourse-automation] Gift exchange script has already been run on #{cf_name} this year #{now.year} for this script version #{version}"+ next+ end++ usernames = group.users.pluck(:username)++ if usernames.size < 3+ Rails.logger.warn "[discourse-automation] Gift exchange needs at least 3 users in a group"+ next+ end++ usernames.shuffle!+ usernames << usernames[0]++ # shuffle the pairs to prevent prying eyes to identify matches by looking at the timestamps of the topics+ pairs = usernames.each_cons(2).to_a.shuffle++ pairs.each do |gifter, giftee|+ placeholders = { year: now.year.to_s, gifter_username: gifter, giftee_username: giftee }++ Array(fields.dig("giftee_assignment_messages", "value")).each do |giftee_assignment_message|+ if giftee_assignment_message["title"].blank?+ Rails.logger.warn "[discourse-automation] Gift exchange requires a title for the PM"+ next+ end++ if giftee_assignment_message["raw"].blank?+ Rails.logger.warn "[discourse-automation] Gift exchange requires a raw for the PM"+ next+ end++ raw = utils.apply_placeholders(giftee_assignment_message["raw"], placeholders)+ title = utils.apply_placeholders(giftee_assignment_message["title"], placeholders)++ utils.send_pm(+ { target_usernames: Array(gifter), title: title, raw: raw },+ delay: giftee_assignment_message["delay"],+ prefers_encrypt: giftee_assignment_message["prefers_encrypt"],+ automation_id: automation.id,+ )+ end+ end++ group.custom_fields[cf_name] = true+ group.save_custom_fields+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/group_category_notification_default.rb b/plugins/automation/lib/discourse_automation/scripts/group_category_notification_default.rbnew file mode 100644index 00000000000..0976cef32e3--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/group_category_notification_default.rb@@ -0,0 +1,60 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(+ DiscourseAutomation::Scripts::GROUP_CATEGORY_NOTIFICATION_DEFAULT,+) do+ version 1++ field :group, component: :group+ field :notification_level, component: :category_notification_level+ field :update_existing_members, component: :boolean++ triggerables %i[category_created_edited]++ script do |context, fields|+ category_id = context["category"].id+ group_id = fields.dig("group", "value")+ notification_level = fields.dig("notification_level", "value")++ unless group = Group.find_by(id: group_id)+ Rails.logger.warn "[discourse-automation] Couldn’t find group with id #{group_id}"+ next+ end++ GroupCategoryNotificationDefault+ .find_or_initialize_by(group_id: group_id, category_id: category_id)+ .tap do |gc|+ gc.notification_level = notification_level+ gc.save!+ end++ if fields.dig("update_existing_members", "value")+ group+ .users+ .select(:id, :user_id)+ .find_in_batches do |batch|+ user_ids = batch.pluck(:user_id)++ category_users = []+ existing_users =+ CategoryUser.where(category_id: category_id, user_id: user_ids).where(+ "notification_level IS NOT NULL",+ )+ skip_user_ids = existing_users.pluck(:user_id)++ batch.each do |group_user|+ next if skip_user_ids.include?(group_user.user_id)+ category_users << {+ category_id: category_id,+ user_id: group_user.user_id,+ notification_level: notification_level,+ }+ end++ next if category_users.blank?++ CategoryUser.insert_all!(category_users)+ end+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/pin_topic.rb b/plugins/automation/lib/discourse_automation/scripts/pin_topic.rbnew file mode 100644index 00000000000..24132409afd--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/pin_topic.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::PIN_TOPIC) do+ field :pinnable_topic, component: :text, required: true+ field :pinned_until, component: :date_time+ field :pinned_globally, component: :boolean++ version 1++ triggerables [:point_in_time]++ script do |_context, fields|+ next unless topic_id = fields.dig("pinnable_topic", "value")+ next unless topic = Topic.find_by(id: topic_id)++ pinned_globally = fields.dig("pinned_globally", "value") || false+ pinned_until = fields.dig("pinned_until", "value") || nil++ topic.update_pinned(true, pinned_globally, pinned_until)+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/post.rb b/plugins/automation/lib/discourse_automation/scripts/post.rbnew file mode 100644index 00000000000..cd25e47ef96--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/post.rb@@ -0,0 +1,66 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::POST) do+ version 1++ placeholder :creator_username++ field :creator, component: :user+ field :creator, component: :user, triggerable: :user_updated, accepted_contexts: [:updated_user]++ field :topic, component: :text, required: true+ field :post, component: :post, required: true, accepts_placeholders: true++ placeholder :creator_username+ placeholder :updated_user_username, triggerable: :user_updated+ placeholder :updated_user_name, triggerable: :user_updated++ triggerables %i[recurring point_in_time user_updated]++ script do |context, fields, automation|+ creator_username = fields.dig("creator", "value")+ creator_username = context["user"]&.username if creator_username == "updated_user"+ creator_username ||= Discourse.system_user.username++ topic_id = fields.dig("topic", "value")+ post_raw = fields.dig("post", "value")++ placeholders = { creator_username: creator_username }.merge(context["placeholders"] || {})+ creator = User.find_by(username: creator_username)+ topic = Topic.find_by(id: topic_id)++ if !topic || topic.closed? || topic.archived?+ Rails.logger.warn "[discourse-automation] topic with id: `#{topic_id}` was not found"+ next+ end++ if context["kind"] == DiscourseAutomation::Triggers::USER_UPDATED+ user = context["user"]+ user_data = context["user_data"]+ user_profile_data = user_data[:profile_data] || {}+ user_custom_fields = {}+ user_data[:custom_fields]&.each do |k, v|+ user_custom_fields[k.gsub(/\s+/, "_").underscore] = v+ end+ user = User.find(context["user"].id)+ placeholders["username"] = user.username+ placeholders["name"] = user.name+ placeholders["updated_user_username"] = user.username+ placeholders["updated_user_name"] = user.name+ placeholders = placeholders.merge(user_profile_data, user_custom_fields)+ end++ post_raw = utils.apply_placeholders(post_raw, placeholders)++ if !creator+ Rails.logger.warn "[discourse-automation] creator with username: `#{creator_username}` was not found"+ next+ end++ new_post = PostCreator.new(creator, topic_id: topic_id, raw: post_raw).create!++ if context["kind"] == DiscourseAutomation::Triggers::USER_UPDATED && new_post.persisted?+ user.user_custom_fields.create(name: automation.name, value: "true")+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/send_pms.rb b/plugins/automation/lib/discourse_automation/scripts/send_pms.rbnew file mode 100644index 00000000000..7bfc61304e6--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/send_pms.rb@@ -0,0 +1,55 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::SEND_PMS) do+ version 1++ placeholder :sender_username+ placeholder :receiver_username++ field :sender, component: :user+ field :receiver, component: :user, triggerable: :recurring+ field :sendable_pms, component: :pms, accepts_placeholders: true, required: true++ triggerables %i[+ user_badge_granted+ user_added_to_group+ stalled_wiki+ recurring+ user_promoted+ api_call+ user_removed_from_group+ ]++ script do |context, fields, automation|+ sender_username = fields.dig("sender", "value") || Discourse.system_user.username++ placeholders = { sender_username: sender_username }.merge(context["placeholders"] || {})++ usernames = context["usernames"] || []++ # optional field when using recurring triggerable+ if u = fields.dig("receiver", "value")+ usernames << u+ end++ usernames.compact.uniq.each do |username|+ placeholders[:receiver_username] = username+ Array(fields.dig("sendable_pms", "value")).each do |sendable|+ next if !sendable["title"] || !sendable["raw"]++ pm = {}+ pm["title"] = utils.apply_placeholders(sendable["title"], placeholders)+ pm["raw"] = utils.apply_placeholders(sendable["raw"], placeholders)+ pm["target_usernames"] = Array(username)++ utils.send_pm(+ pm,+ sender: sender_username,+ automation_id: automation.id,+ delay: sendable["delay"],+ prefers_encrypt: !!sendable["prefers_encrypt"],+ )+ end+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/suspend_user_by_email.rb b/plugins/automation/lib/discourse_automation/scripts/suspend_user_by_email.rbnew file mode 100644index 00000000000..d3be2422d45--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/suspend_user_by_email.rb@@ -0,0 +1,36 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::SUSPEND_USER_BY_EMAIL) do+ version 1++ triggerables %i[api_call]++ field :reason, component: :text, required: true+ field :suspend_until, component: :date_time, required: true+ field :actor, component: :user++ script do |context, fields|+ email = context["email"]+ next unless target = UserEmail.find_by(email: email)&.user++ next if target.suspended?++ unless actor =+ User.find_by(username: fields.dig("actor", "value") || Discourse.system_user.username)+ next+ end+ guardian = Guardian.new(actor)+ guardian.ensure_can_suspend!(target)++ suspend_until = context["suspend_until"].presence || fields.dig("suspend_until", "value")+ reason = context["reason"].presence || fields.dig("reason", "value")++ User.transaction do+ target.suspended_till = suspend_until+ target.suspended_at = DateTime.now+ target.save!++ StaffActionLogger.new(actor).log_user_suspend(target, reason)+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/topic_required_words.rb b/plugins/automation/lib/discourse_automation/scripts/topic_required_words.rbnew file mode 100644index 00000000000..be4dbbbc8fe--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/topic_required_words.rb@@ -0,0 +1,9 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::TOPIC_REQUIRED_WORDS) do+ field :words, component: :text_list++ version 1++ triggerables %i[topic]+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/user_global_notice.rb b/plugins/automation/lib/discourse_automation/scripts/user_global_notice.rbnew file mode 100644index 00000000000..456689bc6df--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/user_global_notice.rb@@ -0,0 +1,59 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::USER_GLOBAL_NOTICE) do+ field :notice, component: :message, required: true, accepts_placeholders: true+ field :level,+ component: :choices,+ extra: {+ content:+ %w[success error warning info].map do |level|+ {+ id: level,+ name: "discourse_automation.scriptables.user_global_notice.levels.#{level}",+ }+ end,+ }++ version 1++ triggerables [:stalled_topic]+ triggerables [:first_accepted_solution] if defined?(DiscourseSolved)++ placeholder :username++ script do |context, fields, automation|+ placeholders = {}.merge(context["placeholders"] || {})++ if context["kind"] == DiscourseAutomation::Triggers::STALLED_TOPIC+ user = context["topic"].user+ placeholders["username"] = user.username+ elsif context["kind"] == "first_accepted_solution"+ username = context["usernames"][0]+ user = User.find_by(username: username)+ placeholders["username"] = username+ end++ notice = utils.apply_placeholders(fields.dig("notice", "value") || "", placeholders)+ level = fields.dig("level", "value")++ begin+ DiscourseAutomation::UserGlobalNotice.upsert(+ {+ identifier: automation.id,+ notice: notice,+ user_id: user.id,+ level: level,+ created_at: Time.now,+ updated_at: Time.now,+ },+ unique_by: "idx_discourse_automation_user_global_notices",+ )+ rescue ActiveRecord::RecordNotUnique+ # do nothing+ end+ end++ on_reset do |automation|+ DiscourseAutomation::UserGlobalNotice.where(identifier: automation.id).destroy_all+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/user_group_membership_through_badge.rb b/plugins/automation/lib/discourse_automation/scripts/user_group_membership_through_badge.rbnew file mode 100644index 00000000000..5b1e05d9b68--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/user_group_membership_through_badge.rb@@ -0,0 +1,116 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(+ DiscourseAutomation::Scripts::USER_GROUP_MEMBERSHIP_THROUGH_BADGE,+) do+ version 2++ field :badge,+ component: :choices,+ extra: {+ content:+ Badge.order(:name).select(:id, :name).map { |b| { id: b.id, translated_name: b.name } },+ },+ required: true+ field :group, component: :group, required: true, extra: { ignore_automatic: true }+ field :update_user_title_and_flair, component: :boolean+ field :remove_members_without_badge, component: :boolean++ triggerables %i[recurring user_first_logged_in]++ script do |context, fields|+ badge_id = fields.dig("badge", "value")+ group_id = fields.dig("group", "value")+ update_user_title_and_flair = fields.dig("update_user_title_and_flair", "value")+ remove_members_without_badge = fields.dig("remove_members_without_badge", "value")+ current_user = context["user"]+ bulk_modify_start_count =+ DiscourseAutomation::USER_GROUP_MEMBERSHIP_THROUGH_BADGE_BULK_MODIFY_START_COUNT++ badge = Badge.find_by(id: badge_id)+ unless badge+ Rails.logger.warn("[discourse-automation] Couldn’t find badge with id #{badge_id}")+ next+ end++ group = Group.find_by(id: group_id)+ unless group+ Rails.logger.warn("[discourse-automation] Couldn’t find group with id #{group_id}")+ next+ end++ query_options = { group_id: group.id, badge_id: badge.id }++ # IDs of users who currently have badge but not members of target group+ user_ids_to_add_query = +<<~SQL+ SELECT u.id AS user_id+ FROM users u+ JOIN user_badges ub ON u.id = ub.user_id+ LEFT JOIN group_users gu ON u.id = gu.user_id AND gu.group_id = :group_id+ WHERE ub.badge_id = :badge_id AND gu.user_id IS NULL+ SQL++ if current_user+ user_ids_to_add_query << " AND u.id = :user_id"+ query_options[:user_id] = current_user.id+ end++ user_ids_to_add = DB.query_single(user_ids_to_add_query, query_options)++ if user_ids_to_add.count < bulk_modify_start_count+ User+ .where(id: user_ids_to_add)+ .each do |user|+ group.add(user)+ GroupActionLogger.new(Discourse.system_user, group).log_add_user_to_group(user)+ end+ else+ group.bulk_add(user_ids_to_add)+ end++ if update_user_title_and_flair && user_ids_to_add.present?+ DB.exec(<<~SQL, ids: user_ids_to_add, title: group.title, flair_group_id: group.id)+ UPDATE users+ SET title = :title, flair_group_id = :flair_group_id+ WHERE id IN (:ids)+ SQL+ end++ next unless remove_members_without_badge++ # IDs of users who are currently target group members without the badge+ user_ids_to_remove_query = +<<~SQL+ SELECT u.id AS user_id+ FROM users u+ JOIN group_users gu ON u.id = gu.user_id+ LEFT JOIN user_badges ub ON u.id = ub.user_id AND ub.badge_id = :badge_id+ WHERE gu.group_id = :group_id AND ub.user_id IS NULL+ SQL++ if current_user+ user_ids_to_remove_query << " AND u.id = :user_id"+ query_options[:user_id] ||= current_user.id+ end++ user_ids_to_remove = DB.query_single(user_ids_to_remove_query, query_options)++ if user_ids_to_remove.count < bulk_modify_start_count+ User+ .where(id: user_ids_to_remove)+ .each do |user|+ group.remove(user)+ GroupActionLogger.new(Discourse.system_user, group).log_remove_user_from_group(user)+ end+ else+ group.bulk_remove(user_ids_to_remove)+ end++ if update_user_title_and_flair && user_ids_to_remove.present?+ DB.exec(<<~SQL, ids: user_ids_to_remove, title: group.title, flair_group_id: group.id)+ UPDATE users+ SET title = NULL, flair_group_id = NULL+ WHERE id IN (:ids) AND (flair_group_id = :flair_group_id OR title = :title)+ SQL+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/scripts/zapier_webhook.rb b/plugins/automation/lib/discourse_automation/scripts/zapier_webhook.rbnew file mode 100644index 00000000000..531d9a06170--- /dev/null+++ b/plugins/automation/lib/discourse_automation/scripts/zapier_webhook.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++DiscourseAutomation::Scriptable.add(DiscourseAutomation::Scripts::ZAPIER_WEBHOOK) do+ field :webhook_url, component: :text, required: true++ version 1++ triggerables %i[user_promoted user_added_to_group user_badge_granted user_removed_from_group]++ script do |context, fields|+ webhook_url = fields.dig("webhook_url", "value")++ unless webhook_url&.start_with?("https://hooks.zapier.com/hooks/catch/")+ Rails.logger.warn "[discourse-automation] #{webhook_url} is not a valid Zapier webhook URL, expecting an URL starting with https://hooks.zapier.com/hooks/catch/"+ next+ end++ Jobs.enqueue(+ :discourse_automation_call_zapier_webhook,+ webhook_url: webhook_url,+ context: context,+ )+ end+enddiff --git a/plugins/automation/lib/discourse_automation/triggerable.rb b/plugins/automation/lib/discourse_automation/triggerable.rbnew file mode 100644index 00000000000..486acbd383d--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggerable.rb@@ -0,0 +1,118 @@+# frozen_string_literal: true++module DiscourseAutomation+ class Triggerable+ attr_reader :fields, :name, :not_found, :settings, :automation++ MANUAL_TRIGGER_KEY = :manual_trigger++ def initialize(name, automation = nil)+ @name = name+ @placeholders = []+ @fields = []+ @settings = { MANUAL_TRIGGER_KEY => false }+ @on_update_block = proc {}+ @on_call_block = proc {}+ @not_found = false+ @validations = []+ @automation = automation++ eval! if @name+ end++ def id+ "trigger"+ end++ def scriptable?+ false+ end++ def triggerable?+ true+ end++ def validate(&block)+ @validations << block+ end++ def valid?(automation)+ @validations.each { |block| automation.instance_exec(&block) }++ automation.errors.blank?+ end++ def placeholders+ @placeholders.uniq.compact.map(&:to_sym)+ end++ def placeholder(*args)+ if args.present?+ @placeholders << args[0]+ elsif block_given?+ @placeholders =+ @placeholders.concat(Array(yield(@automation.serialized_fields, @automation)))+ end+ end++ def field(name, component:, **options)+ @fields << {+ name: name,+ component: component,+ extra: {+ },+ accepts_placeholders: false,+ accepted_contexts: [],+ required: false,+ }.merge(options || {})+ end++ def setting(key, value)+ @settings[key] = value+ end++ def enable_manual_trigger+ setting(MANUAL_TRIGGER_KEY, true)+ end++ def components+ fields.map { |f| f[:component] }.uniq+ end++ def eval!+ begin+ public_send("__triggerable_#{name.underscore}")+ rescue NoMethodError+ @not_found = true+ end++ self+ end++ def on_call(&block)+ if block_given?+ @on_call_block = block+ else+ @on_call_block+ end+ end++ def on_update(&block)+ if block_given?+ @on_update_block = block+ else+ @on_update_block+ end+ end++ def self.add(identifier, &block)+ @all_triggers = nil+ define_method("__triggerable_#{identifier}", block || proc {})+ end++ def self.all+ @all_triggers ||=+ DiscourseAutomation::Triggerable.instance_methods(false).grep(/^__triggerable_/)+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/triggers.rb b/plugins/automation/lib/discourse_automation/triggers.rbnew file mode 100644index 00000000000..a1ad649d589--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++module DiscourseAutomation+ module Triggers+ AFTER_POST_COOK = "after_post_cook"+ API_CALL = "api_call"+ CATEGORY_CREATED_EDITED = "category_created_edited"+ PM_CREATED = "pm_created"+ POINT_IN_TIME = "point_in_time"+ POST_CREATED_EDITED = "post_created_edited"+ RECURRING = "recurring"+ STALLED_TOPIC = "stalled_topic"+ STALLED_WIKI = "stalled_wiki"+ TOPIC = "topic"+ USER_ADDED_TO_GROUP = "user_added_to_group"+ USER_BADGE_GRANTED = "user_badge_granted"+ USER_FIRST_LOGGED_IN = "user_first_logged_in"+ USER_PROMOTED = "user_promoted"+ USER_REMOVED_FROM_GROUP = "user_removed_from_group"+ USER_UPDATED = "user_updated"+ end+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/after_post_cook.rb b/plugins/automation/lib/discourse_automation/triggers/after_post_cook.rbnew file mode 100644index 00000000000..e76f919eb67--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/after_post_cook.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::AFTER_POST_COOK) do+ field :restricted_category, component: :category+ field :restricted_tags, component: :tags+ field :valid_trust_levels, component: :"trust-levels"+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/api_call.rb b/plugins/automation/lib/discourse_automation/triggers/api_call.rbnew file mode 100644index 00000000000..d363d225f96--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/api_call.rb@@ -0,0 +1,3 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::API_CALL) {}diff --git a/plugins/automation/lib/discourse_automation/triggers/category_created_edited.rb b/plugins/automation/lib/discourse_automation/triggers/category_created_edited.rbnew file mode 100644index 00000000000..9dd39103541--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/category_created_edited.rb@@ -0,0 +1,5 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::CATEGORY_CREATED_EDITED) do+ field :restricted_category, component: :category+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/pm_created.rb b/plugins/automation/lib/discourse_automation/triggers/pm_created.rbnew file mode 100644index 00000000000..62890186b86--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/pm_created.rb@@ -0,0 +1,10 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::PM_CREATED) do+ field :restricted_user, component: :user+ field :restricted_group, component: :group+ field :ignore_staff, component: :boolean+ field :ignore_automated, component: :boolean+ field :ignore_group_members, component: :boolean+ field :valid_trust_levels, component: :"trust-levels"+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/point_in_time.rb b/plugins/automation/lib/discourse_automation/triggers/point_in_time.rbnew file mode 100644index 00000000000..8913b41c4f2--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/point_in_time.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::POINT_IN_TIME) do+ field :execute_at, component: :date_time, required: true++ on_update do |automation, metadata|+ # prevents creating a new pending automation on save when date is expired+ execute_at = metadata.dig("execute_at", "value")+ if execute_at && execute_at > Time.zone.now+ automation.pending_automations.create!(execute_at: execute_at)+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/post_created_edited.rb b/plugins/automation/lib/discourse_automation/triggers/post_created_edited.rbnew file mode 100644index 00000000000..fa0f38e15d6--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/post_created_edited.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::POST_CREATED_EDITED) do+ field :action_type,+ component: :choices,+ extra: {+ content: [+ {+ id: "created",+ name: "discourse_automation.triggerables.post_created_edited.created",+ },+ { id: "edited", name: "discourse_automation.triggerables.post_created_edited.edited" },+ ],+ }+ field :restricted_category, component: :category+ field :restricted_group, component: :group+ field :ignore_automated, component: :boolean+ field :ignore_group_members, component: :boolean+ field :valid_trust_levels, component: :"trust-levels"+ field :first_post_only, component: :boolean+ field :first_topic_only, component: :boolean+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/recurring.rb b/plugins/automation/lib/discourse_automation/triggers/recurring.rbnew file mode 100644index 00000000000..659f821d716--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/recurring.rb@@ -0,0 +1,93 @@+# frozen_string_literal: true++module DiscourseAutomation+ module Triggers+ module Recurring+ RECURRENCE_CHOICES = [+ { id: "minute", name: "discourse_automation.triggerables.recurring.frequencies.minute" },+ { id: "hour", name: "discourse_automation.triggerables.recurring.frequencies.hour" },+ { id: "day", name: "discourse_automation.triggerables.recurring.frequencies.day" },+ { id: "weekday", name: "discourse_automation.triggerables.recurring.frequencies.weekday" },+ { id: "week", name: "discourse_automation.triggerables.recurring.frequencies.week" },+ { id: "month", name: "discourse_automation.triggerables.recurring.frequencies.month" },+ { id: "year", name: "discourse_automation.triggerables.recurring.frequencies.year" },+ ]++ def self.setup_pending_automation(automation, fields)+ automation.pending_automations.destroy_all++ return unless start_date = fields.dig("start_date", "value")+ return unless interval = fields.dig("recurrence", "value", "interval")+ return unless frequency = fields.dig("recurrence", "value", "frequency")++ start_date = Time.parse(start_date)+ byday = start_date.strftime("%A").upcase[0, 2]+ interval = interval.to_i+ interval_end = interval + 1++ next_trigger_date =+ case frequency+ when "minute"+ (Time.zone.now + interval.minute).beginning_of_minute+ when "hour"+ (Time.zone.now + interval.hour).beginning_of_hour+ when "day"+ RRule::Rule+ .new("FREQ=DAILY;INTERVAL=#{interval}", dtstart: start_date)+ .between(Time.now, interval_end.days.from_now)+ .first+ when "weekday"+ max_weekends = (interval_end.to_f / 5).ceil+ RRule::Rule+ .new("FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR", dtstart: start_date)+ .between(Time.now.end_of_day, max_weekends.weeks.from_now)+ .drop(interval - 1)+ .first+ when "week"+ RRule::Rule+ .new("FREQ=WEEKLY;INTERVAL=#{interval};BYDAY=#{byday}", dtstart: start_date)+ .between(Time.now.end_of_week, interval_end.weeks.from_now)+ .first+ when "month"+ count = 0+ (start_date.beginning_of_month.to_date..start_date.end_of_month.to_date).each do |date|+ count += 1 if date.strftime("%A") == start_date.strftime("%A")+ break if date.day == start_date.day+ end+ RRule::Rule+ .new("FREQ=MONTHLY;INTERVAL=#{interval};BYDAY=#{count}#{byday}", dtstart: start_date)+ .between(Time.now, interval_end.months.from_now)+ .first+ when "year"+ RRule::Rule+ .new("FREQ=YEARLY;INTERVAL=#{interval}", dtstart: start_date)+ .between(Time.now, interval_end.years.from_now)+ .first+ end++ if next_trigger_date && next_trigger_date > Time.zone.now+ automation.pending_automations.create!(execute_at: next_trigger_date)+ end+ end+ end+ end+end++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::RECURRING) do+ field :recurrence,+ component: :period,+ extra: {+ content: DiscourseAutomation::Triggers::Recurring::RECURRENCE_CHOICES,+ },+ required: true+ field :start_date, component: :date_time, required: true++ on_update do |automation, fields|+ DiscourseAutomation::Triggers::Recurring.setup_pending_automation(automation, fields)+ end+ on_call do |automation, fields|+ DiscourseAutomation::Triggers::Recurring.setup_pending_automation(automation, fields)+ end++ enable_manual_trigger+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/stalled_topic.rb b/plugins/automation/lib/discourse_automation/triggers/stalled_topic.rbnew file mode 100644index 00000000000..803b7e6dbef--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/stalled_topic.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true++key = "discourse_automation.triggerables.stalled_topic.durations"+ids = %w[PT1H P1D P1W P2W P1M P3M P6M P1Y]+duration_choices = ids.map { |id| { id: id, name: "#{key}.#{id}" } }++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::STALLED_TOPIC) do+ field :categories, component: :categories+ field :tags, component: :tags+ field :stalled_after, component: :choices, extra: { content: duration_choices }, required: true++ placeholder :topic_url+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/stalled_wiki.rb b/plugins/automation/lib/discourse_automation/triggers/stalled_wiki.rbnew file mode 100644index 00000000000..bbf9b7ad74b--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/stalled_wiki.rb@@ -0,0 +1,37 @@+# frozen_string_literal: true++module DiscourseAutomation+ module Triggers+ module StalledWiki+ DURATION_CHOICES = [+ { id: "PT1H", name: "discourse_automation.triggerables.stalled_wiki.durations.PT1H" },+ { id: "P1D", name: "discourse_automation.triggerables.stalled_wiki.durations.P1D" },+ { id: "P1W", name: "discourse_automation.triggerables.stalled_wiki.durations.P1W" },+ { id: "P2W", name: "discourse_automation.triggerables.stalled_wiki.durations.P2W" },+ { id: "P1M", name: "discourse_automation.triggerables.stalled_wiki.durations.P1M" },+ { id: "P3M", name: "discourse_automation.triggerables.stalled_wiki.durations.P3M" },+ { id: "P6M", name: "discourse_automation.triggerables.stalled_wiki.durations.P6M" },+ { id: "P1Y", name: "discourse_automation.triggerables.stalled_wiki.durations.P1Y" },+ ]+ end+ end+end++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::STALLED_WIKI) do+ field :restricted_category, component: :category+ field :stalled_after,+ component: :choices,+ extra: {+ content: DiscourseAutomation::Triggers::StalledWiki::DURATION_CHOICES,+ },+ required: true+ field :retriggered_after,+ component: :choices,+ extra: {+ content: DiscourseAutomation::Triggers::StalledWiki::DURATION_CHOICES,+ }++ placeholder :wiki_url++ enable_manual_trigger+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/topic.rb b/plugins/automation/lib/discourse_automation/triggers/topic.rbnew file mode 100644index 00000000000..d1b5ad69cdb--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/topic.rb@@ -0,0 +1,29 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::TOPIC) do+ field :restricted_topic, component: :text++ on_update do |automation, metadata, previous_metadata|+ ActiveRecord::Base.transaction do+ previous_topic_id = previous_metadata.dig("restricted_topic", "value")+ topic_id = metadata.dig("restricted_topic", "value")++ if previous_topic_id && previous_topic_id != topic_id+ previous_topic = Topic.find_by(id: previous_topic_id)++ if previous_topic+ TopicCustomField.where(+ topic_id: previous_topic_id,+ name: DiscourseAutomation::CUSTOM_FIELD,+ value: automation.id,+ ).delete_all+ end+ end++ if topic_id+ topic = Topic.find_by(id: topic_id)+ topic&.upsert_custom_fields(DiscourseAutomation::CUSTOM_FIELD => automation.id)+ end+ end+ end+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/user_added_to_group.rb b/plugins/automation/lib/discourse_automation/triggers/user_added_to_group.rbnew file mode 100644index 00000000000..6706c90692b--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/user_added_to_group.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::USER_ADDED_TO_GROUP) do+ field :joined_group, component: :group, required: true++ placeholder :group_name+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/user_badge_granted.rb b/plugins/automation/lib/discourse_automation/triggers/user_badge_granted.rbnew file mode 100644index 00000000000..003de21a66c--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/user_badge_granted.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::USER_BADGE_GRANTED) do+ field :badge,+ component: :choices,+ extra: {+ content: Badge.all.map { |b| { id: b.id, translated_name: b.name } },+ },+ required: true+ field :only_first_grant, component: :boolean+ placeholder :badge_name+ placeholder :grant_count+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/user_first_logged_in.rb b/plugins/automation/lib/discourse_automation/triggers/user_first_logged_in.rbnew file mode 100644index 00000000000..21bb41f5569--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/user_first_logged_in.rb@@ -0,0 +1,3 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN) {}diff --git a/plugins/automation/lib/discourse_automation/triggers/user_promoted.rb b/plugins/automation/lib/discourse_automation/triggers/user_promoted.rbnew file mode 100644index 00000000000..d4a81f771b3--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/user_promoted.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::USER_PROMOTED) do+ field :restricted_group, component: :group+ field :trust_level_transition,+ component: :choices,+ extra: {+ content: DiscourseAutomation::USER_PROMOTED_TRUST_LEVEL_CHOICES,+ },+ required: true++ placeholder :trust_level_transition+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/user_removed_from_group.rb b/plugins/automation/lib/discourse_automation/triggers/user_removed_from_group.rbnew file mode 100644index 00000000000..0c00a2797ed--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/user_removed_from_group.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::USER_REMOVED_FROM_GROUP) do+ field :left_group, component: :group, required: true++ placeholder :group_name+enddiff --git a/plugins/automation/lib/discourse_automation/triggers/user_updated.rb b/plugins/automation/lib/discourse_automation/triggers/user_updated.rbnew file mode 100644index 00000000000..6080f4caa7e--- /dev/null+++ b/plugins/automation/lib/discourse_automation/triggers/user_updated.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++class DiscourseAutomation::Triggerable+ USER_UPDATED = "user_updated"+end++DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::USER_UPDATED) do+ field :custom_fields, component: :custom_fields+ field :user_profile, component: :user_profile+ field :once_per_user, component: :boolean++ validate do+ has_triggers = has_trigger_field?(:custom_fields) && has_trigger_field?(:user_profile)+ custom_fields = trigger_field(:custom_fields)["value"]+ user_profile = trigger_field(:user_profile)["value"]++ if has_triggers && custom_fields.blank? && user_profile.blank?+ errors.add(+ :base,+ I18n.t("discourse_automation.triggerables.errors.custom_fields_or_user_profile_required"),+ )+ false+ else+ true+ end+ end++ placeholder do |fields, automation|+ custom_fields = automation.trigger_field("custom_fields")["value"] || []+ user_profile = automation.trigger_field("user_profile")["value"] || []+ custom_fields + user_profile+ end+enddiff --git a/plugins/automation/lib/plugin/instance.rb b/plugins/automation/lib/plugin/instance.rbnew file mode 100644index 00000000000..3afd7f1d48f--- /dev/null+++ b/plugins/automation/lib/plugin/instance.rb@@ -0,0 +1,17 @@+# frozen_string_literal: true++class Plugin::Instance+ def add_automation_scriptable(name, &block)+ reloadable_patch { DiscourseAutomation::Scriptable.add(name, &block) }+ end++ def add_automation_triggerable(name, &block)+ reloadable_patch { DiscourseAutomation::Triggerable.add(name, &block) }+ end++ def add_triggerable_to_scriptable(triggerable, scriptable)+ reloadable_patch do+ DiscourseAutomation::Scriptable.add_plugin_triggerable(triggerable, scriptable)+ end+ end+enddiff --git a/plugins/automation/lib/tasks/automation.rake b/plugins/automation/lib/tasks/automation.rakenew file mode 100644index 00000000000..a3998aa544c--- /dev/null+++ b/plugins/automation/lib/tasks/automation.rake@@ -0,0 +1,19 @@+# frozen_string_literal: true++task "run_automation" => :environment do+ script_methods = DiscourseAutomation::Scriptable.all++ scripts = []++ DiscourseAutomation::Automation.find_each do |automation|+ script_methods.each do |name|+ type = name.to_s.gsub("script_", "")++ next if type != automation.script++ scriptable = automation.scriptable+ scriptable.public_send(name)+ scripts << scriptable.script.call+ end+ end+enddiff --git a/plugins/automation/plugin.rb b/plugins/automation/plugin.rbnew file mode 100644index 00000000000..b0baedfda76--- /dev/null+++ b/plugins/automation/plugin.rb@@ -0,0 +1,217 @@+# frozen_string_literal: true++# name: automation+# about: Allows admins to automate actions through scripts and triggers. Customisation is made through an automatically generated UI.+# meta_topic_id: 195773+# version: 0.1+# authors: jjaffeux+# url: https://github.com/discourse/discourse/tree/main/plugins/automation++gem "iso8601", "0.13.0"+gem "rrule", "0.4.4"++enabled_site_setting :discourse_automation_enabled++register_asset "stylesheets/common/discourse-automation.scss"++module ::DiscourseAutomation+ PLUGIN_NAME = "automation"++ CUSTOM_FIELD = "discourse_automation_ids"+ TOPIC_LAST_CHECKED_BY = "discourse_automation_last_checked_by"+ TOPIC_LAST_CHECKED_AT = "discourse_automation_last_checked_at"++ USER_PROMOTED_TRUST_LEVEL_CHOICES = [+ { id: "TLALL", name: "discourse_automation.triggerables.user_promoted.trust_levels.ALL" },+ { id: "TL01", name: "discourse_automation.triggerables.user_promoted.trust_levels.TL01" },+ { id: "TL12", name: "discourse_automation.triggerables.user_promoted.trust_levels.TL12" },+ { id: "TL23", name: "discourse_automation.triggerables.user_promoted.trust_levels.TL23" },+ { id: "TL34", name: "discourse_automation.triggerables.user_promoted.trust_levels.TL34" },+ ]++ AUTO_RESPONDER_TRIGGERED_IDS = "auto_responder_triggered_ids"+ USER_GROUP_MEMBERSHIP_THROUGH_BADGE_BULK_MODIFY_START_COUNT = 1000+end++require_relative "lib/discourse_automation/engine"+require_relative "lib/discourse_automation/scriptable"+require_relative "lib/discourse_automation/triggerable"+require_relative "lib/plugin/instance"++after_initialize do+ %w[+ app/jobs/regular/discourse_automation_call_zapier_webhook+ app/jobs/regular/discourse_automation_trigger+ app/jobs/scheduled/discourse_automation_tracker+ app/jobs/scheduled/stalled_topic_tracker+ app/jobs/scheduled/stalled_wiki_tracker+ app/queries/stalled_topic_finder+ app/services/discourse_automation/user_badge_granted_handler+ lib/discourse_automation/event_handlers+ lib/discourse_automation/post_extension+ lib/discourse_automation/scripts+ lib/discourse_automation/scripts/add_user_to_group_through_custom_field+ lib/discourse_automation/scripts/append_last_checked_by+ lib/discourse_automation/scripts/append_last_edited_by+ lib/discourse_automation/scripts/auto_responder+ lib/discourse_automation/scripts/auto_tag_topic+ lib/discourse_automation/scripts/banner_topic+ lib/discourse_automation/scripts/close_topic+ lib/discourse_automation/scripts/flag_post_on_words+ lib/discourse_automation/scripts/gift_exchange+ lib/discourse_automation/scripts/group_category_notification_default+ lib/discourse_automation/scripts/pin_topic+ lib/discourse_automation/scripts/post+ lib/discourse_automation/scripts/send_pms+ lib/discourse_automation/scripts/suspend_user_by_email+ lib/discourse_automation/scripts/topic_required_words+ lib/discourse_automation/scripts/user_global_notice+ lib/discourse_automation/scripts/user_group_membership_through_badge+ lib/discourse_automation/scripts/zapier_webhook+ lib/discourse_automation/triggers+ lib/discourse_automation/triggers/after_post_cook+ lib/discourse_automation/triggers/api_call+ lib/discourse_automation/triggers/category_created_edited+ lib/discourse_automation/triggers/pm_created+ lib/discourse_automation/triggers/point_in_time+ lib/discourse_automation/triggers/post_created_edited+ lib/discourse_automation/triggers/recurring+ lib/discourse_automation/triggers/stalled_topic+ lib/discourse_automation/triggers/stalled_wiki+ lib/discourse_automation/triggers/topic+ lib/discourse_automation/triggers/user_added_to_group+ lib/discourse_automation/triggers/user_badge_granted+ lib/discourse_automation/triggers/user_promoted+ lib/discourse_automation/triggers/user_removed_from_group+ lib/discourse_automation/triggers/user_first_logged_in+ lib/discourse_automation/triggers/user_updated+ ].each { |path| require_relative path }++ reloadable_patch { Post.prepend DiscourseAutomation::PostExtension }++ add_admin_route "discourse_automation.title", "discourse-automation"++ add_api_key_scope(+ :automations_trigger,+ {+ post: {+ actions: %w[discourse_automation/automations#trigger],+ params: %i[context],+ formats: :json,+ },+ },+ )++ add_to_serializer(:current_user, :global_notices) do+ notices = DiscourseAutomation::UserGlobalNotice.where(user_id: object.id)+ ActiveModel::ArraySerializer.new(+ notices,+ each_serializer: DiscourseAutomation::UserGlobalNoticeSerializer,+ ).as_json+ end++ on(:user_first_logged_in) do |user|+ name = DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN++ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each { |automation| automation.trigger!("kind" => name, "user" => user) }+ end++ on(:user_added_to_group) do |user, group|+ name = DiscourseAutomation::Triggers::USER_ADDED_TO_GROUP++ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each do |automation|+ joined_group = automation.trigger_field("joined_group")+ if joined_group["value"] == group.id+ automation.trigger!(+ "kind" => name,+ "usernames" => [user.username],+ "user" => user,+ "group" => group,+ "placeholders" => {+ "group_name" => group.name,+ },+ )+ end+ end+ end++ on(:user_removed_from_group) do |user, group|+ name = DiscourseAutomation::Triggers::USER_REMOVED_FROM_GROUP++ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each do |automation|+ left_group = automation.trigger_field("left_group")+ if left_group["value"] == group.id+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_REMOVED_FROM_GROUP,+ "usernames" => [user.username],+ "user" => user,+ "group" => group,+ "placeholders" => {+ "group_name" => group.name,+ },+ )+ end+ end+ end++ on(:user_badge_granted) do |badge_id, user_id|+ name = DiscourseAutomation::Triggers::USER_BADGE_GRANTED+ DiscourseAutomation::Automation+ .where(trigger: name, enabled: true)+ .find_each do |automation|+ DiscourseAutomation::UserBadgeGrantedHandler.handle(automation, badge_id, user_id)+ end+ end++ on(:user_promoted) do |payload|+ user_id, new_trust_level, old_trust_level =+ payload.values_at(:user_id, :new_trust_level, :old_trust_level)++ DiscourseAutomation::EventHandlers.handle_user_promoted(+ user_id,+ new_trust_level,+ old_trust_level,+ )+ end++ on(:topic_created) do |topic|+ DiscourseAutomation::EventHandlers.handle_pm_created(topic) if topic.private_message?+ end++ on(:post_created) do |post|+ DiscourseAutomation::EventHandlers.handle_post_created_edited(post, :create)+ end++ on(:post_edited) do |post|+ DiscourseAutomation::EventHandlers.handle_post_created_edited(post, :edit)+ end++ on(:category_created) do |category|+ DiscourseAutomation::EventHandlers.handle_category_created_edited(category, :create)+ end++ on(:category_edited) do |category|+ DiscourseAutomation::EventHandlers.handle_category_created_edited(category, :edit)+ end++ Plugin::Filter.register(:after_post_cook) do |post, cooked|+ DiscourseAutomation::EventHandlers.handle_after_post_cook(post, cooked)+ end++ on(:post_created) { |post| DiscourseAutomation::EventHandlers.handle_stalled_topic(post) }++ register_topic_custom_field_type(DiscourseAutomation::CUSTOM_FIELD, [:integer])+ register_topic_custom_field_type(DiscourseAutomation::AUTO_RESPONDER_TRIGGERED_IDS, [:integer])++ on(:user_updated) { |user| DiscourseAutomation::EventHandlers.handle_user_updated(user) }++ register_user_custom_field_type(DiscourseAutomation::CUSTOM_FIELD, [:integer])+ register_post_custom_field_type(DiscourseAutomation::CUSTOM_FIELD, [:integer])+ register_post_custom_field_type("stalled_wiki_triggered_at", :string)+enddiff --git a/plugins/automation/spec/discourse_automation_helper.rb b/plugins/automation/spec/discourse_automation_helper.rbnew file mode 100644index 00000000000..8db0f0f6af5--- /dev/null+++ b/plugins/automation/spec/discourse_automation_helper.rb@@ -0,0 +1,36 @@+# frozen_string_literal: true++require "rails_helper"++def capture_contexts(&blk)+ DiscourseAutomation::CapturedContext.capture(&blk)+end++module DiscourseAutomation::CapturedContext+ def self.add(context)+ @contexts << context if @capturing+ end++ def self.capture+ raise StandardError, "Nested capture is not supported" if @capturing+ raise StandardError, "Expecting a block" if !block_given?+ @capturing = true+ @contexts = []+ yield+ @contexts+ ensure+ @capturing = false+ end+end++DiscourseAutomation::Scriptable.add("something_about_us") do+ script do |context|+ DiscourseAutomation::CapturedContext.add(context)+ nil+ end+ triggerables [DiscourseAutomation::Triggers::API_CALL]+end++DiscourseAutomation::Scriptable.add("nothing_about_us") do+ triggerables [DiscourseAutomation::Triggers::API_CALL]+enddiff --git a/plugins/automation/spec/fabricators/automation_fabricator.rb b/plugins/automation/spec/fabricators/automation_fabricator.rbnew file mode 100644index 00000000000..07967fb1e20--- /dev/null+++ b/plugins/automation/spec/fabricators/automation_fabricator.rb@@ -0,0 +1,9 @@+# frozen_string_literal: true++Fabricator(:automation, from: DiscourseAutomation::Automation) do+ name "My Automation"+ script "something_about_us"+ trigger DiscourseAutomation::Triggers::TOPIC+ last_updated_by_id Discourse.system_user.id+ enabled true+enddiff --git a/plugins/automation/spec/fabricators/automation_field_fabricator.rb b/plugins/automation/spec/fabricators/automation_field_fabricator.rbnew file mode 100644index 00000000000..691949bd514--- /dev/null+++ b/plugins/automation/spec/fabricators/automation_field_fabricator.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++Fabricator(:automation_field, from: DiscourseAutomation::Field) do+ automation+ name "custom_field_name"+ component "custom_field"+enddiff --git a/plugins/automation/spec/integration/core_ext_spec.rb b/plugins/automation/spec/integration/core_ext_spec.rbnew file mode 100644index 00000000000..78c6668455d--- /dev/null+++ b/plugins/automation/spec/integration/core_ext_spec.rb@@ -0,0 +1,129 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "Core extensions" do+ fab!(:automation_1) { Fabricate(:automation) }+ fab!(:automation_2) { Fabricate(:automation) }++ describe "plugin_api" do+ describe "#add_triggerable_to_scriptable" do+ it "adds the triggerable as a possibility for a scriptable" do+ plugin = Plugin::Instance.new nil, "/tmp/test.rb"+ plugin.add_automation_triggerable(:bar) {}+ plugin.add_automation_scriptable(:foo) {}+ plugin.add_triggerable_to_scriptable(:foo, :bar)++ expect(DiscourseAutomation::Scriptable.plugin_triggerables[:bar]).to contain_exactly(:foo)+ end+ end++ describe "#add_automation_triggerable" do+ it "adds the triggerable" do+ plugin = Plugin::Instance.new nil, "/tmp/test.rb"+ plugin.add_automation_triggerable(:foo) {}++ expect(DiscourseAutomation::Triggerable.all).to include(:__triggerable_foo)+ end+ end++ describe "#add_automation_scriptable" do+ it "adds the scriptable" do+ plugin = Plugin::Instance.new nil, "/tmp/test.rb"+ plugin.add_automation_scriptable(:foo) {}++ expect(DiscourseAutomation::Scriptable.all).to include(:__scriptable_foo)+ end+ end+ end++ describe "post custom fields" do+ it "supports discourse_automation_ids" do+ post = create_post+ automation_1.attach_custom_field(post)++ expect(post.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to eq([automation_1.id])++ automation_2.attach_custom_field(post)++ expect(post.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to eq(+ [automation_1.id, automation_2.id],+ )++ PostCustomField.where(post_id: post.id, name: DiscourseAutomation::CUSTOM_FIELD).delete_all++ expect(post.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to be(nil)++ automation_1.attach_custom_field(post)+ automation_1.attach_custom_field(post)+ automation_1.attach_custom_field(post)+ automation_1.attach_custom_field(post)++ expect(post.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to eq([automation_1.id])++ automation_1.detach_custom_field(post)++ expect(post.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to be(nil)+ end+ end++ describe "topic custom fields" do+ it "supports discourse_automation_ids" do+ topic = create_topic+ automation_1.attach_custom_field(topic)++ expect(topic.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to eq([automation_1.id])++ automation_2.attach_custom_field(topic)++ expect(topic.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to eq(+ [automation_1.id, automation_2.id],+ )++ TopicCustomField.where(topic_id: topic.id, name: DiscourseAutomation::CUSTOM_FIELD).delete_all++ expect(topic.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to be(nil)++ automation_1.attach_custom_field(topic)+ automation_1.attach_custom_field(topic)+ automation_1.attach_custom_field(topic)+ automation_1.attach_custom_field(topic)++ expect(topic.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to eq([automation_1.id])++ automation_1.detach_custom_field(topic)++ expect(topic.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to be(nil)+ end+ end++ describe "user custom fields" do+ it "supports discourse_automation_ids" do+ user = create_user+ automation_1.attach_custom_field(user)++ expect(user.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to eq([automation_1.id])++ automation_2.attach_custom_field(user)++ expect(user.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to eq(+ [automation_1.id, automation_2.id],+ )++ UserCustomField.where(user_id: user.id, name: DiscourseAutomation::CUSTOM_FIELD).delete_all++ expect(user.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to be(nil)++ automation_1.attach_custom_field(user)+ automation_1.attach_custom_field(user)+ automation_1.attach_custom_field(user)+ automation_1.attach_custom_field(user)++ expect(user.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to eq([automation_1.id])++ automation_1.detach_custom_field(user)++ expect(user.reload.custom_fields[DiscourseAutomation::CUSTOM_FIELD]).to be(nil)+ end+ end+enddiff --git a/plugins/automation/spec/jobs/call_zapier_webhook_spec.rb b/plugins/automation/spec/jobs/call_zapier_webhook_spec.rbnew file mode 100644index 00000000000..3bf7f7b45b8--- /dev/null+++ b/plugins/automation/spec/jobs/call_zapier_webhook_spec.rb@@ -0,0 +1,28 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe Jobs::DiscourseAutomationCallZapierWebhook do+ before do+ SiteSetting.discourse_automation_enabled = true+ freeze_time+ Jobs.run_immediately!++ stub_request(:post, "https://foo.com/").with(+ body: "null",+ headers: {+ "Host" => "foo.com",+ },+ ).to_return(status: 200, body: "", headers: {})+ end++ it "is rate limited" do+ RateLimiter.enable++ expect do+ 6.times do+ Jobs.enqueue(:discourse_automation_call_zapier_webhook, webhook_url: "https://foo.com")+ end+ end.to raise_error(RateLimiter::LimitExceeded)+ end+enddiff --git a/plugins/automation/spec/jobs/discourse_automation_tracker_spec.rb b/plugins/automation/spec/jobs/discourse_automation_tracker_spec.rbnew file mode 100644index 00000000000..47b36f5ea58--- /dev/null+++ b/plugins/automation/spec/jobs/discourse_automation_tracker_spec.rb@@ -0,0 +1,105 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe Jobs::DiscourseAutomationTracker do+ before { SiteSetting.discourse_automation_enabled = true }++ describe "pending automation" do+ fab!(:automation) do+ Fabricate(+ :automation,+ script: "gift_exchange",+ trigger: DiscourseAutomation::Triggers::POINT_IN_TIME,+ )+ end++ before do+ automation.upsert_field!(+ "giftee_assignment_messages",+ "pms",+ { value: [{ raw: "foo", title: "bar" }] },+ target: "script",+ )+ automation.upsert_field!("gift_exchangers_group", "group", { value: 1 }, target: "script")+ end++ context "when pending automation is in past" do+ before do+ automation.upsert_field!(+ "execute_at",+ "date_time",+ { value: 2.hours.from_now },+ target: "trigger",+ )+ end++ it "consumes the pending automation" do+ freeze_time 4.hours.from_now do+ expect { Jobs::DiscourseAutomationTracker.new.execute }.to change {+ automation.pending_automations.count+ }.by(-1)+ end+ end+ end++ context "when pending automation is in future" do+ before do+ automation.upsert_field!(+ "execute_at",+ "date_time",+ { value: 2.hours.from_now },+ target: "trigger",+ )+ end++ it "doesn’t consume the pending automation" do+ expect { Jobs::DiscourseAutomationTracker.new.execute }.not_to change {+ automation.pending_automations.count+ }+ end+ end+ end++ describe "pending pms" do+ before { Jobs.run_later! }++ fab!(:automation) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::SEND_PMS,+ trigger: DiscourseAutomation::Triggers::TOPIC,+ )+ end++ let!(:pending_pm) do+ automation.pending_pms.create!(+ title: "Il pleure dans mon cœur Comme il pleut sur la ville;",+ raw: "Quelle est cette langueur Qui pénètre mon cœur ?",+ sender: "system",+ execute_at: Time.now,+ target_usernames: ["system"],+ )+ end++ context "when pending pm is in past" do+ before { pending_pm.update!(execute_at: 2.hours.ago) }++ it "consumes the pending pm" do+ expect { Jobs::DiscourseAutomationTracker.new.execute }.to change {+ automation.pending_pms.count+ }.by(-1)+ end+ end++ context "when pending pm is in future" do+ before { pending_pm.update!(execute_at: 2.hours.from_now) }++ it "doesn’t consume the pending pm" do+ expect { Jobs::DiscourseAutomationTracker.new.execute }.not_to change {+ automation.pending_pms.count+ }+ end+ end+ end+enddiff --git a/plugins/automation/spec/jobs/stalled_topic_tracker_spec.rb b/plugins/automation/spec/jobs/stalled_topic_tracker_spec.rbnew file mode 100644index 00000000000..dece808e56e--- /dev/null+++ b/plugins/automation/spec/jobs/stalled_topic_tracker_spec.rb@@ -0,0 +1,32 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe Jobs::StalledTopicTracker do+ before { SiteSetting.discourse_automation_enabled = true }++ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::STALLED_TOPIC)+ end++ describe "find stalled topics" do+ fab!(:user_1) { Fabricate(:user) }+ fab!(:topic_1) { Fabricate(:topic, user: user_1, created_at: 1.month.ago) }++ before do+ automation.upsert_field!("stalled_after", "choices", { value: "PT1H" }, target: "trigger")+ end++ it "triggers the associated automation" do+ create_post(topic: topic_1, user: user_1, created_at: 1.month.ago)+ create_post(topic: topic_1, user: user_1, created_at: 1.month.ago)++ list = capture_contexts { Jobs::StalledTopicTracker.new.execute }++ expect(list.length).to eq(1)++ expect(list.first["kind"]).to eq(DiscourseAutomation::Triggers::STALLED_TOPIC)+ expect(list.first["topic"]["id"]).to eq(topic_1.id)+ end+ end+enddiff --git a/plugins/automation/spec/lib/scriptable_spec.rb b/plugins/automation/spec/lib/scriptable_spec.rbnew file mode 100644index 00000000000..0a680a44ac7--- /dev/null+++ b/plugins/automation/spec/lib/scriptable_spec.rb@@ -0,0 +1,412 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::Scriptable do+ before do+ DiscourseAutomation::Scriptable.add("cats_everywhere") do+ version 1++ placeholder :foo+ placeholder :bar+ placeholder { |fields, automation| "baz-#{automation.id}" }+ placeholder { |fields, automation| ["foo-baz-#{automation.id}"] }++ field :cat, component: :text+ field :dog, component: :text, accepts_placeholders: true, accepted_contexts: ["user"]+ field :bird, component: :text, triggerable: "recurring"++ script { p "script" }++ on_reset { p "on_reset" }+ end++ DiscourseAutomation::Triggerable.add("dog") { field :kind, component: :text }++ DiscourseAutomation::Scriptable.add("only_dogs") { triggerable! :dog, { kind: "good_boy" } }+ end++ fab!(:automation) do+ Fabricate(:automation, script: "cats_everywhere", trigger: DiscourseAutomation::Triggers::TOPIC)+ end++ describe "#fields" do+ it "returns the fields" do+ expect(automation.scriptable.fields).to match_array(+ [+ {+ extra: {+ },+ name: :cat,+ component: :text,+ accepts_placeholders: false,+ triggerable: nil,+ required: false,+ accepted_contexts: [],+ },+ {+ extra: {+ },+ name: :dog,+ component: :text,+ accepts_placeholders: true,+ triggerable: nil,+ required: false,+ accepted_contexts: ["user"],+ },+ {+ extra: {+ },+ name: :bird,+ component: :text,+ accepts_placeholders: false,+ triggerable: "recurring",+ required: false,+ accepted_contexts: [],+ },+ ],+ )+ end+ end++ describe "#script" do+ it "returns the script proc" do+ output = capture_stdout { automation.scriptable.script.call }++ expect(output).to include("script")+ end+ end++ describe "#on_reset" do+ it "returns the on_reset proc" do+ output = capture_stdout { automation.scriptable.on_reset.call }++ expect(output).to include("on_reset")+ end+ end++ describe "#placeholders" do+ it "returns the specified placeholders" do+ expect(automation.scriptable.placeholders).to eq(+ [+ { name: :foo, triggerable: nil },+ { name: :bar, triggerable: nil },+ { name: :"baz-#{automation.id}", triggerable: nil },+ { name: :"foo-baz-#{automation.id}", triggerable: nil },+ ],+ )+ end+ end++ describe "#version" do+ it "returns the specified version" do+ expect(automation.scriptable.version).to eq(1)+ end+ end++ describe ".add" do+ it "adds the script to the list of available scripts" do+ expect(automation.scriptable).to respond_to(:__scriptable_cats_everywhere)+ end+ end++ describe ".all" do+ it "returns the list of available scripts" do+ expect(DiscourseAutomation::Scriptable.all).to include(:__scriptable_cats_everywhere)+ end+ end++ describe ".name" do+ it "returns the name of the script" do+ expect(automation.scriptable.name).to eq("cats_everywhere")+ end+ end++ describe "triggerable!" do+ fab!(:automation) { Fabricate(:automation, script: "only_dogs", trigger: "dog") }++ it "has a forced triggerable" do+ expect(automation.scriptable.forced_triggerable).to eq(+ triggerable: :dog,+ state: {+ kind: "good_boy",+ },+ )+ end++ it "returns the forced triggerable in triggerables" do+ expect(automation.scriptable.triggerables).to eq([:dog])+ end+ end++ describe ".utils" do+ describe ".fetch_report" do+ context "when the report doesn’t exist" do+ it "does nothing" do+ expect(automation.scriptable.utils.fetch_report(:foo)).to eq(nil)+ end+ end++ context "when the report exists" do+ it "returns the data" do+ freeze_time DateTime.parse("2022-02-25")+ Fabricate(:like, user: Fabricate(:user))+ Fabricate(:like, user: Fabricate(:user))++ expect(automation.scriptable.utils.fetch_report(:likes)).to eq(+ "\n|Day|Count|\n|-|-|\n|2022-02-25|2|\n",+ )+ end+ end+ end++ describe ".apply_placeholders" do+ it "replaces the given string by placeholders" do+ input = "hello %%COOL_CAT%% {{cool_cat}}"+ map = { cool_cat: "siberian cat" }+ output = automation.scriptable.utils.apply_placeholders(input, map)+ expect(output).to eq("hello siberian cat siberian cat")+ end++ it "replaces site_title by default" do+ input = "hello {{site_title}}"+ output = automation.scriptable.utils.apply_placeholders(input)+ expect(output).to eq("hello #{SiteSetting.title}")+ end++ context "when using the REPORT key" do+ context "with no filters specified" do+ it "replaces REPORT key" do+ freeze_time DateTime.parse("2022-02-22")+ Fabricate(:like, user: Fabricate(:user))+ Fabricate(:like, user: Fabricate(:user))+ input = "hello %%REPORT=likes%%"++ output = automation.scriptable.utils.apply_placeholders(input, {})+ expect(output).to eq("hello \n|Day|Count|\n|-|-|\n|2022-02-22|2|\n")+ end+ end++ context "with dates specified" do+ it "replaces REPORT key using dates" do+ freeze_time DateTime.parse("2022-02-14")+ group = Fabricate(:group)+ group.add(Fabricate(:user, created_at: DateTime.parse("2022-02-01")))+ group.add(Fabricate(:user, created_at: DateTime.parse("2022-02-12")))+ input = "hello %%REPORT=signups start_date=2022-02-10%%"++ output = automation.scriptable.utils.apply_placeholders(input, {})+ expect(output).to eq("hello \n|Day|Count|\n|-|-|\n|2022-02-12|1|\n")+ end+ end++ context "with filters specified" do+ it "replaces REPORT key using filters" do+ freeze_time DateTime.parse("2022-02-15")+ group = Fabricate(:group)+ group.add(Fabricate(:user))+ Fabricate(:user)+ input = "hello %%REPORT=signups group=#{group.id}%%"++ output = automation.scriptable.utils.apply_placeholders(input, {})+ expect(output).to eq("hello \n|Day|Count|\n|-|-|\n|2022-02-15|1|\n")+ end+ end+ end+ end++ describe ".send_pm" do+ let(:user) { Fabricate(:user) }++ context "when pm is delayed" do+ it "creates a pending pm" do+ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Tell me and I forget.",+ raw: "Teach me and I remember. Involve me and I learn.",+ target_usernames: Array(user.username),+ },+ delay: 2,+ automation_id: automation.id,+ )+ }.to change { DiscourseAutomation::PendingPm.count }.by(1)+ end+ end++ context "when pm is not delayed" do+ it "creates a pm" do+ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Tell me and I forget.",+ raw: "Teach me and I remember. Involve me and I learn.",+ target_usernames: Array(user.username),+ },+ )+ }.to change { Post.count }.by(1)+ end+ end++ context "when pm exceeds max_post_length" do+ it "throws an error" do+ SiteSetting.max_post_length = 250++ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Tell me and I forget.",+ raw: "0123456789" * 25 + "a",+ target_usernames: [user.username],+ },+ )+ }.to raise_error(ActiveRecord::RecordNotSaved)+ end+ end++ context "when pm target_usernames contain an invalid user" do+ it "skips sending if there is only one target" do+ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Tell me and I forget.",+ raw: "0123456789" * 25 + "a",+ target_usernames: ["non-existent-user"],+ },+ )+ }.not_to change { Topic.count }+ end++ it "sends the pm without the invalid user" do+ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Tell me and I forget.",+ raw: "0123456789" * 25 + "a",+ target_usernames: ["non-existent-user", user.username],+ },+ )+ }.to change { Topic.count }++ expect(Topic.last.allowed_users).to contain_exactly(Discourse.system_user, user)+ end+ end++ context "when pm target_groups with valid group" do+ it "sends the pm" do+ group = Fabricate(:group)++ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Tell me and I forget.",+ raw: "0123456789" * 25 + "a",+ target_group_names: [group.name],+ },+ )+ }.to change { Topic.count }++ expect(Topic.last.allowed_groups).to contain_exactly(group)+ end+ end++ context "when pm target_groups contain an invalid group" do+ it "skips sending if there is only one target" do+ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Tell me and I forget.",+ raw: "0123456789" * 25 + "a",+ target_group_names: ["non-existent-group"],+ },+ )+ }.not_to change { Topic.count }+ end++ it "sends the pm without the invalid group" do+ group = Fabricate(:group)++ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Tell me and I forget.",+ raw: "0123456789" * 25 + "a",+ target_group_names: ["non-existent-group", group.name],+ },+ )+ }.to change { Topic.count }++ expect(Topic.last.allowed_groups).to contain_exactly(group)+ end+ end++ context "when pm target_emails with valid email" do+ it "sends the pm" do+ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Private Message Title",+ raw: "0123456789" * 25 + "a",+ target_emails: ["[email protected]"],+ },+ )+ }.to change { Topic.private_messages.count }+ end++ it "sends shared pm when multiple emails" do+ email_1 = "[email protected]"+ email_2 = "[email protected]"++ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Private Message Title",+ raw: "0123456789" * 25 + "a",+ target_emails: [email_1, email_2],+ },+ )+ }.to change { Topic.private_messages.count }++ # creates new users if they don't exist+ user_1 = User.find_by_email(email_1)+ user_2 = User.find_by_email(email_2)++ expect(+ Topic.private_messages.first.topic_allowed_users.pluck(:user_id),+ ).to contain_exactly(Discourse.system_user.id, user_1.id, user_2.id)+ end+ end++ context "when pm target_emails contain an invalid email" do+ it "skips sending if there is only one target" do+ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Private Message Title",+ raw: "0123456789" * 25 + "a",+ target_emails: ["invalid-email"],+ },+ )+ }.not_to change { Topic.private_messages.count }+ end++ it "sends the pm without the invalid email" do+ expect {+ DiscourseAutomation::Scriptable::Utils.send_pm(+ {+ title: "Private Message Title",+ raw: "0123456789" * 25 + "a",+ target_emails: %w[invalid-email [email protected]],+ },+ )+ }.to change { Topic.private_messages.count }.by(1)++ new_user = User.find_by_email("[email protected]")+ expect(+ Topic.private_messages.first.topic_allowed_users.pluck(:user_id),+ ).to contain_exactly(Discourse.system_user.id, new_user.id)+ end+ end+ end+ end+enddiff --git a/plugins/automation/spec/lib/triggerable_spec.rb b/plugins/automation/spec/lib/triggerable_spec.rbnew file mode 100644index 00000000000..6488936ed9d--- /dev/null+++ b/plugins/automation/spec/lib/triggerable_spec.rb@@ -0,0 +1,65 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::Triggerable do+ before do+ DiscourseAutomation::Triggerable.add("cats_everywhere") do+ placeholder :foo+ placeholder :bar+ placeholder { |fields, automation| "baz-#{automation.id}" }+ placeholder { |fields, automation| ["foo-baz-#{automation.id}"] }+ end++ DiscourseAutomation::Triggerable.add("dog") { field :kind, component: :text }++ DiscourseAutomation::Scriptable.add("only_dogs") { triggerable! :dog, { kind: "good_boy" } }+ end++ fab!(:automation) { Fabricate(:automation, trigger: "foo") }++ describe "#setting" do+ before { DiscourseAutomation::Triggerable.add("foo") { setting :bar, :baz } }++ it "returns the setting value" do+ triggerable = DiscourseAutomation::Triggerable.new(automation.trigger)++ expect(triggerable.settings[:bar]).to eq(:baz)+ end+ end++ describe "#placeholders" do+ fab!(:automation) { Fabricate(:automation, trigger: "cats_everywhere") }++ it "returns the specified placeholders" do+ expect(automation.triggerable.placeholders).to eq(+ [:foo, :bar, :"baz-#{automation.id}", :"foo-baz-#{automation.id}"],+ )+ end+ end++ describe "#enable_manual_trigger" do+ context "when used" do+ before { DiscourseAutomation::Triggerable.add("foo") { enable_manual_trigger } }++ it "returns the correct setting value" do+ triggerable = DiscourseAutomation::Triggerable.new(automation.trigger)+ expect(triggerable.settings[DiscourseAutomation::Triggerable::MANUAL_TRIGGER_KEY]).to eq(+ true,+ )+ end+ end++ context "when not used" do+ before { DiscourseAutomation::Triggerable.add("foo") }++ it "returns the correct setting value" do+ triggerable = DiscourseAutomation::Triggerable.new(automation.trigger)++ expect(triggerable.settings[DiscourseAutomation::Triggerable::MANUAL_TRIGGER_KEY]).to eq(+ false,+ )+ end+ end+ end+enddiff --git a/plugins/automation/spec/models/automation_spec.rb b/plugins/automation/spec/models/automation_spec.rbnew file mode 100644index 00000000000..5420e7976cf--- /dev/null+++ b/plugins/automation/spec/models/automation_spec.rb@@ -0,0 +1,168 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::Automation do+ describe "#trigger!" do+ context "when not enabled" do+ fab!(:automation) { Fabricate(:automation, enabled: false) }++ it "doesn’t do anything" do+ list = capture_contexts { automation.trigger!("Howdy!") }++ expect(list).to eq([])+ end+ end++ context "when enabled" do+ fab!(:automation) { Fabricate(:automation, enabled: true) }++ it "runs the script" do+ list = capture_contexts { automation.trigger!("Howdy!") }++ expect(list).to eq(["Howdy!"])+ end+ end+ end++ describe "when a script is meant to be triggered in the background" do+ fab!(:automation) do+ Fabricate(:automation, enabled: true, script: "test-background-scriptable")+ end++ before do+ DiscourseAutomation::Scriptable.add("test_background_scriptable") do+ run_in_background++ script do |context|+ DiscourseAutomation::CapturedContext.add(context)+ nil+ end+ end+ end++ it "runs a sidekiq job to trigger it" do+ expect { automation.trigger!({ val: "Howdy!" }) }.to change {+ Jobs::DiscourseAutomationTrigger.jobs.size+ }.by(1)+ end++ it "also runs the script properly" do+ Jobs.run_immediately!+ post = Fabricate(:post)+ user = post.user+ list = capture_contexts { automation.trigger!({ post: post, user: user, test: :test }) }+ expect(list[0]["post"].id).to eq(post.id)+ expect(list[0]["user"].id).to eq(user.id)+ expect(list[0]["test"]).to eq(:test)+ end+ end++ describe "#detach_custom_field" do+ fab!(:automation)++ it "expects a User/Topic/Post instance" do+ expect { automation.detach_custom_field(Invite.new) }.to raise_error(RuntimeError)+ end+ end++ describe "#attach_custom_field" do+ fab!(:automation)++ it "expects a User/Topic/Post instance" do+ expect { automation.attach_custom_field(Invite.new) }.to raise_error(RuntimeError)+ end+ end++ context "when automation’s script has a field with validor" do+ before do+ DiscourseAutomation::Scriptable.add("required_dogs") do+ field :dog, component: :text, validator: ->(input) { "must have dog" if input != "dog" }+ end+ end++ context "when validating automation" do+ fab!(:automation) { Fabricate(:automation, enabled: false, script: "required_dogs") }++ it "raises an error if invalid" do+ expect {+ automation.fields.create!(+ name: "dog",+ component: "text",+ metadata: {+ value: nil,+ },+ target: "script",+ )+ }.to raise_error(ActiveRecord::RecordInvalid, /must have dog/)+ end++ it "does nothing if valid" do+ expect {+ automation.fields.create!(+ name: "dog",+ component: "text",+ metadata: {+ value: "dog",+ },+ target: "script",+ )+ }.not_to raise_error+ end+ end+ end++ context "when automation’s script has a required field" do+ before do+ DiscourseAutomation::Scriptable.add("required_dogs") do+ field :dog, component: :text, required: true+ end+ end++ context "when field is not filled" do+ fab!(:automation) { Fabricate(:automation, enabled: false, script: "required_dogs") }++ context "when validating automation" do+ it "raises an error" do+ expect {+ automation.fields.create!(+ name: "dog",+ component: "text",+ metadata: {+ value: nil,+ },+ target: "script",+ )+ }.to raise_error(ActiveRecord::RecordInvalid, /dog/)+ end+ end+ end+ end++ context "when automation’s trigger has a required field" do+ before do+ DiscourseAutomation::Triggerable.add("required_dogs") do+ field :dog, component: :text, required: true+ end+ end++ context "when field is not filled" do+ fab!(:automation) { Fabricate(:automation, enabled: false, trigger: "required_dogs") }++ context "when validating automation" do+ it "raises an error" do+ expect {+ automation.fields.create!(+ name: "dog",+ component: "text",+ metadata: {+ value: nil,+ },+ target: "trigger",+ )+ }.to raise_error(ActiveRecord::RecordInvalid, /dog/)+ end+ end+ end+ end+enddiff --git a/plugins/automation/spec/models/field_spec.rb b/plugins/automation/spec/models/field_spec.rbnew file mode 100644index 00000000000..016c8940c6f--- /dev/null+++ b/plugins/automation/spec/models/field_spec.rb@@ -0,0 +1,123 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::Field do+ describe "post field" do+ DiscourseAutomation::Scriptable.add("test_post_field") { field :foo, component: :post }++ fab!(:automation) { Fabricate(:automation, script: "test_post_field") }++ it "works with an empty value" do+ field =+ DiscourseAutomation::Field.create(automation: automation, component: "post", name: "foo")+ expect(field).to be_valid+ end++ it "works with a text value" do+ field =+ DiscourseAutomation::Field.create(+ automation: automation,+ component: "post",+ name: "foo",+ metadata: {+ value: "foo",+ },+ )+ expect(field).to be_valid+ end++ it "doesn’t work with an object value" do+ field =+ DiscourseAutomation::Field.create(+ automation: automation,+ component: "post",+ name: "foo",+ metadata: {+ value: {+ x: 1,+ },+ },+ )+ expect(field).to_not be_valid+ end+ end++ describe "period field" do+ DiscourseAutomation::Scriptable.add("test_period_field") { field :foo, component: :period }++ fab!(:automation) { Fabricate(:automation, script: "test_period_field") }++ it "works with an object value" do+ value = { interval: "2", frequency: "day" }+ field =+ DiscourseAutomation::Field.create(+ automation: automation,+ component: "period",+ name: "foo",+ metadata: {+ value: value,+ },+ )+ expect(field).to be_valid+ end+ end++ describe "choices field" do+ DiscourseAutomation::Scriptable.add("test_choices_field") { field :foo, component: :choices }++ fab!(:automation) { Fabricate(:automation, script: "test_choices_field") }++ it "works with a string value" do+ field =+ DiscourseAutomation::Field.create(+ automation: automation,+ component: "choices",+ name: "foo",+ metadata: {+ value: "some text",+ },+ )+ expect(field).to be_valid+ end++ it "works with an integer value" do+ field =+ DiscourseAutomation::Field.create(+ automation: automation,+ component: "choices",+ name: "foo",+ metadata: {+ value: 21,+ },+ )+ expect(field).to be_valid+ end++ it "does not work with an array value" do+ field =+ DiscourseAutomation::Field.create(+ automation: automation,+ component: "choices",+ name: "foo",+ metadata: {+ value: [1, 2, 3],+ },+ )+ expect(field).to_not be_valid+ end++ it "works with a nil value" do+ field =+ DiscourseAutomation::Field.create(+ automation: automation,+ component: "choices",+ name: "foo",+ metadata: {+ value: nil,+ },+ )+ expect(field).to be_valid+ end+ end+enddiff --git a/plugins/automation/spec/models/user_global_notice_spec.rb b/plugins/automation/spec/models/user_global_notice_spec.rbnew file mode 100644index 00000000000..817ec4446d1--- /dev/null+++ b/plugins/automation/spec/models/user_global_notice_spec.rb@@ -0,0 +1,23 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::UserGlobalNotice do+ fab!(:user_1) { Fabricate(:user) }++ describe "creating duplicates" do+ it "prevents creating duplicates" do+ row = {+ user_id: user_1.id,+ notice: "foo",+ identifier: "bar",+ created_at: Time.now,+ updated_at: Time.now,+ }++ described_class.upsert(row)++ expect { described_class.upsert(row) }.to raise_error(ActiveRecord::RecordNotUnique)+ end+ end+enddiff --git a/plugins/automation/spec/queries/stalled_topic_finder_spec.rb b/plugins/automation/spec/queries/stalled_topic_finder_spec.rbnew file mode 100644index 00000000000..8503a8179fd--- /dev/null+++ b/plugins/automation/spec/queries/stalled_topic_finder_spec.rb@@ -0,0 +1,103 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe StalledTopicFinder do+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }++ before do+ SiteSetting.discourse_automation_enabled = true+ SiteSetting.tagging_enabled = true+ freeze_time+ end++ describe "default" do+ # topic with only stalled OP+ fab!(:topic_1) { create_topic(user: user) }+ # topic with recent replies+ fab!(:topic_2) { create_topic(user: user) }+ # topic with stalled replies+ fab!(:topic_3) { create_topic(user: user) }+ # topic with only recent OP+ fab!(:topic_4) { create_topic(user: user, created_at: 3.hours.from_now) }++ it "returns only stalled topics with replies" do+ create_post(topic: topic_1, user: user)+ create_post(topic: topic_2, user: user, created_at: 3.hours.from_now)+ create_post(topic: topic_2, user: user, created_at: 3.hours.from_now)+ create_post(topic: topic_3, user: user)+ create_post(topic: topic_3, user: user)++ expect(described_class.call(2.hours.from_now).map(&:id)).to contain_exactly(+ topic_1.id,+ topic_3.id,+ )+ end+ end++ describe "filter by tags" do+ fab!(:tag_1) { Fabricate(:tag) }+ # tagged topic with replies+ fab!(:topic_1) { create_topic(tags: [tag_1.name], user: user) }+ # untagged topic with replies+ fab!(:topic_2) { create_topic(user: user) }+ # tagged topic with no replies+ fab!(:topic_3) { create_topic(user: user, tags: [tag_1.name]) }+ # tagged topic with recent replies+ fab!(:topic_4) { create_topic(user: user, tags: [tag_1.name]) }++ it "returns only stalled topics with replies using the tag" do+ create_post(topic: topic_1, user: user)+ create_post(topic: topic_1, user: user)+ create_post(topic: topic_2, user: user)+ create_post(topic: topic_2, user: user)+ create_post(topic: topic_4, user: user, created_at: 3.hours.from_now)+ create_post(topic: topic_4, user: user, created_at: 3.hours.from_now)++ expect(+ described_class.call(2.hours.from_now, tags: [tag_1.name]).map(&:id),+ ).to contain_exactly(topic_1.id)+ end+ end++ describe "filter by categories" do+ fab!(:category_1) { Fabricate(:category) }++ # topic with stalled replies and category+ fab!(:topic_1) { create_topic(user: user, category: category_1) }+ # topic with stalled replies and no category+ fab!(:topic_2) { create_topic(user: user) }+ # topic with recent replies and category+ fab!(:topic_3) { create_topic(user: user, category: category_1) }++ it "returns only topics with the category" do+ create_post(topic: topic_1, user: user)+ create_post(topic: topic_1, user: user)+ create_post(topic: topic_2, user: user)+ create_post(topic: topic_2, user: user)+ create_post(topic: topic_3, user: user, created_at: 3.hours.from_now)+ create_post(topic: topic_3, user: user, created_at: 3.hours.from_now)++ expect(+ described_class.call(2.hours.from_now, categories: [category_1.id]).map(&:id),+ ).to contain_exactly(topic_1.id)+ end+ end++ describe "filter recent topic owner replies" do+ fab!(:another_user) { Fabricate(:user) }+ # replies from topic owner+ fab!(:topic_1) { create_topic(user: user) }+ # replies from not topic owner+ fab!(:topic_2) { create_topic(user: user) }++ it "doesn’t consider replies from other users" do+ create_post(topic: topic_1, user: user)+ create_post(topic: topic_1, user: user, created_at: 3.hours.from_now)+ create_post(topic: topic_2, user: user)+ create_post(topic: topic_2, user: another_user, created_at: 3.hours.from_now)++ expect(described_class.call(2.hours.from_now).map(&:id)).to contain_exactly(topic_2.id)+ end+ end+enddiff --git a/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb b/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rbnew file mode 100644index 00000000000..295f46c2668--- /dev/null+++ b/plugins/automation/spec/requests/admin_discourse_automation_automations_spec.rb@@ -0,0 +1,187 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::AdminAutomationsController do+ fab!(:automation)++ before { SiteSetting.discourse_automation_enabled = true }++ describe "#show" do+ context "when logged in as an admin" do+ before { sign_in(Fabricate(:admin)) }++ it "shows the automation" do+ get "/admin/plugins/discourse-automation/automations/#{automation.id}.json"+ expect(response.status).to eq(200)+ expect(response.parsed_body["automation"]["id"]).to eq(automation.id)+ end+ end++ context "when logged in as a regular user" do+ before { sign_in(Fabricate(:user)) }++ it "raises a 404" do+ get "/admin/plugins/discourse-automation/automations/#{automation.id}.json"+ expect(response.status).to eq(404)+ end+ end+ end++ describe "#update" do+ context "when logged in as an admin" do+ before { sign_in(Fabricate(:admin)) }++ it "updates the automation" do+ put "/admin/plugins/discourse-automation/automations/#{automation.id}.json",+ params: {+ automation: {+ trigger: "another-trigger",+ },+ }+ expect(response.status).to eq(200)+ end++ describe "invalid field’s component" do+ it "errors" do+ put "/admin/plugins/discourse-automation/automations/#{automation.id}.json",+ params: {+ automation: {+ script: automation.script,+ trigger: automation.trigger,+ fields: [{ name: "foo", component: "bar" }],+ },+ }++ expect(response.status).to eq(422)+ end+ end++ context "with required field" do+ before do+ DiscourseAutomation::Scriptable.add("test_required") do+ field :foo, component: :text, required: true+ end++ automation.update!(script: "test_required")+ end++ it "errors" do+ put "/admin/plugins/discourse-automation/automations/#{automation.id}.json",+ params: {+ automation: {+ script: automation.script,+ trigger: automation.trigger,+ fields: [+ { name: "foo", component: "text", target: "script", metadata: { value: nil } },+ ],+ },+ }+ expect(response.status).to eq(422)+ end+ end++ context "when changing trigger and script of an enabled automation" do+ it "forces the automation to be disabled" do+ expect(automation.enabled).to eq(true)++ put "/admin/plugins/discourse-automation/automations/#{automation.id}.json",+ params: {+ automation: {+ script: "bar",+ trigger: "foo",+ enabled: true,+ },+ }++ expect(automation.reload.enabled).to eq(false)+ end+ end++ context "when changing trigger of an enabled automation" do+ it "forces the automation to be disabled" do+ expect(automation.enabled).to eq(true)++ put "/admin/plugins/discourse-automation/automations/#{automation.id}.json",+ params: {+ automation: {+ script: automation.script,+ trigger: "foo",+ enabled: true,+ },+ }++ expect(automation.reload.enabled).to eq(false)+ end+ end++ context "when changing script of an enabled automation" do+ it "disables the automation" do+ expect(automation.enabled).to eq(true)++ put "/admin/plugins/discourse-automation/automations/#{automation.id}.json",+ params: {+ automation: {+ trigger: automation.trigger,+ script: "foo",+ enabled: true,+ },+ }++ expect(automation.reload.enabled).to eq(false)+ end+ end++ context "with invalid field’s metadata" do+ it "errors" do+ put "/admin/plugins/discourse-automation/automations/#{automation.id}.json",+ params: {+ automation: {+ script: automation.script,+ trigger: automation.trigger,+ fields: [{ name: "sender", component: "users", metadata: { baz: 1 } }],+ },+ }++ expect(response.status).to eq(422)+ end+ end+ end++ context "when logged in as a regular user" do+ before { sign_in(Fabricate(:user)) }++ it "raises a 404" do+ put "/admin/plugins/discourse-automation/automations/#{automation.id}.json",+ params: {+ automation: {+ trigger: "another-trigger",+ },+ }+ expect(response.status).to eq(404)+ end+ end+ end++ describe "#destroy" do+ fab!(:automation)++ context "when logged in as an admin" do+ before { sign_in(Fabricate(:admin)) }++ it "destroys the automation" do+ delete "/admin/plugins/discourse-automation/automations/#{automation.id}.json"+ expect(DiscourseAutomation::Automation.find_by(id: automation.id)).to eq(nil)+ end+ end++ context "when logged in as a regular user" do+ before { sign_in(Fabricate(:user)) }++ it "raises a 404" do+ delete "/admin/plugins/discourse-automation/automations/#{automation.id}.json"+ expect(response.status).to eq(404)+ end+ end+ end+enddiff --git a/plugins/automation/spec/requests/discourse_automation_append_last_checked_by_controller_spec.rb b/plugins/automation/spec/requests/discourse_automation_append_last_checked_by_controller_spec.rbnew file mode 100644index 00000000000..cf8f3a23593--- /dev/null+++ b/plugins/automation/spec/requests/discourse_automation_append_last_checked_by_controller_spec.rb@@ -0,0 +1,32 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::AppendLastCheckedByController do+ before { SiteSetting.discourse_automation_enabled = true }++ describe "#post_checked" do+ fab!(:post)+ fab!(:topic) { post.topic }++ it "updates the topic custom fields" do+ freeze_time+ admin = Fabricate(:admin)+ sign_in(admin)++ put "/append-last-checked-by/#{post.id}.json"+ expect(response.status).to eq(200)+ expect(topic.custom_fields[DiscourseAutomation::TOPIC_LAST_CHECKED_BY]).to eq(admin.username)+ topic_last_checked_at =+ Time.parse(topic.custom_fields[DiscourseAutomation::TOPIC_LAST_CHECKED_AT])+ expect(topic_last_checked_at).to be_within_one_second_of(Time.zone.now)+ end++ it "returns error if user can not edit the post" do+ sign_in(Fabricate(:user))++ put "/append-last-checked-by/#{post.id}.json"+ expect(response.status).to eq(403)+ end+ end+enddiff --git a/plugins/automation/spec/requests/discourse_automation_automations_spec.rb b/plugins/automation/spec/requests/discourse_automation_automations_spec.rbnew file mode 100644index 00000000000..cc8205ee09b--- /dev/null+++ b/plugins/automation/spec/requests/discourse_automation_automations_spec.rb@@ -0,0 +1,103 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::AdminAutomationsController do+ before { SiteSetting.discourse_automation_enabled = true }++ describe "#trigger" do+ fab!(:automation)++ describe "access" do+ context "when user is not logged in" do+ before { sign_out }++ it "raises a 404" do+ post "/automations/#{automation.id}/trigger.json"+ expect(response.status).to eq(404)+ end+ end++ context "when user is logged in" do+ context "when user is admin" do+ before do+ Jobs.run_immediately!+ sign_in(Fabricate(:admin))+ end++ it "triggers the automation" do+ list = capture_contexts { post "/automations/#{automation.id}/trigger.json" }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("api_call")+ end+ end++ context "when user is moderator" do+ before { sign_in(Fabricate(:moderator)) }++ it "raises a 404" do+ post "/automations/#{automation.id}/trigger.json"+ expect(response.status).to eq(404)+ end+ end++ context "when user is regular" do+ before { sign_in(Fabricate(:user)) }++ it "raises a 404" do+ post "/automations/#{automation.id}/trigger.json"+ expect(response.status).to eq(404)+ end+ end+ end++ context "when using a user api key" do+ before { sign_out }++ let(:admin) { Fabricate(:admin) }+ let(:api_key) { Fabricate(:api_key, user: admin) }++ it "works" do+ post "/automations/#{automation.id}/trigger.json",+ params: {+ context: {+ foo: :bar,+ },+ },+ headers: {+ HTTP_API_KEY: api_key.key,+ }++ expect(response.status).to eq(200)+ expect(Jobs::DiscourseAutomationTrigger.jobs.size).to eq(1)+ end+ end+ end++ describe "params as context" do+ fab!(:admin)+ fab!(:automation) { Fabricate(:automation, trigger: "api_call") }++ before do+ Jobs.run_immediately!+ sign_in(admin)+ end++ it "passes the params" do+ list =+ capture_contexts do+ post "/automations/#{automation.id}/trigger.json", params: { foo: "1", bar: "2" }+ end++ expect(list.length).to eq(1)++ first = list.first++ expect(first["foo"]).to eq("1")+ expect(first["bar"]).to eq("2")+ expect(response.status).to eq(200)+ end+ end+ end+enddiff --git a/plugins/automation/spec/requests/discourse_automation_user_global_notices_spec.rb b/plugins/automation/spec/requests/discourse_automation_user_global_notices_spec.rbnew file mode 100644index 00000000000..7de4ec683e0--- /dev/null+++ b/plugins/automation/spec/requests/discourse_automation_user_global_notices_spec.rb@@ -0,0 +1,47 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::UserGlobalNoticesController do+ fab!(:user_1) { Fabricate(:user) }++ before { SiteSetting.discourse_automation_enabled = true }++ describe "#destroy" do+ let!(:notice_1) do+ DiscourseAutomation::UserGlobalNotice.create!(+ user_id: user_1.id,+ notice: "foo",+ identifier: "bar",+ )+ end++ context "when user is not logged in" do+ it "raises a 403" do+ delete "/user-global-notices/#{notice_1.id}.json"++ expect(response.status).to eq(403)+ end+ end++ context "when user is owner of the notice" do+ before { sign_in(user_1) }++ it "destroys the notice" do+ delete "/user-global-notices/#{notice_1.id}.json"++ expect(DiscourseAutomation::UserGlobalNotice.count).to eq(0)+ end+ end++ context "when user is not owner of the notice" do+ before { sign_in(Fabricate(:user)) }++ it "raises a 404" do+ delete "/user-global-notices/#{notice_1.id}.json"++ expect(response.status).to eq(404)+ end+ end+ end+enddiff --git a/plugins/automation/spec/scripts/add_user_to_group_through_custom_field_spec.rb b/plugins/automation/spec/scripts/add_user_to_group_through_custom_field_spec.rbnew file mode 100644index 00000000000..14077ba9829--- /dev/null+++ b/plugins/automation/spec/scripts/add_user_to_group_through_custom_field_spec.rb@@ -0,0 +1,122 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "AddUserTogroupThroughCustomField" do+ fab!(:user_1) { Fabricate(:user) }+ fab!(:user_2) { Fabricate(:user) }+ fab!(:target_group) { Fabricate(:group, full_name: "Groupity Group") }+ fab!(:user_field) do+ Fabricate(:user_field, name: "groupity_group", field_type: "text", description: "a nice field")+ end++ fab!(:automation) { Fabricate(:automation, script: "add_user_to_group_through_custom_field") }++ before do+ automation.upsert_field!(+ "custom_field_name",+ "custom_field",+ { value: user_field.id },+ target: "script",+ )+ end++ context "with no matching user custom fields" do+ it "works" do+ expect(user_1.in_any_groups?([target_group.id])).to eq(false)+ expect(user_2.in_any_groups?([target_group.id])).to eq(false)++ automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)++ expect(user_1.reload.in_any_groups?([target_group.id])).to eq(false)+ expect(user_2.reload.in_any_groups?([target_group.id])).to eq(false)+ end+ end++ context "with one matching user" do+ before do+ UserCustomField.create!(+ user_id: user_1.id,+ name: "user_field_#{user_field.id}",+ value: target_group.full_name,+ )+ end++ it "works" do+ expect(user_1.in_any_groups?([target_group.id])).to eq(false)+ expect(user_2.in_any_groups?([target_group.id])).to eq(false)++ automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)++ expect(user_1.reload.in_any_groups?([target_group.id])).to eq(true)+ expect(user_2.reload.in_any_groups?([target_group.id])).to eq(false)+ end+ end++ context "when group is already present" do+ before { target_group.add(user_1) }++ it "works" do+ expect(user_1.in_any_groups?([target_group.id])).to eq(true)+ expect(user_2.in_any_groups?([target_group.id])).to eq(false)++ automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)++ expect(user_1.reload.in_any_groups?([target_group.id])).to eq(true)+ expect(user_2.reload.in_any_groups?([target_group.id])).to eq(false)+ end+ end++ context "with user_first_logged_in trigger" do+ fab!(:automation) { Fabricate(:automation, script: "add_user_to_group_through_custom_field") }++ context "with existing custom fields" do+ before do+ UserCustomField.create!(+ user_id: user_1.id,+ name: "user_field_#{user_field.id}",+ value: target_group.full_name,+ )+ end++ it "adds the user to the group" do+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user_1,+ )++ expect(user_1.reload.in_any_groups?([target_group.id])).to eq(true)+ end+ end++ context "with non existing/matching custom fields" do+ it "does nothing" do+ expect {+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user_1,+ )+ }.not_to change { user_1.reload.belonging_to_group_ids.length }+ end+ end++ context "with non existing target group" do+ before do+ UserCustomField.create!(+ user_id: user_1.id,+ name: "user_field_#{user_field.id}",+ value: "xx",+ )+ end++ it "does nothing" do+ expect {+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user_1,+ )+ }.not_to change { user_1.reload.belonging_to_group_ids.length }+ end+ end+ end+enddiff --git a/plugins/automation/spec/scripts/append_last_checked_by_spec.rb b/plugins/automation/spec/scripts/append_last_checked_by_spec.rbnew file mode 100644index 00000000000..5893655c6c4--- /dev/null+++ b/plugins/automation/spec/scripts/append_last_checked_by_spec.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "AppendLastCheckedBy" do+ fab!(:post) { Fabricate(:post, raw: "this is a post with no edit") }+ fab!(:moderator)++ fab!(:automation) do+ Fabricate(:automation, script: DiscourseAutomation::Scripts::APPEND_LAST_CHECKED_BY)+ end++ def trigger_automation(post)+ cooked = automation.trigger!("post" => post, "cooked" => post.cooked)+ checked_at = post.updated_at + 1.hour+ date_time = checked_at.strftime("%Y-%m-%dT%H:%M:%SZ")+ [cooked, checked_at, date_time]+ end++ def text(key)+ I18n.t("discourse_automation.scriptables.append_last_checked_by.#{key}")+ end++ describe "#trigger!" do+ it "works for newly created post" do+ cooked, checked_at, date_time = trigger_automation(post)++ expect(cooked.include?("<blockquote class=\"discourse-automation\">")).to be_truthy+ expect(+ cooked.include?(+ "<details><summary>#{text("summary")}</summary>#{text("details")}<input type=\"button\" value=\"#{text("button_text")}\" class=\"btn btn-checked\"></details>",+ ),+ ).to be_truthy+ end++ it "works for checked post" do+ topic = post.topic+ topic.custom_fields[DiscourseAutomation::TOPIC_LAST_CHECKED_BY] = moderator.username+ topic.custom_fields[DiscourseAutomation::TOPIC_LAST_CHECKED_AT] = post.updated_at + 1.hour+ topic.save_custom_fields++ cooked, checked_at = trigger_automation(post)++ expect(+ cooked.include?(+ PrettyText.cook(+ I18n.t(+ "discourse_automation.scriptables.append_last_checked_by.text",+ username: moderator.username,+ date_time:+ "[date=#{checked_at.to_date} time=#{checked_at.strftime("%H:%M:%S")} timezone=UTC]",+ ),+ ),+ ),+ ).to be_truthy+ end+ end+enddiff --git a/plugins/automation/spec/scripts/append_last_edited_by_spec.rb b/plugins/automation/spec/scripts/append_last_edited_by_spec.rbnew file mode 100644index 00000000000..32c42f4c81d--- /dev/null+++ b/plugins/automation/spec/scripts/append_last_edited_by_spec.rb@@ -0,0 +1,73 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "AppendLastEditedBy" do+ fab!(:post) { Fabricate(:post, raw: "this is a post with no edit") }+ fab!(:moderator)++ fab!(:automation) do+ Fabricate(:automation, script: DiscourseAutomation::Scripts::APPEND_LAST_EDITED_BY)+ end++ def trigger_automation(post)+ cooked = automation.trigger!("post" => post, "cooked" => post.cooked)+ updated_at = post.updated_at+ date_time = updated_at.strftime("%Y-%m-%dT%H:%M:%SZ")+ [cooked, updated_at]+ end++ describe "#trigger!" do+ it "works for newly created post" do+ freeze_time++ cooked, updated_at = trigger_automation(post)+ expect(+ cooked.include?(+ PrettyText.cook(+ I18n.t(+ "discourse_automation.scriptables.append_last_edited_by.text",+ username: post.user.username,+ date_time:+ "[date=#{updated_at.to_date} time=#{updated_at.strftime("%H:%M:%S")} timezone=UTC]",+ ),+ ),+ ),+ ).to be_truthy+ end++ it "works for existing post with last edited by detail" do+ freeze_time++ cooked, updated_at = trigger_automation(post)+ expect(+ cooked.include?(+ PrettyText.cook(+ I18n.t(+ "discourse_automation.scriptables.append_last_edited_by.text",+ username: post.user.username,+ date_time:+ "[date=#{updated_at.to_date} time=#{updated_at.strftime("%H:%M:%S")} timezone=UTC]",+ ),+ ),+ ),+ ).to be_truthy++ PostRevisor.new(post).revise!(moderator, raw: "this is a post with edit")++ cooked, updated_at = trigger_automation(post.reload)+ expect(+ cooked.include?(+ PrettyText.cook(+ I18n.t(+ "discourse_automation.scriptables.append_last_edited_by.text",+ username: moderator.username,+ date_time:+ "[date=#{updated_at.to_date} time=#{updated_at.strftime("%H:%M:%S")} timezone=UTC]",+ ),+ ),+ ),+ ).to be_truthy+ end+ end+enddiff --git a/plugins/automation/spec/scripts/auto_responder_spec.rb b/plugins/automation/spec/scripts/auto_responder_spec.rbnew file mode 100644index 00000000000..303e505ea19--- /dev/null+++ b/plugins/automation/spec/scripts/auto_responder_spec.rb@@ -0,0 +1,208 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "AutoResponder" do+ fab!(:topic)++ fab!(:automation) { Fabricate(:automation, script: DiscourseAutomation::Scripts::AUTO_RESPONDER) }++ context "without word filter" do+ before do+ automation.upsert_field!(+ "word_answer_list",+ "key-value",+ { value: [{ key: "", value: "this is the reply" }].to_json },+ )+ end++ it "creates an answer" do+ post = create_post(topic: topic, raw: "this is a post")+ automation.trigger!("post" => post)++ expect(topic.reload.posts.last.raw).to eq("this is the reply")+ end+ end++ context "with present word_answer list" do+ before do+ automation.upsert_field!(+ "word_answer_list",+ "key-value",+ {+ value: [+ { key: "fooz?|bar", value: "this is {{key}}" },+ { key: "bar", value: "this is {{key}}" },+ ].to_json,+ },+ )+ end++ context "when post is first post" do+ context "when topic title contains keywords" do+ it "creates an answer" do+ topic = Fabricate(:topic, title: "What a foo day to walk")+ post = create_post(topic: topic, raw: "this is a post with no keyword")+ automation.trigger!("post" => post)++ expect(topic.reload.posts.last.raw).to eq("this is foo")+ end+ end++ context "when post and topic title contain keyword" do+ it "creates only one answer" do+ topic = Fabricate(:topic, title: "What a foo day to walk")+ post = create_post(topic: topic, raw: "this is a post with foo keyword")+ automation.trigger!("post" => post)++ expect(topic.reload.posts.last.raw).to eq("this is foo")+ end+ end++ context "when the word answer list has a wildcard (empty string) for key" do+ before do+ automation.upsert_field!(+ "word_answer_list",+ "key-value",+ { value: [{ key: "", value: "this is a response" }].to_json },+ )+ end++ it "creates an answer" do+ topic = Fabricate(:topic, title: "What a foo day to walk")+ post = create_post(topic: topic, raw: "this is a post with no keyword")+ automation.trigger!("post" => post)++ expect(topic.reload.posts.last.raw).to eq("this is a response")+ end+ end+ end++ context "when post contains a keyword" do+ it "creates an answer" do+ post = create_post(topic: topic, raw: "this is foo a post with foo")+ automation.trigger!("post" => post)++ expect(topic.reload.posts.last.raw).to eq("this is foo")+ end++ context "when post has direct replies from answering user" do+ fab!(:answering_user) { Fabricate(:user) }++ before do+ automation.upsert_field!(+ "answering_user",+ "user",+ { value: answering_user.username },+ target: "script",+ )+ end++ it "doesn’t create another answer" do+ post_1 = create_post(topic: topic, raw: "this is a post with foo")+ create_post(user: answering_user, reply_to_post_number: post_1.post_number, topic: topic)++ expect { automation.trigger!("post" => post_1) }.not_to change { Post.count }+ end+ end++ context "when user is replying to own post" do+ fab!(:answering_user) { Fabricate(:user) }++ before do+ automation.upsert_field!(+ "answering_user",+ "user",+ { value: answering_user.username },+ target: "script",+ )+ end++ it "doesn’t create an answer" do+ post_1 = create_post(topic: topic)+ post_2 =+ create_post(+ user: answering_user,+ topic: topic,+ reply_to_post_number: post_1.post_number,+ raw: "this is a post with foo",+ )++ expect { automation.trigger!("post" => post_2) }.not_to change { Post.count }+ end+ end++ context "when once is used" do+ before { automation.upsert_field!("once", "boolean", { value: true }, target: "script") }++ it "allows only one response by automation" do+ post = create_post(topic: topic, raw: "this is a post with foo and bar")+ automation.trigger!("post" => post)++ expect(post.topic.reload.posts_count).to eq(2)++ post = create_post(topic: topic, raw: "this is another post with foo and bar")+ automation.trigger!("post" => post)++ expect(post.topic.reload.posts_count).to eq(3)++ another_automation =+ Fabricate(:automation, script: DiscourseAutomation::Scripts::AUTO_RESPONDER)+ another_automation.upsert_field!("once", "boolean", { value: true }, target: "script")+ another_automation.upsert_field!(+ "word_answer_list",+ "key-value",+ { value: [{ key: "", value: "this is the reply" }].to_json },+ )+ post = create_post(topic: topic, raw: "this is the last post with foo and bar")+ another_automation.trigger!("post" => post)++ expect(post.topic.reload.posts_count).to eq(5)+ end+ end+ end++ context "when post contains two keywords" do+ it "creates an answer with both answers" do+ post = create_post(topic: topic, raw: "this is a post with FOO and bar")+ automation.trigger!("post" => post)++ expect(topic.reload.posts.last.raw).to eq("this is FOO\n\nthis is bar")+ end+ end++ context "when post doesn’t contain a keyword" do+ it "doesn’t create an answer" do+ post = create_post(topic: topic, raw: "this is a post with no keyword")++ expect { automation.trigger!("post" => post) }.not_to change { Post.count }+ end+ end++ context "when post contains two keywords" do+ it "creates an answer with both answers" do+ post = create_post(topic: topic, raw: "this is a post with foo and bar")+ automation.trigger!("post" => post)++ expect(topic.reload.posts.last.raw).to eq("this is foo\n\nthis is bar")+ end+ end++ context "when post doesn’t contain a keyword" do+ it "doesn’t create an answer" do+ post = create_post(topic: topic, raw: "this is a post bfoo with no keyword fooa")++ expect { automation.trigger!("post" => post) }.not_to change { Post.count }+ end+ end+ end++ context "when word_answer list is empty" do+ it "exits early with no error" do+ expect {+ post = create_post(topic: topic, raw: "this is a post with foo and bar")+ automation.trigger!("post" => post)+ }.to_not raise_error+ end+ end+enddiff --git a/plugins/automation/spec/scripts/auto_tag_topic_spec.rb b/plugins/automation/spec/scripts/auto_tag_topic_spec.rbnew file mode 100644index 00000000000..6feed06f029--- /dev/null+++ b/plugins/automation/spec/scripts/auto_tag_topic_spec.rb@@ -0,0 +1,41 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "AutoTagTopic" do+ fab!(:topic)+ fab!(:tag1) { Fabricate(:tag, name: "tag1") }+ fab!(:tag2) { Fabricate(:tag, name: "tag2") }+ fab!(:tag3) { Fabricate(:tag, name: "tag3") }+ fab!(:admin) { Fabricate(:admin, refresh_auto_groups: true) }++ fab!(:automation) { Fabricate(:automation, script: DiscourseAutomation::Scripts::AUTO_TAG_TOPIC) }++ context "when tags list is empty" do+ it "exits early with no error" do+ expect {+ post = create_post(topic: topic)+ automation.trigger!("post" => post)+ }.to_not raise_error+ end+ end++ context "when there are tags" do+ before { automation.upsert_field!("tags", "tags", { value: %w[tag1 tag2] }) }++ it "works" do+ post = create_post(topic: topic)+ automation.trigger!("post" => post)++ expect(topic.reload.tags.pluck(:name)).to match_array(%w[tag1 tag2])+ end++ it "does not remove existing tags" do+ post = create_post(topic: topic, tags: %w[totally])+ DiscourseTagging.tag_topic_by_names(topic, Guardian.new(admin), ["tag3"])+ automation.trigger!("post" => post)++ expect(topic.reload.tags.pluck(:name).sort).to match_array(%w[tag1 tag2 tag3])+ end+ end+enddiff --git a/plugins/automation/spec/scripts/banner_topic_spec.rb b/plugins/automation/spec/scripts/banner_topic_spec.rbnew file mode 100644index 00000000000..d79d090f209--- /dev/null+++ b/plugins/automation/spec/scripts/banner_topic_spec.rb@@ -0,0 +1,42 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "BannerTopic" do+ before { automation.upsert_field!("topic_id", "text", { value: topic.id }) }++ fab!(:automation) { Fabricate(:automation, script: DiscourseAutomation::Scripts::BANNER_TOPIC) }+ fab!(:topic)++ context "when banner until is set" do+ before do+ freeze_time+ automation.upsert_field!("banner_until", "date_time", { value: 10.days.from_now })+ automation.upsert_field!("topic_id", "text", { value: topic.id })+ end++ it "banners the topic" do+ expect(topic.bannered_until).to be_nil+ expect(topic.archetype).to eq(Archetype.default)++ automation.trigger!+ topic.reload++ expect(topic.bannered_until).to be_within_one_minute_of(10.days.from_now)+ expect(topic.archetype).to eq(Archetype.banner)+ end+ end++ context "when banner until is not set" do+ it "banners the topic" do+ expect(topic.bannered_until).to be_nil+ expect(topic.archetype).to eq(Archetype.default)++ automation.trigger!+ topic.reload++ expect(topic.bannered_until).to be_nil+ expect(topic.archetype).to eq(Archetype.banner)+ end+ end+enddiff --git a/plugins/automation/spec/scripts/close_topic_spec.rb b/plugins/automation/spec/scripts/close_topic_spec.rbnew file mode 100644index 00000000000..68baf5c01f7--- /dev/null+++ b/plugins/automation/spec/scripts/close_topic_spec.rb@@ -0,0 +1,85 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "CloseTopic" do+ fab!(:user)+ fab!(:category) { Fabricate(:category, user: user) }+ fab!(:topic) { Fabricate(:topic, category: category) }+ fab!(:automation) { Fabricate(:automation, script: DiscourseAutomation::Scripts::CLOSE_TOPIC) }++ before { automation.upsert_field!("topic", "text", { value: topic.id }, target: "script") }++ context "with default params" do+ it "works" do+ expect(topic.closed).to be_falsey++ automation.trigger!+ topic.reload++ expect(topic.closed).to be_truthy++ closing_post = topic.posts.where(action_code: "closed.enabled").last+ expect(closing_post.raw).to eq("")+ expect(closing_post.user_id).to eq(-1)+ end+ end++ context "with message" do+ before do+ automation.upsert_field!(+ "message",+ "text",+ { value: "dingity dongity dong, this topic is closed!" },+ )+ end++ it "works" do+ expect(topic.closed).to be_falsey++ automation.trigger!+ topic.reload++ expect(topic.closed).to be_truthy++ closing_post = topic.posts.where(action_code: "closed.enabled").last+ expect(closing_post.raw).to eq("dingity dongity dong, this topic is closed!")+ end+ end++ # NOTE: this is only possible because we skip validations for now.+ # As soon as discourse-automation supports proper error handling and validations take place again,+ # this test should be removed.+ context "with very short message" do+ before { automation.upsert_field!("message", "text", { value: "bye" }) }++ it "closes the topic" do+ expect(topic.closed).to be_falsey++ automation.trigger!+ topic.reload++ expect(topic.closed).to be_truthy++ closing_post = topic.posts.where(action_code: "closed.enabled").last+ expect(closing_post.raw).to eq("bye")+ end+ end++ context "with a specific user" do+ fab!(:specific_user) { Fabricate(:user, admin: true) }++ before { automation.upsert_field!("user", "user", { value: specific_user.username }) }++ it "closes the topic" do+ expect(topic.closed).to be_falsey++ automation.trigger!+ topic.reload++ expect(topic.closed).to be_truthy+ closing_post = topic.posts.where(action_code: "closed.enabled").last+ expect(closing_post.user_id).to eq(specific_user.id)+ end+ end+enddiff --git a/plugins/automation/spec/scripts/flag_post_on_words_spec.rb b/plugins/automation/spec/scripts/flag_post_on_words_spec.rbnew file mode 100644index 00000000000..70eaa8f814d--- /dev/null+++ b/plugins/automation/spec/scripts/flag_post_on_words_spec.rb@@ -0,0 +1,84 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "FlagPostsOnWords" do+ fab!(:user)+ fab!(:category) { Fabricate(:category, user: user) }+ fab!(:topic) { Fabricate(:topic, category_id: category.id) }+ fab!(:automation) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::FLAG_POST_ON_WORDS,+ trigger: DiscourseAutomation::Triggers::POST_CREATED_EDITED,+ )+ end++ before do+ SiteSetting.discourse_automation_enabled = true+ automation.fields.create!(+ component: "text_list",+ name: "words",+ metadata: {+ value: ["foo,bar"],+ },+ target: "script",+ )+ end++ context "when editing/creating a post" do+ context "when editing a post" do+ fab!(:post)++ context "when post has flagged words" do+ it "flags the post" do+ post.revise(post.user, raw: "this is another cool topic foo bar")+ expect(post.reviewable_flag).to be_present+ end+ end++ context "when post has no/not all flagged words" do+ it "doesn’t flag the post" do+ post.revise(post.user, raw: "this is another cool topic")+ expect(post.reviewable_flag).to_not be_present++ post.revise(post.user, raw: "this is another cool bar topic")+ expect(post.reviewable_flag).to_not be_present+ end+ end+ end++ context "when creating a post" do+ context "when post has flagged words" do+ it "flags the post" do+ post_creator =+ PostCreator.new(+ user,+ topic_id: topic.id,+ raw: "this is quite bar cool a very cool foo post",+ )+ post = post_creator.create+ expect(post.reviewable_flag).to be_present+ end+ end++ context "when post has no/not all flagged words" do+ it "doesn’t flag the post" do+ post_creator =+ PostCreator.new(user, topic_id: topic.id, raw: "this is quite cool a very cool post")+ post = post_creator.create+ expect(post.reviewable_flag).to_not be_present++ post_creator =+ PostCreator.new(+ user,+ topic_id: topic.id,+ raw: "this is quite cool a foo very cool post",+ )+ post = post_creator.create+ expect(post.reviewable_flag).to_not be_present+ end+ end+ end+ end+enddiff --git a/plugins/automation/spec/scripts/gift_exchange_spec.rb b/plugins/automation/spec/scripts/gift_exchange_spec.rbnew file mode 100644index 00000000000..62acce38e01--- /dev/null+++ b/plugins/automation/spec/scripts/gift_exchange_spec.rb@@ -0,0 +1,75 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "GiftExchange" do+ fab!(:automation) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::GIFT_EXCHANGE,+ trigger: DiscourseAutomation::Triggers::POINT_IN_TIME,+ )+ end+ fab!(:gift_group) { Fabricate(:group) }+ fab!(:user_1) { Fabricate(:user) }+ fab!(:user_2) { Fabricate(:user) }+ fab!(:user_3) { Fabricate(:user) }++ before do+ SiteSetting.discourse_automation_enabled = true++ gift_group.add(user_1)+ gift_group.add(user_2)+ gift_group.add(user_3)++ automation.upsert_field!(+ "gift_exchangers_group",+ "group",+ { value: gift_group.id },+ target: "script",+ )+ automation.upsert_field!(+ "giftee_assignment_messages",+ "pms",+ {+ value: [+ {+ title: "Gift {{year}}",+ raw: "@{{gifter_username}} you should send a gift to {{giftee_username}}",+ },+ ],+ },+ target: "script",+ )+ end++ context "when run from point_in_time trigger" do+ before do+ automation.upsert_field!(+ "execute_at",+ "date_time",+ { value: 3.hours.from_now },+ target: "trigger",+ )+ end++ it "creates expected PM" do+ freeze_time 6.hours.from_now do+ expect {+ Jobs::DiscourseAutomationTracker.new.execute++ raws = Post.order(created_at: :desc).limit(3).pluck(:raw)+ expect(raws.any? { |r| r.start_with?("@#{user_1.username}") }).to be_truthy+ expect(raws.any? { |r| r.start_with?("@#{user_2.username}") }).to be_truthy+ expect(raws.any? { |r| r.start_with?("@#{user_3.username}") }).to be_truthy+ expect(raws.any? { |r| r.end_with?("#{user_1.username}") }).to be_truthy+ expect(raws.any? { |r| r.end_with?("#{user_2.username}") }).to be_truthy+ expect(raws.any? { |r| r.end_with?("#{user_3.username}") }).to be_truthy++ title = Post.order(created_at: :desc).limit(3).map { |post| post.topic.title }.uniq.first+ expect(title).to eq("Gift #{Time.zone.now.year}")+ }.to change { Post.count }.by(3) # each pair receives a PM+ end+ end+ end+enddiff --git a/plugins/automation/spec/scripts/group_category_notification_default_spec.rb b/plugins/automation/spec/scripts/group_category_notification_default_spec.rbnew file mode 100644index 00000000000..73fc0dda5e8--- /dev/null+++ b/plugins/automation/spec/scripts/group_category_notification_default_spec.rb@@ -0,0 +1,71 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "GroupCategoryNotificationDefault" do+ fab!(:category)+ fab!(:group)++ before { SiteSetting.discourse_automation_enabled = true }++ context "when using category_created_edited trigger" do+ fab!(:automation) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::GROUP_CATEGORY_NOTIFICATION_DEFAULT,+ trigger: DiscourseAutomation::Triggers::CATEGORY_CREATED_EDITED,+ )+ end++ before do+ automation.upsert_field!(+ "restricted_category",+ "category",+ { value: category.id },+ target: "trigger",+ )+ automation.upsert_field!("group", "group", { value: group.id }, target: "script")+ automation.upsert_field!(+ "notification_level",+ "category_notification_level",+ { value: 4 },+ target: "script",+ )+ end++ context "when category is allowed" do+ it "creates a GroupCategoryNotificationDefault record" do+ subcategory = nil+ expect { subcategory = Fabricate(:category, parent_category_id: category.id) }.to change {+ GroupCategoryNotificationDefault.count+ }.by(1)++ record = GroupCategoryNotificationDefault.last+ expect(record.category_id).to eq(subcategory.id)+ expect(record.group_id).to eq(group.id)+ expect(record.notification_level).to eq(4)+ end++ it "updates category notification level for existing members" do+ automation.upsert_field!(+ "update_existing_members",+ "boolean",+ { value: true },+ target: "script",+ )+ user = Fabricate(:user)+ group.add(user)+ subcategory = nil++ expect { subcategory = Fabricate(:category, parent_category_id: category.id) }.to change {+ CategoryUser.count+ }.by(1)++ record = CategoryUser.last+ expect(record.category_id).to eq(subcategory.id)+ expect(record.user_id).to eq(user.id)+ expect(record.notification_level).to eq(4)+ end+ end+ end+enddiff --git a/plugins/automation/spec/scripts/pin_topic_spec.rb b/plugins/automation/spec/scripts/pin_topic_spec.rbnew file mode 100644index 00000000000..a65b646c12a--- /dev/null+++ b/plugins/automation/spec/scripts/pin_topic_spec.rb@@ -0,0 +1,66 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "PinTopic" do+ fab!(:user)+ fab!(:category) { Fabricate(:category, user: user) }+ fab!(:topic) { Fabricate(:topic, category: category) }+ fab!(:automation) { Fabricate(:automation, script: DiscourseAutomation::Scripts::PIN_TOPIC) }++ before do+ automation.upsert_field!("pinnable_topic", "text", { value: topic.id }, target: "script")+ end++ context "when not pinned globally" do+ it "works" do+ expect(topic.pinned_at).to be_nil++ automation.trigger!+ topic.reload++ expect(topic.pinned_at).to be_within_one_minute_of(Time.zone.now)+ expect(topic.pinned_globally).to be_falsey+ expect(topic.pinned_until).to be_nil+ end+ end++ context "when pinned globally" do+ before { automation.upsert_field!("pinned_globally", "boolean", { value: true }) }++ it "works" do+ expect(topic.pinned_at).to be_nil++ automation.trigger!+ topic.reload++ expect(topic.pinned_at).to be_within_one_minute_of(Time.zone.now)+ expect(topic.pinned_globally).to be_truthy+ expect(topic.pinned_until).to be_nil+ end+ end++ describe "pinned until" do+ before do+ freeze_time+ automation.upsert_field!("pinned_until", "date_time", { value: 10.days.from_now })+ end++ it "works" do+ expect(topic.pinned_at).to be_nil++ automation.trigger!++ # expect_enqueued_with is sometimes failing with float precision+ job = Jobs::UnpinTopic.jobs.last+ expect(job["args"][0]["topic_id"]).to eq(topic.id)+ expect(Time.at(job["at"])).to be_within_one_minute_of(10.days.from_now)++ topic.reload++ expect(topic.pinned_at).to be_within_one_minute_of(Time.zone.now)+ expect(topic.pinned_globally).to be_falsey+ expect(topic.pinned_until).to be_within_one_minute_of(10.days.from_now)+ end+ end+enddiff --git a/plugins/automation/spec/scripts/post_spec.rb b/plugins/automation/spec/scripts/post_spec.rbnew file mode 100644index 00000000000..8eea0f8c89c--- /dev/null+++ b/plugins/automation/spec/scripts/post_spec.rb@@ -0,0 +1,154 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "Post" do+ fab!(:topic_1) { Fabricate(:topic) }+ let!(:raw) { "this is me testing a post" }++ before { SiteSetting.discourse_automation_enabled = true }++ context "when using point_in_time trigger" do+ fab!(:automation) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::POST,+ trigger: DiscourseAutomation::Triggers::POINT_IN_TIME,+ )+ end++ before do+ automation.upsert_field!(+ "execute_at",+ "date_time",+ { value: 3.hours.from_now },+ target: "trigger",+ )+ automation.upsert_field!("topic", "text", { value: topic_1.id }, target: "script")+ automation.upsert_field!("post", "post", { value: raw }, target: "script")+ end++ it "creates expected post" do+ freeze_time 6.hours.from_now do+ expect {+ Jobs::DiscourseAutomationTracker.new.execute++ expect(topic_1.posts.last.raw).to eq(raw)+ }.to change { topic_1.posts.count }.by(1)+ end+ end++ context "when topic is deleted" do+ before { topic_1.trash! }++ it "does nothing and does not error" do+ freeze_time 6.hours.from_now do+ expect { Jobs::DiscourseAutomationTracker.new.execute }.not_to change { Post.count }+ end+ end+ end+ end++ context "when using recurring trigger" do+ fab!(:automation) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::POST,+ trigger: DiscourseAutomation::Triggers::RECURRING,+ )+ end++ before do+ automation.upsert_field!("topic", "text", { value: topic_1.id }, target: "script")+ automation.upsert_field!("post", "post", { value: raw }, target: "script")+ end++ it "creates expected post" do+ expect {+ automation.trigger!++ expect(topic_1.posts.last.raw).to eq(raw)+ }.to change { topic_1.posts.count }.by(1)+ end++ it "does not create post on a closed topic" do+ topic_1.update_status(:closed, true, topic_1.user)++ expect { automation.trigger! }.not_to change { topic_1.posts.count }+ end++ it "does not create post on an archived topic" do+ topic_1.update_status(:archived, true, topic_1.user)++ expect { automation.trigger! }.not_to change { topic_1.posts.count }+ end+ end++ context "when using user_updated trigger" do+ fab!(:user_field_1) { Fabricate(:user_field, name: "custom field 1") }+ fab!(:user_field_2) { Fabricate(:user_field, name: "custom field 2") }++ fab!(:user) do+ user = Fabricate(:user, trust_level: TrustLevel[0])+ user.set_user_field(user_field_1.id, "Answer custom 1")+ user.set_user_field(user_field_2.id, "Answer custom 2")+ user.user_profile.location = "Japan"+ user.user_profile.save+ user.save+ user+ end++ fab!(:automation) do+ automation =+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::POST,+ trigger: DiscourseAutomation::Triggers::USER_UPDATED,+ )+ automation.upsert_field!(+ "custom_fields",+ "custom_fields",+ { value: ["custom field 1", "custom field 2"] },+ target: "trigger",+ )+ automation.upsert_field!(+ "user_profile",+ "user_profile",+ { value: ["location"] },+ target: "trigger",+ )+ automation.upsert_field!("first_post_only", "boolean", { value: true }, target: "trigger")+ automation+ end+ let!(:user_raw_post) do+ "This is a raw test post for user custom field 1: {{custom_field_1}}, custom field 2: {{custom_field_2}} and location: {{location}}"+ end+ let!(:placeholder_applied_user_raw_post) do+ "This is a raw test post for user custom field 1: #{user.custom_fields["user_field_#{user_field_1.id}"]}, custom field 2: #{user.custom_fields["user_field_#{user_field_2.id}"]} and location: #{user.user_profile.location}"+ end++ before do+ automation.upsert_field!("topic", "text", { value: topic_1.id }, target: "script")+ automation.upsert_field!("post", "post", { value: user_raw_post }, target: "script")+ end++ it "Creates a post correctly" do+ expect {+ UserUpdater.new(user, user).update(location: "Japan")+ expect(topic_1.posts.last.raw).to eq(placeholder_applied_user_raw_post)+ }.to change { topic_1.posts.count }.by(1)+ end++ context "when creator is one of accepted context" do+ before do+ automation.upsert_field!("creator", "user", { value: "updated_user" }, target: "script")+ end++ it "sets the creator to the post creator" do+ expect { UserUpdater.new(user, user).update(location: "Japan") }.to change {+ Post.where(user_id: user.id).count+ }.by(1)+ end+ end+ end+enddiff --git a/plugins/automation/spec/scripts/send_pms_spec.rb b/plugins/automation/spec/scripts/send_pms_spec.rbnew file mode 100644index 00000000000..bd2c31d4bca--- /dev/null+++ b/plugins/automation/spec/scripts/send_pms_spec.rb@@ -0,0 +1,137 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "SendPms" do+ fab!(:automation) do+ Fabricate(:automation, script: DiscourseAutomation::Scripts::SEND_PMS, trigger: "stalled_wiki")+ end++ before do+ SiteSetting.discourse_automation_enabled = true++ automation.upsert_field!("sender", "user", { value: Discourse.system_user.username })+ automation.upsert_field!(+ "sendable_pms",+ "pms",+ {+ value: [+ {+ title: "A message from {{sender_username}}",+ raw: "This is a message sent to @{{receiver_username}}",+ },+ ],+ },+ )+ end++ context "when run from stalled_wiki trigger" do+ fab!(:post_creator_1) { Fabricate(:user, admin: true) }+ fab!(:post_1) { Fabricate(:post, user: post_creator_1) }++ before do+ automation.upsert_field!("stalled_after", "choices", { value: "PT1H" }, target: "trigger")+ automation.upsert_field!("retriggered_after", "choices", { value: "PT1H" }, target: "trigger")++ post_1.revise(+ post_creator_1,+ { wiki: true },+ { force_new_version: true, revised_at: 2.hours.ago },+ )+ end++ it "creates expected PM" do+ expect {+ Jobs::StalledWikiTracker.new.execute(nil)++ post = Post.last+ expect(post.topic.title).to eq("A message from #{Discourse.system_user.username}")+ expect(post.raw).to eq("This is a message sent to @#{post_creator_1.username}")+ expect(post.topic.topic_allowed_users.exists?(user_id: post_creator_1.id)).to eq(true)+ expect(post.topic.topic_allowed_users.exists?(user_id: Discourse.system_user.id)).to eq(+ true,+ )+ }.to change { Post.count }.by(1)+ end+ end++ context "when run from user_added_to_group trigger" do+ fab!(:user_1) { Fabricate(:user) }+ fab!(:tracked_group_1) { Fabricate(:group) }++ before do+ automation.update!(trigger: "user_added_to_group")+ automation.upsert_field!(+ "joined_group",+ "group",+ { value: tracked_group_1.id },+ target: "trigger",+ )+ end++ it "creates expected PM" do+ expect {+ tracked_group_1.add(user_1)++ post = Post.last+ expect(post.topic.title).to eq("A message from #{Discourse.system_user.username}")+ expect(post.raw).to eq("This is a message sent to @#{user_1.username}")+ expect(post.topic.topic_allowed_users.exists?(user_id: user_1.id)).to eq(true)+ expect(post.topic.topic_allowed_users.exists?(user_id: Discourse.system_user.id)).to eq(+ true,+ )+ }.to change { Post.count }.by(1)+ end+ end++ context "when delayed" do+ fab!(:user_1) { Fabricate(:user) }++ before { automation.update!(trigger: DiscourseAutomation::Triggers::RECURRING) }++ it "correctly sets encrypt preference to false even when option is not specified" do+ automation.upsert_field!(+ "sendable_pms",+ "pms",+ {+ value: [+ {+ title: "A message from {{sender_username}}",+ raw: "This is a message sent to @{{receiver_username}}",+ delay: 1,+ },+ ],+ },+ target: "script",+ )+ automation.upsert_field!("receiver", "user", { value: Discourse.system_user.username })++ automation.trigger!++ expect(DiscourseAutomation::PendingPm.last.prefers_encrypt).to eq(false)+ end++ it "correctly stores encrypt preference to false" do+ automation.upsert_field!(+ "sendable_pms",+ "pms",+ {+ value: [+ {+ title: "A message from {{sender_username}}",+ raw: "This is a message sent to @{{receiver_username}}",+ delay: 1,+ prefers_encrypt: false,+ },+ ],+ },+ target: "script",+ )+ automation.upsert_field!("receiver", "user", { value: Discourse.system_user.username })++ automation.trigger!++ expect(DiscourseAutomation::PendingPm.last.prefers_encrypt).to eq(false)+ end+ end+enddiff --git a/plugins/automation/spec/scripts/suspend_user_by_email_spec.rb b/plugins/automation/spec/scripts/suspend_user_by_email_spec.rbnew file mode 100644index 00000000000..22360f625d0--- /dev/null+++ b/plugins/automation/spec/scripts/suspend_user_by_email_spec.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "SuspendUserByEmail" do+ let(:suspend_until) { 10.days.from_now }+ let(:reason) { "banned for spam" }++ fab!(:automation) do+ Fabricate(:automation, script: DiscourseAutomation::Scripts::SUSPEND_USER_BY_EMAIL)+ end+ fab!(:user)++ before do+ automation.upsert_field!("suspend_until", "date_time", { value: suspend_until })+ automation.upsert_field!("reason", "text", { value: reason })+ end++ describe "using fields" do+ it "suspends the user" do+ expect(user.suspended?).to be(false)++ expect { automation.trigger!("email" => user.email) }.to change { UserHistory.count }.by(1)++ user.reload++ expect(user.suspended?).to be(true)+ expect(user.suspended_till).to be_within_one_minute_of(suspend_until)++ user_history = UserHistory.last+ expect(user_history.details).to eq(reason)+ expect(user_history.acting_user_id).to eq(Discourse.system_user.id)+ end+ end++ describe "trigger override" do+ let(:reason) { "very bad behavior" }+ let(:suspend_until) { 20.days.from_now }++ it "suspends the user" do+ expect(user.suspended?).to be(false)++ expect {+ automation.trigger!(+ "email" => user.email,+ "reason" => reason,+ "suspend_until" => suspend_until,+ )+ }.to change { UserHistory.count }.by(1)++ user.reload++ expect(user.suspended?).to be(true)+ expect(user.suspended_till).to be_within_one_minute_of(suspend_until)+ expect(UserHistory.last.details).to eq(reason)+ end+ end+enddiff --git a/plugins/automation/spec/scripts/topic_required_words_spec.rb b/plugins/automation/spec/scripts/topic_required_words_spec.rbnew file mode 100644index 00000000000..dc236b189a0--- /dev/null+++ b/plugins/automation/spec/scripts/topic_required_words_spec.rb@@ -0,0 +1,74 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "TopicRequiredWords" do+ fab!(:user)+ fab!(:category) { Fabricate(:category, user: user) }+ fab!(:topic) { Fabricate(:topic, category: category) }+ fab!(:automation) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::TOPIC_REQUIRED_WORDS,+ trigger: DiscourseAutomation::Triggers::TOPIC,+ )+ end++ before do+ SiteSetting.discourse_automation_enabled = true+ topic.upsert_custom_fields(discourse_automation_ids: automation.id)+ automation.upsert_field!("words", "text_list", { value: %w[#foo #bar] })+ end++ describe "editing/creating a post" do+ before do+ automation.upsert_field!("restricted_topic", "text", { value: topic.id }, target: "trigger")+ end++ context "when topic has a topic_required_words automation associated" do+ context "when post has at least a required word" do+ it "validates the post" do+ post_creator = PostCreator.new(user, topic_id: topic.id, raw: "this is quite cool #foo")+ post = post_creator.create+ expect(post.valid?).to be(true)+ end+ end++ context "when post has no required word" do+ it "doesn’t validate the post" do+ post_creator = PostCreator.new(user, topic_id: topic.id, raw: "this is quite cool")+ post = post_creator.create+ expect(post.valid?).to be(false)+ end+ end+ end++ context "when topic has no topic_required_words automation associated" do+ context "when post has no required word" do+ it "validates the post" do+ no_automation_topic = create_topic(category: category)+ post_creator =+ PostCreator.new(user, topic_id: no_automation_topic.id, raw: "this is quite cool")+ post = post_creator.create+ expect(post.valid?).to be(true)+ end+ end+ end+ end++ describe "moving posts" do+ fab!(:admin)+ fab!(:first_post) { Fabricate(:post, topic: topic, raw: "this is quite cool #foo") }+ fab!(:post) { Fabricate(:post, topic: topic, raw: "this is quite cool #bar") }+ fab!(:destination_topic) { Fabricate(:post).topic }++ it "works" do+ expect do+ topic.move_posts(admin, [post.id], destination_topic_id: destination_topic.id)+ end.to_not raise_error++ expect(topic.posts.where(post_type: Post.types[:regular]).size).to eq(1)+ expect(destination_topic.posts.where(post_type: Post.types[:regular]).size).to eq(2)+ end+ end+enddiff --git a/plugins/automation/spec/scripts/user_global_notice_spec.rb b/plugins/automation/spec/scripts/user_global_notice_spec.rbnew file mode 100644index 00000000000..09cde5e6313--- /dev/null+++ b/plugins/automation/spec/scripts/user_global_notice_spec.rb@@ -0,0 +1,129 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "UserGlobalNotice" do+ before { SiteSetting.discourse_automation_enabled = true }++ context "when triggered by a stalled topic" do+ fab!(:automation_1) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::USER_GLOBAL_NOTICE,+ trigger: "stalled_topic",+ )+ end++ fab!(:topic_1) { Fabricate(:topic) }++ before do+ automation_1.upsert_field!("stalled_after", "choices", { value: "PT1H" }, target: "trigger")+ automation_1.upsert_field!("notice", "message", { value: "foo bar" }, target: "script")+ automation_1.upsert_field!("level", "choices", { value: "error" }, target: "script")+ end++ describe "script" do+ describe "StalledTopic trigger" do+ it "creates a notice for the topic owner" do+ expect do+ automation_1.trigger!(+ "kind" => DiscourseAutomation::Triggers::STALLED_TOPIC,+ "topic" => topic_1,+ )+ end.to change { DiscourseAutomation::UserGlobalNotice.count }.by(1)++ user_notice = DiscourseAutomation::UserGlobalNotice.last+ expect(user_notice.user_id).to eq(topic_1.user_id)+ expect(user_notice.level).to eq("error")+ expect(user_notice.notice).to eq("foo bar")+ end+ end+ end++ it "creates and destroy global notices" do+ post = Fabricate(:post, created_at: 1.day.ago)++ expect { Jobs::StalledTopicTracker.new.execute }.to change {+ DiscourseAutomation::UserGlobalNotice.count+ }.by(1)++ expect {+ PostCreator.create!(post.user, topic_id: post.topic_id, raw: "lorem ipsum dolor sit amet")+ }.to change { DiscourseAutomation::UserGlobalNotice.count }.by(-1)+ end+ end++ context "when triggered by a first accepted solution" do+ fab!(:automation_1) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::USER_GLOBAL_NOTICE,+ trigger: "first_accepted_solution",+ )+ end++ fab!(:user_1) { Fabricate(:user, username: "user_solved_1") }+ fab!(:post_1) { Fabricate(:post, user: user_1) }++ before do+ automation_1.upsert_field!(+ "notice",+ "message",+ { value: "notice for {{username}}" },+ target: "script",+ )+ automation_1.upsert_field!("level", "choices", { value: "success" }, target: "script")+ end++ it "creates a notice for the solution author" do+ expect do+ automation_1.trigger!(+ "kind" => "first_accepted_solution",+ "accepted_post_id" => post_1.id,+ "usernames" => [post_1.user.username],+ "placeholders" => {+ "post_url" => Discourse.base_url + post_1.url,+ },+ )+ end.to change { DiscourseAutomation::UserGlobalNotice.count }.by(1)++ user_notice = DiscourseAutomation::UserGlobalNotice.last+ expect(user_notice.user_id).to eq(post_1.user.id)+ expect(user_notice.level).to eq("success")+ expect(user_notice.notice).to eq("notice for user_solved_1")+ end+ end++ describe "on_reset" do+ fab!(:topic_1) { Fabricate(:topic) }++ fab!(:automation_1) do+ Fabricate(:automation, script: DiscourseAutomation::Scripts::USER_GLOBAL_NOTICE)+ end++ fab!(:automation_2) do+ Fabricate(:automation, script: DiscourseAutomation::Scripts::USER_GLOBAL_NOTICE)+ end++ before do+ [automation_1, automation_2].each do |automation|+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::STALLED_TOPIC,+ "topic" => topic_1,+ )+ end+ end++ it "destroys all existing notices" do+ klass = DiscourseAutomation::UserGlobalNotice++ expect(klass.exists?(identifier: automation_1.id)).to eq(true)+ expect(klass.exists?(identifier: automation_2.id)).to eq(true)++ automation_1.scriptable.on_reset.call(automation_1)++ expect(klass.exists?(identifier: automation_1.id)).to eq(false)+ expect(klass.exists?(identifier: automation_2.id)).to eq(true)+ end+ end+enddiff --git a/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rb b/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rbnew file mode 100644index 00000000000..441fdba1e8e--- /dev/null+++ b/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rb@@ -0,0 +1,390 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "UserGroupMembershipThroughBadge" do+ fab!(:user)+ fab!(:other_users) { Fabricate.times(5, :user) }+ fab!(:badge)+ fab!(:target_group) { Fabricate(:group, title: "Target Title", flair_icon: "ad") }++ fab!(:automation) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::USER_GROUP_MEMBERSHIP_THROUGH_BADGE,+ )+ end++ before { BadgeGranter.enable_queue }+ after do+ BadgeGranter.disable_queue+ BadgeGranter.clear_queue!+ end++ def target_group_member?(user_ids)+ GroupUser.exists?(group_id: target_group.id, user_id: user_ids)+ end++ def owns_badge?(user_ids)+ UserBadge.exists?(user_id: user_ids, badge_id: badge.id)+ end++ context "with invalid field values" do+ before do+ @original_logger = Rails.logger+ Rails.logger = @fake_logger = FakeLogger.new+ end++ after { Rails.logger = @original_logger }++ context "with an unknown badge" do+ let(:unknown_badge_id) { -1 }++ before do+ automation.upsert_field!("badge", "choices", { value: unknown_badge_id }, target: "script")+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )+ end++ it "logs warning message and does nothing" do+ expect(@fake_logger.warnings).to include(+ "[discourse-automation] Couldn’t find badge with id #{unknown_badge_id}",+ )+ expect(user.reload.groups).to be_empty+ end+ end++ context "with a non-existent group" do+ before do+ automation.upsert_field!("badge", "choices", { value: badge.id }, target: "script")+ automation.upsert_field!("group", "group", { value: target_group.id }, target: "script")+ end++ it "logs warning message and does nothing" do+ target_group.destroy++ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )++ expect(@fake_logger.warnings).to include(+ "[discourse-automation] Couldn’t find group with id #{target_group.id}",+ )+ expect(user.reload.groups).to be_empty+ end+ end+ end++ context "with valid field values" do+ before do+ automation.upsert_field!("badge", "choices", { value: badge.id }, target: "script")+ automation.upsert_field!("group", "group", { value: target_group.id }, target: "script")+ end++ context "when triggered with a user" do+ context "when user has badge" do+ before { BadgeGranter.grant(badge, user) }++ it "adds user to group" do+ expect(target_group_member?([user.id])).to eq(false)++ expect do+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )+ end.to change { target_group.users.count }.by(1)++ expect(target_group_member?([user.id])).to eq(true)+ expect(owns_badge?([user.id])).to eq(true)+ end++ it "does nothing if user is an existing group member" do+ target_group.add(user)+ user.reload+ current_membership = user.group_users.find_by(group_id: target_group.id)++ expect(current_membership).not_to be_nil++ expect do+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )+ end.not_to change { target_group.reload.users.count }++ expect(GroupUser.find_by(group_id: target_group.id, user_id: user.id)).to eq(+ current_membership,+ )+ expect(owns_badge?([user.id])).to eq(true)+ end++ it "does not add other badge owners" do+ other_users.each { |u| BadgeGranter.grant(badge, u) }++ expect(badge.user_badges.count).to eq(6)+ expect(target_group.users.count).to eq(0)++ expect do+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )+ end.to change { target_group.reload.users.count }.by(1)++ expect(target_group_member?([user.id])).to eq(true)+ expect(owns_badge?([user.id])).to eq(true)+ end+ end++ context "when user does not have badge" do+ it "does not add user to group" do+ expect(target_group_member?([user.id])).to eq(false)+ expect(owns_badge?([user.id])).to eq(false)++ expect do+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )+ end.not_to change { target_group.users.count }++ expect(target_group_member?([user.id])).to eq(false)+ expect(owns_badge?([user.id])).to eq(false)+ end++ it "does not add other badge owners" do+ other_users.each { |u| BadgeGranter.grant(badge, u) }++ expect(badge.user_badges.count).to eq(5)+ expect(target_group.users.count).to eq(0)++ expect do+ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )+ end.not_to change { target_group.reload.users.count }++ expect(target_group_member?([user.id])).to eq(false)+ expect(owns_badge?([user.id])).to eq(false)+ expect(target_group.users.count).to eq(0)+ end+ end+ end++ context "when triggered without a user" do+ let(:badge_owners) { other_users.first(3) }+ let(:non_badge_owners) { other_users.last(2) }+ let(:badge_owner_ids) { badge_owners.map(&:id) }+ let(:non_badge_owner_ids) { non_badge_owners.map(&:id) }++ before { badge_owners.each { |u| BadgeGranter.grant(badge, u) } }++ it "adds all users with badge to group" do+ expect(target_group_member?(badge_owner_ids)).to eq(false)+ expect(target_group_member?(non_badge_owner_ids)).to eq(false)++ expect do+ automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)+ end.to change { target_group.reload.users.count }.by(badge_owners.size)++ expect(target_group_member?(badge_owner_ids)).to eq(true)+ expect(target_group_member?(non_badge_owner_ids)).to eq(false)+ end++ it "skips existing group members with badge" do+ badge_owners.each { |u| target_group.add(u) }++ expect(target_group_member?(badge_owner_ids)).to eq(true)+ expect(target_group_member?(non_badge_owner_ids)).to eq(false)++ expect do+ automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)+ end.not_to change { target_group.reload.users.count }++ expect(target_group_member?(badge_owner_ids)).to eq(true)+ expect(target_group_member?(non_badge_owner_ids)).to eq(false)+ end+ end++ context "with remove_members_without_badge = true" do+ before do+ automation.upsert_field!(+ "remove_members_without_badge",+ "boolean",+ { value: true },+ target: "script",+ )+ other_users.each { |u| target_group.add(u) }+ end++ it "removes existing members without badge" do+ expect(target_group_member?(other_users.map(&:id))).to eq(true)++ expect do+ automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)+ end.to change { target_group.reload.users.count }.by(-other_users.count)++ expect(target_group_member?(other_users.map(&:id))).to eq(false)+ end++ it "keeps existing members with badge" do+ BadgeGranter.grant(badge, user)+ target_group.add(user)++ expect(target_group_member?(other_users.map(&:id))).to eq(true)+ expect(owns_badge?(other_users.map(&:id))).to eq(false)+ expect(target_group_member?([user.id])).to eq(true)+ expect(owns_badge?([user.id])).to eq(true)++ expect do+ automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)+ end.to change { target_group.reload.users.count }++ expect(target_group_member?(other_users.map(&:id))).to eq(false)+ expect(owns_badge?(other_users.map(&:id))).to eq(false)+ expect(target_group_member?([user.id])).to eq(true)+ expect(owns_badge?([user.id])).to eq(true)+ end+ end++ context "with remove_members_without_badge = false" do+ before do+ automation.upsert_field!(+ "remove_members_without_badge",+ "boolean",+ { value: false },+ target: "script",+ )+ end++ it "keeps existing members without badge" do+ other_users.each { |u| target_group.add(u) }++ expect(target_group_member?(other_users.map(&:id))).to eq(true)+ expect(owns_badge?(other_users.map(&:id))).to eq(false)++ expect do+ automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)+ end.not_to change { target_group.reload.users.count }++ expect(target_group_member?(other_users.map(&:id))).to eq(true)+ expect(owns_badge?(other_users.map(&:id))).to eq(false)+ end+ end++ context "with update_user_title_and_flair = true" do+ before do+ BadgeGranter.grant(badge, user)+ automation.upsert_field!(+ "update_user_title_and_flair",+ "boolean",+ { value: true },+ target: "script",+ )+ end++ it "sets user title and flair" do+ expect(user.title).to be_nil+ expect(user.flair_group_id).to be_nil++ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )++ user.reload+ expect(user.title).to eq("Target Title")+ expect(user.flair_group_id).to eq(target_group.id)+ end++ it "updates existing user title and flair" do+ existing_flair_group = Fabricate(:group)+ user.update(title: "Existing Title", flair_group_id: existing_flair_group.id)++ expect(user.title).to eq("Existing Title")+ expect(user.flair_group_id).to eq(existing_flair_group.id)++ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )++ user.reload+ expect(user.title).to eq("Target Title")+ expect(user.flair_group_id).to eq(target_group.id)++ user_badge = UserBadge.find_by(user_id: user.id, badge_id: badge.id)+ user_badge.destroy++ automation.upsert_field!(+ "remove_members_without_badge",+ "boolean",+ { value: true },+ target: "script",+ )++ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )++ user.reload+ expect(user.title).to be_nil+ expect(user.flair_group_id).to be_nil+ end+ end++ context "with update_user_title_and_flair = false" do+ before do+ BadgeGranter.grant(badge, user)+ automation.upsert_field!(+ "update_user_title_and_flair",+ "boolean",+ { value: false },+ target: "script",+ )+ end++ it "does not update existing user title and flair" do+ existing_flair_group = Fabricate(:group)+ user.update(title: "Existing Title", flair_group_id: existing_flair_group.id)++ expect(user.title).to eq("Existing Title")+ expect(user.flair_group_id).to eq(existing_flair_group.id)++ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )++ user.reload+ expect(user.title).to eq("Existing Title")+ expect(user.flair_group_id).to eq(existing_flair_group.id)++ user_badge = UserBadge.find_by(user_id: user.id, badge_id: badge.id)+ user_badge.destroy++ automation.upsert_field!(+ "remove_members_without_badge",+ "boolean",+ { value: true },+ target: "script",+ )++ automation.trigger!(+ "kind" => DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN,+ "user" => user,+ )++ user.reload+ expect(user.title).to eq("Existing Title")+ expect(user.flair_group_id).to eq(existing_flair_group.id)+ end+ end+ end+enddiff --git a/plugins/automation/spec/scripts/zapier_webhook_spec.rb b/plugins/automation/spec/scripts/zapier_webhook_spec.rbnew file mode 100644index 00000000000..b25b5a04de0--- /dev/null+++ b/plugins/automation/spec/scripts/zapier_webhook_spec.rb@@ -0,0 +1,42 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "ZapierWebhook" do+ fab!(:topic)++ fab!(:automation) { Fabricate(:automation, script: DiscourseAutomation::Scripts::ZAPIER_WEBHOOK) }++ context "with valid webhook url" do+ before do+ automation.upsert_field!(+ "webhook_url",+ "text",+ { value: "https://hooks.zapier.com/hooks/catch/foo/bar" },+ )+ end++ it "enqueues the zapier call" do+ expect { automation.trigger! }.to change {+ Jobs::DiscourseAutomationCallZapierWebhook.jobs.length+ }.by(1)+ end+ end++ context "with invalid webhook url" do+ before do+ @orig_logger = Rails.logger+ Rails.logger = @fake_logger = FakeLogger.new+ end++ after { Rails.logger = @orig_logger }++ it "logs an error and do nothing" do+ expect { automation.trigger! }.not_to change {+ Jobs::DiscourseAutomationCallZapierWebhook.jobs.length+ }++ expect(Rails.logger.warnings.first).to match(/is not a valid Zapier/)+ end+ end+enddiff --git a/plugins/automation/spec/serializers/automation_serializer_spec.rb b/plugins/automation/spec/serializers/automation_serializer_spec.rbnew file mode 100644index 00000000000..ed6098b8435--- /dev/null+++ b/plugins/automation/spec/serializers/automation_serializer_spec.rb@@ -0,0 +1,117 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::AutomationSerializer do+ fab!(:user)+ fab!(:automation) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::FLAG_POST_ON_WORDS,+ trigger: DiscourseAutomation::Triggers::POST_CREATED_EDITED,+ )+ end++ context "when there are pending automations" do+ before { automation.pending_automations.create!(execute_at: 2.hours.from_now) }++ it "has a next_pending_automation_at field" do+ serializer =+ DiscourseAutomation::AutomationSerializer.new(+ automation,+ scope: Guardian.new(user),+ root: false,+ )+ expect(serializer.next_pending_automation_at).to be_within_one_minute_of(2.hours.from_now)+ end+ end++ context "when has no pending automation" do+ it "doesn’t have a next_pending_automation_at field" do+ serializer =+ DiscourseAutomation::AutomationSerializer.new(+ automation,+ scope: Guardian.new(user),+ root: false,+ )+ expect(serializer.next_pending_automation_at).to_not be+ end+ end++ context "when script with fields limited to a specific trigger" do+ before do+ DiscourseAutomation::Scriptable.add("foo") do+ field :bar, component: :text, triggerable: DiscourseAutomation::Triggers::TOPIC+ end+ end++ context "when automation is not using the specific trigger" do+ fab!(:automation) do+ Fabricate(+ :automation,+ script: "foo",+ trigger: DiscourseAutomation::Triggers::POST_CREATED_EDITED,+ )+ end++ it "filters the field" do+ serializer =+ DiscourseAutomation::AutomationSerializer.new(+ automation,+ scope: Guardian.new(user),+ root: false,+ )+ expect(serializer.script[:templates]).to eq([])+ end+ end++ context "when automation is using the specific trigger" do+ fab!(:automation) do+ Fabricate(:automation, script: "foo", trigger: DiscourseAutomation::Triggers::TOPIC)+ end++ it "doesn’t filter the field" do+ serializer =+ DiscourseAutomation::AutomationSerializer.new(+ automation,+ scope: Guardian.new(user),+ root: false,+ )+ expect(serializer.script[:templates].length).to eq(1)+ expect(serializer.script[:templates].first[:name]).to eq(:bar)+ end+ end+ end++ describe "#placeholders" do+ before do+ DiscourseAutomation::Scriptable.add("foo_bar") do+ version 1++ placeholder :foo+ placeholder :bar+ placeholder :bar, triggerable: :user_updated+ placeholder :bar, triggerable: :user_updated+ placeholder :bar, triggerable: :something+ placeholder(triggerable: :user_updated) { :cool }+ placeholder(triggerable: :whatever) { :not_cool }+ placeholder { "Why not" }++ triggerables %i[user_updated something whatever]+ end+ end++ fab!(:automation) { Fabricate(:automation, script: :foo_bar, trigger: :user_updated) }++ it "correctly renders placeholders" do+ serializer =+ DiscourseAutomation::AutomationSerializer.new(+ automation,+ scope: Guardian.new(user),+ root: false,+ )++ expect(serializer.placeholders).to eq(%w[foo bar cool why_not])+ end+ end+enddiff --git a/plugins/automation/spec/services/user_badge_granted_spec.rb b/plugins/automation/spec/services/user_badge_granted_spec.rbnew file mode 100644index 00000000000..57d07342687--- /dev/null+++ b/plugins/automation/spec/services/user_badge_granted_spec.rb@@ -0,0 +1,76 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::UserBadgeGrantedHandler do+ fab!(:user)+ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::USER_BADGE_GRANTED)+ end+ fab!(:tracked_badge) { Fabricate(:badge, multiple_grant: true) }++ before { SiteSetting.discourse_automation_enabled = true }++ context "when badge is not tracked" do+ it "doesn’t trigger the automation" do+ list = capture_contexts { described_class.handle(automation, tracked_badge.id, user.id) }+ expect(list).to be_blank+ end+ end++ context "when badge is tracked" do+ before do+ automation.upsert_field!("badge", "choices", { value: tracked_badge.id }, target: "trigger")+ end++ describe "only trigger on first grant" do+ before do+ automation.upsert_field!("only_first_grant", "boolean", { value: true }, target: "trigger")+ end++ context "when badge has been granted two times" do+ before do+ BadgeGranter.grant(tracked_badge, user)+ BadgeGranter.grant(tracked_badge, user)+ end++ it "doesn’t trigger the automation" do+ list = capture_contexts { described_class.handle(automation, tracked_badge.id, user.id) }+ expect(list).to be_blank+ end+ end++ context "when badge has not been granted already" do+ it "triggers the automation" do+ list = capture_contexts { described_class.handle(automation, tracked_badge.id, user.id) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq(DiscourseAutomation::Triggers::USER_BADGE_GRANTED)+ end+ end++ context "when user doesn’t exist" do+ it "raises an error" do+ expect { described_class.handle(automation, tracked_badge.id, -999) }.to raise_error(+ ActiveRecord::RecordNotFound,+ /'id'=-999/,+ )+ end+ end+ end++ it "triggers the automation" do+ list = capture_contexts { described_class.handle(automation, tracked_badge.id, user.id) }++ expect(list.length).to eq(1)+ output = list[0]+ expect(output["kind"]).to eq(DiscourseAutomation::Triggers::USER_BADGE_GRANTED)+ expect(output["usernames"]).to eq([user.username])+ expect(output["placeholders"]).to eq(+ "badge_name" => tracked_badge.name,+ "grant_count" => tracked_badge.grant_count,+ )+ expect(output["badge"]["id"]).to eq(tracked_badge.id)+ end+ end+enddiff --git a/plugins/automation/spec/system/smoke_test_spec.rb b/plugins/automation/spec/system/smoke_test_spec.rbnew file mode 100644index 00000000000..30f7488c520--- /dev/null+++ b/plugins/automation/spec/system/smoke_test_spec.rb@@ -0,0 +1,63 @@+# frozen_string_literal: true++describe "DiscourseAutomation | smoke test", type: :system, js: true do+ fab!(:admin)+ fab!(:group) { Fabricate(:group, name: "test") }+ fab!(:badge) { Fabricate(:badge, name: "badge") }++ before do+ SiteSetting.discourse_automation_enabled = true+ sign_in(admin)+ end++ context "when default_value fields are set" do+ before do+ DiscourseAutomation::Scriptable.add("test") do+ triggerables %i[post_created_edited]+ field :test, component: :text, default_value: "test-default-value"+ end+ end++ after { DiscourseAutomation::Scriptable.remove("test") }++ it "populate correctly" do+ visit("/admin/plugins/discourse-automation")+ find(".new-automation").click+ fill_in("automation-name", with: "aaaaa")+ select_kit = PageObjects::Components::SelectKit.new(".scriptables")+ select_kit.expand+ select_kit.select_row_by_value("test")+ find(".create-automation").click++ select_kit = PageObjects::Components::SelectKit.new(".triggerables")+ select_kit.expand+ select_kit.select_row_by_value("post_created_edited")++ expect(find(".field input[name=test]").value).to eq("test-default-value")+ end+ end++ it "works" do+ visit("/admin/plugins/discourse-automation")++ find(".new-automation").click+ fill_in("automation-name", with: "aaaaa")+ select_kit = PageObjects::Components::SelectKit.new(".scriptables")+ select_kit.expand+ select_kit.select_row_by_value("user_group_membership_through_badge")+ find(".create-automation").click+ select_kit = PageObjects::Components::SelectKit.new(".triggerables")+ select_kit.expand+ select_kit.select_row_by_value("user_first_logged_in")+ select_kit = PageObjects::Components::SelectKit.new(".fields-section .combo-box")+ select_kit.expand+ select_kit.select_row_by_name("badge")+ select_kit = PageObjects::Components::SelectKit.new(".group-chooser")+ select_kit.expand+ select_kit.select_row_by_name("test")+ find(".automation-enabled input").click+ find(".update-automation").click++ expect(page).to have_field("automation-name", with: "aaaaa")+ end+enddiff --git a/plugins/automation/spec/triggers/after_post_cook_spec.rb b/plugins/automation/spec/triggers/after_post_cook_spec.rbnew file mode 100644index 00000000000..ce0481b2de7--- /dev/null+++ b/plugins/automation/spec/triggers/after_post_cook_spec.rb@@ -0,0 +1,87 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::Triggers::AFTER_POST_COOK do+ before { SiteSetting.discourse_automation_enabled = true }++ fab!(:post)+ let(:topic) { post.topic }+ let(:parent_category) { Fabricate(:category_with_definition) }+ let(:subcategory) { Fabricate(:category_with_definition, parent_category_id: parent_category.id) }++ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::AFTER_POST_COOK)+ end++ context "when filtered to a tag" do+ let(:filtered_tag) { Fabricate(:tag) }++ before do+ automation.upsert_field!(+ "restricted_tags",+ "tags",+ { value: ["random", filtered_tag.name] },+ target: "trigger",+ )+ automation.reload+ end++ it "should not fire when tag is missing" do+ captured = capture_contexts { post.rebake! }++ expect(captured).to be_blank+ end++ it "should fire when tag is present" do+ topic.tags << filtered_tag+ topic.save!++ list = capture_contexts { post.rebake! }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq(DiscourseAutomation::Triggers::AFTER_POST_COOK)+ end+ end++ context "when filtered to a category" do+ context "when restricted to a subcategory" do+ before do+ automation.upsert_field!(+ "restricted_category",+ "category",+ { value: subcategory.id },+ target: "trigger",+ )+ topic.category = subcategory+ topic.save!+ end++ it "fires the trigger" do+ list = capture_contexts { post.rebake! }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq(DiscourseAutomation::Triggers::AFTER_POST_COOK)+ end+ end++ context "when restricted to a parent category" do+ before do+ automation.upsert_field!(+ "restricted_category",+ "category",+ { value: parent_category.id },+ target: "trigger",+ )+ topic.category = subcategory+ topic.save!+ end++ it "fires the trigger for a subcategory" do+ list = capture_contexts { post.rebake! }++ expect(list.length).to eq(1)+ end+ end+ end+enddiff --git a/plugins/automation/spec/triggers/category_created_edited_spec.rb b/plugins/automation/spec/triggers/category_created_edited_spec.rbnew file mode 100644index 00000000000..a4a3b63e3f1--- /dev/null+++ b/plugins/automation/spec/triggers/category_created_edited_spec.rb@@ -0,0 +1,52 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "CategoryCreatedEdited" do+ before { SiteSetting.discourse_automation_enabled = true }++ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::CATEGORY_CREATED_EDITED)+ end++ context "when editing/creating a post" do+ it "fires the trigger" do+ category = nil++ list = capture_contexts { category = Fabricate(:category) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("category_created_edited")+ expect(list[0]["action"].to_s).to eq("create")+ end++ context "when category is restricted" do+ let(:parent_category_id) { Category.first.id }+ before do+ automation.upsert_field!(+ "restricted_category",+ "category",+ { value: parent_category_id },+ target: "trigger",+ )+ end++ context "when category is allowed" do+ it "fires the trigger" do+ list = capture_contexts { Fabricate(:category, parent_category_id: parent_category_id) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("category_created_edited")+ end+ end++ context "when category is not allowed" do+ it "doesn’t fire the trigger" do+ list = capture_contexts { Fabricate(:category) }++ expect(list).to be_blank+ end+ end+ end+ end+enddiff --git a/plugins/automation/spec/triggers/pm_created_spec.rb b/plugins/automation/spec/triggers/pm_created_spec.rbnew file mode 100644index 00000000000..e1b18d48341--- /dev/null+++ b/plugins/automation/spec/triggers/pm_created_spec.rb@@ -0,0 +1,239 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "PMCreated" do+ before do+ SiteSetting.discourse_automation_enabled = true+ SiteSetting.personal_email_time_window_seconds = 0+ Group.refresh_automatic_groups!+ end++ fab!(:user)+ fab!(:automation) { Fabricate(:automation, trigger: DiscourseAutomation::Triggers::PM_CREATED) }++ context "when creating a PM to a user" do+ fab!(:target_user) { Fabricate(:user) }+ let(:basic_topic_params) do+ {+ title: "hello world topic",+ raw: "my name is fred",+ archetype: Archetype.private_message,+ target_usernames: [target_user.username],+ }+ end++ before do+ automation.upsert_field!(+ "restricted_user",+ "user",+ { value: target_user.username },+ target: "trigger",+ )+ end++ it "fires the trigger" do+ list = capture_contexts { PostCreator.create(user, basic_topic_params) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("pm_created")+ end++ context "when user is not targeted" do+ fab!(:user2) { Fabricate(:user) }++ it "doesn't fire the trigger" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ basic_topic_params.merge({ target_usernames: [user2.username] }),+ )+ end++ expect(list).to be_blank+ end+ end++ context "when trust_levels are restricted" do+ before do+ automation.upsert_field!(+ "valid_trust_levels",+ "trust-levels",+ { value: [2] },+ target: "trigger",+ )+ end++ context "when trust level is allowed" do+ it "fires the trigger" do+ list =+ capture_contexts do+ user.trust_level = TrustLevel[2]+ user.save!+ PostCreator.create(user, basic_topic_params)+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("pm_created")+ end+ end++ context "when trust level is not allowed" do+ it "doesn’t fire the trigger" do+ list =+ capture_contexts do+ user.trust_level = TrustLevel[1]+ user.save!+ PostCreator.create(user, basic_topic_params)+ end++ expect(list).to be_blank+ end+ end+ end++ context "when staff users ignored" do+ before do+ automation.upsert_field!("ignore_staff", "boolean", { value: true }, target: "trigger")+ end++ it "doesn’t fire the trigger" do+ list =+ capture_contexts do+ user.moderator = true+ user.save!+ PostCreator.create(user, basic_topic_params)+ end++ expect(list).to be_blank+ end+ end+ end++ context "when creating a PM to a group" do+ fab!(:target_group) { Fabricate(:group, messageable_level: Group::ALIAS_LEVELS[:everyone]) }+ let(:basic_topic_params) do+ {+ title: "hello world topic",+ raw: "my name is fred",+ archetype: Archetype.private_message,+ target_group_names: [target_group.name],+ }+ end++ before do+ automation.upsert_field!(+ "restricted_group",+ "group",+ { value: target_group.id },+ target: "trigger",+ )+ end++ it "fires the trigger" do+ list = capture_contexts { PostCreator.create(user, basic_topic_params) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("pm_created")+ end++ context "when members of the group are ignored" do+ before do+ automation.upsert_field!(+ "ignore_group_members",+ "boolean",+ { value: true },+ target: "trigger",+ )+ end++ it "doesn’t fire the trigger" do+ list =+ capture_contexts do+ user.groups << target_group+ PostCreator.create(user, basic_topic_params)+ end++ expect(list).to be_blank+ end+ end++ context "when the PM is being created from an incoming email" do+ before do+ target_group.update!(+ email_username: "[email protected]",+ incoming_email: "[email protected]|[email protected]",+ smtp_server: "smtp.test.com",+ smtp_port: 587,+ smtp_ssl: true,+ smtp_enabled: true,+ )+ SiteSetting.email_in = true+ end++ it "fires the trigger" do+ list =+ capture_contexts do+ Email::Receiver.new(email("email_to_group_email_username_1")).process!+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("pm_created")+ end++ context "when the restricted group does not match" do+ before do+ automation.upsert_field!(+ "restricted_group",+ "group",+ { value: Fabricate(:group).id },+ target: "trigger",+ )+ end++ it "doesn’t fire the trigger" do+ list =+ capture_contexts do+ Email::Receiver.new(email("email_to_group_email_username_1")).process!+ end+ expect(list).to be_blank+ end+ end++ context "when the incoming email is automated" do+ before { SiteSetting.block_auto_generated_emails = false }++ it "fires the trigger" do+ list =+ capture_contexts do+ Email::Receiver.new(email("email_to_group_email_username_auto_generated")).process!+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("pm_created")+ end++ context "when ignore_automated is true" do+ before do+ automation.upsert_field!(+ "ignore_automated",+ "boolean",+ { value: true },+ target: "trigger",+ )+ end++ it "doesn't fire the trigger" do+ list =+ capture_contexts do+ Email::Receiver.new(email("email_to_group_email_username_auto_generated")).process!+ end++ expect(list).to be_blank+ end+ end+ end+ end+ end+enddiff --git a/plugins/automation/spec/triggers/point_in_time_spec.rb b/plugins/automation/spec/triggers/point_in_time_spec.rbnew file mode 100644index 00000000000..317c01531d1--- /dev/null+++ b/plugins/automation/spec/triggers/point_in_time_spec.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "PointInTime" do+ fab!(:user)+ fab!(:topic)+ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::POINT_IN_TIME)+ end++ context "when updating trigger" do+ context "when date is in future" do+ it "creates a pending automation" do+ expect {+ automation.upsert_field!(+ "execute_at",+ "date_time",+ { value: 2.hours.from_now },+ target: "trigger",+ )+ }.to change { DiscourseAutomation::PendingAutomation.count }.by(1)++ expect(DiscourseAutomation::PendingAutomation.last.execute_at).to be_within_one_minute_of(+ 2.hours.from_now,+ )+ end+ end++ context "when date is in past" do+ it "doesn’t create a pending automation" do+ expect {+ automation.upsert_field!(+ "execute_at",+ "date_time",+ { value: 2.hours.ago },+ target: "trigger",+ )+ }.not_to change { DiscourseAutomation::PendingAutomation.count }+ end+ end+ end+enddiff --git a/plugins/automation/spec/triggers/post_created_edited_spec.rb b/plugins/automation/spec/triggers/post_created_edited_spec.rbnew file mode 100644index 00000000000..df9aa5dfe33--- /dev/null+++ b/plugins/automation/spec/triggers/post_created_edited_spec.rb@@ -0,0 +1,409 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "PostCreatedEdited" do+ before { SiteSetting.discourse_automation_enabled = true }++ let(:basic_topic_params) do+ { title: "hello world topic", raw: "my name is fred", archetype: Archetype.default }+ end+ let(:parent_category) { Fabricate(:category_with_definition) }+ let(:subcategory) { Fabricate(:category_with_definition, parent_category_id: parent_category.id) }++ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:automation) { Fabricate(:automation, trigger: "post_created_edited") }++ context "when filtering on first post only" do+ before do+ automation.upsert_field!("first_post_only", "boolean", { value: true }, target: "trigger")+ end++ it "fires on first post, but not on second" do+ post = create_post(title: "hello world topic", raw: "my name is fred")+ topic = post.topic++ list =+ capture_contexts do+ PostCreator.create!(user, raw: "this is a test reply", topic_id: topic.id)+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ expect(list[0]["action"].to_s).to eq("create")++ list =+ capture_contexts do+ PostCreator.create!(user, raw: "this is another test reply", topic_id: topic.id)+ end+ expect(list.length).to eq(0)+ end+ end++ context "when filtering on first topic only" do+ before do+ automation.upsert_field!("first_topic_only", "boolean", { value: true }, target: "trigger")+ end++ it "does not fire if it is not a topic" do+ post = create_post(title: "hello world topic", raw: "my name is fred")+ topic = post.topic++ list =+ capture_contexts do+ PostCreator.create!(user, raw: "this is a test reply", topic_id: topic.id)+ end++ expect(list.length).to eq(0)+ end++ it "fires if it is a first topic (and not on second)" do+ list =+ capture_contexts do+ PostCreator.create!(user, raw: "this is a test reply", title: "hello there mister")+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ expect(list[0]["action"].to_s).to eq("create")++ list =+ capture_contexts do+ PostCreator.create!(user, raw: "this is a test reply 2", title: "hello there mister 2")+ end++ expect(list.length).to eq(0)+ end+ end++ context "when editing/creating a post" do+ it "fires the trigger" do+ post = nil++ list = capture_contexts { post = PostCreator.create(user, basic_topic_params) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ expect(list[0]["action"].to_s).to eq("create")++ list = capture_contexts { post.revise(post.user, raw: "this is another cool topic") }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ expect(list[0]["action"].to_s).to eq("edit")+ end++ context "when trust_levels are restricted" do+ before do+ automation.upsert_field!(+ "valid_trust_levels",+ "trust-levels",+ { value: [0] },+ target: "trigger",+ )+ end++ context "when trust level is allowed" do+ it "fires the trigger" do+ list =+ capture_contexts do+ user.trust_level = TrustLevel[0]+ PostCreator.create(user, basic_topic_params)+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end+ end++ context "when trust level is not allowed" do+ it "doesn’t fire the trigger" do+ list =+ capture_contexts do+ user.trust_level = TrustLevel[1]+ PostCreator.create(user, basic_topic_params)+ end++ expect(list).to be_blank+ end+ end+ end++ context "when group is restricted" do+ fab!(:target_group) { Fabricate(:group, messageable_level: Group::ALIAS_LEVELS[:everyone]) }++ before do+ automation.upsert_field!(+ "restricted_group",+ "group",+ { value: target_group.id },+ target: "trigger",+ )+ end++ it "fires the trigger" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ basic_topic_params.merge(+ target_group_names: [target_group.name],+ archetype: Archetype.private_message,+ ),+ )+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end++ context "when the topic is not a PM" do+ it "doesn’t fire the trigger" do+ list =+ capture_contexts do+ user.groups << target_group+ PostCreator.create(user, basic_topic_params)+ end++ expect(list).to be_blank+ end+ end++ context "when members of the group are ignored" do+ before do+ automation.upsert_field!(+ "ignore_group_members",+ "boolean",+ { value: true },+ target: "trigger",+ )+ end++ it "doesn’t fire the trigger" do+ list =+ capture_contexts do+ user.groups << target_group+ PostCreator.create(+ user,+ basic_topic_params.merge(+ target_group_names: [target_group.name],+ archetype: Archetype.private_message,+ ),+ )+ end++ expect(list).to be_blank+ end+ end++ context "when a different group is used" do+ it "does not fire the trigger" do+ list =+ capture_contexts do+ PostCreator.create(+ user,+ basic_topic_params.merge(+ target_group_names: [Fabricate(:group).name],+ archetype: Archetype.private_message,+ ),+ )+ end++ expect(list).to be_blank+ end+ end+ end++ context "when the post is being created from an incoming email" do+ let(:reply_key) { "4f97315cc828096c9cb34c6f1a0d6fe8" }+ fab!(:user) { Fabricate(:user, email: "[email protected]", refresh_auto_groups: true) }+ fab!(:topic) { create_topic(user: user) }+ fab!(:post) { create_post(topic: topic) }++ let!(:post_reply_key) do+ Fabricate(:post_reply_key, reply_key: reply_key, user: user, post: post)+ end++ before do+ SiteSetting.email_in = true+ SiteSetting.reply_by_email_address = "reply+%{reply_key}@bar.com"+ SiteSetting.alternative_reply_by_email_addresses = "alt+%{reply_key}@bar.com"+ end++ it "fires the trigger" do+ list = capture_contexts { Email::Receiver.new(email("html_reply")).process! }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ expect(list[0]["action"].to_s).to eq("create")+ end++ context "when the incoming email is automated" do+ before { SiteSetting.block_auto_generated_emails = false }++ it "fires the trigger" do+ list =+ capture_contexts { Email::Receiver.new(email("auto_generated_unblocked")).process! }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end++ context "when ignore_automated is true" do+ before do+ automation.upsert_field!(+ "ignore_automated",+ "boolean",+ { value: true },+ target: "trigger",+ )+ end++ it "doesn't fire the trigger" do+ list =+ capture_contexts { Email::Receiver.new(email("auto_generated_unblocked")).process! }++ expect(list).to be_blank+ end+ end+ end+ end++ context "when category is restricted" do+ before do+ automation.upsert_field!(+ "restricted_category",+ "category",+ { value: Category.first.id },+ target: "trigger",+ )+ end++ context "when category is allowed" do+ it "fires the trigger" do+ list =+ capture_contexts do+ PostCreator.create(user, basic_topic_params.merge({ category: Category.first.id }))+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end+ end++ context "when restricted to a subcategory" do+ before do+ automation.upsert_field!(+ "restricted_category",+ "category",+ { value: subcategory.id },+ target: "trigger",+ )+ end++ it "fires the trigger" do+ list =+ capture_contexts do+ PostCreator.create(user, basic_topic_params.merge({ category: subcategory.id }))+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end++ it "does not fire the trigger for the parent" do+ list =+ capture_contexts do+ PostCreator.create(user, basic_topic_params.merge({ category: parent_category.id }))+ end++ expect(list.length).to eq(0)+ end+ end++ context "when restricted to a parent category" do+ before do+ automation.upsert_field!(+ "restricted_category",+ "category",+ { value: parent_category.id },+ target: "trigger",+ )+ end++ it "fires the trigger for a subcategory" do+ list =+ capture_contexts do+ PostCreator.create(user, basic_topic_params.merge({ category: subcategory.id }))+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end++ it "fires the trigger for the parent" do+ list =+ capture_contexts do+ PostCreator.create(user, basic_topic_params.merge({ category: parent_category.id }))+ end++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ end+ end++ context "when category is not allowed" do+ fab!(:category)++ it "doesn’t fire the trigger" do+ list =+ capture_contexts do+ PostCreator.create(user, basic_topic_params.merge({ category: category.id }))+ end++ expect(list).to be_blank+ end+ end+ end++ context "when action_type is set to create" do+ before do+ automation.upsert_field!("action_type", "choices", { value: "created" }, target: "trigger")+ end++ it "fires the trigger only for create" do+ post = nil++ list = capture_contexts { post = PostCreator.create(user, basic_topic_params) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ expect(list[0]["action"].to_s).to eq("create")++ list = capture_contexts { post.revise(post.user, raw: "this is another cool topic") }++ expect(list.length).to eq(0)+ end+ end++ context "when action_type is set to edit" do+ before do+ automation.upsert_field!("action_type", "choices", { value: "edited" }, target: "trigger")+ end++ it "fires the trigger only for edit" do+ post = nil++ list = capture_contexts { post = PostCreator.create(user, basic_topic_params) }++ expect(list.length).to eq(0)++ list = capture_contexts { post.revise(post.user, raw: "this is another cool topic") }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("post_created_edited")+ expect(list[0]["action"].to_s).to eq("edit")+ end+ end+ end+enddiff --git a/plugins/automation/spec/triggers/recurring_spec.rb b/plugins/automation/spec/triggers/recurring_spec.rbnew file mode 100644index 00000000000..c13337bc365--- /dev/null+++ b/plugins/automation/spec/triggers/recurring_spec.rb@@ -0,0 +1,214 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "Recurring" do+ fab!(:user)+ fab!(:topic)+ fab!(:automation) do+ Fabricate(+ :automation,+ trigger: DiscourseAutomation::Triggers::RECURRING,+ script: "nothing_about_us",+ )+ end++ def upsert_period_field!(interval, frequency)+ metadata = { value: { interval: interval, frequency: frequency } }+ automation.upsert_field!("recurrence", "period", metadata, target: "trigger")+ end++ it "allows manual trigger" do+ triggerable = DiscourseAutomation::Triggerable.new(automation.trigger)+ expect(triggerable.settings[DiscourseAutomation::Triggerable::MANUAL_TRIGGER_KEY]).to eq(true)+ end++ describe "updating trigger" do+ context "when date is in future" do+ before { freeze_time Time.parse("2021-06-04 10:00 UTC") }++ it "creates a pending trigger" do+ expect {+ automation.upsert_field!(+ "start_date",+ "date_time",+ { value: 2.hours.from_now },+ target: "trigger",+ )+ upsert_period_field!(1, "hour")+ }.to change { DiscourseAutomation::PendingAutomation.count }.by(1)++ expect(DiscourseAutomation::PendingAutomation.last.execute_at).to be_within_one_minute_of(+ 1.hours.from_now,+ )+ end+ end++ context "when date is in past" do+ it "doesn’t create a pending trigger" do+ expect {+ automation.upsert_field!(+ "start_date",+ "date_time",+ { value: 2.hours.ago },+ target: "trigger",+ )+ }.not_to change { DiscourseAutomation::PendingAutomation.count }+ end+ end+ end++ context "when trigger is called" do+ before do+ freeze_time Time.zone.parse("2021-06-04 10:00")+ automation.fields.insert!(+ {+ name: "start_date",+ component: "date_time",+ metadata: {+ value: 2.hours.ago,+ },+ target: "trigger",+ created_at: Time.now,+ updated_at: Time.now,+ },+ )+ metadata = { value: { interval: "1", frequency: "week" } }+ automation.fields.insert!(+ {+ name: "recurrence",+ component: "period",+ metadata: metadata,+ target: "trigger",+ created_at: Time.now,+ updated_at: Time.now,+ },+ )+ end++ it "creates the next iteration" do+ expect { automation.trigger! }.to change { DiscourseAutomation::PendingAutomation.count }.by(+ 1,+ )++ pending_automation = DiscourseAutomation::PendingAutomation.last++ start_date = Time.parse(automation.trigger_field("start_date")["value"])+ expect(pending_automation.execute_at).to be_within_one_minute_of(start_date + 7.days)+ end++ describe "every_month" do+ before { upsert_period_field!(1, "month") }++ it "creates the next iteration one month later" do+ automation.trigger!++ pending_automation = DiscourseAutomation::PendingAutomation.last+ expect(pending_automation.execute_at).to be_within_one_minute_of(+ Time.parse("2021-07-02 08:00:00 UTC"),+ )+ end+ end++ describe "every_day" do+ before do+ automation.upsert_field!(+ "start_date",+ "date_time",+ { value: 1.minute.from_now },+ target: "trigger",+ )+ upsert_period_field!(1, "day")+ end++ it "creates the next iteration one day later" do+ automation.trigger!++ pending_automation = DiscourseAutomation::PendingAutomation.last+ start_date = Time.parse(automation.trigger_field("start_date")["value"])+ expect(pending_automation.execute_at).to be_within_one_minute_of(start_date)+ end+ end++ describe "every_weekday" do+ it "creates the next iteration one day after without Saturday/Sunday" do+ upsert_period_field!(1, "weekday")+ automation.trigger!++ pending_automation = DiscourseAutomation::PendingAutomation.last+ start_date = Time.parse(automation.trigger_field("start_date")["value"])+ expect(pending_automation.execute_at).to be_within_one_minute_of(start_date + 3.day)+ end++ it "creates the next iteration three days after without Saturday/Sunday" do+ now = DateTime.parse("2022-05-19").end_of_day+ start_date = now - 1.hour+ freeze_time now++ automation.pending_automations.destroy_all+ automation.upsert_field!(+ "start_date",+ "date_time",+ { value: start_date },+ target: "trigger",+ )+ upsert_period_field!(3, "weekday")++ automation.trigger!++ pending_automation = automation.pending_automations.last+ expect(pending_automation.execute_at).to be_within_one_minute_of(start_date + 5.days)+ end+ end++ describe "every_hour" do+ before { upsert_period_field!(1, "hour") }++ it "creates the next iteration one hour later" do+ automation.trigger!++ pending_automation = DiscourseAutomation::PendingAutomation.last+ expect(pending_automation.execute_at).to be_within_one_minute_of(+ (Time.zone.now + 1.hour).beginning_of_hour,+ )+ end+ end++ describe "every_minute" do+ before { upsert_period_field!(1, "minute") }++ it "creates the next iteration one minute later" do+ automation.trigger!++ pending_automation = DiscourseAutomation::PendingAutomation.last+ expect(pending_automation.execute_at).to be_within_one_minute_of(+ (Time.zone.now + 1.minute).beginning_of_minute,+ )+ end+ end++ describe "every_year" do+ before { upsert_period_field!(1, "year") }++ it "creates the next iteration one year later" do+ automation.trigger!++ pending_automation = DiscourseAutomation::PendingAutomation.last+ start_date = Time.parse(automation.trigger_field("start_date")["value"])+ expect(pending_automation.execute_at).to be_within_one_minute_of(start_date + 1.year)+ end+ end++ describe "every_other_week" do+ before { upsert_period_field!(2, "week") }++ it "creates the next iteration two weeks later" do+ automation.trigger!++ pending_automation = DiscourseAutomation::PendingAutomation.last+ start_date = Time.parse(automation.trigger_field("start_date")["value"])+ expect(pending_automation.execute_at).to be_within_one_minute_of(start_date + 2.weeks)+ end+ end+ end+enddiff --git a/plugins/automation/spec/triggers/stalled_wiki_spec.rb b/plugins/automation/spec/triggers/stalled_wiki_spec.rbnew file mode 100644index 00000000000..80a8377cd4b--- /dev/null+++ b/plugins/automation/spec/triggers/stalled_wiki_spec.rb@@ -0,0 +1,190 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "StalledWiki" do+ fab!(:topic_1) { Fabricate(:topic) }+ fab!(:automation) { Fabricate(:automation, trigger: DiscourseAutomation::Triggers::STALLED_WIKI) }+ fab!(:post_creator_1) { Fabricate(:user, admin: true) }+ let!(:post) do+ post_creator =+ PostCreator.new(+ post_creator_1,+ topic_id: topic_1.id,+ raw: "this is a post that will become a wiki",+ )+ post_creator.create+ end++ it "allows manual trigger" do+ triggerable = DiscourseAutomation::Triggerable.new(automation.trigger)+ expect(triggerable.settings[DiscourseAutomation::Triggerable::MANUAL_TRIGGER_KEY]).to eq(true)+ end++ describe "default" do+ before do+ automation.upsert_field!("stalled_after", "choices", { value: "PT10H" }, target: "trigger")+ automation.upsert_field!("retriggered_after", "choices", { value: "PT1H" }, target: "trigger")+ end++ it "supports manual triggering" do+ DiscourseAutomation::AutomationSerializer.new(automation, root: "automation").as_json+ end++ context "when the post has been revised recently" do+ it "doesn’t trigger" do+ post.revise(+ post_creator_1,+ { wiki: true },+ { force_new_version: true, revised_at: 40.minutes.ago },+ )++ list = capture_contexts { Jobs::StalledWikiTracker.new.execute(nil) }++ expect(list.length).to eq(0)+ end+ end++ context "when the post hasn’t been revised recently" do+ it "triggers" do+ post.revise(+ post_creator_1,+ { wiki: true },+ { force_new_version: true, revised_at: 1.month.ago },+ )++ list = capture_contexts { Jobs::StalledWikiTracker.new.execute(nil) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("stalled_wiki")+ end++ context "when trigger has a category" do+ fab!(:category)++ before do+ automation.upsert_field!(+ "stalled_after",+ "choices",+ { value: "PT10H" },+ target: "trigger",+ )+ automation.upsert_field!(+ "retriggered_after",+ "choices",+ { value: "PT1H" },+ target: "trigger",+ )+ automation.upsert_field!(+ "restricted_category",+ "category",+ { value: category.id },+ target: "trigger",+ )+ end++ context "when the post is in a sub category" do+ before do+ subcategory = Fabricate(:category, parent_category: category)+ subcategory.save!++ post.topic.update(category: subcategory)+ end++ it "doesn’t trigger" do+ post.revise(+ post_creator_1,+ { wiki: true },+ { force_new_version: true, revised_at: 40.minutes.ago },+ )++ list = capture_contexts { Jobs::StalledWikiTracker.new.execute(nil) }++ expect(list).to be_empty+ end+ end++ context "when the post is in this category" do+ before { post.topic.update(category: category) }++ it "triggers" do+ post.revise(+ post_creator_1,+ { wiki: true },+ { force_new_version: true, revised_at: 1.month.ago },+ )++ list = capture_contexts { Jobs::StalledWikiTracker.new.execute(nil) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("stalled_wiki")+ end+ end++ context "when the post is not in this category" do+ it "doesn’t trigger" do+ post.revise(+ post_creator_1,+ { wiki: true },+ { force_new_version: true, revised_at: 40.minutes.ago },+ )++ list = capture_contexts { Jobs::StalledWikiTracker.new.execute(nil) }++ expect(list).to be_empty+ end+ end+ end++ context "when trigger hasn’t been running recently" do+ before { freeze_time 2.hours.from_now }++ it "sets custom field" do+ expect(post.reload.custom_fields["stalled_wiki_triggered_at"]).to eq(nil)++ post.revise(+ post_creator_1,+ { wiki: true },+ { force_new_version: true, revised_at: 1.month.ago },+ )+ Jobs::StalledWikiTracker.new.execute(nil)++ expect(post.reload.custom_fields["stalled_wiki_triggered_at"]).to eq(Time.zone.now.to_s)+ end++ it "triggers again" do+ post.revise(+ post_creator_1,+ { wiki: true },+ { force_new_version: true, revised_at: 2.months.ago },+ )+ post.upsert_custom_fields(stalled_wiki_triggered_at: 2.months.ago)++ list = capture_contexts { Jobs::StalledWikiTracker.new.execute(nil) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("stalled_wiki")+ expect(post.reload.custom_fields["stalled_wiki_triggered_at"]).to eq(Time.zone.now.to_s)+ end+ end++ context "when trigger has been running recently" do+ before { freeze_time 2.hours.from_now }++ it "doesn’t trigger again" do+ post.revise(+ post_creator_1,+ { wiki: true },+ { force_new_version: true, revised_at: 1.month.ago },+ )+ post.upsert_custom_fields(stalled_wiki_triggered_at: 10.minutes.ago)++ list = capture_contexts { Jobs::StalledWikiTracker.new.execute(nil) }++ expect(list.length).to eq(0)+ expect(post.reload.custom_fields["stalled_wiki_triggered_at"]).to eq(10.minutes.ago.to_s)+ end+ end+ end+ end+enddiff --git a/plugins/automation/spec/triggers/topic_spec.rb b/plugins/automation/spec/triggers/topic_spec.rbnew file mode 100644index 00000000000..67ccfe4be84--- /dev/null+++ b/plugins/automation/spec/triggers/topic_spec.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "TopicRequiredWords" do+ fab!(:user)+ fab!(:topic)+ fab!(:automation) do+ Fabricate(+ :automation,+ script: DiscourseAutomation::Scripts::TOPIC_REQUIRED_WORDS,+ trigger: DiscourseAutomation::Triggers::TOPIC,+ )+ end++ context "when updating trigger" do+ it "updates the custom field" do+ automation.upsert_field!("restricted_topic", "text", { value: topic.id }, target: "trigger")+ expect(topic.custom_fields["discourse_automation_ids"]).to eq([automation.id])++ new_topic = create_topic+ automation.upsert_field!(+ "restricted_topic",+ "text",+ { value: new_topic.id },+ target: "trigger",+ )+ expect(new_topic.custom_fields["discourse_automation_ids"]).to eq([automation.id])+ end+ end+enddiff --git a/plugins/automation/spec/triggers/user_added_to_group_spec.rb b/plugins/automation/spec/triggers/user_added_to_group_spec.rbnew file mode 100644index 00000000000..f0a19b54e00--- /dev/null+++ b/plugins/automation/spec/triggers/user_added_to_group_spec.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "UserAddedToGroup" do+ fab!(:user)+ fab!(:tracked_group) { Fabricate(:group) }+ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::USER_ADDED_TO_GROUP)+ end++ before do+ SiteSetting.discourse_automation_enabled = true+ automation.upsert_field!(+ "joined_group",+ "group",+ { value: tracked_group.id },+ target: "trigger",+ )+ end++ context "when group is tracked" do+ it "fires the trigger" do+ list = capture_contexts { tracked_group.add(user) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq(DiscourseAutomation::Triggers::USER_ADDED_TO_GROUP)+ expect(list[0]["user"]).to eq(user)+ expect(list[0]["group"]).to eq(tracked_group)+ expect(list[0]["usernames"]).to eq([user.username])+ end+ end++ context "when group is not tracked" do+ let(:untracked_group) { Fabricate(:group) }++ it "doesn’t fire the trigger" do+ list = capture_contexts { untracked_group.add(user) }++ expect(list).to eq([])+ end+ end+enddiff --git a/plugins/automation/spec/triggers/user_badge_granted_spec.rb b/plugins/automation/spec/triggers/user_badge_granted_spec.rbnew file mode 100644index 00000000000..e4de0f03772--- /dev/null+++ b/plugins/automation/spec/triggers/user_badge_granted_spec.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "UserBadgeGranted" do+ fab!(:user)+ fab!(:tracked_badge) { Fabricate(:badge) }+ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::USER_BADGE_GRANTED)+ end++ before do+ SiteSetting.discourse_automation_enabled = true+ automation.upsert_field!("badge", "choices", { value: tracked_badge.id }, target: "trigger")+ end++ context "when a badge is granted" do+ it "fires the trigger" do+ contexts = capture_contexts { BadgeGranter.grant(tracked_badge, user) }++ expect(contexts.length).to eq(1)+ expect(contexts[0]["kind"]).to eq(DiscourseAutomation::Triggers::USER_BADGE_GRANTED)+ end+ end+enddiff --git a/plugins/automation/spec/triggers/user_first_logged_in_spec.rb b/plugins/automation/spec/triggers/user_first_logged_in_spec.rbnew file mode 100644index 00000000000..476746715a7--- /dev/null+++ b/plugins/automation/spec/triggers/user_first_logged_in_spec.rb@@ -0,0 +1,32 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN do+ before { SiteSetting.discourse_automation_enabled = true }++ fab!(:user)+ let(:topic) { post.topic }++ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN)+ end++ context "when user logs in for first time" do+ it "triggers the automation" do+ contexts = capture_contexts { user.logged_in }++ expect(contexts[0]["kind"]).to eq(DiscourseAutomation::Triggers::USER_FIRST_LOGGED_IN)+ expect(contexts[0]["user"]).to eq(user)+ end+ end++ context "when user logs in multiple times" do+ it "doesn’t trigger the automation" do+ user.update_last_seen!(2.days.ago)+ contexts = capture_contexts { user.logged_in }++ expect(contexts).to eq([])+ end+ end+enddiff --git a/plugins/automation/spec/triggers/user_promoted_spec.rb b/plugins/automation/spec/triggers/user_promoted_spec.rbnew file mode 100644index 00000000000..0da249b5e0c--- /dev/null+++ b/plugins/automation/spec/triggers/user_promoted_spec.rb@@ -0,0 +1,100 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "UserPromoted" do+ before { SiteSetting.discourse_automation_enabled = true }++ fab!(:user) { Fabricate(:user, trust_level: TrustLevel[0]) }+ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::USER_PROMOTED)+ end++ it "runs without any restrictions" do+ list = capture_contexts { user.change_trust_level!(TrustLevel[1]) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("user_promoted")+ expect(list[0]["placeholders"]).to eq(+ { "trust_level_transition" => "from new user to basic user" },+ )+ end++ it "does not run if the user is being demoted" do+ user.change_trust_level!(TrustLevel[4])++ list = capture_contexts { user.change_trust_level!(TrustLevel[1]) }++ expect(list).to eq([])+ end++ context "when there is a group restriction" do+ let!(:group) { Fabricate(:group) }+ before do+ automation.upsert_field!(+ "restricted_group",+ "group",+ { "value" => group.id },+ target: "trigger",+ )+ end++ it "does not run if the user is not part of the group" do+ list = capture_contexts { user.change_trust_level!(TrustLevel[1]) }++ expect(list).to eq([])+ end++ it "does run if the user is part of the group" do+ Fabricate(:group_user, group: group, user: user)+ list = capture_contexts { user.change_trust_level!(TrustLevel[1]) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("user_promoted")+ end+ end++ context "when there is a trust_level_transition restriction" do+ before do+ automation.upsert_field!(+ "trust_level_transition",+ "choices",+ { "value" => "TL01" },+ target: "trigger",+ )+ end++ it "does not run if the trust level transition does not match" do+ user.change_trust_level!(TrustLevel[2])++ list = capture_contexts { user.change_trust_level!(TrustLevel[3]) }++ expect(list).to eq([])+ end++ it "does run if the trust level transition matches" do+ user.change_trust_level!(TrustLevel[0])++ list = capture_contexts { user.change_trust_level!(TrustLevel[1]) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to include("user_promoted")+ end++ it "does run if the transition is for all trust levels" do+ automation.upsert_field!(+ "trust_level_transition",+ "choices",+ { "value" => "TLALL" },+ target: "trigger",+ )++ user.change_trust_level!(TrustLevel[2])++ list = capture_contexts { user.change_trust_level!(TrustLevel[4]) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq("user_promoted")+ end+ end+enddiff --git a/plugins/automation/spec/triggers/user_removed_from_group_spec.rb b/plugins/automation/spec/triggers/user_removed_from_group_spec.rbnew file mode 100644index 00000000000..43bf84e69e0--- /dev/null+++ b/plugins/automation/spec/triggers/user_removed_from_group_spec.rb@@ -0,0 +1,40 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "UserRemovedFromGroup" do+ fab!(:user)+ fab!(:group)+ fab!(:automation) do+ Fabricate(:automation, trigger: DiscourseAutomation::Triggers::USER_REMOVED_FROM_GROUP)+ end++ before do+ SiteSetting.discourse_automation_enabled = true+ group.add(user)+ end++ context "when group is tracked" do+ before do+ automation.upsert_field!("left_group", "group", { value: group.id }, target: "trigger")+ end++ it "fires the trigger" do+ list = capture_contexts { group.remove(user) }++ expect(list.length).to eq(1)+ expect(list[0]["kind"]).to eq(DiscourseAutomation::Triggers::USER_REMOVED_FROM_GROUP)+ expect(list[0]["user"]).to eq(user)+ expect(list[0]["group"]).to eq(group)+ expect(list[0]["usernames"]).to eq([user.username])+ end+ end++ context "when group is not tracked" do+ it "doesn’t fire the trigger" do+ list = capture_contexts { group.remove(user) }++ expect(list).to eq([])+ end+ end+enddiff --git a/plugins/automation/spec/triggers/user_updated_spec.rb b/plugins/automation/spec/triggers/user_updated_spec.rbnew file mode 100644index 00000000000..aebd21be6da--- /dev/null+++ b/plugins/automation/spec/triggers/user_updated_spec.rb@@ -0,0 +1,127 @@+# frozen_string_literal: true++require_relative "../discourse_automation_helper"++describe "UserUpdated" do+ before { SiteSetting.discourse_automation_enabled = true }++ fab!(:user_field_1) { Fabricate(:user_field, name: "custom field 1") }+ fab!(:user_field_2) { Fabricate(:user_field, name: "custom field 2") }+ fab!(:user) do+ user = Fabricate(:user, trust_level: TrustLevel[0])+ user.set_user_field(user_field_1.id, "Answer custom 1")+ user.set_user_field(user_field_2.id, "Answer custom 2")+ user.save+ user+ end++ fab!(:automation) do+ automation = Fabricate(:automation, trigger: DiscourseAutomation::Triggers::USER_UPDATED)+ automation.upsert_field!(+ "custom_fields",+ "custom_fields",+ { value: ["custom field 1", "custom field 2"] },+ target: "trigger",+ )+ automation.upsert_field!(+ "user_profile",+ "user_profile",+ { value: %w[location bio_raw] },+ target: "trigger",+ )+ automation+ end++ context "when custom_fields and user_profile are blank" do+ let(:automation) do+ Fabricate(+ :automation,+ trigger: DiscourseAutomation::Triggers::USER_UPDATED,+ ).tap do |automation|+ automation.upsert_field!("custom_fields", "custom_fields", { value: [] }, target: "trigger")+ automation.upsert_field!("user_profile", "user_profile", { value: [] }, target: "trigger")+ end+ end++ it "adds an error to the automation" do+ expect(automation.save).to eq(false)+ errors = automation.errors.full_messages+ expect(errors).to include(+ I18n.t("discourse_automation.triggerables.errors.custom_fields_or_user_profile_required"),+ )+ end+ end++ it "has the correct data" do+ output =+ capture_contexts { UserUpdater.new(user, user).update(location: "Japan", bio_raw: "fine") }+ output = output.first++ expect(output["kind"]).to eq(DiscourseAutomation::Triggers::USER_UPDATED)+ expect(output["user"]).to eq(user)+ expect(output["user_data"].count).to eq(2)+ expect(output["user_data"][:custom_fields][user_field_1.name]).to eq(+ user.custom_fields["user_field_#{user_field_1.id}"],+ )+ expect(output["user_data"][:profile_data]["location"]).to eq("Japan")+ end++ context "when once_per_user is set" do+ before do+ automation.upsert_field!("once_per_user", "boolean", { value: true }, target: "trigger")+ end++ it "doesnt trigger if automation already triggered" do+ automation.attach_custom_field(user)++ output =+ capture_contexts { UserUpdater.new(user, user).update(location: "Japan", bio_raw: "fine") }++ expect(output).to eq([])+ end++ it "triggers once when automation has never triggered" do+ output =+ capture_contexts { UserUpdater.new(user, user).update(location: "Japan", bio_raw: "fine") }++ expect(output.first["kind"]).to eq("user_updated")++ output =+ capture_contexts { UserUpdater.new(user, user).update(location: "Japan", bio_raw: "fine") }++ expect(output).to eq([])+ end+ end++ context "when once_per_user is no set" do+ it "triggers every time" do+ output =+ capture_contexts { UserUpdater.new(user, user).update(location: "Japan", bio_raw: "fine") }++ expect(output.first["kind"]).to eq("user_updated")++ output =+ capture_contexts { UserUpdater.new(user, user).update(location: "Japan", bio_raw: "fine") }++ expect(output.first["kind"]).to eq("user_updated")+ end+ end++ context "when not all fields are set" do+ it "doesn’t trigger" do+ output =+ capture_contexts { UserUpdater.new(user, user).update(location: "Japan", bio_raw: "fine") }++ expect(output.first["kind"]).to eq("user_updated")+ end+ end++ context "when all fields are set" do+ it "triggers" do+ output =+ capture_contexts { UserUpdater.new(user, user).update(location: "Japan", bio_raw: "fine") }++ expect(output.first["kind"]).to eq("user_updated")+ end+ end+enddiff --git a/plugins/automation/test/javascripts/integration/components/da-boolean-field-test.js b/plugins/automation/test/javascripts/integration/components/da-boolean-field-test.jsnew file mode 100644index 00000000000..fe68f57a7fa--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-boolean-field-test.js@@ -0,0 +1,25 @@+import { click, render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-boolean-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field();++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );+ await click("input");++ assert.dom("input").isChecked();+ assert.strictEqual(this.field.metadata.value, true);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-categories-field-test.js b/plugins/automation/test/javascripts/integration/components/da-categories-field-test.jsnew file mode 100644index 00000000000..2589d2c44f5--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-categories-field-test.js@@ -0,0 +1,28 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-categories-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("sets values", async function (assert) {+ this.field = fabricators.field({ component: "categories" });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().selectRowByValue(6);+ await selectKit().selectRowByValue(8);++ assert.deepEqual(this.field.metadata.value, [6, 8]);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-category-field-test.js b/plugins/automation/test/javascripts/integration/components/da-category-field-test.jsnew file mode 100644index 00000000000..e306ed57bff--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-category-field-test.js@@ -0,0 +1,27 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-category-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({ component: "category" });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().selectRowByValue(6);++ assert.strictEqual(this.field.metadata.value, 6);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-category-notification-level-field-test.js b/plugins/automation/test/javascripts/integration/components/da-category-notification-level-field-test.jsnew file mode 100644index 00000000000..d62be347fa6--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-category-notification-level-field-test.js@@ -0,0 +1,32 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module(+ "Integration | Component | da-category-notification-level-field",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({+ component: "category_notification_level",+ });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().selectRowByValue(2);++ assert.strictEqual(this.field.metadata.value, 2);+ });+ }+);diff --git a/plugins/automation/test/javascripts/integration/components/da-choices-field-test.js b/plugins/automation/test/javascripts/integration/components/da-choices-field-test.jsnew file mode 100644index 00000000000..a01208ffeba--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-choices-field-test.js@@ -0,0 +1,30 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-choices-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({+ component: "choices",+ extra: { content: [{ name: "One", id: 1 }] },+ });++ await render(+ hbs` <AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().selectRowByValue(1);++ assert.strictEqual(this.field.metadata.value, 1);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-custom-field-test.js b/plugins/automation/test/javascripts/integration/components/da-custom-field-test.jsnew file mode 100644index 00000000000..46e9d89964d--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-custom-field-test.js@@ -0,0 +1,46 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-custom-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();++ pretender.get("/admin/customize/user_fields", () => {+ return response({+ user_fields: [+ {+ id: 1,+ name: "Title",+ description: "your title",+ field_type: "text",+ editable: true,+ required: true,+ show_on_profile: true,+ show_on_user_card: true,+ searchable: true,+ position: 1,+ },+ ],+ });+ });+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({ component: "custom_field" });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().selectRowByValue(1);+ assert.strictEqual(this.field.metadata.value, 1);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-date-time-field-test.js b/plugins/automation/test/javascripts/integration/components/da-date-time-field-test.jsnew file mode 100644index 00000000000..e3f791667ed--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-date-time-field-test.js@@ -0,0 +1,24 @@+import { fillIn, render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-date-time-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({ component: "date_time" });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );+ await fillIn("input", "2023-10-03T12:34");++ assert.ok(this.field.metadata.value !== null);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-email-group-user-field-test.js b/plugins/automation/test/javascripts/integration/components/da-email-group-user-field-test.jsnew file mode 100644index 00000000000..c152684649b--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-email-group-user-field-test.js@@ -0,0 +1,23 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import { exists, query } from "discourse/tests/helpers/qunit-helpers";++module("Integration | Component | email-group-user-field", function (hooks) {+ setupRenderingTest(hooks);++ test("Email group user field uses email-group-user-chooser component", async function (assert) {+ const template = hbs` <Fields::DaEmailGroupUserField @label="a label" />`;++ await render(template);++ assert.equal(query(".control-label").innerText, "a label");+ assert.ok(+ exists(+ ".controls details.select-kit.multi-select.user-chooser.email-group-user-chooser"+ ),+ "has email-group-user-chooser"+ );+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-group-field-test.js b/plugins/automation/test/javascripts/integration/components/da-group-field-test.jsnew file mode 100644index 00000000000..afd461b5dd6--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-group-field-test.js@@ -0,0 +1,40 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-group-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();++ pretender.get("/groups/search.json", () => {+ return response([+ {+ id: 1,+ name: "cats",+ flair_url: "fa-bars",+ flair_bg_color: "CC000A",+ flair_color: "FFFFFA",+ },+ ]);+ });+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({ component: "group" });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().selectRowByValue(1);++ assert.strictEqual(this.field.metadata.value, 1);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-message-field-test.js b/plugins/automation/test/javascripts/integration/components/da-message-field-test.jsnew file mode 100644index 00000000000..054ce03e765--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-message-field-test.js@@ -0,0 +1,24 @@+import { fillIn, render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-message-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({ component: "message" });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );+ await fillIn("textarea", "Hello World");++ assert.strictEqual(this.field.metadata.value, "Hello World");+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-pms-field-test.js b/plugins/automation/test/javascripts/integration/components/da-pms-field-test.jsnew file mode 100644index 00000000000..476badaa207--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-pms-field-test.js@@ -0,0 +1,39 @@+import { click, fillIn, render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-pms-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({+ component: "pms",+ });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await click(".insert-pm");++ await fillIn(".pm-title", "title");+ await fillIn(".d-editor-input", "raw");+ await fillIn(".pm-delay", 6);+ await click(".pm-prefers-encrypt", 6);++ assert.deepEqual(this.field.metadata.value, [+ {+ delay: "6",+ prefers_encrypt: false,+ raw: "raw",+ title: "title",+ },+ ]);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-post-field-test.js b/plugins/automation/test/javascripts/integration/components/da-post-field-test.jsnew file mode 100644index 00000000000..3121d59f027--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-post-field-test.js@@ -0,0 +1,24 @@+import { fillIn, render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-post-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({ component: "post" });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );+ await fillIn("textarea", "Hello World");++ assert.strictEqual(this.field.metadata.value, "Hello World");+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-tags-field-test.js b/plugins/automation/test/javascripts/integration/components/da-tags-field-test.jsnew file mode 100644index 00000000000..e8bf5ac6b84--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-tags-field-test.js@@ -0,0 +1,29 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-tags-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({+ component: "tags",+ });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().selectRowByValue("monkey");++ assert.deepEqual(this.field.metadata.value, ["monkey"]);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-text-field-test.js b/plugins/automation/test/javascripts/integration/components/da-text-field-test.jsnew file mode 100644index 00000000000..16b51200dc2--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-text-field-test.js@@ -0,0 +1,24 @@+import { fillIn, render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-text-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({ component: "text" });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );+ await fillIn("input", "Hello World");++ assert.strictEqual(this.field.metadata.value, "Hello World");+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-text-list-field-test.js b/plugins/automation/test/javascripts/integration/components/da-text-list-field-test.jsnew file mode 100644index 00000000000..9e76ea9a089--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-text-list-field-test.js@@ -0,0 +1,29 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-text-list-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({+ component: "text_list",+ });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );+ await selectKit().expand();+ await selectKit().fillInFilter("test");+ await selectKit().selectRowByValue("test");++ assert.deepEqual(this.field.metadata.value, ["test"]);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-trust-levels-field-test.js b/plugins/automation/test/javascripts/integration/components/da-trust-levels-field-test.jsnew file mode 100644index 00000000000..49a89796b17--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-trust-levels-field-test.js@@ -0,0 +1,30 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-trust-levels-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({+ component: "trust-levels",+ });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().selectRowByValue(1);+ await selectKit().selectRowByValue(2);++ assert.deepEqual(this.field.metadata.value, [1, 2]);+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-user-field-test.js b/plugins/automation/test/javascripts/integration/components/da-user-field-test.jsnew file mode 100644index 00000000000..09154935e2e--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-user-field-test.js@@ -0,0 +1,43 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-user-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();++ pretender.get("/u/search/users", () =>+ response({+ users: [+ {+ username: "sam",+ avatar_template:+ "https://avatars.discourse.org/v3/letter/t/41988e/{size}.png",+ },+ ],+ })+ );+ });++ test("set value", async function (assert) {+ this.field = fabricators.field({+ component: "user",+ });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().fillInFilter("sam");+ await selectKit().selectRowByValue("sam");++ assert.strictEqual(this.field.metadata.value, "sam");+ });+});diff --git a/plugins/automation/test/javascripts/integration/components/da-users-field-test.js b/plugins/automation/test/javascripts/integration/components/da-users-field-test.jsnew file mode 100644index 00000000000..1a9b5cc1a72--- /dev/null+++ b/plugins/automation/test/javascripts/integration/components/da-users-field-test.js@@ -0,0 +1,66 @@+import { render } from "@ember/test-helpers";+import { hbs } from "ember-cli-htmlbars";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import selectKit from "discourse/tests/helpers/select-kit-helper";+import fabricators from "discourse/plugins/automation/discourse/lib/fabricators";++module("Integration | Component | da-users-field", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.automation = fabricators.automation();++ pretender.get("/u/search/users", () =>+ response({+ users: [+ {+ username: "sam",+ avatar_template:+ "https://avatars.discourse.org/v3/letter/t/41988e/{size}.png",+ },+ {+ username: "joffrey",+ avatar_template:+ "https://avatars.discourse.org/v3/letter/t/41988e/{size}.png",+ },+ ],+ })+ );+ });++ test("sets values", async function (assert) {+ this.field = fabricators.field({+ component: "users",+ });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().fillInFilter("sam");+ await selectKit().selectRowByValue("sam");+ await selectKit().fillInFilter("joffrey");+ await selectKit().selectRowByValue("joffrey");++ assert.deepEqual(this.field.metadata.value, ["sam", "joffrey"]);+ });++ test("allows emails", async function (assert) {+ this.field = fabricators.field({+ component: "users",+ });++ await render(+ hbs`<AutomationField @automation={{this.automation}} @field={{this.field}} />`+ );++ await selectKit().expand();+ await selectKit().fillInFilter("[email protected]");+ await selectKit().selectRowByValue("[email protected]");++ assert.deepEqual(this.field.metadata.value, ["[email protected]"]);+ });+});diff --git a/script/i18n_lint.rb b/script/i18n_lint.rbindex 794b07b34ae..b63c6e599b4 100755--- a/script/i18n_lint.rb+++ b/script/i18n_lint.rb@@ -42,6 +42,10 @@ class LocaleFileValidatorPLURALIZATION_KEYS = %w[zero one two few many other]ENGLISH_KEYS = %w[one other]+ EXEMPTED_DOUBLE_CURLY_BRACKET_KEYS = [+ "js.discourse_automation.scriptables.auto_responder.fields.word_answer_list.description",+ ]+def initialize(filename)@filename = filename@errors = {}@@ -92,7 +96,8 @@ class LocaleFileValidator@errors[:invalid_relative_image_sources] << key if value.match?(%r{src\s*=\s*["']/[^/]}i)- if value.match?(/{{.+?}}/) && !key.end_with?("_MF")+ if value.match?(/{{.+?}}/) && !key.end_with?("_MF") &&+ !EXEMPTED_DOUBLE_CURLY_BRACKET_KEYS.include?(key)@errors[:invalid_interpolation_key_format] << keyendend