diff --git a/calculators/total_contributions_calculator.rb b/calculators/total_contributions_calculator.rb index 363619b02..6b951bf4b 100644 --- a/calculators/total_contributions_calculator.rb +++ b/calculators/total_contributions_calculator.rb @@ -17,8 +17,8 @@ def fetch WHERE "Filer_ID" = "FPPC"::varchar AND "Form_Type" = 'F460' AND "Line_Item" = '5' - AND ("Start_Date" IS NULL OR "Rpt_Date" >= "Start_Date") - AND ("End_Date" IS NULL OR "Rpt_Date" <= "End_Date") + AND ("Start_Date" IS NULL OR "From_Date" >= "Start_Date") + AND ("End_Date" IS NULL OR "Thru_Date" <= "End_Date") GROUP BY "Filer_ID" ORDER BY "Filer_ID" SQL @@ -46,10 +46,42 @@ def fetch contributions_by_filer_id[filer_id] += result['Total'].to_f end + # For candidates where we specify a "Start Date", we include their initial + # "Beginning Cash Balance" as a contribution so that our calculation of + # their remaining balance matches up with their actual reported balance. + starting_balances_by_filer_id.each do |filer_id, result| + # Skip records with no Summary sheet for now, to prevent conflicting + # `total_contributions` calculation with contribution_list_calculator. + next unless contributions_by_filer_id.include?(filer_id) + + contributions_by_filer_id[filer_id] += result['Starting_Balance'].to_f + end + contributions_by_filer_id.each do |filer_id, total_contributions| candidate = @candidates_by_filer_id[filer_id] candidate.save_calculation(:total_contributions, total_contributions) end end + + def starting_balances_by_filer_id + ActiveRecord::Base.connection.execute(<<-SQL).index_by { |r| r['Filer_ID'] } + WITH first_filing_after_start_dates AS ( + -- Get the first report after the Start Date for each filer + SELECT "Filer_ID", MIN("Thru_Date") as "Thru_Date" + FROM "Summary", candidates + WHERE "Filer_ID" = "FPPC"::varchar + AND "Start_Date" IS NOT NULL + AND "Thru_Date" >= "Start_Date" + GROUP BY "Filer_ID" + ) + SELECT "Summary"."Filer_ID", "Summary"."Thru_Date", "Amount_A" as "Starting_Balance" + FROM "Summary" + INNER JOIN first_filing_after_start_dates + ON first_filing_after_start_dates."Filer_ID" = "Summary"."Filer_ID" + AND first_filing_after_start_dates."Thru_Date" = "Summary"."Thru_Date" + WHERE "Form_Type" = 'F460' + AND "Line_Item" = '12'; + SQL + end end