checks_core_workflow.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Copyright (C) 2012-2024 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. class_methods do
  11. # defines the screens which core workflow executes
  12. def core_workflow_screens(*screens)
  13. @core_workflow_screens ||= screens
  14. end
  15. # defines the screens which are configurable via admin interface
  16. def core_workflow_admin_screens(*screens)
  17. @core_workflow_admin_screens ||= screens
  18. end
  19. end
  20. def validate_workflows
  21. return if !screen
  22. return if !UserInfo.current_user_id
  23. perform_result = CoreWorkflow.perform(payload: {
  24. 'event' => 'core_workflow',
  25. 'request_id' => 'ChecksCoreWorkflow.validate_workflows',
  26. 'class_name' => self.class.to_s,
  27. 'screen' => screen,
  28. 'params' => attributes
  29. }, user: UserInfo.current_user, assets: false)
  30. check_restrict_values(perform_result)
  31. check_mandatory(perform_result)
  32. end
  33. def check_restrict_values(perform_result)
  34. changes.each_key do |key|
  35. next if perform_result[:restrict_values][key].blank?
  36. next if self[key].blank?
  37. next if restricted_value?(perform_result, key)
  38. raise Exceptions::ApplicationModel.new(self, "Invalid value '#{self[key]}' for field '#{key}'!")
  39. end
  40. end
  41. def restricted_value?(perform_result, key)
  42. if self[key].is_a?(Array)
  43. (self[key].map(&:to_s) - perform_result[:restrict_values][key].map(&:to_s)).blank?
  44. else
  45. perform_result[:restrict_values][key].any? { |value| value.to_s == self[key].to_s }
  46. end
  47. end
  48. def check_mandatory(perform_result)
  49. perform_result[:mandatory].each_key do |key|
  50. next if field_visible?(perform_result, key)
  51. next if !field_mandatory?(perform_result, key)
  52. next if !column_empty?(key)
  53. next if !colum_default?(key)
  54. raise Exceptions::ApplicationModel.new(self, "Missing required value for field '#{key}'!")
  55. end
  56. end
  57. def field_visible?(perform_result, key)
  58. %w[hide remove].include?(perform_result[:visibility][key])
  59. end
  60. def field_mandatory?(perform_result, key)
  61. perform_result[:mandatory][key]
  62. end
  63. def column_empty?(key)
  64. self[key].nil? || ([true, false].exclude?(self[key]) && self[key].blank?)
  65. end
  66. def colum_default?(key)
  67. self.class.column_defaults[key].nil?
  68. end
  69. end