email_address.rb 2.4 KB

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