checks_core_workflow.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. module ChecksCoreWorkflow
  3. extend ActiveSupport::Concern
  4. included do
  5. before_create :validate_workflows
  6. before_update :validate_workflows
  7. attr_accessor :screen
  8. end
  9. private
  10. def validate_workflows
  11. return if !screen
  12. return if !UserInfo.current_user_id
  13. perform_result = CoreWorkflow.perform(payload: {
  14. 'event' => 'core_workflow',
  15. 'request_id' => 'ChecksCoreWorkflow.validate_workflows',
  16. 'class_name' => self.class.to_s,
  17. 'screen' => screen,
  18. 'params' => attributes
  19. }, user: User.find(UserInfo.current_user_id))
  20. check_restrict_values(perform_result)
  21. check_mandatory(perform_result)
  22. end
  23. def check_restrict_values(perform_result)
  24. changes.each_key do |key|
  25. next if perform_result[:restrict_values][key].blank?
  26. next if self[key].blank?
  27. next if restricted_value?(perform_result, key)
  28. raise Exceptions::ApplicationModel.new(self, "Invalid value '#{self[key]}' for field '#{key}'!")
  29. end
  30. end
  31. def restricted_value?(perform_result, key)
  32. if self[key].is_a?(Array)
  33. (self[key].map(&:to_s) - perform_result[:restrict_values][key].map(&:to_s)).blank?
  34. else
  35. perform_result[:restrict_values][key].any? { |value| value.to_s == self[key].to_s }
  36. end
  37. end
  38. def check_mandatory(perform_result)
  39. perform_result[:mandatory].each_key do |key|
  40. next if field_visible?(perform_result, key)
  41. next if !field_mandatory?(perform_result, key)
  42. next if !column_value?(key)
  43. next if !colum_default?(key)
  44. raise Exceptions::ApplicationModel.new(self, "Missing required value for field '#{key}'!")
  45. end
  46. end
  47. def field_visible?(perform_result, key)
  48. %w[hide remove].include?(perform_result[:visibility][key])
  49. end
  50. def field_mandatory?(perform_result, key)
  51. perform_result[:mandatory][key]
  52. end
  53. def column_value?(key)
  54. self[key].nil?
  55. end
  56. def colum_default?(key)
  57. self.class.column_defaults[key].nil?
  58. end
  59. end