overview.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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, class_name: 'User'
  11. store :condition
  12. store :order
  13. store :view
  14. validates :name, presence: true
  15. validates :roles, presence: true
  16. before_create :fill_link_on_create, :fill_prio
  17. before_update :fill_link_on_update, :rearrangement
  18. private
  19. def rearrangement
  20. return true if !changes['prio']
  21. prio = 0
  22. Overview.all.order(prio: :asc, updated_at: :desc).pluck(:id).each do |overview_id|
  23. prio += 1
  24. next if id == overview_id
  25. Overview.without_callback(:update, :before, :rearrangement) do
  26. overview = Overview.find(overview_id)
  27. next if overview.prio == prio
  28. overview.prio = prio
  29. overview.save!
  30. end
  31. end
  32. end
  33. def fill_prio
  34. return true if prio.present?
  35. self.prio = Overview.count + 1
  36. true
  37. end
  38. def fill_link_on_create
  39. self.link = if link.present?
  40. link_name(link)
  41. else
  42. link_name(name)
  43. end
  44. true
  45. end
  46. def fill_link_on_update
  47. return true if !changes['name'] && !changes['link']
  48. self.link = if link.present?
  49. link_name(link)
  50. else
  51. link_name(name)
  52. end
  53. true
  54. end
  55. def link_name(name)
  56. local_link = name.downcase
  57. local_link = local_link.parameterize(separator: '_')
  58. local_link.gsub!(/\s/, '_')
  59. local_link.gsub!(/_+/, '_')
  60. local_link = CGI.escape(local_link)
  61. if local_link.blank?
  62. local_link = id || rand(999)
  63. end
  64. check = true
  65. count = 0
  66. local_lookup_link = local_link
  67. while check
  68. count += 1
  69. exists = Overview.find_by(link: local_lookup_link)
  70. if exists && exists.id != id
  71. local_lookup_link = "#{local_link}_#{count}"
  72. else
  73. check = false
  74. local_link = local_lookup_link
  75. end
  76. end
  77. local_link
  78. end
  79. end