organization.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class Organization < ApplicationModel
  3. include HasActivityStreamLog
  4. include ChecksClientNotification
  5. include ChecksLatestChangeObserved
  6. include HasHistory
  7. include HasSearchIndexBackend
  8. include CanCsvImport
  9. include ChecksHtmlSanitized
  10. include HasObjectManagerAttributes
  11. include HasTaskbars
  12. include Organization::Assets
  13. include Organization::Search
  14. include Organization::SearchIndex
  15. include HasTransactionDispatcher
  16. has_many :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. association_attributes_ignored :tickets, :created_by, :updated_by
  27. activity_stream_permission 'admin.role'
  28. sanitized_html :note
  29. def destroy(associations: false)
  30. if associations
  31. delete_associations
  32. else
  33. unset_associations
  34. end
  35. super()
  36. end
  37. private
  38. def domain_cleanup
  39. return true if domain.blank?
  40. domain.gsub!(%r{@}, '')
  41. domain.gsub!(%r{\s*}, '')
  42. domain.strip!
  43. domain.downcase!
  44. true
  45. end
  46. def delete_associations
  47. User.where(organization_id: id).find_each(&:destroy)
  48. Ticket.where(organization_id: id).find_each(&:destroy)
  49. end
  50. def unset_associations
  51. User.where(organization_id: id).find_each do |user|
  52. user.update(organization_id: nil)
  53. end
  54. Ticket.where(organization_id: id).find_each do |ticket|
  55. ticket.update(organization_id: nil)
  56. end
  57. end
  58. end