-
-
Save derekprior/03ad1f7fd4537321cd6ee7100f95e453 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
class InsurancePlanTypeQuery | |
MANUAL_PLAN_TYPES_JOIN = 'INNER JOIN accepted_plan_types '\ | |
'ON accepted_plan_types.accepted_insurer_id = accepted_insurers.id'.freeze | |
def self.call(scope, search) | |
new(scope).call(search) | |
end | |
def initialize(scope) | |
@scope = scope | |
end | |
def call(search) | |
if search.plan_type_id.present? | |
contracted_accepted_plan_types(search) | |
else | |
scope | |
end | |
end | |
private | |
attr_reader :scope | |
def contracted_accepted_plan_types(search) | |
scope. | |
joins(plan_types_join). | |
where(accepted_plan_types: plan_type_conditions_from(search)) | |
end | |
# The passed in scope may already have `joins(accepted_insurers: :insurance_payor)` | |
# Attempting to then `joins(accepted_insurers: :accepted_plan_types)` duplicates the | |
# `accepted_insurers` join. So, we detect if this join is already in place and if so | |
# we use a manual SQL string to do just the additional join we need. | |
def plan_types_join | |
if joined_to_accepted_insurers? | |
MANUAL_PLAN_TYPES_JOIN | |
else | |
{ accepted_insurers: :accepted_plan_types } | |
end | |
end | |
def joined_to_accepted_insurers? | |
scope.joins_values.any? do |join| | |
case join | |
when Hash | |
join.keys.include?(:accepted_insurers) | |
else | |
join == :accepted_insurers | |
end | |
end | |
end | |
def plan_type_conditions_from(search) | |
{ | |
plan_type_id: search.plan_type_id, | |
status: plan_statuses(search) | |
} | |
end | |
def plan_statuses(search) | |
if search.display_unknown_insurance_plans? | |
[:contracted, :unknown] | |
else | |
[:contracted] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment