##// END OF EJS Templates
Refactor: move method to Model....
Eric Davis -
r3972:8900797adaf2
parent child
Show More
@@ -1,324 +1,324
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2007 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class TimelogController < ApplicationController
19 19 menu_item :issues
20 20 before_filter :find_project, :authorize, :only => [:edit, :destroy]
21 21 before_filter :find_optional_project, :only => [:report, :details]
22 22 before_filter :load_available_criterias, :only => [:report]
23 23
24 24 verify :method => :post, :only => :destroy, :redirect_to => { :action => :details }
25 25
26 26 helper :sort
27 27 include SortHelper
28 28 helper :issues
29 29 include TimelogHelper
30 30 helper :custom_fields
31 31 include CustomFieldsHelper
32 32
33 33 def report
34 34 @criterias = params[:criterias] || []
35 35 @criterias = @criterias.select{|criteria| @available_criterias.has_key? criteria}
36 36 @criterias.uniq!
37 37 @criterias = @criterias[0,3]
38 38
39 39 @columns = (params[:columns] && %w(year month week day).include?(params[:columns])) ? params[:columns] : 'month'
40 40
41 41 retrieve_date_range
42 42
43 43 unless @criterias.empty?
44 44 sql_select = @criterias.collect{|criteria| @available_criterias[criteria][:sql] + " AS " + criteria}.join(', ')
45 45 sql_group_by = @criterias.collect{|criteria| @available_criterias[criteria][:sql]}.join(', ')
46 46 sql_condition = ''
47 47
48 48 if @project.nil?
49 49 sql_condition = Project.allowed_to_condition(User.current, :view_time_entries)
50 50 elsif @issue.nil?
51 51 sql_condition = @project.project_condition(Setting.display_subprojects_issues?)
52 52 else
53 53 sql_condition = "#{Issue.table_name}.root_id = #{@issue.root_id} AND #{Issue.table_name}.lft >= #{@issue.lft} AND #{Issue.table_name}.rgt <= #{@issue.rgt}"
54 54 end
55 55
56 56 sql = "SELECT #{sql_select}, tyear, tmonth, tweek, spent_on, SUM(hours) AS hours"
57 57 sql << " FROM #{TimeEntry.table_name}"
58 58 sql << time_report_joins
59 59 sql << " WHERE"
60 60 sql << " (%s) AND" % sql_condition
61 61 sql << " (spent_on BETWEEN '%s' AND '%s')" % [ActiveRecord::Base.connection.quoted_date(@from), ActiveRecord::Base.connection.quoted_date(@to)]
62 62 sql << " GROUP BY #{sql_group_by}, tyear, tmonth, tweek, spent_on"
63 63
64 64 @hours = ActiveRecord::Base.connection.select_all(sql)
65 65
66 66 @hours.each do |row|
67 67 case @columns
68 68 when 'year'
69 69 row['year'] = row['tyear']
70 70 when 'month'
71 71 row['month'] = "#{row['tyear']}-#{row['tmonth']}"
72 72 when 'week'
73 73 row['week'] = "#{row['tyear']}-#{row['tweek']}"
74 74 when 'day'
75 75 row['day'] = "#{row['spent_on']}"
76 76 end
77 77 end
78 78
79 79 @total_hours = @hours.inject(0) {|s,k| s = s + k['hours'].to_f}
80 80
81 81 @periods = []
82 82 # Date#at_beginning_of_ not supported in Rails 1.2.x
83 83 date_from = @from.to_time
84 84 # 100 columns max
85 85 while date_from <= @to.to_time && @periods.length < 100
86 86 case @columns
87 87 when 'year'
88 88 @periods << "#{date_from.year}"
89 89 date_from = (date_from + 1.year).at_beginning_of_year
90 90 when 'month'
91 91 @periods << "#{date_from.year}-#{date_from.month}"
92 92 date_from = (date_from + 1.month).at_beginning_of_month
93 93 when 'week'
94 94 @periods << "#{date_from.year}-#{date_from.to_date.cweek}"
95 95 date_from = (date_from + 7.day).at_beginning_of_week
96 96 when 'day'
97 97 @periods << "#{date_from.to_date}"
98 98 date_from = date_from + 1.day
99 99 end
100 100 end
101 101 end
102 102
103 103 respond_to do |format|
104 104 format.html { render :layout => !request.xhr? }
105 105 format.csv { send_data(report_to_csv(@criterias, @periods, @hours), :type => 'text/csv; header=present', :filename => 'timelog.csv') }
106 106 end
107 107 end
108 108
109 109 def details
110 110 sort_init 'spent_on', 'desc'
111 111 sort_update 'spent_on' => 'spent_on',
112 112 'user' => 'user_id',
113 113 'activity' => 'activity_id',
114 114 'project' => "#{Project.table_name}.name",
115 115 'issue' => 'issue_id',
116 116 'hours' => 'hours'
117 117
118 118 cond = ARCondition.new
119 119 if @project.nil?
120 120 cond << Project.allowed_to_condition(User.current, :view_time_entries)
121 121 elsif @issue.nil?
122 122 cond << @project.project_condition(Setting.display_subprojects_issues?)
123 123 else
124 124 cond << "#{Issue.table_name}.root_id = #{@issue.root_id} AND #{Issue.table_name}.lft >= #{@issue.lft} AND #{Issue.table_name}.rgt <= #{@issue.rgt}"
125 125 end
126 126
127 127 retrieve_date_range
128 128 cond << ['spent_on BETWEEN ? AND ?', @from, @to]
129 129
130 130 TimeEntry.visible_by(User.current) do
131 131 respond_to do |format|
132 132 format.html {
133 133 # Paginate results
134 134 @entry_count = TimeEntry.count(:include => [:project, :issue], :conditions => cond.conditions)
135 135 @entry_pages = Paginator.new self, @entry_count, per_page_option, params['page']
136 136 @entries = TimeEntry.find(:all,
137 137 :include => [:project, :activity, :user, {:issue => :tracker}],
138 138 :conditions => cond.conditions,
139 139 :order => sort_clause,
140 140 :limit => @entry_pages.items_per_page,
141 141 :offset => @entry_pages.current.offset)
142 142 @total_hours = TimeEntry.sum(:hours, :include => [:project, :issue], :conditions => cond.conditions).to_f
143 143
144 144 render :layout => !request.xhr?
145 145 }
146 146 format.atom {
147 147 entries = TimeEntry.find(:all,
148 148 :include => [:project, :activity, :user, {:issue => :tracker}],
149 149 :conditions => cond.conditions,
150 150 :order => "#{TimeEntry.table_name}.created_on DESC",
151 151 :limit => Setting.feeds_limit.to_i)
152 152 render_feed(entries, :title => l(:label_spent_time))
153 153 }
154 154 format.csv {
155 155 # Export all entries
156 156 @entries = TimeEntry.find(:all,
157 157 :include => [:project, :activity, :user, {:issue => [:tracker, :assigned_to, :priority]}],
158 158 :conditions => cond.conditions,
159 159 :order => sort_clause)
160 160 send_data(entries_to_csv(@entries), :type => 'text/csv; header=present', :filename => 'timelog.csv')
161 161 }
162 162 end
163 163 end
164 164 end
165 165
166 166 def edit
167 167 (render_403; return) if @time_entry && !@time_entry.editable_by?(User.current)
168 168 @time_entry ||= TimeEntry.new(:project => @project, :issue => @issue, :user => User.current, :spent_on => User.current.today)
169 169 @time_entry.attributes = params[:time_entry]
170 170
171 171 call_hook(:controller_timelog_edit_before_save, { :params => params, :time_entry => @time_entry })
172 172
173 173 if request.post? and @time_entry.save
174 174 flash[:notice] = l(:notice_successful_update)
175 175 redirect_back_or_default :action => 'details', :project_id => @time_entry.project
176 176 return
177 177 end
178 178 end
179 179
180 180 def destroy
181 181 (render_404; return) unless @time_entry
182 182 (render_403; return) unless @time_entry.editable_by?(User.current)
183 183 if @time_entry.destroy && @time_entry.destroyed?
184 184 flash[:notice] = l(:notice_successful_delete)
185 185 else
186 186 flash[:error] = l(:notice_unable_delete_time_entry)
187 187 end
188 188 redirect_to :back
189 189 rescue ::ActionController::RedirectBackError
190 190 redirect_to :action => 'details', :project_id => @time_entry.project
191 191 end
192 192
193 193 private
194 194 def find_project
195 195 if params[:id]
196 196 @time_entry = TimeEntry.find(params[:id])
197 197 @project = @time_entry.project
198 198 elsif params[:issue_id]
199 199 @issue = Issue.find(params[:issue_id])
200 200 @project = @issue.project
201 201 elsif params[:project_id]
202 202 @project = Project.find(params[:project_id])
203 203 else
204 204 render_404
205 205 return false
206 206 end
207 207 rescue ActiveRecord::RecordNotFound
208 208 render_404
209 209 end
210 210
211 211 def find_optional_project
212 212 if !params[:issue_id].blank?
213 213 @issue = Issue.find(params[:issue_id])
214 214 @project = @issue.project
215 215 elsif !params[:project_id].blank?
216 216 @project = Project.find(params[:project_id])
217 217 end
218 218 deny_access unless User.current.allowed_to?(:view_time_entries, @project, :global => true)
219 219 end
220 220
221 221 # Retrieves the date range based on predefined ranges or specific from/to param dates
222 222 def retrieve_date_range
223 223 @free_period = false
224 224 @from, @to = nil, nil
225 225
226 226 if params[:period_type] == '1' || (params[:period_type].nil? && !params[:period].nil?)
227 227 case params[:period].to_s
228 228 when 'today'
229 229 @from = @to = Date.today
230 230 when 'yesterday'
231 231 @from = @to = Date.today - 1
232 232 when 'current_week'
233 233 @from = Date.today - (Date.today.cwday - 1)%7
234 234 @to = @from + 6
235 235 when 'last_week'
236 236 @from = Date.today - 7 - (Date.today.cwday - 1)%7
237 237 @to = @from + 6
238 238 when '7_days'
239 239 @from = Date.today - 7
240 240 @to = Date.today
241 241 when 'current_month'
242 242 @from = Date.civil(Date.today.year, Date.today.month, 1)
243 243 @to = (@from >> 1) - 1
244 244 when 'last_month'
245 245 @from = Date.civil(Date.today.year, Date.today.month, 1) << 1
246 246 @to = (@from >> 1) - 1
247 247 when '30_days'
248 248 @from = Date.today - 30
249 249 @to = Date.today
250 250 when 'current_year'
251 251 @from = Date.civil(Date.today.year, 1, 1)
252 252 @to = Date.civil(Date.today.year, 12, 31)
253 253 end
254 254 elsif params[:period_type] == '2' || (params[:period_type].nil? && (!params[:from].nil? || !params[:to].nil?))
255 255 begin; @from = params[:from].to_s.to_date unless params[:from].blank?; rescue; end
256 256 begin; @to = params[:to].to_s.to_date unless params[:to].blank?; rescue; end
257 257 @free_period = true
258 258 else
259 259 # default
260 260 end
261 261
262 262 @from, @to = @to, @from if @from && @to && @from > @to
263 @from ||= (TimeEntry.minimum(:spent_on, :include => :project, :conditions => Project.allowed_to_condition(User.current, :view_time_entries)) || Date.today) - 1
264 @to ||= (TimeEntry.maximum(:spent_on, :include => :project, :conditions => Project.allowed_to_condition(User.current, :view_time_entries)) || Date.today)
263 @from ||= (TimeEntry.earilest_date_for_project || Date.today) - 1
264 @to ||= (TimeEntry.latest_date_for_project || Date.today)
265 265 end
266 266
267 267 def load_available_criterias
268 268 @available_criterias = { 'project' => {:sql => "#{TimeEntry.table_name}.project_id",
269 269 :klass => Project,
270 270 :label => :label_project},
271 271 'version' => {:sql => "#{Issue.table_name}.fixed_version_id",
272 272 :klass => Version,
273 273 :label => :label_version},
274 274 'category' => {:sql => "#{Issue.table_name}.category_id",
275 275 :klass => IssueCategory,
276 276 :label => :field_category},
277 277 'member' => {:sql => "#{TimeEntry.table_name}.user_id",
278 278 :klass => User,
279 279 :label => :label_member},
280 280 'tracker' => {:sql => "#{Issue.table_name}.tracker_id",
281 281 :klass => Tracker,
282 282 :label => :label_tracker},
283 283 'activity' => {:sql => "#{TimeEntry.table_name}.activity_id",
284 284 :klass => TimeEntryActivity,
285 285 :label => :label_activity},
286 286 'issue' => {:sql => "#{TimeEntry.table_name}.issue_id",
287 287 :klass => Issue,
288 288 :label => :label_issue}
289 289 }
290 290
291 291 # Add list and boolean custom fields as available criterias
292 292 custom_fields = (@project.nil? ? IssueCustomField.for_all : @project.all_issue_custom_fields)
293 293 custom_fields.select {|cf| %w(list bool).include? cf.field_format }.each do |cf|
294 294 @available_criterias["cf_#{cf.id}"] = {:sql => "(SELECT c.value FROM #{CustomValue.table_name} c WHERE c.custom_field_id = #{cf.id} AND c.customized_type = 'Issue' AND c.customized_id = #{Issue.table_name}.id)",
295 295 :format => cf.field_format,
296 296 :label => cf.name}
297 297 end if @project
298 298
299 299 # Add list and boolean time entry custom fields
300 300 TimeEntryCustomField.find(:all).select {|cf| %w(list bool).include? cf.field_format }.each do |cf|
301 301 @available_criterias["cf_#{cf.id}"] = {:sql => "(SELECT c.value FROM #{CustomValue.table_name} c WHERE c.custom_field_id = #{cf.id} AND c.customized_type = 'TimeEntry' AND c.customized_id = #{TimeEntry.table_name}.id)",
302 302 :format => cf.field_format,
303 303 :label => cf.name}
304 304 end
305 305
306 306 # Add list and boolean time entry activity custom fields
307 307 TimeEntryActivityCustomField.find(:all).select {|cf| %w(list bool).include? cf.field_format }.each do |cf|
308 308 @available_criterias["cf_#{cf.id}"] = {:sql => "(SELECT c.value FROM #{CustomValue.table_name} c WHERE c.custom_field_id = #{cf.id} AND c.customized_type = 'Enumeration' AND c.customized_id = #{TimeEntry.table_name}.activity_id)",
309 309 :format => cf.field_format,
310 310 :label => cf.name}
311 311 end
312 312
313 313 call_hook(:controller_timelog_available_criterias, { :available_criterias => @available_criterias, :project => @project })
314 314 @available_criterias
315 315 end
316 316
317 317 def time_report_joins
318 318 sql = ''
319 319 sql << " LEFT JOIN #{Issue.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id"
320 320 sql << " LEFT JOIN #{Project.table_name} ON #{TimeEntry.table_name}.project_id = #{Project.table_name}.id"
321 321 call_hook(:controller_timelog_time_report_joins, {:sql => sql} )
322 322 sql
323 323 end
324 324 end
@@ -1,84 +1,92
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2008 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class TimeEntry < ActiveRecord::Base
19 19 # could have used polymorphic association
20 20 # project association here allows easy loading of time entries at project level with one database trip
21 21 belongs_to :project
22 22 belongs_to :issue
23 23 belongs_to :user
24 24 belongs_to :activity, :class_name => 'TimeEntryActivity', :foreign_key => 'activity_id'
25 25
26 26 attr_protected :project_id, :user_id, :tyear, :tmonth, :tweek
27 27
28 28 acts_as_customizable
29 29 acts_as_event :title => Proc.new {|o| "#{l_hours(o.hours)} (#{(o.issue || o.project).event_title})"},
30 30 :url => Proc.new {|o| {:controller => 'timelog', :action => 'details', :project_id => o.project, :issue_id => o.issue}},
31 31 :author => :user,
32 32 :description => :comments
33 33
34 34 acts_as_activity_provider :timestamp => "#{table_name}.created_on",
35 35 :author_key => :user_id,
36 36 :find_options => {:include => :project}
37 37
38 38 validates_presence_of :user_id, :activity_id, :project_id, :hours, :spent_on
39 39 validates_numericality_of :hours, :allow_nil => true, :message => :invalid
40 40 validates_length_of :comments, :maximum => 255, :allow_nil => true
41 41
42 42 def after_initialize
43 43 if new_record? && self.activity.nil?
44 44 if default_activity = TimeEntryActivity.default
45 45 self.activity_id = default_activity.id
46 46 end
47 47 self.hours = nil if hours == 0
48 48 end
49 49 end
50 50
51 51 def before_validation
52 52 self.project = issue.project if issue && project.nil?
53 53 end
54 54
55 55 def validate
56 56 errors.add :hours, :invalid if hours && (hours < 0 || hours >= 1000)
57 57 errors.add :project_id, :invalid if project.nil?
58 58 errors.add :issue_id, :invalid if (issue_id && !issue) || (issue && project!=issue.project)
59 59 end
60 60
61 61 def hours=(h)
62 62 write_attribute :hours, (h.is_a?(String) ? (h.to_hours || h) : h)
63 63 end
64 64
65 65 # tyear, tmonth, tweek assigned where setting spent_on attributes
66 66 # these attributes make time aggregations easier
67 67 def spent_on=(date)
68 68 super
69 69 self.tyear = spent_on ? spent_on.year : nil
70 70 self.tmonth = spent_on ? spent_on.month : nil
71 71 self.tweek = spent_on ? Date.civil(spent_on.year, spent_on.month, spent_on.day).cweek : nil
72 72 end
73 73
74 74 # Returns true if the time entry can be edited by usr, otherwise false
75 75 def editable_by?(usr)
76 76 (usr == user && usr.allowed_to?(:edit_own_time_entries, project)) || usr.allowed_to?(:edit_time_entries, project)
77 77 end
78 78
79 79 def self.visible_by(usr)
80 80 with_scope(:find => { :conditions => Project.allowed_to_condition(usr, :view_time_entries) }) do
81 81 yield
82 82 end
83 83 end
84
85 def self.earilest_date_for_project
86 TimeEntry.minimum(:spent_on, :include => :project, :conditions => Project.allowed_to_condition(User.current, :view_time_entries))
87 end
88
89 def self.latest_date_for_project
90 TimeEntry.maximum(:spent_on, :include => :project, :conditions => Project.allowed_to_condition(User.current, :view_time_entries))
91 end
84 92 end
@@ -1,51 +1,66
1 1 # redMine - project management software
2 2 # Copyright (C) 2006-2008 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require File.dirname(__FILE__) + '/../test_helper'
19 19
20 20 class TimeEntryTest < ActiveSupport::TestCase
21 21 fixtures :issues, :projects, :users, :time_entries
22 22
23 23 def test_hours_format
24 24 assertions = { "2" => 2.0,
25 25 "21.1" => 21.1,
26 26 "2,1" => 2.1,
27 27 "1,5h" => 1.5,
28 28 "7:12" => 7.2,
29 29 "10h" => 10.0,
30 30 "10 h" => 10.0,
31 31 "45m" => 0.75,
32 32 "45 m" => 0.75,
33 33 "3h15" => 3.25,
34 34 "3h 15" => 3.25,
35 35 "3 h 15" => 3.25,
36 36 "3 h 15m" => 3.25,
37 37 "3 h 15 m" => 3.25,
38 38 "3 hours" => 3.0,
39 39 "12min" => 0.2,
40 40 }
41 41
42 42 assertions.each do |k, v|
43 43 t = TimeEntry.new(:hours => k)
44 44 assert_equal v, t.hours, "Converting #{k} failed:"
45 45 end
46 46 end
47 47
48 48 def test_hours_should_default_to_nil
49 49 assert_nil TimeEntry.new.hours
50 50 end
51
52 context "#earilest_date_for_project" do
53 should "return the lowest spent_on value that is visible to the current user" do
54 User.current = nil
55 assert_equal "2007-03-12", TimeEntry.earilest_date_for_project.to_s
56 end
57 end
58
59 context "#latest_date_for_project" do
60 should "return the highest spent_on value that is visible to the current user" do
61 User.current = nil
62 assert_equal "2007-04-22", TimeEntry.latest_date_for_project.to_s
63 end
64 end
65
51 66 end
General Comments 0
You need to be logged in to leave comments. Login now