required.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class Validations::ObjectManager::AttributeValidator::Required < Validations::ObjectManager::AttributeValidator::Backend
  3. def validate
  4. return if record.class.include?(ChecksCoreWorkflow)
  5. return if !value.nil?
  6. return if optional_for_user?
  7. invalid_because_attribute(__('is required but missing'))
  8. end
  9. private
  10. def optional_for_user?
  11. return true if system_user?
  12. return true if required_for_permissions.blank?
  13. return false if required_for_permissions.include?('-all-')
  14. !user.permissions?(required_for_permissions)
  15. end
  16. def system_user?
  17. user_id.blank? || user_id == 1
  18. end
  19. def user_id
  20. @user_id ||= UserInfo.current_user_id
  21. end
  22. def user
  23. @user ||= User.lookup(id: user_id)
  24. end
  25. def required_for_permissions
  26. @required_for_permissions ||= begin
  27. attribute.screens[action]&.each_with_object([]) do |(permission, config), result|
  28. result.push(permission) if config[:required].present?
  29. end
  30. end
  31. end
  32. def action
  33. return :edit if record.persisted?
  34. attribute.screens.keys.find { |e| e.start_with?('create') }
  35. end
  36. end