email_address.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class EmailAddress < ApplicationModel
  3. include LatestChangeObserved
  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_create :check_if_channel_exists_set_inactive
  9. before_update :check_if_channel_exists_set_inactive
  10. after_create :update_email_address_id
  11. after_update :update_email_address_id
  12. after_destroy :delete_group_reference
  13. =begin
  14. check and if channel not exists reset configured channels for email addresses
  15. EmailAddress.channel_cleanup
  16. =end
  17. def self.channel_cleanup
  18. EmailAddress.all.each { |email_address|
  19. # set to active if channel exists
  20. if email_address.channel_id && Channel.find_by(id: email_address.channel_id)
  21. if !email_address.active
  22. email_address.save
  23. end
  24. next
  25. end
  26. # set in inactive if channel not longer exists
  27. next if !email_address.active
  28. email_address.save
  29. }
  30. end
  31. private
  32. # set email address to inactive/active if channel exists or not
  33. def check_if_channel_exists_set_inactive
  34. # set to active if channel exists
  35. if channel_id && Channel.find_by(id: channel_id)
  36. self.active = true
  37. return true
  38. end
  39. # set in inactive if channel not longer exists
  40. self.channel_id = nil
  41. self.active = false
  42. true
  43. end
  44. # delete group.email_address_id reference if email address get's deleted
  45. def delete_group_reference
  46. Group.where(email_address_id: id).each { |group|
  47. group.email_address_id = nil
  48. }
  49. end
  50. # keep email email address is of inital group filled
  51. def update_email_address_id
  52. not_configured = Group.where(email_address_id: nil).count
  53. total = Group.count
  54. return if not_configured.zero?
  55. return if total != 1
  56. group = Group.find_by(email_address_id: nil)
  57. group.email_address_id = id
  58. group.updated_by_id = updated_by_id
  59. group.save
  60. end
  61. end