organization.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # Copyright (C) 2012-2023 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 Organization::TriggersSubscriptions
  15. include HasTransactionDispatcher
  16. has_many :members, class_name: 'User'
  17. has_and_belongs_to_many :secondary_members, class_name: 'User'
  18. has_many :tickets, class_name: 'Ticket'
  19. belongs_to :created_by, class_name: 'User'
  20. belongs_to :updated_by, class_name: 'User'
  21. before_create :domain_cleanup
  22. before_update :domain_cleanup
  23. # workflow checks should run after before_create and before_update callbacks
  24. include ChecksCoreWorkflow
  25. core_workflow_screens 'create', 'edit'
  26. validates :name, presence: true
  27. validates :domain, presence: { message: 'required when Domain Based Assignment is enabled' }, if: :domain_assignment
  28. # secondary_members will break eager_load of attributes_with_association_ids because it mixes up with the members relation.
  29. # so it will get added afterwards
  30. association_attributes_ignored :secondary_members, :tickets, :created_by, :updated_by
  31. activity_stream_permission 'admin.role'
  32. validates :note, length: { maximum: 5000 }
  33. sanitized_html :note, no_images: true
  34. def destroy(associations: false)
  35. if associations
  36. delete_associations
  37. else
  38. unset_associations
  39. end
  40. super()
  41. end
  42. def attributes_with_association_ids
  43. attributes = super
  44. attributes['secondary_member_ids'] = secondary_member_ids
  45. attributes
  46. end
  47. private
  48. def domain_cleanup
  49. return true if domain.blank?
  50. domain.gsub!(%r{@}, '')
  51. domain.gsub!(%r{\s*}, '')
  52. domain.strip!
  53. domain.downcase!
  54. true
  55. end
  56. def delete_associations
  57. User.where(organization_id: id).find_each(&:destroy)
  58. Ticket.where(organization_id: id).find_each(&:destroy)
  59. end
  60. def unset_associations
  61. User.where(organization_id: id).find_each do |user|
  62. user.update(organization_id: nil)
  63. end
  64. Ticket.where(organization_id: id).find_each do |ticket|
  65. ticket.update(organization_id: nil)
  66. end
  67. end
  68. end