trigger.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Trigger < ApplicationModel
  3. include ChecksConditionValidation
  4. include ChecksHtmlSanitized
  5. include CanSeed
  6. include HasSearchIndexBackend
  7. include CanSelector
  8. include CanSearch
  9. include Trigger::Assets
  10. store :condition
  11. store :perform
  12. validates :name, presence: true, uniqueness: { case_sensitive: false }
  13. validates :perform, 'validations/verify_perform_rules': true
  14. validates :activator, presence: true, inclusion: { in: %w[action time] }
  15. validates :execution_condition_mode, presence: true, inclusion: { in: %w[selective always] }
  16. validates :note, length: { maximum: 250 }
  17. sanitized_html :note
  18. scope :activated_by, ->(activator) { where(active: true, activator: activator) }
  19. def performed_on(object, activator_type:)
  20. return if !time_based?
  21. history_scope(object, activator_type:).create sourceable_name: name
  22. end
  23. def performable_on?(object, activator_type:)
  24. return if !time_based?
  25. already_notified_cutoff = Time.use_zone(Setting.get('timezone_default')) { Time.current.beginning_of_day }
  26. !history_scope(object, activator_type:).exists?(['created_at > ?', already_notified_cutoff])
  27. end
  28. def condition_changes_required?
  29. activator == 'action' && execution_condition_mode == 'selective'
  30. end
  31. private
  32. def time_based?
  33. activator == 'time'
  34. end
  35. def history_scope(object, activator_type:)
  36. History
  37. .where(
  38. history_object_id: History.object_lookup(object.class.name).id,
  39. o_id: object.id,
  40. history_type_id: History.type_lookup('time_trigger_performed').id,
  41. sourceable: self,
  42. value_from: activator_type
  43. )
  44. end
  45. end