diff --git a/calculators/total_contributions_calculator.rb b/calculators/total_contributions_calculator.rb index 363619b02..46518d6d8 100644 --- a/calculators/total_contributions_calculator.rb +++ b/calculators/total_contributions_calculator.rb @@ -46,10 +46,39 @@ 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| + contributions_by_filer_id[filer_id] ||= 0 + 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