FEATURE: Add 'New users only' option to user_updated trigger (#26648)

This commit adds a new option to the `user_updated` trigger of the automation plugin to only trigger an automation for new users that join after the automation is enabled.

Internal topic: t/125829/9.
This commit is contained in:
Osama Sayegh
2024-04-16 21:13:11 +03:00
committed by GitHub
parent 57d29b6f3b
commit 4733369f71
7 changed files with 190 additions and 2 deletions

View File

@ -65,7 +65,7 @@ module DiscourseAutomation
end
end
def self.handle_user_updated(user)
def self.handle_user_updated(user, new_user: false)
return if user.id < 0
name = DiscourseAutomation::Triggers::USER_UPDATED
@ -79,6 +79,13 @@ module DiscourseAutomation
next
end
new_users_only = automation.trigger_field("new_users_only")["value"]
new_user_custom_field = automation.new_user_custom_field_name
new_user ||= user.custom_fields[new_user_custom_field].present?
next if new_users_only && !new_user
required_custom_fields = automation.trigger_field("custom_fields")
user_data = {}
user_custom_fields_data = DB.query <<-SQL
@ -87,16 +94,22 @@ module DiscourseAutomation
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?
}
if new_users_only
user.custom_fields[new_user_custom_field] = "1"
user.save_custom_fields
end
next
end
user_data[:custom_fields] = user_custom_fields_data
@ -108,11 +121,20 @@ module DiscourseAutomation
if required_user_profile_fields["value"].any? { |field|
user_profile_data[field].blank?
}
if new_users_only
user.custom_fields[new_user_custom_field] = "1"
user.save_custom_fields
end
next
end
user_data[:profile_data] = user_profile_data
end
if new_users_only && once_per_user
user.custom_fields.delete(new_user_custom_field)
user.save_custom_fields
end
automation.attach_custom_field(user)
automation.trigger!("kind" => name, "user" => user, "user_data" => user_data)
end

View File

@ -8,6 +8,7 @@ DiscourseAutomation::Triggerable.add(DiscourseAutomation::Triggers::USER_UPDATED
field :custom_fields, component: :custom_fields
field :user_profile, component: :user_profile
field :once_per_user, component: :boolean
field :new_users_only, component: :boolean
validate do
has_triggers = has_trigger_field?(:custom_fields) && has_trigger_field?(:user_profile)