diff --git a/app/models/payroll_run.rb b/app/models/payroll_run.rb index dcb42507c2..6b7ca1e0ec 100644 --- a/app/models/payroll_run.rb +++ b/app/models/payroll_run.rb @@ -84,16 +84,34 @@ def payments_count @payments_count ||= payments.count end - def line_items(policy, filter: :all) - items = [] + case filter + when :all + policy_items(policy) + when :claims + policy_items(policy).select { |item| item.is_a?(Claim) } + when :topups + policy_items(policy).select { |item| item.is_a?(Topup) } + end + end + + def policy_items(policy) + policy_items_cache[policy] ||= build_policy_items(policy) + end + def policy_items_cache + @policy_items_cache ||= {} + end + + def build_policy_items(policy) policy_payments = if policy == :all payments else payments.joins(:claims).merge(Claim.by_policy(policy)) end + items = [] + policy_payments.includes(:claims).includes(:topups).each do |payment| payment.claims.each do |claim| # Payments can have multiple claims @@ -109,14 +127,7 @@ def line_items(policy, filter: :all) end end - case filter - when :all - items - when :claims - items.select { |item| item.is_a?(Claim) } - when :topups - items.select { |item| item.is_a?(Topup) } - end + items end def ensure_no_payroll_run_this_month