Revision 1297:0a574315af3e .svn/pristine/b5

View differences:

.svn/pristine/b5/b50241919b7b81279d644e95a3326c2189de1da8.svn-base
1
# Redmine - project management software
2
# Copyright (C) 2006-2012  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

  
18
require File.expand_path('../../test_helper', __FILE__)
19

  
20
class RepositoriesSubversionControllerTest < ActionController::TestCase
21
  tests RepositoriesController
22

  
23
  fixtures :projects, :users, :roles, :members, :member_roles, :enabled_modules,
24
           :repositories, :issues, :issue_statuses, :changesets, :changes,
25
           :issue_categories, :enumerations, :custom_fields, :custom_values, :trackers
26

  
27
  PRJ_ID = 3
28
  NUM_REV = 11
29

  
30
  def setup
31
    Setting.default_language = 'en'
32
    User.current = nil
33

  
34
    @project = Project.find(PRJ_ID)
35
    @repository = Repository::Subversion.create(:project => @project,
36
               :url => self.class.subversion_repository_url)
37
    assert @repository
38
  end
39

  
40
  if repository_configured?('subversion')
41
    def test_new
42
      @request.session[:user_id] = 1
43
      @project.repository.destroy
44
      get :new, :project_id => 'subproject1', :repository_scm => 'Subversion'
45
      assert_response :success
46
      assert_template 'new'
47
      assert_kind_of Repository::Subversion, assigns(:repository)
48
      assert assigns(:repository).new_record?
49
    end
50

  
51
    def test_show
52
      assert_equal 0, @repository.changesets.count
53
      @repository.fetch_changesets
54
      @project.reload
55
      assert_equal NUM_REV, @repository.changesets.count
56
      get :show, :id => PRJ_ID
57
      assert_response :success
58
      assert_template 'show'
59
      assert_not_nil assigns(:entries)
60
      assert_not_nil assigns(:changesets)
61

  
62
      entry = assigns(:entries).detect {|e| e.name == 'subversion_test'}
63
      assert_not_nil entry
64
      assert_equal 'dir', entry.kind
65
      assert_select 'tr.dir a[href=/projects/subproject1/repository/show/subversion_test]'
66

  
67
      assert_tag 'input', :attributes => {:name => 'rev'}
68
      assert_tag 'a', :content => 'Statistics'
69
      assert_tag 'a', :content => 'Atom'
70
      assert_tag :tag => 'a',
71
                 :attributes => {:href => '/projects/subproject1/repository'},
72
                 :content => 'root'
73
    end
74

  
75
    def test_show_non_default
76
      Repository::Subversion.create(:project => @project,
77
        :url => self.class.subversion_repository_url,
78
        :is_default => false, :identifier => 'svn')
79

  
80
      get :show, :id => PRJ_ID, :repository_id => 'svn'
81
      assert_response :success
82
      assert_template 'show'
83
      assert_select 'tr.dir a[href=/projects/subproject1/repository/svn/show/subversion_test]'
84
      # Repository menu should link to the main repo
85
      assert_select '#main-menu a[href=/projects/subproject1/repository]'
86
    end
87

  
88
    def test_browse_directory
89
      assert_equal 0, @repository.changesets.count
90
      @repository.fetch_changesets
91
      @project.reload
92
      assert_equal NUM_REV, @repository.changesets.count
93
      get :show, :id => PRJ_ID, :path => repository_path_hash(['subversion_test'])[:param]
94
      assert_response :success
95
      assert_template 'show'
96
      assert_not_nil assigns(:entries)
97
      assert_equal [
98
           '[folder_with_brackets]', 'folder', '.project',
99
           'helloworld.c', 'textfile.txt'
100
         ],
101
        assigns(:entries).collect(&:name)
102
      entry = assigns(:entries).detect {|e| e.name == 'helloworld.c'}
103
      assert_equal 'file', entry.kind
104
      assert_equal 'subversion_test/helloworld.c', entry.path
105
      assert_tag :a, :content => 'helloworld.c', :attributes => { :class => /text\-x\-c/ }
106
    end
107

  
108
    def test_browse_at_given_revision
109
      assert_equal 0, @repository.changesets.count
110
      @repository.fetch_changesets
111
      @project.reload
112
      assert_equal NUM_REV, @repository.changesets.count
113
      get :show, :id => PRJ_ID, :path => repository_path_hash(['subversion_test'])[:param],
114
          :rev => 4
115
      assert_response :success
116
      assert_template 'show'
117
      assert_not_nil assigns(:entries)
118
      assert_equal ['folder', '.project', 'helloworld.c', 'helloworld.rb', 'textfile.txt'],
119
                   assigns(:entries).collect(&:name)
120
    end
121

  
122
    def test_file_changes
123
      assert_equal 0, @repository.changesets.count
124
      @repository.fetch_changesets
125
      @project.reload
126
      assert_equal NUM_REV, @repository.changesets.count
127
      get :changes, :id => PRJ_ID,
128
          :path => repository_path_hash(['subversion_test', 'folder', 'helloworld.rb'])[:param]
129
      assert_response :success
130
      assert_template 'changes'
131

  
132
      changesets = assigns(:changesets)
133
      assert_not_nil changesets
134
      assert_equal %w(6 3 2), changesets.collect(&:revision)
135

  
136
      # svn properties displayed with svn >= 1.5 only
137
      if Redmine::Scm::Adapters::SubversionAdapter.client_version_above?([1, 5, 0])
138
        assert_not_nil assigns(:properties)
139
        assert_equal 'native', assigns(:properties)['svn:eol-style']
140
        assert_tag :ul,
141
                   :child => { :tag => 'li',
142
                               :child => { :tag => 'b', :content => 'svn:eol-style' },
143
                               :child => { :tag => 'span', :content => 'native' } }
144
      end
145
    end
146

  
147
    def test_directory_changes
148
      assert_equal 0, @repository.changesets.count
149
      @repository.fetch_changesets
150
      @project.reload
151
      assert_equal NUM_REV, @repository.changesets.count
152
      get :changes, :id => PRJ_ID,
153
          :path => repository_path_hash(['subversion_test', 'folder'])[:param]
154
      assert_response :success
155
      assert_template 'changes'
156

  
157
      changesets = assigns(:changesets)
158
      assert_not_nil changesets
159
      assert_equal %w(10 9 7 6 5 2), changesets.collect(&:revision)
160
    end
161

  
162
    def test_entry
163
      assert_equal 0, @repository.changesets.count
164
      @repository.fetch_changesets
165
      @project.reload
166
      assert_equal NUM_REV, @repository.changesets.count
167
      get :entry, :id => PRJ_ID,
168
          :path => repository_path_hash(['subversion_test', 'helloworld.c'])[:param]
169
      assert_response :success
170
      assert_template 'entry'
171
    end
172

  
173
    def test_entry_should_send_if_too_big
174
      assert_equal 0, @repository.changesets.count
175
      @repository.fetch_changesets
176
      @project.reload
177
      assert_equal NUM_REV, @repository.changesets.count
178
      # no files in the test repo is larger than 1KB...
179
      with_settings :file_max_size_displayed => 0 do
180
        get :entry, :id => PRJ_ID,
181
            :path => repository_path_hash(['subversion_test', 'helloworld.c'])[:param]
182
        assert_response :success
183
        assert_equal 'attachment; filename="helloworld.c"',
184
                     @response.headers['Content-Disposition']
185
      end
186
    end
187

  
188
    def test_entry_should_send_images_inline
189
      get :entry, :id => PRJ_ID,
190
          :path => repository_path_hash(['subversion_test', 'folder', 'subfolder', 'rubylogo.gif'])[:param]
191
      assert_response :success
192
      assert_equal 'inline; filename="rubylogo.gif"', response.headers['Content-Disposition']
193
    end
194

  
195
    def test_entry_at_given_revision
196
      assert_equal 0, @repository.changesets.count
197
      @repository.fetch_changesets
198
      @project.reload
199
      assert_equal NUM_REV, @repository.changesets.count
200
      get :entry, :id => PRJ_ID,
201
          :path => repository_path_hash(['subversion_test', 'helloworld.rb'])[:param],
202
          :rev => 2
203
      assert_response :success
204
      assert_template 'entry'
205
      # this line was removed in r3 and file was moved in r6
206
      assert_tag :tag => 'td', :attributes => { :class => /line-code/},
207
                               :content => /Here's the code/
208
    end
209

  
210
    def test_entry_not_found
211
      assert_equal 0, @repository.changesets.count
212
      @repository.fetch_changesets
213
      @project.reload
214
      assert_equal NUM_REV, @repository.changesets.count
215
      get :entry, :id => PRJ_ID,
216
          :path => repository_path_hash(['subversion_test', 'zzz.c'])[:param]
217
      assert_tag :tag => 'p', :attributes => { :id => /errorExplanation/ },
218
                 :content => /The entry or revision was not found in the repository/
219
    end
220

  
221
    def test_entry_download
222
      assert_equal 0, @repository.changesets.count
223
      @repository.fetch_changesets
224
      @project.reload
225
      assert_equal NUM_REV, @repository.changesets.count
226
      get :raw, :id => PRJ_ID,
227
          :path => repository_path_hash(['subversion_test', 'helloworld.c'])[:param]
228
      assert_response :success
229
      assert_equal 'attachment; filename="helloworld.c"', @response.headers['Content-Disposition']
230
    end
231

  
232
    def test_directory_entry
233
      assert_equal 0, @repository.changesets.count
234
      @repository.fetch_changesets
235
      @project.reload
236
      assert_equal NUM_REV, @repository.changesets.count
237
      get :entry, :id => PRJ_ID,
238
          :path => repository_path_hash(['subversion_test', 'folder'])[:param]
239
      assert_response :success
240
      assert_template 'show'
241
      assert_not_nil assigns(:entry)
242
      assert_equal 'folder', assigns(:entry).name
243
    end
244

  
245
    # TODO: this test needs fixtures.
246
    def test_revision
247
      get :revision, :id => 1, :rev => 2
248
      assert_response :success
249
      assert_template 'revision'
250

  
251
      assert_select 'ul' do
252
        assert_select 'li' do
253
          # link to the entry at rev 2
254
          assert_select 'a[href=?]', '/projects/ecookbook/repository/revisions/2/entry/test/some/path/in/the/repo', :text => 'repo'
255
          # link to partial diff
256
          assert_select 'a[href=?]', '/projects/ecookbook/repository/revisions/2/diff/test/some/path/in/the/repo'
257
        end
258
      end
259
    end
260

  
261
    def test_invalid_revision
262
      assert_equal 0, @repository.changesets.count
263
      @repository.fetch_changesets
264
      @project.reload
265
      assert_equal NUM_REV, @repository.changesets.count
266
      get :revision, :id => PRJ_ID, :rev => 'something_weird'
267
      assert_response 404
268
      assert_error_tag :content => /was not found/
269
    end
270

  
271
    def test_invalid_revision_diff
272
      get :diff, :id => PRJ_ID, :rev => '1', :rev_to => 'something_weird'
273
      assert_response 404
274
      assert_error_tag :content => /was not found/
275
    end
276

  
277
    def test_empty_revision
278
      assert_equal 0, @repository.changesets.count
279
      @repository.fetch_changesets
280
      @project.reload
281
      assert_equal NUM_REV, @repository.changesets.count
282
      ['', ' ', nil].each do |r|
283
        get :revision, :id => PRJ_ID, :rev => r
284
        assert_response 404
285
        assert_error_tag :content => /was not found/
286
      end
287
    end
288

  
289
    # TODO: this test needs fixtures.
290
    def test_revision_with_repository_pointing_to_a_subdirectory
291
      r = Project.find(1).repository
292
      # Changes repository url to a subdirectory
293
      r.update_attribute :url, (r.url + '/test/some')
294

  
295
      get :revision, :id => 1, :rev => 2
296
      assert_response :success
297
      assert_template 'revision'
298

  
299
      assert_select 'ul' do
300
        assert_select 'li' do
301
          # link to the entry at rev 2
302
          assert_select 'a[href=?]', '/projects/ecookbook/repository/revisions/2/entry/path/in/the/repo', :text => 'repo'
303
          # link to partial diff
304
          assert_select 'a[href=?]', '/projects/ecookbook/repository/revisions/2/diff/path/in/the/repo'
305
        end
306
      end
307
    end
308

  
309
    def test_revision_diff
310
      assert_equal 0, @repository.changesets.count
311
      @repository.fetch_changesets
312
      @project.reload
313
      assert_equal NUM_REV, @repository.changesets.count
314
      ['inline', 'sbs'].each do |dt|
315
        get :diff, :id => PRJ_ID, :rev => 3, :type => dt
316
        assert_response :success
317
        assert_template 'diff'
318
        assert_select 'h2', :text => /Revision 3/
319
        assert_select 'th.filename', :text => 'subversion_test/textfile.txt'
320
      end
321
    end
322

  
323
    def test_revision_diff_raw_format
324
      assert_equal 0, @repository.changesets.count
325
      @repository.fetch_changesets
326
      @project.reload
327
      assert_equal NUM_REV, @repository.changesets.count
328

  
329
      get :diff, :id => PRJ_ID, :rev => 3, :format => 'diff'
330
      assert_response :success
331
      assert_equal 'text/x-patch', @response.content_type
332
      assert_equal 'Index: subversion_test/textfile.txt', @response.body.split(/\r?\n/).first
333
    end
334

  
335
    def test_directory_diff
336
      assert_equal 0, @repository.changesets.count
337
      @repository.fetch_changesets
338
      @project.reload
339
      assert_equal NUM_REV, @repository.changesets.count
340
      ['inline', 'sbs'].each do |dt|
341
        get :diff, :id => PRJ_ID, :rev => 6, :rev_to => 2,
342
            :path => repository_path_hash(['subversion_test', 'folder'])[:param],
343
            :type => dt
344
        assert_response :success
345
        assert_template 'diff'
346

  
347
        diff = assigns(:diff)
348
        assert_not_nil diff
349
        # 2 files modified
350
        assert_equal 2, Redmine::UnifiedDiff.new(diff).size
351
        assert_tag :tag => 'h2', :content => /2:6/
352
      end
353
    end
354

  
355
    def test_annotate
356
      assert_equal 0, @repository.changesets.count
357
      @repository.fetch_changesets
358
      @project.reload
359
      assert_equal NUM_REV, @repository.changesets.count
360
      get :annotate, :id => PRJ_ID,
361
          :path => repository_path_hash(['subversion_test', 'helloworld.c'])[:param]
362
      assert_response :success
363
      assert_template 'annotate'
364

  
365
      assert_select 'tr' do
366
        assert_select 'th.line-num', :text => '1'
367
        assert_select 'td.revision', :text => '4'
368
        assert_select 'td.author', :text => 'jp'
369
        assert_select 'td', :text => /stdio.h/
370
      end
371
      # Same revision
372
      assert_select 'tr' do
373
        assert_select 'th.line-num', :text => '2'
374
        assert_select 'td.revision', :text => ''
375
        assert_select 'td.author', :text => ''
376
      end
377
    end
378

  
379
    def test_annotate_at_given_revision
380
      assert_equal 0, @repository.changesets.count
381
      @repository.fetch_changesets
382
      @project.reload
383
      assert_equal NUM_REV, @repository.changesets.count
384
      get :annotate, :id => PRJ_ID, :rev => 8,
385
          :path => repository_path_hash(['subversion_test', 'helloworld.c'])[:param]
386
      assert_response :success
387
      assert_template 'annotate'
388
      assert_tag :tag => 'h2', :content => /@ 8/
389
    end
390

  
391
    def test_destroy_valid_repository
392
      @request.session[:user_id] = 1 # admin
393
      assert_equal 0, @repository.changesets.count
394
      @repository.fetch_changesets
395
      assert_equal NUM_REV, @repository.changesets.count
396

  
397
      assert_difference 'Repository.count', -1 do
398
        delete :destroy, :id => @repository.id
399
      end
400
      assert_response 302
401
      @project.reload
402
      assert_nil @project.repository
403
    end
404

  
405
    def test_destroy_invalid_repository
406
      @request.session[:user_id] = 1 # admin
407
      @project.repository.destroy
408
      @repository = Repository::Subversion.create!(
409
                       :project => @project,
410
                       :url     => "file:///invalid")
411
      @repository.fetch_changesets
412
      assert_equal 0, @repository.changesets.count
413

  
414
      assert_difference 'Repository.count', -1 do
415
        delete :destroy, :id => @repository.id
416
      end
417
      assert_response 302
418
      @project.reload
419
      assert_nil @project.repository
420
    end
421
  else
422
    puts "Subversion test repository NOT FOUND. Skipping functional tests !!!"
423
    def test_fake; assert true end
424
  end
425
end
.svn/pristine/b5/b56c752cc763f92dc3d4dfc7ce0b9df55a884899.svn-base
1
/* English/UK initialisation for the jQuery UI date picker plugin. */
2
/* Written by Stuart. */
3
jQuery(function($){
4
	$.datepicker.regional['en-GB'] = {
5
		closeText: 'Done',
6
		prevText: 'Prev',
7
		nextText: 'Next',
8
		currentText: 'Today',
9
		monthNames: ['January','February','March','April','May','June',
10
		'July','August','September','October','November','December'],
11
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
12
		'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
13
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
14
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
15
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'],
16
		weekHeader: 'Wk',
17
		dateFormat: 'dd/mm/yy',
18
		firstDay: 1,
19
		isRTL: false,
20
		showMonthAfterYear: false,
21
		yearSuffix: ''};
22
	$.datepicker.setDefaults($.datepicker.regional['en-GB']);
23
});
.svn/pristine/b5/b57e9408687aade7204892e8ef5a9083ae04b593.svn-base
1
<h2><%= @controller_class %>Controller#<%= @action_name %></h2>
.svn/pristine/b5/b582b98d925d01a2fdc9c5e286bdae900edab917.svn-base
1
# Redmine - project management software
2
# Copyright (C) 2006-2012  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

  
18
class Issue < ActiveRecord::Base
19
  include Redmine::SafeAttributes
20
  include Redmine::Utils::DateCalculation
21

  
22
  belongs_to :project
23
  belongs_to :tracker
24
  belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
25
  belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
26
  belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
27
  belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
28
  belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
29
  belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
30

  
31
  has_many :journals, :as => :journalized, :dependent => :destroy
32
  has_many :visible_journals,
33
    :class_name => 'Journal',
34
    :as => :journalized,
35
    :conditions => Proc.new { 
36
      ["(#{Journal.table_name}.private_notes = ? OR (#{Project.allowed_to_condition(User.current, :view_private_notes)}))", false]
37
    },
38
    :readonly => true
39

  
40
  has_many :time_entries, :dependent => :delete_all
41
  has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
42

  
43
  has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
44
  has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
45

  
46
  acts_as_nested_set :scope => 'root_id', :dependent => :destroy
47
  acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
48
  acts_as_customizable
49
  acts_as_watchable
50
  acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
51
                     :include => [:project, :visible_journals],
52
                     # sort by id so that limited eager loading doesn't break with postgresql
53
                     :order_column => "#{table_name}.id"
54
  acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
55
                :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
56
                :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
57

  
58
  acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
59
                            :author_key => :author_id
60

  
61
  DONE_RATIO_OPTIONS = %w(issue_field issue_status)
62

  
63
  attr_reader :current_journal
64
  delegate :notes, :notes=, :private_notes, :private_notes=, :to => :current_journal, :allow_nil => true
65

  
66
  validates_presence_of :subject, :priority, :project, :tracker, :author, :status
67

  
68
  validates_length_of :subject, :maximum => 255
69
  validates_inclusion_of :done_ratio, :in => 0..100
70
  validates_numericality_of :estimated_hours, :allow_nil => true
71
  validate :validate_issue, :validate_required_fields
72

  
73
  scope :visible,
74
        lambda {|*args| { :include => :project,
75
                          :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
76

  
77
  scope :open, lambda {|*args|
78
    is_closed = args.size > 0 ? !args.first : false
79
    {:conditions => ["#{IssueStatus.table_name}.is_closed = ?", is_closed], :include => :status}
80
  }
81

  
82
  scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
83
  scope :on_active_project, :include => [:status, :project, :tracker],
84
                            :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
85

  
86
  before_create :default_assign
87
  before_save :close_duplicates, :update_done_ratio_from_issue_status, :force_updated_on_change
88
  after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?} 
89
  after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
90
  # Should be after_create but would be called before previous after_save callbacks
91
  after_save :after_create_from_copy
92
  after_destroy :update_parent_attributes
93

  
94
  # Returns a SQL conditions string used to find all issues visible by the specified user
95
  def self.visible_condition(user, options={})
96
    Project.allowed_to_condition(user, :view_issues, options) do |role, user|
97
      if user.logged?
98
        case role.issues_visibility
99
        when 'all'
100
          nil
101
        when 'default'
102
          user_ids = [user.id] + user.groups.map(&:id)
103
          "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
104
        when 'own'
105
          user_ids = [user.id] + user.groups.map(&:id)
106
          "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
107
        else
108
          '1=0'
109
        end
110
      else
111
        "(#{table_name}.is_private = #{connection.quoted_false})"
112
      end
113
    end
114
  end
115

  
116
  # Returns true if usr or current user is allowed to view the issue
117
  def visible?(usr=nil)
118
    (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
119
      if user.logged?
120
        case role.issues_visibility
121
        when 'all'
122
          true
123
        when 'default'
124
          !self.is_private? || (self.author == user || user.is_or_belongs_to?(assigned_to))
125
        when 'own'
126
          self.author == user || user.is_or_belongs_to?(assigned_to)
127
        else
128
          false
129
        end
130
      else
131
        !self.is_private?
132
      end
133
    end
134
  end
135

  
136
  def initialize(attributes=nil, *args)
137
    super
138
    if new_record?
139
      # set default values for new records only
140
      self.status ||= IssueStatus.default
141
      self.priority ||= IssuePriority.default
142
      self.watcher_user_ids = []
143
    end
144
  end
145

  
146
  # AR#Persistence#destroy would raise and RecordNotFound exception
147
  # if the issue was already deleted or updated (non matching lock_version).
148
  # This is a problem when bulk deleting issues or deleting a project
149
  # (because an issue may already be deleted if its parent was deleted
150
  # first).
151
  # The issue is reloaded by the nested_set before being deleted so
152
  # the lock_version condition should not be an issue but we handle it.
153
  def destroy
154
    super
155
  rescue ActiveRecord::RecordNotFound
156
    # Stale or already deleted
157
    begin
158
      reload
159
    rescue ActiveRecord::RecordNotFound
160
      # The issue was actually already deleted
161
      @destroyed = true
162
      return freeze
163
    end
164
    # The issue was stale, retry to destroy
165
    super
166
  end
167

  
168
  def reload(*args)
169
    @workflow_rule_by_attribute = nil
170
    @assignable_versions = nil
171
    super
172
  end
173

  
174
  # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
175
  def available_custom_fields
176
    (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
177
  end
178

  
179
  # Copies attributes from another issue, arg can be an id or an Issue
180
  def copy_from(arg, options={})
181
    issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
182
    self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
183
    self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
184
    self.status = issue.status
185
    self.author = User.current
186
    unless options[:attachments] == false
187
      self.attachments = issue.attachments.map do |attachement| 
188
        attachement.copy(:container => self)
189
      end
190
    end
191
    @copied_from = issue
192
    @copy_options = options
193
    self
194
  end
195

  
196
  # Returns an unsaved copy of the issue
197
  def copy(attributes=nil, copy_options={})
198
    copy = self.class.new.copy_from(self, copy_options)
199
    copy.attributes = attributes if attributes
200
    copy
201
  end
202

  
203
  # Returns true if the issue is a copy
204
  def copy?
205
    @copied_from.present?
206
  end
207

  
208
  # Moves/copies an issue to a new project and tracker
209
  # Returns the moved/copied issue on success, false on failure
210
  def move_to_project(new_project, new_tracker=nil, options={})
211
    ActiveSupport::Deprecation.warn "Issue#move_to_project is deprecated, use #project= instead."
212

  
213
    if options[:copy]
214
      issue = self.copy
215
    else
216
      issue = self
217
    end
218

  
219
    issue.init_journal(User.current, options[:notes])
220

  
221
    # Preserve previous behaviour
222
    # #move_to_project doesn't change tracker automatically
223
    issue.send :project=, new_project, true
224
    if new_tracker
225
      issue.tracker = new_tracker
226
    end
227
    # Allow bulk setting of attributes on the issue
228
    if options[:attributes]
229
      issue.attributes = options[:attributes]
230
    end
231

  
232
    issue.save ? issue : false
233
  end
234

  
235
  def status_id=(sid)
236
    self.status = nil
237
    result = write_attribute(:status_id, sid)
238
    @workflow_rule_by_attribute = nil
239
    result
240
  end
241

  
242
  def priority_id=(pid)
243
    self.priority = nil
244
    write_attribute(:priority_id, pid)
245
  end
246

  
247
  def category_id=(cid)
248
    self.category = nil
249
    write_attribute(:category_id, cid)
250
  end
251

  
252
  def fixed_version_id=(vid)
253
    self.fixed_version = nil
254
    write_attribute(:fixed_version_id, vid)
255
  end
256

  
257
  def tracker_id=(tid)
258
    self.tracker = nil
259
    result = write_attribute(:tracker_id, tid)
260
    @custom_field_values = nil
261
    @workflow_rule_by_attribute = nil
262
    result
263
  end
264

  
265
  def project_id=(project_id)
266
    if project_id.to_s != self.project_id.to_s
267
      self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
268
    end
269
  end
270

  
271
  def project=(project, keep_tracker=false)
272
    project_was = self.project
273
    write_attribute(:project_id, project ? project.id : nil)
274
    association_instance_set('project', project)
275
    if project_was && project && project_was != project
276
      @assignable_versions = nil
277

  
278
      unless keep_tracker || project.trackers.include?(tracker)
279
        self.tracker = project.trackers.first
280
      end
281
      # Reassign to the category with same name if any
282
      if category
283
        self.category = project.issue_categories.find_by_name(category.name)
284
      end
285
      # Keep the fixed_version if it's still valid in the new_project
286
      if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
287
        self.fixed_version = nil
288
      end
289
      # Clear the parent task if it's no longer valid
290
      unless valid_parent_project?
291
        self.parent_issue_id = nil
292
      end
293
      @custom_field_values = nil
294
    end
295
  end
296

  
297
  def description=(arg)
298
    if arg.is_a?(String)
299
      arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
300
    end
301
    write_attribute(:description, arg)
302
  end
303

  
304
  # Overrides assign_attributes so that project and tracker get assigned first
305
  def assign_attributes_with_project_and_tracker_first(new_attributes, *args)
306
    return if new_attributes.nil?
307
    attrs = new_attributes.dup
308
    attrs.stringify_keys!
309

  
310
    %w(project project_id tracker tracker_id).each do |attr|
311
      if attrs.has_key?(attr)
312
        send "#{attr}=", attrs.delete(attr)
313
      end
314
    end
315
    send :assign_attributes_without_project_and_tracker_first, attrs, *args
316
  end
317
  # Do not redefine alias chain on reload (see #4838)
318
  alias_method_chain(:assign_attributes, :project_and_tracker_first) unless method_defined?(:assign_attributes_without_project_and_tracker_first)
319

  
320
  def estimated_hours=(h)
321
    write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
322
  end
323

  
324
  safe_attributes 'project_id',
325
    :if => lambda {|issue, user|
326
      if issue.new_record?
327
        issue.copy?
328
      elsif user.allowed_to?(:move_issues, issue.project)
329
        projects = Issue.allowed_target_projects_on_move(user)
330
        projects.include?(issue.project) && projects.size > 1
331
      end
332
    }
333

  
334
  safe_attributes 'tracker_id',
335
    'status_id',
336
    'category_id',
337
    'assigned_to_id',
338
    'priority_id',
339
    'fixed_version_id',
340
    'subject',
341
    'description',
342
    'start_date',
343
    'due_date',
344
    'done_ratio',
345
    'estimated_hours',
346
    'custom_field_values',
347
    'custom_fields',
348
    'lock_version',
349
    'notes',
350
    :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
351

  
352
  safe_attributes 'status_id',
353
    'assigned_to_id',
354
    'fixed_version_id',
355
    'done_ratio',
356
    'lock_version',
357
    'notes',
358
    :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
359

  
360
  safe_attributes 'notes',
361
    :if => lambda {|issue, user| user.allowed_to?(:add_issue_notes, issue.project)}
362

  
363
  safe_attributes 'private_notes',
364
    :if => lambda {|issue, user| !issue.new_record? && user.allowed_to?(:set_notes_private, issue.project)} 
365

  
366
  safe_attributes 'watcher_user_ids',
367
    :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)} 
368

  
369
  safe_attributes 'is_private',
370
    :if => lambda {|issue, user|
371
      user.allowed_to?(:set_issues_private, issue.project) ||
372
        (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
373
    }
374

  
375
  safe_attributes 'parent_issue_id',
376
    :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
377
      user.allowed_to?(:manage_subtasks, issue.project)}
378

  
379
  def safe_attribute_names(user=nil)
380
    names = super
381
    names -= disabled_core_fields
382
    names -= read_only_attribute_names(user)
383
    names
384
  end
385

  
386
  # Safely sets attributes
387
  # Should be called from controllers instead of #attributes=
388
  # attr_accessible is too rough because we still want things like
389
  # Issue.new(:project => foo) to work
390
  def safe_attributes=(attrs, user=User.current)
391
    return unless attrs.is_a?(Hash)
392

  
393
    attrs = attrs.dup
394

  
395
    # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
396
    if (p = attrs.delete('project_id')) && safe_attribute?('project_id')
397
      if allowed_target_projects(user).collect(&:id).include?(p.to_i)
398
        self.project_id = p
399
      end
400
    end
401

  
402
    if (t = attrs.delete('tracker_id')) && safe_attribute?('tracker_id')
403
      self.tracker_id = t
404
    end
405

  
406
    if (s = attrs.delete('status_id')) && safe_attribute?('status_id')
407
      if new_statuses_allowed_to(user).collect(&:id).include?(s.to_i)
408
        self.status_id = s
409
      end
410
    end
411

  
412
    attrs = delete_unsafe_attributes(attrs, user)
413
    return if attrs.empty?
414

  
415
    unless leaf?
416
      attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
417
    end
418

  
419
    if attrs['parent_issue_id'].present?
420
      s = attrs['parent_issue_id'].to_s
421
      unless (m = s.match(%r{\A#?(\d+)\z})) && Issue.visible(user).exists?(m[1])
422
        @invalid_parent_issue_id = attrs.delete('parent_issue_id')
423
      end
424
    end
425

  
426
    if attrs['custom_field_values'].present?
427
      attrs['custom_field_values'] = attrs['custom_field_values'].reject {|k, v| read_only_attribute_names(user).include? k.to_s}
428
    end
429

  
430
    if attrs['custom_fields'].present?
431
      attrs['custom_fields'] = attrs['custom_fields'].reject {|c| read_only_attribute_names(user).include? c['id'].to_s}
432
    end
433

  
434
    # mass-assignment security bypass
435
    assign_attributes attrs, :without_protection => true
436
  end
437

  
438
  def disabled_core_fields
439
    tracker ? tracker.disabled_core_fields : []
440
  end
441

  
442
  # Returns the custom_field_values that can be edited by the given user
443
  def editable_custom_field_values(user=nil)
444
    custom_field_values.reject do |value|
445
      read_only_attribute_names(user).include?(value.custom_field_id.to_s)
446
    end
447
  end
448

  
449
  # Returns the names of attributes that are read-only for user or the current user
450
  # For users with multiple roles, the read-only fields are the intersection of
451
  # read-only fields of each role
452
  # The result is an array of strings where sustom fields are represented with their ids
453
  #
454
  # Examples:
455
  #   issue.read_only_attribute_names # => ['due_date', '2']
456
  #   issue.read_only_attribute_names(user) # => []
457
  def read_only_attribute_names(user=nil)
458
    workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'readonly'}.keys
459
  end
460

  
461
  # Returns the names of required attributes for user or the current user
462
  # For users with multiple roles, the required fields are the intersection of
463
  # required fields of each role
464
  # The result is an array of strings where sustom fields are represented with their ids
465
  #
466
  # Examples:
467
  #   issue.required_attribute_names # => ['due_date', '2']
468
  #   issue.required_attribute_names(user) # => []
469
  def required_attribute_names(user=nil)
470
    workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'required'}.keys
471
  end
472

  
473
  # Returns true if the attribute is required for user
474
  def required_attribute?(name, user=nil)
475
    required_attribute_names(user).include?(name.to_s)
476
  end
477

  
478
  # Returns a hash of the workflow rule by attribute for the given user
479
  #
480
  # Examples:
481
  #   issue.workflow_rule_by_attribute # => {'due_date' => 'required', 'start_date' => 'readonly'}
482
  def workflow_rule_by_attribute(user=nil)
483
    return @workflow_rule_by_attribute if @workflow_rule_by_attribute && user.nil?
484

  
485
    user_real = user || User.current
486
    roles = user_real.admin ? Role.all : user_real.roles_for_project(project)
487
    return {} if roles.empty?
488

  
489
    result = {}
490
    workflow_permissions = WorkflowPermission.where(:tracker_id => tracker_id, :old_status_id => status_id, :role_id => roles.map(&:id)).all
491
    if workflow_permissions.any?
492
      workflow_rules = workflow_permissions.inject({}) do |h, wp|
493
        h[wp.field_name] ||= []
494
        h[wp.field_name] << wp.rule
495
        h
496
      end
497
      workflow_rules.each do |attr, rules|
498
        next if rules.size < roles.size
499
        uniq_rules = rules.uniq
500
        if uniq_rules.size == 1
501
          result[attr] = uniq_rules.first
502
        else
503
          result[attr] = 'required'
504
        end
505
      end
506
    end
507
    @workflow_rule_by_attribute = result if user.nil?
508
    result
509
  end
510
  private :workflow_rule_by_attribute
511

  
512
  def done_ratio
513
    if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
514
      status.default_done_ratio
515
    else
516
      read_attribute(:done_ratio)
517
    end
518
  end
519

  
520
  def self.use_status_for_done_ratio?
521
    Setting.issue_done_ratio == 'issue_status'
522
  end
523

  
524
  def self.use_field_for_done_ratio?
525
    Setting.issue_done_ratio == 'issue_field'
526
  end
527

  
528
  def validate_issue
529
    if due_date.nil? && @attributes['due_date'].present?
530
      errors.add :due_date, :not_a_date
531
    end
532

  
533
    if start_date.nil? && @attributes['start_date'].present?
534
      errors.add :start_date, :not_a_date
535
    end
536

  
537
    if due_date && start_date && due_date < start_date
538
      errors.add :due_date, :greater_than_start_date
539
    end
540

  
541
    if start_date && soonest_start && start_date < soonest_start
542
      errors.add :start_date, :invalid
543
    end
544

  
545
    if fixed_version
546
      if !assignable_versions.include?(fixed_version)
547
        errors.add :fixed_version_id, :inclusion
548
      elsif reopened? && fixed_version.closed?
549
        errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
550
      end
551
    end
552

  
553
    # Checks that the issue can not be added/moved to a disabled tracker
554
    if project && (tracker_id_changed? || project_id_changed?)
555
      unless project.trackers.include?(tracker)
556
        errors.add :tracker_id, :inclusion
557
      end
558
    end
559

  
560
    # Checks parent issue assignment
561
    if @invalid_parent_issue_id.present?
562
      errors.add :parent_issue_id, :invalid
563
    elsif @parent_issue
564
      if !valid_parent_project?(@parent_issue)
565
        errors.add :parent_issue_id, :invalid
566
      elsif !new_record?
567
        # moving an existing issue
568
        if @parent_issue.root_id != root_id
569
          # we can always move to another tree
570
        elsif move_possible?(@parent_issue)
571
          # move accepted inside tree
572
        else
573
          errors.add :parent_issue_id, :invalid
574
        end
575
      end
576
    end
577
  end
578

  
579
  # Validates the issue against additional workflow requirements
580
  def validate_required_fields
581
    user = new_record? ? author : current_journal.try(:user)
582

  
583
    required_attribute_names(user).each do |attribute|
584
      if attribute =~ /^\d+$/
585
        attribute = attribute.to_i
586
        v = custom_field_values.detect {|v| v.custom_field_id == attribute }
587
        if v && v.value.blank?
588
          errors.add :base, v.custom_field.name + ' ' + l('activerecord.errors.messages.blank')
589
        end
590
      else
591
        if respond_to?(attribute) && send(attribute).blank?
592
          errors.add attribute, :blank
593
        end
594
      end
595
    end
596
  end
597

  
598
  # Set the done_ratio using the status if that setting is set.  This will keep the done_ratios
599
  # even if the user turns off the setting later
600
  def update_done_ratio_from_issue_status
601
    if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
602
      self.done_ratio = status.default_done_ratio
603
    end
604
  end
605

  
606
  def init_journal(user, notes = "")
607
    @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
608
    if new_record?
609
      @current_journal.notify = false
610
    else
611
      @attributes_before_change = attributes.dup
612
      @custom_values_before_change = {}
613
      self.custom_field_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
614
    end
615
    @current_journal
616
  end
617

  
618
  # Returns the id of the last journal or nil
619
  def last_journal_id
620
    if new_record?
621
      nil
622
    else
623
      journals.maximum(:id)
624
    end
625
  end
626

  
627
  # Returns a scope for journals that have an id greater than journal_id
628
  def journals_after(journal_id)
629
    scope = journals.reorder("#{Journal.table_name}.id ASC")
630
    if journal_id.present?
631
      scope = scope.where("#{Journal.table_name}.id > ?", journal_id.to_i)
632
    end
633
    scope
634
  end
635

  
636
  # Return true if the issue is closed, otherwise false
637
  def closed?
638
    self.status.is_closed?
639
  end
640

  
641
  # Return true if the issue is being reopened
642
  def reopened?
643
    if !new_record? && status_id_changed?
644
      status_was = IssueStatus.find_by_id(status_id_was)
645
      status_new = IssueStatus.find_by_id(status_id)
646
      if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
647
        return true
648
      end
649
    end
650
    false
651
  end
652

  
653
  # Return true if the issue is being closed
654
  def closing?
655
    if !new_record? && status_id_changed?
656
      status_was = IssueStatus.find_by_id(status_id_was)
657
      status_new = IssueStatus.find_by_id(status_id)
658
      if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
659
        return true
660
      end
661
    end
662
    false
663
  end
664

  
665
  # Returns true if the issue is overdue
666
  def overdue?
667
    !due_date.nil? && (due_date < Date.today) && !status.is_closed?
668
  end
669

  
670
  # Is the amount of work done less than it should for the due date
671
  def behind_schedule?
672
    return false if start_date.nil? || due_date.nil?
673
    done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
674
    return done_date <= Date.today
675
  end
676

  
677
  # Does this issue have children?
678
  def children?
679
    !leaf?
680
  end
681

  
682
  # Users the issue can be assigned to
683
  def assignable_users
684
    users = project.assignable_users
685
    users << author if author
686
    users << assigned_to if assigned_to
687
    users.uniq.sort
688
  end
689

  
690
  # Versions that the issue can be assigned to
691
  def assignable_versions
692
    return @assignable_versions if @assignable_versions
693

  
694
    versions = project.shared_versions.open.all
695
    if fixed_version
696
      if fixed_version_id_changed?
697
        # nothing to do
698
      elsif project_id_changed?
699
        if project.shared_versions.include?(fixed_version)
700
          versions << fixed_version
701
        end
702
      else
703
        versions << fixed_version
704
      end
705
    end
706
    @assignable_versions = versions.uniq.sort
707
  end
708

  
709
  # Returns true if this issue is blocked by another issue that is still open
710
  def blocked?
711
    !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
712
  end
713

  
714
  # Returns an array of statuses that user is able to apply
715
  def new_statuses_allowed_to(user=User.current, include_default=false)
716
    if new_record? && @copied_from
717
      [IssueStatus.default, @copied_from.status].compact.uniq.sort
718
    else
719
      initial_status = nil
720
      if new_record?
721
        initial_status = IssueStatus.default
722
      elsif status_id_was
723
        initial_status = IssueStatus.find_by_id(status_id_was)
724
      end
725
      initial_status ||= status
726
  
727
      statuses = initial_status.find_new_statuses_allowed_to(
728
        user.admin ? Role.all : user.roles_for_project(project),
729
        tracker,
730
        author == user,
731
        assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
732
        )
733
      statuses << initial_status unless statuses.empty?
734
      statuses << IssueStatus.default if include_default
735
      statuses = statuses.compact.uniq.sort
736
      blocked? ? statuses.reject {|s| s.is_closed?} : statuses
737
    end
738
  end
739

  
740
  def assigned_to_was
741
    if assigned_to_id_changed? && assigned_to_id_was.present?
742
      @assigned_to_was ||= User.find_by_id(assigned_to_id_was)
743
    end
744
  end
745

  
746
  # Returns the users that should be notified
747
  def notified_users
748
    notified = []
749
    # Author and assignee are always notified unless they have been
750
    # locked or don't want to be notified
751
    notified << author if author
752
    if assigned_to
753
      notified += (assigned_to.is_a?(Group) ? assigned_to.users : [assigned_to])
754
    end
755
    if assigned_to_was
756
      notified += (assigned_to_was.is_a?(Group) ? assigned_to_was.users : [assigned_to_was])
757
    end
758
    notified = notified.select {|u| u.active? && u.notify_about?(self)}
759

  
760
    notified += project.notified_users
761
    notified.uniq!
762
    # Remove users that can not view the issue
763
    notified.reject! {|user| !visible?(user)}
764
    notified
765
  end
766

  
767
  # Returns the email addresses that should be notified
768
  def recipients
769
    notified_users.collect(&:mail)
770
  end
771

  
772
  # Returns the number of hours spent on this issue
773
  def spent_hours
774
    @spent_hours ||= time_entries.sum(:hours) || 0
775
  end
776

  
777
  # Returns the total number of hours spent on this issue and its descendants
778
  #
779
  # Example:
780
  #   spent_hours => 0.0
781
  #   spent_hours => 50.2
782
  def total_spent_hours
783
    @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
784
      :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
785
  end
786

  
787
  def relations
788
    @relations ||= IssueRelations.new(self, (relations_from + relations_to).sort)
789
  end
790

  
791
  # Preloads relations for a collection of issues
792
  def self.load_relations(issues)
793
    if issues.any?
794
      relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
795
      issues.each do |issue|
796
        issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
797
      end
798
    end
799
  end
800

  
801
  # Preloads visible spent time for a collection of issues
802
  def self.load_visible_spent_hours(issues, user=User.current)
803
    if issues.any?
804
      hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
805
      issues.each do |issue|
806
        issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
807
      end
808
    end
809
  end
810

  
811
  # Preloads visible relations for a collection of issues
812
  def self.load_visible_relations(issues, user=User.current)
813
    if issues.any?
814
      issue_ids = issues.map(&:id)
815
      # Relations with issue_from in given issues and visible issue_to
816
      relations_from = IssueRelation.includes(:issue_to => [:status, :project]).where(visible_condition(user)).where(:issue_from_id => issue_ids).all
817
      # Relations with issue_to in given issues and visible issue_from
818
      relations_to = IssueRelation.includes(:issue_from => [:status, :project]).where(visible_condition(user)).where(:issue_to_id => issue_ids).all
819

  
820
      issues.each do |issue|
821
        relations =
822
          relations_from.select {|relation| relation.issue_from_id == issue.id} +
823
          relations_to.select {|relation| relation.issue_to_id == issue.id}
824

  
825
        issue.instance_variable_set "@relations", IssueRelations.new(issue, relations.sort)
826
      end
827
    end
828
  end
829

  
830
  # Finds an issue relation given its id.
831
  def find_relation(relation_id)
832
    IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
833
  end
834

  
835
  def all_dependent_issues(except=[])
836
    except << self
837
    dependencies = []
838
    relations_from.each do |relation|
839
      if relation.issue_to && !except.include?(relation.issue_to)
840
        dependencies << relation.issue_to
841
        dependencies += relation.issue_to.all_dependent_issues(except)
842
      end
843
    end
844
    dependencies
845
  end
846

  
847
  # Returns an array of issues that duplicate this one
848
  def duplicates
849
    relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
850
  end
851

  
852
  # Returns the due date or the target due date if any
853
  # Used on gantt chart
854
  def due_before
855
    due_date || (fixed_version ? fixed_version.effective_date : nil)
856
  end
857

  
858
  # Returns the time scheduled for this issue.
859
  #
860
  # Example:
861
  #   Start Date: 2/26/09, End Date: 3/04/09
862
  #   duration => 6
863
  def duration
864
    (start_date && due_date) ? due_date - start_date : 0
865
  end
866

  
867
  # Returns the duration in working days
868
  def working_duration
869
    (start_date && due_date) ? working_days(start_date, due_date) : 0
870
  end
871

  
872
  def soonest_start(reload=false)
873
    @soonest_start = nil if reload
874
    @soonest_start ||= (
875
        relations_to(reload).collect{|relation| relation.successor_soonest_start} +
876
        ancestors.collect(&:soonest_start)
877
      ).compact.max
878
  end
879

  
880
  # Sets start_date on the given date or the next working day
881
  # and changes due_date to keep the same working duration.
882
  def reschedule_on(date)
883
    wd = working_duration
884
    date = next_working_date(date)
885
    self.start_date = date
886
    self.due_date = add_working_days(date, wd)
887
  end
888

  
889
  # Reschedules the issue on the given date or the next working day and saves the record.
890
  # If the issue is a parent task, this is done by rescheduling its subtasks.
891
  def reschedule_on!(date)
892
    return if date.nil?
893
    if leaf?
894
      if start_date.nil? || start_date != date
895
        if start_date && start_date > date
896
          # Issue can not be moved earlier than its soonest start date
897
          date = [soonest_start(true), date].compact.max
898
        end
899
        reschedule_on(date)
900
        begin
901
          save
902
        rescue ActiveRecord::StaleObjectError
903
          reload
904
          reschedule_on(date)
905
          save
906
        end
907
      end
908
    else
909
      leaves.each do |leaf|
910
        if leaf.start_date
911
          # Only move subtask if it starts at the same date as the parent
912
          # or if it starts before the given date
913
          if start_date == leaf.start_date || date > leaf.start_date 
914
            leaf.reschedule_on!(date)
915
          end
916
        else
917
          leaf.reschedule_on!(date)
918
        end
919
      end
920
    end
921
  end
922

  
923
  def <=>(issue)
924
    if issue.nil?
925
      -1
926
    elsif root_id != issue.root_id
927
      (root_id || 0) <=> (issue.root_id || 0)
928
    else
929
      (lft || 0) <=> (issue.lft || 0)
930
    end
931
  end
932

  
933
  def to_s
934
    "#{tracker} ##{id}: #{subject}"
935
  end
936

  
937
  # Returns a string of css classes that apply to the issue
938
  def css_classes
939
    s = "issue status-#{status_id} #{priority.try(:css_classes)}"
940
    s << ' closed' if closed?
941
    s << ' overdue' if overdue?
942
    s << ' child' if child?
943
    s << ' parent' unless leaf?
944
    s << ' private' if is_private?
945
    s << ' created-by-me' if User.current.logged? && author_id == User.current.id
946
    s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
947
    s
948
  end
949

  
950
  # Saves an issue and a time_entry from the parameters
951
  def save_issue_with_child_records(params, existing_time_entry=nil)
952
    Issue.transaction do
953
      if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
954
        @time_entry = existing_time_entry || TimeEntry.new
955
        @time_entry.project = project
956
        @time_entry.issue = self
957
        @time_entry.user = User.current
958
        @time_entry.spent_on = User.current.today
959
        @time_entry.attributes = params[:time_entry]
960
        self.time_entries << @time_entry
961
      end
962

  
963
      # TODO: Rename hook
964
      Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
965
      if save
966
        # TODO: Rename hook
967
        Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
968
      else
969
        raise ActiveRecord::Rollback
970
      end
971
    end
972
  end
973

  
974
  # Unassigns issues from +version+ if it's no longer shared with issue's project
975
  def self.update_versions_from_sharing_change(version)
976
    # Update issues assigned to the version
977
    update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
978
  end
979

  
980
  # Unassigns issues from versions that are no longer shared
981
  # after +project+ was moved
982
  def self.update_versions_from_hierarchy_change(project)
983
    moved_project_ids = project.self_and_descendants.reload.collect(&:id)
984
    # Update issues of the moved projects and issues assigned to a version of a moved project
985
    Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
986
  end
987

  
988
  def parent_issue_id=(arg)
989
    s = arg.to_s.strip.presence
990
    if s && (m = s.match(%r{\A#?(\d+)\z})) && (@parent_issue = Issue.find_by_id(m[1]))
991
      @parent_issue.id
992
    else
993
      @parent_issue = nil
994
      @invalid_parent_issue_id = arg
995
    end
996
  end
997

  
998
  def parent_issue_id
999
    if @invalid_parent_issue_id
1000
      @invalid_parent_issue_id
1001
    elsif instance_variable_defined? :@parent_issue
1002
      @parent_issue.nil? ? nil : @parent_issue.id
1003
    else
1004
      parent_id
1005
    end
1006
  end
1007

  
1008
	# Returns true if issue's project is a valid
1009
	# parent issue project
1010
  def valid_parent_project?(issue=parent)
1011
    return true if issue.nil? || issue.project_id == project_id
1012

  
1013
    case Setting.cross_project_subtasks
1014
    when 'system'
1015
      true
1016
    when 'tree'
1017
      issue.project.root == project.root
1018
    when 'hierarchy'
1019
      issue.project.is_or_is_ancestor_of?(project) || issue.project.is_descendant_of?(project)
1020
    when 'descendants'
1021
      issue.project.is_or_is_ancestor_of?(project)
1022
    else
1023
      false
1024
    end
1025
  end
1026

  
1027
  # Extracted from the ReportsController.
1028
  def self.by_tracker(project)
1029
    count_and_group_by(:project => project,
1030
                       :field => 'tracker_id',
1031
                       :joins => Tracker.table_name)
1032
  end
1033

  
1034
  def self.by_version(project)
1035
    count_and_group_by(:project => project,
1036
                       :field => 'fixed_version_id',
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff