email_address.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class EmailAddress < ApplicationModel
  3. include ChecksHtmlSanitized
  4. include HasCollectionUpdate
  5. has_many :groups, after_add: :cache_update, after_remove: :cache_update
  6. belongs_to :channel, optional: true
  7. validates :realname, presence: true
  8. validates :email, presence: true
  9. before_validation :check_email
  10. before_create :check_if_channel_exists_set_inactive
  11. after_create :update_email_address_id
  12. before_update :check_if_channel_exists_set_inactive
  13. after_update :update_email_address_id
  14. before_destroy :delete_group_reference
  15. sanitized_html :note
  16. collection_push_permission('ticket.agent')
  17. =begin
  18. check and if channel not exists reset configured channels for email addresses
  19. EmailAddress.channel_cleanup
  20. =end
  21. def self.channel_cleanup
  22. EmailAddress.all.each do |email_address|
  23. # set to active if channel exists
  24. if email_address.channel_id && Channel.exists?(email_address.channel_id)
  25. if !email_address.active
  26. email_address.save!
  27. end
  28. next
  29. end
  30. # set in inactive if channel not longer exists
  31. next if !email_address.active
  32. email_address.save!
  33. end
  34. end
  35. private
  36. def check_email
  37. return true if Setting.get('import_mode')
  38. return true if email.blank?
  39. self.email = email.downcase.strip
  40. email_address_validation = EmailAddressValidation.new(email)
  41. if !email_address_validation.valid_format?
  42. raise Exceptions::UnprocessableEntity, "Invalid email '#{email}'"
  43. end
  44. true
  45. end
  46. # set email address to inactive/active if channel exists or not
  47. def check_if_channel_exists_set_inactive
  48. # set to active if channel exists
  49. if channel_id && Channel.exists?(id: channel_id)
  50. self.active = true
  51. return true
  52. end
  53. # set in inactive if channel not longer exists
  54. self.channel_id = nil
  55. self.active = false
  56. true
  57. end
  58. # delete group.email_address_id reference if email address get's deleted
  59. def delete_group_reference
  60. Group.where(email_address_id: id).each do |group|
  61. group.update!(email_address_id: nil)
  62. end
  63. end
  64. # keep email email address is of initial group filled
  65. def update_email_address_id
  66. not_configured = Group.where(email_address_id: nil).count
  67. total = Group.count
  68. return if not_configured.zero?
  69. return if total != 1
  70. group = Group.find_by(email_address_id: nil)
  71. group.email_address_id = id
  72. group.updated_by_id = updated_by_id
  73. group.save!
  74. end
  75. end