group.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class FormUpdater::Relation::Group < FormUpdater::Relation
  3. attr_accessor :lookup_parent_child_groups, :root_groups
  4. def initialize(...)
  5. super
  6. @root_groups = []
  7. @lookup_parent_child_groups = {}
  8. end
  9. def options
  10. # If we have no child groups in the current list, we can handle it in a easy way, because
  11. # we have only a flat structure.
  12. if items.none? { |item| item.parent_id.present? }
  13. return items.map do |item|
  14. { value: item.id, label: display_name(item) }
  15. end
  16. end
  17. options_tree_preparation
  18. options_tree
  19. end
  20. private
  21. def relation_type
  22. ::Group
  23. end
  24. def order
  25. { name: :asc }
  26. end
  27. def display_name(item)
  28. item.name_last
  29. end
  30. def usable_group_ids
  31. @usable_group_ids ||= items.pluck(:id)
  32. end
  33. def options_tree_preparation
  34. items.each do |item|
  35. next if root_group?(item)
  36. prepare_lookup_parent_child_groups(item)
  37. end
  38. end
  39. def prepare_lookup_parent_child_groups(item)
  40. last_item = item
  41. item.all_parents.each do |parent|
  42. if !lookup_parent_child_groups.key?(parent.id)
  43. lookup_parent_child_groups[parent.id] = []
  44. end
  45. parent_child_group?(parent, last_item)
  46. last_item = parent
  47. root_group?(parent)
  48. end
  49. end
  50. def parent_child_group?(parent, item)
  51. return false if lookup_parent_child_groups[parent.id].include?(item)
  52. lookup_parent_child_groups[parent.id].push(item)
  53. true
  54. end
  55. def root_group?(item)
  56. return false if item.parent_id.present? || root_groups.include?(item)
  57. root_groups.push(item)
  58. true
  59. end
  60. def options_tree(groups = root_groups)
  61. groups.each_with_object([]) do |group, options|
  62. children = []
  63. if lookup_parent_child_groups.key?(group.id)
  64. children = options_tree(lookup_parent_child_groups[group.id])
  65. end
  66. options.push(option_array_resolved(display_name(group), group.id, usable_group_ids.exclude?(group.id), children))
  67. end
  68. end
  69. def option_array_resolved(label, value, disabled, children)
  70. resolved_option = {
  71. value: value,
  72. label: label,
  73. disabled: disabled,
  74. }
  75. if children.any?
  76. resolved_option[:children] = children
  77. end
  78. resolved_option
  79. end
  80. end