organization.rb 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class Organization < ApplicationModel
  3. include HasActivityStreamLog
  4. include ChecksClientNotification
  5. include HasHistory
  6. include HasSearchIndexBackend
  7. include CanCsvImport
  8. include ChecksHtmlSanitized
  9. include HasObjectManagerAttributes
  10. include HasTaskbars
  11. include Organization::Assets
  12. include Organization::Search
  13. include Organization::SearchIndex
  14. include HasTransactionDispatcher
  15. has_many :members, class_name: 'User'
  16. has_and_belongs_to_many :secondary_members, class_name: 'User'
  17. has_many :tickets, class_name: 'Ticket'
  18. belongs_to :created_by, class_name: 'User'
  19. belongs_to :updated_by, class_name: 'User'
  20. before_create :domain_cleanup
  21. before_update :domain_cleanup
  22. # workflow checks should run after before_create and before_update callbacks
  23. include ChecksCoreWorkflow
  24. validates :name, presence: true
  25. validates :domain, presence: { message: 'required when Domain Based Assignment is enabled' }, if: :domain_assignment
  26. # secondary_members will break eager_load of attributes_with_association_ids because it mixes up with the members relation.
  27. # so it will get added afterwards
  28. association_attributes_ignored :secondary_members, :tickets, :created_by, :updated_by
  29. activity_stream_permission 'admin.role'
  30. sanitized_html :note
  31. def destroy(associations: false)
  32. if associations
  33. delete_associations
  34. else
  35. unset_associations
  36. end
  37. super()
  38. end
  39. def attributes_with_association_ids
  40. attributes = super
  41. attributes['secondary_member_ids'] = secondary_member_ids
  42. attributes
  43. end
  44. private
  45. def domain_cleanup
  46. return true if domain.blank?
  47. domain.gsub!(%r{@}, '')
  48. domain.gsub!(%r{\s*}, '')
  49. domain.strip!
  50. domain.downcase!
  51. true
  52. end
  53. def delete_associations
  54. User.where(organization_id: id).find_each(&:destroy)
  55. Ticket.where(organization_id: id).find_each(&:destroy)
  56. end
  57. def unset_associations
  58. User.where(organization_id: id).find_each do |user|
  59. user.update(organization_id: nil)
  60. end
  61. Ticket.where(organization_id: id).find_each do |ticket|
  62. ticket.update(organization_id: nil)
  63. end
  64. end
  65. end