diff --git a/app/models/rate.rb b/app/models/rate.rb index 36cff18..58beebd 100644 --- a/app/models/rate.rb +++ b/app/models/rate.rb @@ -82,6 +82,19 @@ class Rate < ActiveRecord::Base end store_cache_timestamp('last_caching_run', Time.now.to_s) end + + def self.update_all_time_entries_to_refresh_cache + Lockfile('refresh_cache', :retries => 0) do + TimeEntry.find_each do |time_entry| # batch find + begin + time_entry.save_cached_cost + rescue Rate::InvalidParameterException => ex + puts "Error saving #{time_entry.id}: #{ex.message}" + end + end + end + store_cache_timestamp('last_cache_clearing_run', Time.now.to_s) + end private def self.for_user_project_and_date(user, project, date) diff --git a/lib/tasks/cache.rake b/lib/tasks/cache.rake index e60cf15..f8710ff 100644 --- a/lib/tasks/cache.rake +++ b/lib/tasks/cache.rake @@ -1,8 +1,13 @@ namespace :rate_plugin do namespace :cache do - desc "Update Time Entry cost caches" + desc "Update Time Entry cost caches for Time Entries without a cost" task :update_cost_cache => :environment do Rate.update_all_time_entries_with_missing_cost end + + desc "Clear and update all Time Entry cost caches" + task :refresh_cost_cache => :environment do + Rate.update_all_time_entries_to_refresh_cache + end end end diff --git a/test/unit/rate_test.rb b/test/unit/rate_test.rb index e492771..99a585e 100644 --- a/test/unit/rate_test.rb +++ b/test/unit/rate_test.rb @@ -301,4 +301,33 @@ class RateTest < ActiveSupport::TestCase assert Time.parse(Setting.plugin_redmine_rate['last_caching_run']), "Last run timestamp not parseable" end end + + context "#update_all_time_entries_to_refresh_cache" do + setup do + @user = User.generate! + @project = Project.generate! + @date = Date.today.to_s + @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 => @date, :hours => 20.0, :activity => TimeEntryActivity.generate!}) + end + + should "update the caches of all Time Entries" do + assert_equal "0", ActiveRecord::Base.connection.select_all('select count(*) as count from time_entries where cost IS NULL').first["count"] + + Rate.update_all_time_entries_to_refresh_cache + + assert_equal "0", ActiveRecord::Base.connection.select_all('select count(*) as count from time_entries where cost IS NULL').first["count"] + + end + + should "timestamp a successful run" do + assert_equal nil, Setting.plugin_redmine_rate['last_cache_clearing_run'] + + Rate.update_all_time_entries_to_refresh_cache + + assert Setting.plugin_redmine_rate['last_cache_clearing_run'], "Last run not timestamped" + assert Time.parse(Setting.plugin_redmine_rate['last_cache_clearing_run']), "Last run timestamp not parseable" + end + end end