0
0
Fork 1
Spiegel von https://github.com/paviliondev/discourse-custom-wizard.git synchronisiert 2024-11-22 17:30:29 +01:00
discourse-custom-wizard/lib/custom_wizard/validator.rb

81 Zeilen
1,9 KiB
Ruby

2020-04-13 14:17:22 +02:00
class CustomWizard::Validator
2020-11-03 01:24:20 +01:00
include HasErrors
2020-04-13 14:17:22 +02:00
2020-11-03 01:24:20 +01:00
def initialize(data, opts={})
@data = data
2020-04-13 14:17:22 +02:00
@opts = opts
end
def perform
2020-11-03 01:24:20 +01:00
data = @data
2020-04-14 01:39:21 +02:00
2020-11-03 01:24:20 +01:00
check_id(data, :wizard)
check_required(data, :wizard)
validate_after_time
2020-04-14 01:39:21 +02:00
2020-11-03 01:24:20 +01:00
data[:steps].each do |step|
check_required(step, :step)
2020-04-13 14:17:22 +02:00
2020-11-03 01:24:20 +01:00
if data[:fields].present?
data[:fields].each do |field|
check_required(field, :field)
2020-04-13 14:17:22 +02:00
end
end
end
2020-11-03 01:24:20 +01:00
if data[:actions].present?
data[:actions].each do |action|
check_required(action, :action)
end
end
2020-04-14 01:39:21 +02:00
2020-11-03 01:24:20 +01:00
if errors.any?
false
2020-04-13 14:17:22 +02:00
else
2020-11-03 01:24:20 +01:00
true
2020-04-13 14:17:22 +02:00
end
end
def self.required
{
wizard: ['id', 'name', 'steps'],
step: ['id'],
field: ['id', 'type'],
action: ['id', 'type']
}
end
private
def check_required(object, type)
CustomWizard::Validator.required[type].each do |property|
if object[property].blank?
2020-11-03 01:24:20 +01:00
errors.add :validation, I18n.t("wizard.validation.required", property: property)
2020-04-13 14:17:22 +02:00
end
end
end
2020-11-03 01:24:20 +01:00
2020-04-13 14:17:22 +02:00
def check_id(object, type)
2020-10-31 08:05:50 +01:00
if type === :wizard && @opts[:create] && CustomWizard::Template.exists?(object[:id])
2020-11-03 01:24:20 +01:00
errors.add :validation, I18n.t("wizard.validation.conflict", id: object[:id])
2020-04-13 14:17:22 +02:00
end
end
2020-11-03 01:24:20 +01:00
def validate_after_time
return unless @data[:after_time]
wizard = CustomWizard::Wizard.create(@data[:id]) if !@opts[:create]
2020-04-14 01:39:21 +02:00
current_time = wizard.present? ? wizard.after_time_scheduled : nil
2020-11-03 01:24:20 +01:00
new_time = @data[:after_time_scheduled]
2020-04-14 07:46:06 +02:00
begin
active_time = Time.parse(new_time.present? ? new_time : current_time).utc
rescue ArgumentError
invalid_time = true
end
2020-04-13 14:17:22 +02:00
2020-04-14 07:46:06 +02:00
if invalid_time || active_time.blank? || active_time < Time.now.utc
2020-11-03 01:24:20 +01:00
errors.add :validation, I18n.t("wizard.validation.after_time")
2020-04-13 14:17:22 +02:00
end
end
end