diff --git a/app/models/rate.rb b/app/models/rate.rb index c8c0a29..5416215 100644 --- a/app/models/rate.rb +++ b/app/models/rate.rb @@ -11,6 +11,7 @@ class Rate < ActiveRecord::Base validates_numericality_of :amount before_save :unlocked? + after_save :update_time_entry_cost_cache before_destroy :unlocked? named_scope :history_for_user, lambda { |user, order| @@ -36,6 +37,10 @@ class Rate < ActiveRecord::Base def specific? return !self.default? end + + def update_time_entry_cost_cache + TimeEntry.update_cost_cache(user, project) + end # API to find the Rate for a +user+ on a +project+ at a +date+ def self.for(user, project = nil, date = Date.today.to_s) diff --git a/lib/rate_time_entry_patch.rb b/lib/rate_time_entry_patch.rb index fa93f83..5a2e959 100644 --- a/lib/rate_time_entry_patch.rb +++ b/lib/rate_time_entry_patch.rb @@ -17,7 +17,16 @@ module RateTimeEntryPatch end module ClassMethods - + # Updated the cached cost of all TimeEntries for user and project + def update_cost_cache(user, project=nil) + c = ARCondition.new + c << ["#{TimeEntry.table_name}.user_id = ?", user] + c << ["#{TimeEntry.table_name}.project_id = ?", project] if project + + TimeEntry.all(:conditions => c.conditions).each do |time_entry| + time_entry.save_cached_cost + end + end end module InstanceMethods @@ -53,6 +62,7 @@ module RateTimeEntryPatch end def save_cached_cost + clear_cost_cache update_attribute(:cost, cost) end diff --git a/test/unit/rate_test.rb b/test/unit/rate_test.rb index 89bce69..62ec0f5 100644 --- a/test/unit/rate_test.rb +++ b/test/unit/rate_test.rb @@ -84,6 +84,28 @@ class RateTest < ActiveSupport::TestCase end end + context "after save" do + should "recalculate all of the cached cost of all Time Entries for the user" do + @user = User.generate! + @project = Project.generate! + @date = Date.today.to_s + @past_date = 1.month.ago.strftime('%Y-%m-%d') + @rate = Rate.generate!(:user => @user, :project => @project, :date_in_effect => @date, :amount => 200.0) + @time_entry1 = TimeEntry.generate!({:user => @user, :project => @project, :spent_on => @date, :hours => 10.0, :activity => TimeEntryActivity.generate!}) + @time_entry2 = TimeEntry.generate!({:user => @user, :project => @project, :spent_on => @past_date, :hours => 20.0, :activity => TimeEntryActivity.generate!}) + + + assert_equal 2000.00, @time_entry1.cost + assert_equal 0, @time_entry2.cost + + @old_rate = Rate.generate!(:user => @user, :project => @project, :date_in_effect => 2.months.ago.strftime('%Y-%m-%d'), :amount => 10.0) + + assert_equal 2000.00, TimeEntry.find(@time_entry1.id).cost + assert_equal 200.00, TimeEntry.find(@time_entry2.id).cost + end + + end + context '#for' do setup do @user = User.generate!