-
-
Save i2chris/0cdb8ef9d921a0335857769f3a733aef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Quoting | |
module Services | |
class AddTestsToQuoteGroup < Service | |
Schema = Dry::Validation.Params do | |
configure do | |
def self.messages | |
super.merge( | |
en: {errors: { | |
attempt_is_preliminary: "Quote Attempt must be preliminary", | |
tests_are_active: "All tests must be active", | |
quote_group_is_active: "Selected quote group must be active", | |
}}, | |
) | |
end | |
end | |
required(:attempt_id).filled(&:int?) | |
required(:quote_group_id).filled(&:int?) | |
required(:test_ids, Types::Integer).filled(&:array?) | |
validate(attempt_is_preliminary: [:attempt_id]) do |attempt_id| | |
Attempt.find(attempt_id).preliminary? | |
end | |
validate(tests_are_active: [:test_ids]) do |test_ids| | |
Testing::Test.find_active(test_ids).count == test_ids.size | |
end | |
validate(quote_group_is_active: [:attempt_id, :quote_group_id]) do |attempt_id, quote_group_id| | |
quote_group = Attempt.find(attempt_id).quote_groups.find(quote_group_id) | |
!quote_group.expired? && !quote_group.group_placeholder.expired? | |
end | |
end | |
def call(attempt_id:, test_ids:, quote_group_id:) | |
result = Schema.({ | |
attempt_id: attempt_id, | |
test_ids: test_ids, | |
quote_group_id: quote_group_id, | |
}) | |
if result.errors.any? | |
Failure(result.errors) | |
else | |
quote_group = QuoteGroup.find result[:quote_group_id] | |
attempt = Attempt.find result[:attempt_id] | |
Attempt.transaction do | |
Testing::Test.find_active(result[:test_ids]).each do |test| | |
quote_group.quote_items.active.create!( | |
attempt: attempt, | |
test_id: test.id, | |
position: (quote_group.quote_items.active.maximum("position") || 0) + 10, | |
) | |
end | |
end | |
Success(quote_group) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment