overview.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class Overview < ApplicationModel
  3. include ChecksClientNotification
  4. include ChecksLatestChangeObserved
  5. include ChecksConditionValidation
  6. include CanSeed
  7. load 'overview/assets.rb'
  8. include Overview::Assets
  9. has_and_belongs_to_many :roles, after_add: :cache_update, after_remove: :cache_update, class_name: 'Role'
  10. has_and_belongs_to_many :users, after_add: :cache_update, after_remove: :cache_update
  11. store :condition
  12. store :order
  13. store :view
  14. validates :name, presence: true
  15. before_create :fill_link_on_create, :fill_prio
  16. before_update :fill_link_on_update, :rearrangement
  17. private
  18. def rearrangement
  19. return true if !changes['prio']
  20. prio = 0
  21. Overview.all.order(prio: :asc, updated_at: :desc).pluck(:id).each do |overview_id|
  22. prio += 1
  23. next if id == overview_id
  24. Overview.without_callback(:update, :before, :rearrangement) do
  25. overview = Overview.find(overview_id)
  26. next if overview.prio == prio
  27. overview.prio = prio
  28. overview.save!
  29. end
  30. end
  31. end
  32. def fill_prio
  33. return true if prio.present?
  34. self.prio = Overview.count + 1
  35. true
  36. end
  37. def fill_link_on_create
  38. self.link = if link.present?
  39. link_name(link)
  40. else
  41. link_name(name)
  42. end
  43. true
  44. end
  45. def fill_link_on_update
  46. return true if !changes['name'] && !changes['link']
  47. self.link = if link.present?
  48. link_name(link)
  49. else
  50. link_name(name)
  51. end
  52. true
  53. end
  54. def link_name(name)
  55. local_link = name.downcase
  56. local_link = local_link.parameterize(separator: '_')
  57. local_link.gsub!(/\s/, '_')
  58. local_link.gsub!(/_+/, '_')
  59. local_link = CGI.escape(local_link)
  60. if local_link.blank?
  61. local_link = id || rand(999)
  62. end
  63. check = true
  64. count = 0
  65. local_lookup_link = local_link
  66. while check
  67. count += 1
  68. exists = Overview.find_by(link: local_lookup_link)
  69. if exists && exists.id != id # rubocop:disable Style/SafeNavigation
  70. local_lookup_link = "#{local_link}_#{count}"
  71. else
  72. check = false
  73. local_link = local_lookup_link
  74. end
  75. end
  76. local_link
  77. end
  78. end