organization.rb 2.4 KB

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