email_address.rb 2.5 KB

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