organization.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. validates :note, length: { maximum: 5000 }
  31. sanitized_html :note
  32. def destroy(associations: false)
  33. if associations
  34. delete_associations
  35. else
  36. unset_associations
  37. end
  38. super()
  39. end
  40. def attributes_with_association_ids
  41. attributes = super
  42. attributes['secondary_member_ids'] = secondary_member_ids
  43. attributes
  44. end
  45. private
  46. def domain_cleanup
  47. return true if domain.blank?
  48. domain.gsub!(%r{@}, '')
  49. domain.gsub!(%r{\s*}, '')
  50. domain.strip!
  51. domain.downcase!
  52. true
  53. end
  54. def delete_associations
  55. User.where(organization_id: id).find_each(&:destroy)
  56. Ticket.where(organization_id: id).find_each(&:destroy)
  57. end
  58. def unset_associations
  59. User.where(organization_id: id).find_each do |user|
  60. user.update(organization_id: nil)
  61. end
  62. Ticket.where(organization_id: id).find_each do |ticket|
  63. ticket.update(organization_id: nil)
  64. end
  65. end
  66. end