You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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. class Issue < ActiveRecord::Base
  18. include Redmine::SafeAttributes
  19. belongs_to :project
  20. belongs_to :tracker
  21. belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
  22. belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
  23. belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
  24. belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
  25. belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
  26. belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
  27. has_many :journals, :as => :journalized, :dependent => :destroy
  28. has_many :time_entries, :dependent => :delete_all
  29. has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
  30. has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
  31. has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
  32. acts_as_nested_set :scope => 'root_id', :dependent => :destroy
  33. acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
  34. acts_as_customizable
  35. acts_as_watchable
  36. acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
  37. :include => [:project, :journals],
  38. # sort by id so that limited eager loading doesn't break with postgresql
  39. :order_column => "#{table_name}.id"
  40. acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
  41. :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
  42. :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
  43. acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
  44. :author_key => :author_id
  45. DONE_RATIO_OPTIONS = %w(issue_field issue_status)
  46. attr_reader :current_journal
  47. validates_presence_of :subject, :priority, :project, :tracker, :author, :status
  48. validates_length_of :subject, :maximum => 255
  49. validates_inclusion_of :done_ratio, :in => 0..100
  50. validates_numericality_of :estimated_hours, :allow_nil => true
  51. validate :validate_issue
  52. scope :visible,
  53. lambda {|*args| { :include => :project,
  54. :conditions => Issue.visible_condition(args.shift || User.current, *args) } }
  55. scope :open, lambda {|*args|
  56. is_closed = args.size > 0 ? !args.first : false
  57. {:conditions => ["#{IssueStatus.table_name}.is_closed = ?", is_closed], :include => :status}
  58. }
  59. scope :recently_updated, :order => "#{Issue.table_name}.updated_on DESC"
  60. scope :with_limit, lambda { |limit| { :limit => limit} }
  61. scope :on_active_project, :include => [:status, :project, :tracker],
  62. :conditions => ["#{Project.table_name}.status=#{Project::STATUS_ACTIVE}"]
  63. before_create :default_assign
  64. before_save :close_duplicates, :update_done_ratio_from_issue_status
  65. after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?}
  66. after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
  67. after_destroy :update_parent_attributes
  68. # Returns a SQL conditions string used to find all issues visible by the specified user
  69. def self.visible_condition(user, options={})
  70. Project.allowed_to_condition(user, :view_issues, options) do |role, user|
  71. case role.issues_visibility
  72. when 'all'
  73. nil
  74. when 'default'
  75. user_ids = [user.id] + user.groups.map(&:id)
  76. "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
  77. when 'own'
  78. user_ids = [user.id] + user.groups.map(&:id)
  79. "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
  80. else
  81. '1=0'
  82. end
  83. end
  84. end
  85. # Returns true if usr or current user is allowed to view the issue
  86. def visible?(usr=nil)
  87. (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
  88. case role.issues_visibility
  89. when 'all'
  90. true
  91. when 'default'
  92. !self.is_private? || self.author == user || user.is_or_belongs_to?(assigned_to)
  93. when 'own'
  94. self.author == user || user.is_or_belongs_to?(assigned_to)
  95. else
  96. false
  97. end
  98. end
  99. end
  100. def initialize(attributes=nil, *args)
  101. super
  102. if new_record?
  103. # set default values for new records only
  104. self.status ||= IssueStatus.default
  105. self.priority ||= IssuePriority.default
  106. self.watcher_user_ids = []
  107. end
  108. end
  109. # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
  110. def available_custom_fields
  111. (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
  112. end
  113. # Copies attributes from another issue, arg can be an id or an Issue
  114. def copy_from(arg, options={})
  115. issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
  116. self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
  117. self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
  118. self.status = issue.status
  119. self.author = User.current
  120. unless options[:attachments] == false
  121. self.attachments = issue.attachments.map do |attachement|
  122. attachement.copy(:container => self)
  123. end
  124. end
  125. @copied_from = issue
  126. self
  127. end
  128. # Returns an unsaved copy of the issue
  129. def copy(attributes=nil, copy_options={})
  130. copy = self.class.new.copy_from(self, copy_options)
  131. copy.attributes = attributes if attributes
  132. copy
  133. end
  134. # Returns true if the issue is a copy
  135. def copy?
  136. @copied_from.present?
  137. end
  138. # Moves/copies an issue to a new project and tracker
  139. # Returns the moved/copied issue on success, false on failure
  140. def move_to_project(new_project, new_tracker=nil, options={})
  141. ActiveSupport::Deprecation.warn "Issue#move_to_project is deprecated, use #project= instead."
  142. if options[:copy]
  143. issue = self.copy
  144. else
  145. issue = self
  146. end
  147. issue.init_journal(User.current, options[:notes])
  148. # Preserve previous behaviour
  149. # #move_to_project doesn't change tracker automatically
  150. issue.send :project=, new_project, true
  151. if new_tracker
  152. issue.tracker = new_tracker
  153. end
  154. # Allow bulk setting of attributes on the issue
  155. if options[:attributes]
  156. issue.attributes = options[:attributes]
  157. end
  158. issue.save ? issue : false
  159. end
  160. def status_id=(sid)
  161. self.status = nil
  162. write_attribute(:status_id, sid)
  163. end
  164. def priority_id=(pid)
  165. self.priority = nil
  166. write_attribute(:priority_id, pid)
  167. end
  168. def category_id=(cid)
  169. self.category = nil
  170. write_attribute(:category_id, cid)
  171. end
  172. def fixed_version_id=(vid)
  173. self.fixed_version = nil
  174. write_attribute(:fixed_version_id, vid)
  175. end
  176. def tracker_id=(tid)
  177. self.tracker = nil
  178. result = write_attribute(:tracker_id, tid)
  179. @custom_field_values = nil
  180. result
  181. end
  182. def project_id=(project_id)
  183. if project_id.to_s != self.project_id.to_s
  184. self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
  185. end
  186. end
  187. def project=(project, keep_tracker=false)
  188. project_was = self.project
  189. write_attribute(:project_id, project ? project.id : nil)
  190. association_instance_set('project', project)
  191. if project_was && project && project_was != project
  192. unless keep_tracker || project.trackers.include?(tracker)
  193. self.tracker = project.trackers.first
  194. end
  195. # Reassign to the category with same name if any
  196. if category
  197. self.category = project.issue_categories.find_by_name(category.name)
  198. end
  199. # Keep the fixed_version if it's still valid in the new_project
  200. if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
  201. self.fixed_version = nil
  202. end
  203. if parent && parent.project_id != project_id
  204. self.parent_issue_id = nil
  205. end
  206. @custom_field_values = nil
  207. end
  208. end
  209. def description=(arg)
  210. if arg.is_a?(String)
  211. arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
  212. end
  213. write_attribute(:description, arg)
  214. end
  215. # Overrides assign_attributes so that project and tracker get assigned first
  216. def assign_attributes_with_project_and_tracker_first(new_attributes, *args)
  217. return if new_attributes.nil?
  218. attrs = new_attributes.dup
  219. attrs.stringify_keys!
  220. %w(project project_id tracker tracker_id).each do |attr|
  221. if attrs.has_key?(attr)
  222. send "#{attr}=", attrs.delete(attr)
  223. end
  224. end
  225. send :assign_attributes_without_project_and_tracker_first, attrs, *args
  226. end
  227. # Do not redefine alias chain on reload (see #4838)
  228. alias_method_chain(:assign_attributes, :project_and_tracker_first) unless method_defined?(:assign_attributes_without_project_and_tracker_first)
  229. def estimated_hours=(h)
  230. write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
  231. end
  232. safe_attributes 'project_id',
  233. :if => lambda {|issue, user|
  234. if issue.new_record?
  235. issue.copy?
  236. elsif user.allowed_to?(:move_issues, issue.project)
  237. projects = Issue.allowed_target_projects_on_move(user)
  238. projects.include?(issue.project) && projects.size > 1
  239. end
  240. }
  241. safe_attributes 'tracker_id',
  242. 'status_id',
  243. 'category_id',
  244. 'assigned_to_id',
  245. 'priority_id',
  246. 'fixed_version_id',
  247. 'subject',
  248. 'description',
  249. 'start_date',
  250. 'due_date',
  251. 'done_ratio',
  252. 'estimated_hours',
  253. 'custom_field_values',
  254. 'custom_fields',
  255. 'lock_version',
  256. :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
  257. safe_attributes 'status_id',
  258. 'assigned_to_id',
  259. 'fixed_version_id',
  260. 'done_ratio',
  261. 'lock_version',
  262. :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
  263. safe_attributes 'watcher_user_ids',
  264. :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
  265. safe_attributes 'is_private',
  266. :if => lambda {|issue, user|
  267. user.allowed_to?(:set_issues_private, issue.project) ||
  268. (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
  269. }
  270. safe_attributes 'parent_issue_id',
  271. :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
  272. user.allowed_to?(:manage_subtasks, issue.project)}
  273. # Safely sets attributes
  274. # Should be called from controllers instead of #attributes=
  275. # attr_accessible is too rough because we still want things like
  276. # Issue.new(:project => foo) to work
  277. def safe_attributes=(attrs, user=User.current)
  278. return unless attrs.is_a?(Hash)
  279. # User can change issue attributes only if he has :edit permission or if a workflow transition is allowed
  280. attrs = delete_unsafe_attributes(attrs, user)
  281. return if attrs.empty?
  282. # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
  283. if p = attrs.delete('project_id')
  284. if allowed_target_projects(user).collect(&:id).include?(p.to_i)
  285. self.project_id = p
  286. end
  287. end
  288. if t = attrs.delete('tracker_id')
  289. self.tracker_id = t
  290. end
  291. if attrs['status_id']
  292. unless new_statuses_allowed_to(user).collect(&:id).include?(attrs['status_id'].to_i)
  293. attrs.delete('status_id')
  294. end
  295. end
  296. unless leaf?
  297. attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
  298. end
  299. if attrs['parent_issue_id'].present?
  300. attrs.delete('parent_issue_id') unless Issue.visible(user).exists?(attrs['parent_issue_id'].to_i)
  301. end
  302. # mass-assignment security bypass
  303. assign_attributes attrs, :without_protection => true
  304. end
  305. def done_ratio
  306. if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
  307. status.default_done_ratio
  308. else
  309. read_attribute(:done_ratio)
  310. end
  311. end
  312. def self.use_status_for_done_ratio?
  313. Setting.issue_done_ratio == 'issue_status'
  314. end
  315. def self.use_field_for_done_ratio?
  316. Setting.issue_done_ratio == 'issue_field'
  317. end
  318. def validate_issue
  319. if self.due_date.nil? && @attributes['due_date'] && !@attributes['due_date'].empty?
  320. errors.add :due_date, :not_a_date
  321. end
  322. if self.due_date and self.start_date and self.due_date < self.start_date
  323. errors.add :due_date, :greater_than_start_date
  324. end
  325. if start_date && soonest_start && start_date < soonest_start
  326. errors.add :start_date, :invalid
  327. end
  328. if fixed_version
  329. if !assignable_versions.include?(fixed_version)
  330. errors.add :fixed_version_id, :inclusion
  331. elsif reopened? && fixed_version.closed?
  332. errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
  333. end
  334. end
  335. # Checks that the issue can not be added/moved to a disabled tracker
  336. if project && (tracker_id_changed? || project_id_changed?)
  337. unless project.trackers.include?(tracker)
  338. errors.add :tracker_id, :inclusion
  339. end
  340. end
  341. # Checks parent issue assignment
  342. if @parent_issue
  343. if @parent_issue.project_id != project_id
  344. errors.add :parent_issue_id, :not_same_project
  345. elsif !new_record?
  346. # moving an existing issue
  347. if @parent_issue.root_id != root_id
  348. # we can always move to another tree
  349. elsif move_possible?(@parent_issue)
  350. # move accepted inside tree
  351. else
  352. errors.add :parent_issue_id, :not_a_valid_parent
  353. end
  354. end
  355. end
  356. end
  357. # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
  358. # even if the user turns off the setting later
  359. def update_done_ratio_from_issue_status
  360. if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
  361. self.done_ratio = status.default_done_ratio
  362. end
  363. end
  364. def init_journal(user, notes = "")
  365. @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
  366. if new_record?
  367. @current_journal.notify = false
  368. else
  369. @attributes_before_change = attributes.dup
  370. @custom_values_before_change = {}
  371. self.custom_field_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
  372. end
  373. # Make sure updated_on is updated when adding a note.
  374. updated_on_will_change!
  375. @current_journal
  376. end
  377. # Returns the id of the last journal or nil
  378. def last_journal_id
  379. if new_record?
  380. nil
  381. else
  382. journals.first(:order => "#{Journal.table_name}.id DESC").try(:id)
  383. end
  384. end
  385. # Return true if the issue is closed, otherwise false
  386. def closed?
  387. self.status.is_closed?
  388. end
  389. # Return true if the issue is being reopened
  390. def reopened?
  391. if !new_record? && status_id_changed?
  392. status_was = IssueStatus.find_by_id(status_id_was)
  393. status_new = IssueStatus.find_by_id(status_id)
  394. if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
  395. return true
  396. end
  397. end
  398. false
  399. end
  400. # Return true if the issue is being closed
  401. def closing?
  402. if !new_record? && status_id_changed?
  403. status_was = IssueStatus.find_by_id(status_id_was)
  404. status_new = IssueStatus.find_by_id(status_id)
  405. if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
  406. return true
  407. end
  408. end
  409. false
  410. end
  411. # Returns true if the issue is overdue
  412. def overdue?
  413. !due_date.nil? && (due_date < Date.today) && !status.is_closed?
  414. end
  415. # Is the amount of work done less than it should for the due date
  416. def behind_schedule?
  417. return false if start_date.nil? || due_date.nil?
  418. done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
  419. return done_date <= Date.today
  420. end
  421. # Does this issue have children?
  422. def children?
  423. !leaf?
  424. end
  425. # Users the issue can be assigned to
  426. def assignable_users
  427. users = project.assignable_users
  428. users << author if author
  429. users << assigned_to if assigned_to
  430. users.uniq.sort
  431. end
  432. # Versions that the issue can be assigned to
  433. def assignable_versions
  434. @assignable_versions ||= (project.shared_versions.open + [Version.find_by_id(fixed_version_id_was)]).compact.uniq.sort
  435. end
  436. # Returns true if this issue is blocked by another issue that is still open
  437. def blocked?
  438. !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
  439. end
  440. # Returns an array of statuses that user is able to apply
  441. def new_statuses_allowed_to(user=User.current, include_default=false)
  442. if new_record? && @copied_from
  443. [IssueStatus.default, @copied_from.status].compact.uniq.sort
  444. else
  445. initial_status = nil
  446. if new_record?
  447. initial_status = IssueStatus.default
  448. elsif status_id_was
  449. initial_status = IssueStatus.find_by_id(status_id_was)
  450. end
  451. initial_status ||= status
  452. statuses = initial_status.find_new_statuses_allowed_to(
  453. user.admin ? Role.all : user.roles_for_project(project),
  454. tracker,
  455. author == user,
  456. assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
  457. )
  458. statuses << initial_status unless statuses.empty?
  459. statuses << IssueStatus.default if include_default
  460. statuses = statuses.compact.uniq.sort
  461. blocked? ? statuses.reject {|s| s.is_closed?} : statuses
  462. end
  463. end
  464. def assigned_to_was
  465. if assigned_to_id_changed? && assigned_to_id_was.present?
  466. @assigned_to_was ||= User.find_by_id(assigned_to_id_was)
  467. end
  468. end
  469. # Returns the mail adresses of users that should be notified
  470. def recipients
  471. notified = []
  472. # Author and assignee are always notified unless they have been
  473. # locked or don't want to be notified
  474. notified << author if author
  475. if assigned_to
  476. notified += (assigned_to.is_a?(Group) ? assigned_to.users : [assigned_to])
  477. end
  478. if assigned_to_was
  479. notified += (assigned_to_was.is_a?(Group) ? assigned_to_was.users : [assigned_to_was])
  480. end
  481. notified = notified.select {|u| u.active? && u.notify_about?(self)}
  482. notified += project.notified_users
  483. notified.uniq!
  484. # Remove users that can not view the issue
  485. notified.reject! {|user| !visible?(user)}
  486. notified.collect(&:mail)
  487. end
  488. # Returns the number of hours spent on this issue
  489. def spent_hours
  490. @spent_hours ||= time_entries.sum(:hours) || 0
  491. end
  492. # Returns the total number of hours spent on this issue and its descendants
  493. #
  494. # Example:
  495. # spent_hours => 0.0
  496. # spent_hours => 50.2
  497. def total_spent_hours
  498. @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
  499. :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
  500. end
  501. def relations
  502. @relations ||= (relations_from + relations_to).sort
  503. end
  504. # Preloads relations for a collection of issues
  505. def self.load_relations(issues)
  506. if issues.any?
  507. relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
  508. issues.each do |issue|
  509. issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
  510. end
  511. end
  512. end
  513. # Preloads visible spent time for a collection of issues
  514. def self.load_visible_spent_hours(issues, user=User.current)
  515. if issues.any?
  516. hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
  517. issues.each do |issue|
  518. issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
  519. end
  520. end
  521. end
  522. # Finds an issue relation given its id.
  523. def find_relation(relation_id)
  524. IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
  525. end
  526. def all_dependent_issues(except=[])
  527. except << self
  528. dependencies = []
  529. relations_from.each do |relation|
  530. if relation.issue_to && !except.include?(relation.issue_to)
  531. dependencies << relation.issue_to
  532. dependencies += relation.issue_to.all_dependent_issues(except)
  533. end
  534. end
  535. dependencies
  536. end
  537. # Returns an array of issues that duplicate this one
  538. def duplicates
  539. relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
  540. end
  541. # Returns the due date or the target due date if any
  542. # Used on gantt chart
  543. def due_before
  544. due_date || (fixed_version ? fixed_version.effective_date : nil)
  545. end
  546. # Returns the time scheduled for this issue.
  547. #
  548. # Example:
  549. # Start Date: 2/26/09, End Date: 3/04/09
  550. # duration => 6
  551. def duration
  552. (start_date && due_date) ? due_date - start_date : 0
  553. end
  554. def soonest_start
  555. @soonest_start ||= (
  556. relations_to.collect{|relation| relation.successor_soonest_start} +
  557. ancestors.collect(&:soonest_start)
  558. ).compact.max
  559. end
  560. def reschedule_after(date)
  561. return if date.nil?
  562. if leaf?
  563. if start_date.nil? || start_date < date
  564. self.start_date, self.due_date = date, date + duration
  565. begin
  566. save
  567. rescue ActiveRecord::StaleObjectError
  568. reload
  569. self.start_date, self.due_date = date, date + duration
  570. save
  571. end
  572. end
  573. else
  574. leaves.each do |leaf|
  575. leaf.reschedule_after(date)
  576. end
  577. end
  578. end
  579. def <=>(issue)
  580. if issue.nil?
  581. -1
  582. elsif root_id != issue.root_id
  583. (root_id || 0) <=> (issue.root_id || 0)
  584. else
  585. (lft || 0) <=> (issue.lft || 0)
  586. end
  587. end
  588. def to_s
  589. "#{tracker} ##{id}: #{subject}"
  590. end
  591. # Returns a string of css classes that apply to the issue
  592. def css_classes
  593. s = "issue status-#{status.position} priority-#{priority.position}"
  594. s << ' closed' if closed?
  595. s << ' overdue' if overdue?
  596. s << ' child' if child?
  597. s << ' parent' unless leaf?
  598. s << ' private' if is_private?
  599. s << ' created-by-me' if User.current.logged? && author_id == User.current.id
  600. s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
  601. s
  602. end
  603. # Saves an issue and a time_entry from the parameters
  604. def save_issue_with_child_records(params, existing_time_entry=nil)
  605. Issue.transaction do
  606. if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
  607. @time_entry = existing_time_entry || TimeEntry.new
  608. @time_entry.project = project
  609. @time_entry.issue = self
  610. @time_entry.user = User.current
  611. @time_entry.spent_on = User.current.today
  612. @time_entry.attributes = params[:time_entry]
  613. self.time_entries << @time_entry
  614. end
  615. # TODO: Rename hook
  616. Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
  617. if save
  618. # TODO: Rename hook
  619. Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
  620. else
  621. raise ActiveRecord::Rollback
  622. end
  623. end
  624. end
  625. # Unassigns issues from +version+ if it's no longer shared with issue's project
  626. def self.update_versions_from_sharing_change(version)
  627. # Update issues assigned to the version
  628. update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
  629. end
  630. # Unassigns issues from versions that are no longer shared
  631. # after +project+ was moved
  632. def self.update_versions_from_hierarchy_change(project)
  633. moved_project_ids = project.self_and_descendants.reload.collect(&:id)
  634. # Update issues of the moved projects and issues assigned to a version of a moved project
  635. Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
  636. end
  637. def parent_issue_id=(arg)
  638. parent_issue_id = arg.blank? ? nil : arg.to_i
  639. if parent_issue_id && @parent_issue = Issue.find_by_id(parent_issue_id)
  640. @parent_issue.id
  641. else
  642. @parent_issue = nil
  643. nil
  644. end
  645. end
  646. def parent_issue_id
  647. if instance_variable_defined? :@parent_issue
  648. @parent_issue.nil? ? nil : @parent_issue.id
  649. else
  650. parent_id
  651. end
  652. end
  653. # Extracted from the ReportsController.
  654. def self.by_tracker(project)
  655. count_and_group_by(:project => project,
  656. :field => 'tracker_id',
  657. :joins => Tracker.table_name)
  658. end
  659. def self.by_version(project)
  660. count_and_group_by(:project => project,
  661. :field => 'fixed_version_id',
  662. :joins => Version.table_name)
  663. end
  664. def self.by_priority(project)
  665. count_and_group_by(:project => project,
  666. :field => 'priority_id',
  667. :joins => IssuePriority.table_name)
  668. end
  669. def self.by_category(project)
  670. count_and_group_by(:project => project,
  671. :field => 'category_id',
  672. :joins => IssueCategory.table_name)
  673. end
  674. def self.by_assigned_to(project)
  675. count_and_group_by(:project => project,
  676. :field => 'assigned_to_id',
  677. :joins => User.table_name)
  678. end
  679. def self.by_author(project)
  680. count_and_group_by(:project => project,
  681. :field => 'author_id',
  682. :joins => User.table_name)
  683. end
  684. def self.by_subproject(project)
  685. ActiveRecord::Base.connection.select_all("select s.id as status_id,
  686. s.is_closed as closed,
  687. #{Issue.table_name}.project_id as project_id,
  688. count(#{Issue.table_name}.id) as total
  689. from
  690. #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
  691. where
  692. #{Issue.table_name}.status_id=s.id
  693. and #{Issue.table_name}.project_id = #{Project.table_name}.id
  694. and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
  695. and #{Issue.table_name}.project_id <> #{project.id}
  696. group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
  697. end
  698. # End ReportsController extraction
  699. # Returns an array of projects that user can assign the issue to
  700. def allowed_target_projects(user=User.current)
  701. if new_record?
  702. Project.all(:conditions => Project.allowed_to_condition(user, :add_issues))
  703. else
  704. self.class.allowed_target_projects_on_move(user)
  705. end
  706. end
  707. # Returns an array of projects that user can move issues to
  708. def self.allowed_target_projects_on_move(user=User.current)
  709. Project.all(:conditions => Project.allowed_to_condition(user, :move_issues))
  710. end
  711. private
  712. def after_project_change
  713. # Update project_id on related time entries
  714. TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
  715. # Delete issue relations
  716. unless Setting.cross_project_issue_relations?
  717. relations_from.clear
  718. relations_to.clear
  719. end
  720. # Move subtasks
  721. children.each do |child|
  722. # Change project and keep project
  723. child.send :project=, project, true
  724. unless child.save
  725. raise ActiveRecord::Rollback
  726. end
  727. end
  728. end
  729. def update_nested_set_attributes
  730. if root_id.nil?
  731. # issue was just created
  732. self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
  733. set_default_left_and_right
  734. Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
  735. if @parent_issue
  736. move_to_child_of(@parent_issue)
  737. end
  738. reload
  739. elsif parent_issue_id != parent_id
  740. former_parent_id = parent_id
  741. # moving an existing issue
  742. if @parent_issue && @parent_issue.root_id == root_id
  743. # inside the same tree
  744. move_to_child_of(@parent_issue)
  745. else
  746. # to another tree
  747. unless root?
  748. move_to_right_of(root)
  749. reload
  750. end
  751. old_root_id = root_id
  752. self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
  753. target_maxright = nested_set_scope.maximum(right_column_name) || 0
  754. offset = target_maxright + 1 - lft
  755. Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
  756. ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
  757. self[left_column_name] = lft + offset
  758. self[right_column_name] = rgt + offset
  759. if @parent_issue
  760. move_to_child_of(@parent_issue)
  761. end
  762. end
  763. reload
  764. # delete invalid relations of all descendants
  765. self_and_descendants.each do |issue|
  766. issue.relations.each do |relation|
  767. relation.destroy unless relation.valid?
  768. end
  769. end
  770. # update former parent
  771. recalculate_attributes_for(former_parent_id) if former_parent_id
  772. end
  773. remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
  774. end
  775. def update_parent_attributes
  776. recalculate_attributes_for(parent_id) if parent_id
  777. end
  778. def recalculate_attributes_for(issue_id)
  779. if issue_id && p = Issue.find_by_id(issue_id)
  780. # priority = highest priority of children
  781. if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
  782. p.priority = IssuePriority.find_by_position(priority_position)
  783. end
  784. # start/due dates = lowest/highest dates of children
  785. p.start_date = p.children.minimum(:start_date)
  786. p.due_date = p.children.maximum(:due_date)
  787. if p.start_date && p.due_date && p.due_date < p.start_date
  788. p.start_date, p.due_date = p.due_date, p.start_date
  789. end
  790. # done ratio = weighted average ratio of leaves
  791. unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
  792. leaves_count = p.leaves.count
  793. if leaves_count > 0
  794. average = p.leaves.average(:estimated_hours).to_f
  795. if average == 0
  796. average = 1
  797. end
  798. done = p.leaves.sum("COALESCE(estimated_hours, #{average}) * (CASE WHEN is_closed = #{connection.quoted_true} THEN 100 ELSE COALESCE(done_ratio, 0) END)", :joins => :status).to_f
  799. progress = done / (average * leaves_count)
  800. p.done_ratio = progress.round
  801. end
  802. end
  803. # estimate = sum of leaves estimates
  804. p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
  805. p.estimated_hours = nil if p.estimated_hours == 0.0
  806. # ancestors will be recursively updated
  807. p.save(:validate => false)
  808. end
  809. end
  810. # Update issues so their versions are not pointing to a
  811. # fixed_version that is not shared with the issue's project
  812. def self.update_versions(conditions=nil)
  813. # Only need to update issues with a fixed_version from
  814. # a different project and that is not systemwide shared
  815. Issue.scoped(:conditions => conditions).all(
  816. :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
  817. " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
  818. " AND #{Version.table_name}.sharing <> 'system'",
  819. :include => [:project, :fixed_version]
  820. ).each do |issue|
  821. next if issue.project.nil? || issue.fixed_version.nil?
  822. unless issue.project.shared_versions.include?(issue.fixed_version)
  823. issue.init_journal(User.current)
  824. issue.fixed_version = nil
  825. issue.save
  826. end
  827. end
  828. end
  829. # Callback on attachment deletion
  830. def attachment_added(obj)
  831. if @current_journal && !obj.new_record?
  832. @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
  833. end
  834. end
  835. # Callback on attachment deletion
  836. def attachment_removed(obj)
  837. if @current_journal && !obj.new_record?
  838. @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :old_value => obj.filename)
  839. @current_journal.save
  840. end
  841. end
  842. # Default assignment based on category
  843. def default_assign
  844. if assigned_to.nil? && category && category.assigned_to
  845. self.assigned_to = category.assigned_to
  846. end
  847. end
  848. # Updates start/due dates of following issues
  849. def reschedule_following_issues
  850. if start_date_changed? || due_date_changed?
  851. relations_from.each do |relation|
  852. relation.set_issue_to_dates
  853. end
  854. end
  855. end
  856. # Closes duplicates if the issue is being closed
  857. def close_duplicates
  858. if closing?
  859. duplicates.each do |duplicate|
  860. # Reload is need in case the duplicate was updated by a previous duplicate
  861. duplicate.reload
  862. # Don't re-close it if it's already closed
  863. next if duplicate.closed?
  864. # Same user and notes
  865. if @current_journal
  866. duplicate.init_journal(@current_journal.user, @current_journal.notes)
  867. end
  868. duplicate.update_attribute :status, self.status
  869. end
  870. end
  871. end
  872. # Saves the changes in a Journal
  873. # Called after_save
  874. def create_journal
  875. if @current_journal
  876. # attributes changes
  877. if @attributes_before_change
  878. (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
  879. before = @attributes_before_change[c]
  880. after = send(c)
  881. next if before == after || (before.blank? && after.blank?)
  882. @current_journal.details << JournalDetail.new(:property => 'attr',
  883. :prop_key => c,
  884. :old_value => before,
  885. :value => after)
  886. }
  887. end
  888. if @custom_values_before_change
  889. # custom fields changes
  890. custom_field_values.each {|c|
  891. before = @custom_values_before_change[c.custom_field_id]
  892. after = c.value
  893. next if before == after || (before.blank? && after.blank?)
  894. if before.is_a?(Array) || after.is_a?(Array)
  895. before = [before] unless before.is_a?(Array)
  896. after = [after] unless after.is_a?(Array)
  897. # values removed
  898. (before - after).reject(&:blank?).each do |value|
  899. @current_journal.details << JournalDetail.new(:property => 'cf',
  900. :prop_key => c.custom_field_id,
  901. :old_value => value,
  902. :value => nil)
  903. end
  904. # values added
  905. (after - before).reject(&:blank?).each do |value|
  906. @current_journal.details << JournalDetail.new(:property => 'cf',
  907. :prop_key => c.custom_field_id,
  908. :old_value => nil,
  909. :value => value)
  910. end
  911. else
  912. @current_journal.details << JournalDetail.new(:property => 'cf',
  913. :prop_key => c.custom_field_id,
  914. :old_value => before,
  915. :value => after)
  916. end
  917. }
  918. end
  919. @current_journal.save
  920. # reset current journal
  921. init_journal @current_journal.user, @current_journal.notes
  922. end
  923. end
  924. # Query generator for selecting groups of issue counts for a project
  925. # based on specific criteria
  926. #
  927. # Options
  928. # * project - Project to search in.
  929. # * field - String. Issue field to key off of in the grouping.
  930. # * joins - String. The table name to join against.
  931. def self.count_and_group_by(options)
  932. project = options.delete(:project)
  933. select_field = options.delete(:field)
  934. joins = options.delete(:joins)
  935. where = "#{Issue.table_name}.#{select_field}=j.id"
  936. ActiveRecord::Base.connection.select_all("select s.id as status_id,
  937. s.is_closed as closed,
  938. j.id as #{select_field},
  939. count(#{Issue.table_name}.id) as total
  940. from
  941. #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
  942. where
  943. #{Issue.table_name}.status_id=s.id
  944. and #{where}
  945. and #{Issue.table_name}.project_id=#{Project.table_name}.id
  946. and #{visible_condition(User.current, :project => project)}
  947. group by s.id, s.is_closed, j.id")
  948. end
  949. end