[#4604] Clear and recalculate the #cost on Rate#save

This commit is contained in:
Eric Davis
2010-10-06 12:42:17 -07:00
parent d656121b20
commit f7b03b825f
3 changed files with 38 additions and 1 deletions

View File

@@ -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)

View File

@@ -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

View File

@@ -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!