applies_taskbar_state.rb 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module FormUpdater::Concerns::AppliesTaskbarState
  3. extend ActiveSupport::Concern
  4. SKIP_FIELDS = %w[attachments].freeze
  5. class_methods do
  6. def apply_state_group_keys(group_keys)
  7. @apply_state_group_keys ||= group_keys
  8. end
  9. end
  10. def resolve
  11. if current_taskbar.present? && should_apply?
  12. apply_taskbar_state
  13. end
  14. super
  15. end
  16. private
  17. def apply_taskbar_state
  18. apply_value = FormUpdater::ApplyValue.new(context:, data:, result:)
  19. apply_state_group_keys = self.class.instance_variable_get(:@apply_state_group_keys)
  20. current_taskbar.state.each_pair do |field, value|
  21. next if SKIP_FIELDS.include?(field)
  22. if apply_state_group_keys.present? && apply_state_group_keys.include?(field) && value.is_a?(Hash)
  23. value.each_pair do |sub_field, sub_value|
  24. next if SKIP_FIELDS.include?(sub_field)
  25. apply_value.perform(field: sub_field, config: { 'value' => sub_value }, include_blank: true, parent_field: field)
  26. end
  27. else
  28. apply_value.perform(field: field, config: { 'value' => value }, include_blank: true)
  29. end
  30. end
  31. # When no object exists, we can ignore the additional check.
  32. return if object.blank?
  33. apply_taskbar_object_defaults(apply_value)
  34. end
  35. def apply_taskbar_object_defaults(apply_value)
  36. apply_state_group_keys = self.class.instance_variable_get(:@apply_state_group_keys)
  37. # We need to check the current dirty fields, to restore maybe some default value from the current ticket.
  38. meta[:dirty_fields]&.each do |field|
  39. next if SKIP_FIELDS.include?(field)
  40. # Check first on the first level if it's present in the current state.
  41. next if current_taskbar.state.key?(field)
  42. next if apply_state_group_keys.present? && apply_state_group_keys.any? { |group_key| current_taskbar.state[group_key]&.key?(field) }
  43. next if !object.respond_to?(field)
  44. next if object[field] == data[field]
  45. apply_value.perform(field: field, config: { 'value' => object[field] }, include_blank: true)
  46. end
  47. end
  48. def current_taskbar
  49. id = meta.dig(:additional_data, 'taskbarId')
  50. Gql::ZammadSchema.authorized_object_from_id(id, type: Taskbar, user: context[:current_user]) if id.present?
  51. end
  52. def should_apply?
  53. meta.dig(:additional_data, 'applyTaskbarState') == true || meta[:initial]
  54. end
  55. end