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.

issue.rb 49KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. # Redmine - project management software
  2. # Copyright (C) 2006-2013 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. include Redmine::Utils::DateCalculation
  20. belongs_to :project
  21. belongs_to :tracker
  22. belongs_to :status, :class_name => 'IssueStatus', :foreign_key => 'status_id'
  23. belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
  24. belongs_to :assigned_to, :class_name => 'Principal', :foreign_key => 'assigned_to_id'
  25. belongs_to :fixed_version, :class_name => 'Version', :foreign_key => 'fixed_version_id'
  26. belongs_to :priority, :class_name => 'IssuePriority', :foreign_key => 'priority_id'
  27. belongs_to :category, :class_name => 'IssueCategory', :foreign_key => 'category_id'
  28. has_many :journals, :as => :journalized, :dependent => :destroy
  29. has_many :visible_journals,
  30. :class_name => 'Journal',
  31. :as => :journalized,
  32. :conditions => Proc.new {
  33. ["(#{Journal.table_name}.private_notes = ? OR (#{Project.allowed_to_condition(User.current, :view_private_notes)}))", false]
  34. },
  35. :readonly => true
  36. has_many :time_entries, :dependent => :delete_all
  37. has_and_belongs_to_many :changesets, :order => "#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC"
  38. has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
  39. has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
  40. acts_as_nested_set :scope => 'root_id', :dependent => :destroy
  41. acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
  42. acts_as_customizable
  43. acts_as_watchable
  44. acts_as_searchable :columns => ['subject', "#{table_name}.description", "#{Journal.table_name}.notes"],
  45. :include => [:project, :visible_journals],
  46. # sort by id so that limited eager loading doesn't break with postgresql
  47. :order_column => "#{table_name}.id"
  48. acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
  49. :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
  50. :type => Proc.new {|o| 'issue' + (o.closed? ? ' closed' : '') }
  51. acts_as_activity_provider :find_options => {:include => [:project, :author, :tracker]},
  52. :author_key => :author_id
  53. DONE_RATIO_OPTIONS = %w(issue_field issue_status)
  54. attr_reader :current_journal
  55. delegate :notes, :notes=, :private_notes, :private_notes=, :to => :current_journal, :allow_nil => true
  56. validates_presence_of :subject, :priority, :project, :tracker, :author, :status
  57. validates_length_of :subject, :maximum => 255
  58. validates_inclusion_of :done_ratio, :in => 0..100
  59. validates :estimated_hours, :numericality => {:greater_than_or_equal_to => 0, :allow_nil => true, :message => :invalid}
  60. validates :start_date, :date => true
  61. validates :due_date, :date => true
  62. validate :validate_issue, :validate_required_fields
  63. scope :visible, lambda {|*args|
  64. includes(:project).where(Issue.visible_condition(args.shift || User.current, *args))
  65. }
  66. scope :open, lambda {|*args|
  67. is_closed = args.size > 0 ? !args.first : false
  68. includes(:status).where("#{IssueStatus.table_name}.is_closed = ?", is_closed)
  69. }
  70. scope :recently_updated, lambda { order("#{Issue.table_name}.updated_on DESC") }
  71. scope :on_active_project, lambda {
  72. includes(:status, :project, :tracker).where("#{Project.table_name}.status = ?", Project::STATUS_ACTIVE)
  73. }
  74. scope :fixed_version, lambda {|versions|
  75. ids = [versions].flatten.compact.map {|v| v.is_a?(Version) ? v.id : v}
  76. ids.any? ? where(:fixed_version_id => ids) : where('1=0')
  77. }
  78. before_create :default_assign
  79. before_save :close_duplicates, :update_done_ratio_from_issue_status, :force_updated_on_change
  80. after_save {|issue| issue.send :after_project_change if !issue.id_changed? && issue.project_id_changed?}
  81. after_save :reschedule_following_issues, :update_nested_set_attributes, :update_parent_attributes, :create_journal
  82. # Should be after_create but would be called before previous after_save callbacks
  83. after_save :after_create_from_copy
  84. after_destroy :update_parent_attributes
  85. # Returns a SQL conditions string used to find all issues visible by the specified user
  86. def self.visible_condition(user, options={})
  87. Project.allowed_to_condition(user, :view_issues, options) do |role, user|
  88. if user.logged?
  89. case role.issues_visibility
  90. when 'all'
  91. nil
  92. when 'default'
  93. user_ids = [user.id] + user.groups.map(&:id)
  94. "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
  95. when 'own'
  96. user_ids = [user.id] + user.groups.map(&:id)
  97. "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
  98. else
  99. '1=0'
  100. end
  101. else
  102. "(#{table_name}.is_private = #{connection.quoted_false})"
  103. end
  104. end
  105. end
  106. # Returns true if usr or current user is allowed to view the issue
  107. def visible?(usr=nil)
  108. (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
  109. if user.logged?
  110. case role.issues_visibility
  111. when 'all'
  112. true
  113. when 'default'
  114. !self.is_private? || (self.author == user || user.is_or_belongs_to?(assigned_to))
  115. when 'own'
  116. self.author == user || user.is_or_belongs_to?(assigned_to)
  117. else
  118. false
  119. end
  120. else
  121. !self.is_private?
  122. end
  123. end
  124. end
  125. # Returns true if user or current user is allowed to edit or add a note to the issue
  126. def editable?(user=User.current)
  127. user.allowed_to?(:edit_issues, project) || user.allowed_to?(:add_issue_notes, project)
  128. end
  129. def initialize(attributes=nil, *args)
  130. super
  131. if new_record?
  132. # set default values for new records only
  133. self.status ||= IssueStatus.default
  134. self.priority ||= IssuePriority.default
  135. self.watcher_user_ids = []
  136. end
  137. end
  138. # AR#Persistence#destroy would raise and RecordNotFound exception
  139. # if the issue was already deleted or updated (non matching lock_version).
  140. # This is a problem when bulk deleting issues or deleting a project
  141. # (because an issue may already be deleted if its parent was deleted
  142. # first).
  143. # The issue is reloaded by the nested_set before being deleted so
  144. # the lock_version condition should not be an issue but we handle it.
  145. def destroy
  146. super
  147. rescue ActiveRecord::RecordNotFound
  148. # Stale or already deleted
  149. begin
  150. reload
  151. rescue ActiveRecord::RecordNotFound
  152. # The issue was actually already deleted
  153. @destroyed = true
  154. return freeze
  155. end
  156. # The issue was stale, retry to destroy
  157. super
  158. end
  159. def reload(*args)
  160. @workflow_rule_by_attribute = nil
  161. @assignable_versions = nil
  162. super
  163. end
  164. # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
  165. def available_custom_fields
  166. (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields.all) : []
  167. end
  168. # Copies attributes from another issue, arg can be an id or an Issue
  169. def copy_from(arg, options={})
  170. issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
  171. self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on")
  172. self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
  173. self.status = issue.status
  174. self.author = User.current
  175. unless options[:attachments] == false
  176. self.attachments = issue.attachments.map do |attachement|
  177. attachement.copy(:container => self)
  178. end
  179. end
  180. @copied_from = issue
  181. @copy_options = options
  182. self
  183. end
  184. # Returns an unsaved copy of the issue
  185. def copy(attributes=nil, copy_options={})
  186. copy = self.class.new.copy_from(self, copy_options)
  187. copy.attributes = attributes if attributes
  188. copy
  189. end
  190. # Returns true if the issue is a copy
  191. def copy?
  192. @copied_from.present?
  193. end
  194. # Moves/copies an issue to a new project and tracker
  195. # Returns the moved/copied issue on success, false on failure
  196. def move_to_project(new_project, new_tracker=nil, options={})
  197. ActiveSupport::Deprecation.warn "Issue#move_to_project is deprecated, use #project= instead."
  198. if options[:copy]
  199. issue = self.copy
  200. else
  201. issue = self
  202. end
  203. issue.init_journal(User.current, options[:notes])
  204. # Preserve previous behaviour
  205. # #move_to_project doesn't change tracker automatically
  206. issue.send :project=, new_project, true
  207. if new_tracker
  208. issue.tracker = new_tracker
  209. end
  210. # Allow bulk setting of attributes on the issue
  211. if options[:attributes]
  212. issue.attributes = options[:attributes]
  213. end
  214. issue.save ? issue : false
  215. end
  216. def status_id=(sid)
  217. self.status = nil
  218. result = write_attribute(:status_id, sid)
  219. @workflow_rule_by_attribute = nil
  220. result
  221. end
  222. def priority_id=(pid)
  223. self.priority = nil
  224. write_attribute(:priority_id, pid)
  225. end
  226. def category_id=(cid)
  227. self.category = nil
  228. write_attribute(:category_id, cid)
  229. end
  230. def fixed_version_id=(vid)
  231. self.fixed_version = nil
  232. write_attribute(:fixed_version_id, vid)
  233. end
  234. def tracker_id=(tid)
  235. self.tracker = nil
  236. result = write_attribute(:tracker_id, tid)
  237. @custom_field_values = nil
  238. @workflow_rule_by_attribute = nil
  239. result
  240. end
  241. def project_id=(project_id)
  242. if project_id.to_s != self.project_id.to_s
  243. self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
  244. end
  245. end
  246. def project=(project, keep_tracker=false)
  247. project_was = self.project
  248. write_attribute(:project_id, project ? project.id : nil)
  249. association_instance_set('project', project)
  250. if project_was && project && project_was != project
  251. @assignable_versions = nil
  252. unless keep_tracker || project.trackers.include?(tracker)
  253. self.tracker = project.trackers.first
  254. end
  255. # Reassign to the category with same name if any
  256. if category
  257. self.category = project.issue_categories.find_by_name(category.name)
  258. end
  259. # Keep the fixed_version if it's still valid in the new_project
  260. if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
  261. self.fixed_version = nil
  262. end
  263. # Clear the parent task if it's no longer valid
  264. unless valid_parent_project?
  265. self.parent_issue_id = nil
  266. end
  267. @custom_field_values = nil
  268. end
  269. end
  270. def description=(arg)
  271. if arg.is_a?(String)
  272. arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
  273. end
  274. write_attribute(:description, arg)
  275. end
  276. # Overrides assign_attributes so that project and tracker get assigned first
  277. def assign_attributes_with_project_and_tracker_first(new_attributes, *args)
  278. return if new_attributes.nil?
  279. attrs = new_attributes.dup
  280. attrs.stringify_keys!
  281. %w(project project_id tracker tracker_id).each do |attr|
  282. if attrs.has_key?(attr)
  283. send "#{attr}=", attrs.delete(attr)
  284. end
  285. end
  286. send :assign_attributes_without_project_and_tracker_first, attrs, *args
  287. end
  288. # Do not redefine alias chain on reload (see #4838)
  289. alias_method_chain(:assign_attributes, :project_and_tracker_first) unless method_defined?(:assign_attributes_without_project_and_tracker_first)
  290. def estimated_hours=(h)
  291. write_attribute :estimated_hours, (h.is_a?(String) ? h.to_hours : h)
  292. end
  293. safe_attributes 'project_id',
  294. :if => lambda {|issue, user|
  295. if issue.new_record?
  296. issue.copy?
  297. elsif user.allowed_to?(:move_issues, issue.project)
  298. projects = Issue.allowed_target_projects_on_move(user)
  299. projects.include?(issue.project) && projects.size > 1
  300. end
  301. }
  302. safe_attributes 'tracker_id',
  303. 'status_id',
  304. 'category_id',
  305. 'assigned_to_id',
  306. 'priority_id',
  307. 'fixed_version_id',
  308. 'subject',
  309. 'description',
  310. 'start_date',
  311. 'due_date',
  312. 'done_ratio',
  313. 'estimated_hours',
  314. 'custom_field_values',
  315. 'custom_fields',
  316. 'lock_version',
  317. 'notes',
  318. :if => lambda {|issue, user| issue.new_record? || user.allowed_to?(:edit_issues, issue.project) }
  319. safe_attributes 'status_id',
  320. 'assigned_to_id',
  321. 'fixed_version_id',
  322. 'done_ratio',
  323. 'lock_version',
  324. 'notes',
  325. :if => lambda {|issue, user| issue.new_statuses_allowed_to(user).any? }
  326. safe_attributes 'notes',
  327. :if => lambda {|issue, user| user.allowed_to?(:add_issue_notes, issue.project)}
  328. safe_attributes 'private_notes',
  329. :if => lambda {|issue, user| !issue.new_record? && user.allowed_to?(:set_notes_private, issue.project)}
  330. safe_attributes 'watcher_user_ids',
  331. :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
  332. safe_attributes 'is_private',
  333. :if => lambda {|issue, user|
  334. user.allowed_to?(:set_issues_private, issue.project) ||
  335. (issue.author == user && user.allowed_to?(:set_own_issues_private, issue.project))
  336. }
  337. safe_attributes 'parent_issue_id',
  338. :if => lambda {|issue, user| (issue.new_record? || user.allowed_to?(:edit_issues, issue.project)) &&
  339. user.allowed_to?(:manage_subtasks, issue.project)}
  340. def safe_attribute_names(user=nil)
  341. names = super
  342. names -= disabled_core_fields
  343. names -= read_only_attribute_names(user)
  344. names
  345. end
  346. # Safely sets attributes
  347. # Should be called from controllers instead of #attributes=
  348. # attr_accessible is too rough because we still want things like
  349. # Issue.new(:project => foo) to work
  350. def safe_attributes=(attrs, user=User.current)
  351. return unless attrs.is_a?(Hash)
  352. attrs = attrs.dup
  353. # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
  354. if (p = attrs.delete('project_id')) && safe_attribute?('project_id')
  355. if allowed_target_projects(user).collect(&:id).include?(p.to_i)
  356. self.project_id = p
  357. end
  358. end
  359. if (t = attrs.delete('tracker_id')) && safe_attribute?('tracker_id')
  360. self.tracker_id = t
  361. end
  362. if (s = attrs.delete('status_id')) && safe_attribute?('status_id')
  363. if new_statuses_allowed_to(user).collect(&:id).include?(s.to_i)
  364. self.status_id = s
  365. end
  366. end
  367. attrs = delete_unsafe_attributes(attrs, user)
  368. return if attrs.empty?
  369. unless leaf?
  370. attrs.reject! {|k,v| %w(priority_id done_ratio start_date due_date estimated_hours).include?(k)}
  371. end
  372. if attrs['parent_issue_id'].present?
  373. s = attrs['parent_issue_id'].to_s
  374. unless (m = s.match(%r{\A#?(\d+)\z})) && (m[1] == parent_id.to_s || Issue.visible(user).exists?(m[1]))
  375. @invalid_parent_issue_id = attrs.delete('parent_issue_id')
  376. end
  377. end
  378. if attrs['custom_field_values'].present?
  379. attrs['custom_field_values'] = attrs['custom_field_values'].reject {|k, v| read_only_attribute_names(user).include? k.to_s}
  380. end
  381. if attrs['custom_fields'].present?
  382. attrs['custom_fields'] = attrs['custom_fields'].reject {|c| read_only_attribute_names(user).include? c['id'].to_s}
  383. end
  384. # mass-assignment security bypass
  385. assign_attributes attrs, :without_protection => true
  386. end
  387. def disabled_core_fields
  388. tracker ? tracker.disabled_core_fields : []
  389. end
  390. # Returns the custom_field_values that can be edited by the given user
  391. def editable_custom_field_values(user=nil)
  392. custom_field_values.reject do |value|
  393. read_only_attribute_names(user).include?(value.custom_field_id.to_s)
  394. end
  395. end
  396. # Returns the names of attributes that are read-only for user or the current user
  397. # For users with multiple roles, the read-only fields are the intersection of
  398. # read-only fields of each role
  399. # The result is an array of strings where sustom fields are represented with their ids
  400. #
  401. # Examples:
  402. # issue.read_only_attribute_names # => ['due_date', '2']
  403. # issue.read_only_attribute_names(user) # => []
  404. def read_only_attribute_names(user=nil)
  405. workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'readonly'}.keys
  406. end
  407. # Returns the names of required attributes for user or the current user
  408. # For users with multiple roles, the required fields are the intersection of
  409. # required fields of each role
  410. # The result is an array of strings where sustom fields are represented with their ids
  411. #
  412. # Examples:
  413. # issue.required_attribute_names # => ['due_date', '2']
  414. # issue.required_attribute_names(user) # => []
  415. def required_attribute_names(user=nil)
  416. workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'required'}.keys
  417. end
  418. # Returns true if the attribute is required for user
  419. def required_attribute?(name, user=nil)
  420. required_attribute_names(user).include?(name.to_s)
  421. end
  422. # Returns a hash of the workflow rule by attribute for the given user
  423. #
  424. # Examples:
  425. # issue.workflow_rule_by_attribute # => {'due_date' => 'required', 'start_date' => 'readonly'}
  426. def workflow_rule_by_attribute(user=nil)
  427. return @workflow_rule_by_attribute if @workflow_rule_by_attribute && user.nil?
  428. user_real = user || User.current
  429. roles = user_real.admin ? Role.all : user_real.roles_for_project(project)
  430. return {} if roles.empty?
  431. result = {}
  432. workflow_permissions = WorkflowPermission.where(:tracker_id => tracker_id, :old_status_id => status_id, :role_id => roles.map(&:id)).all
  433. if workflow_permissions.any?
  434. workflow_rules = workflow_permissions.inject({}) do |h, wp|
  435. h[wp.field_name] ||= []
  436. h[wp.field_name] << wp.rule
  437. h
  438. end
  439. workflow_rules.each do |attr, rules|
  440. next if rules.size < roles.size
  441. uniq_rules = rules.uniq
  442. if uniq_rules.size == 1
  443. result[attr] = uniq_rules.first
  444. else
  445. result[attr] = 'required'
  446. end
  447. end
  448. end
  449. @workflow_rule_by_attribute = result if user.nil?
  450. result
  451. end
  452. private :workflow_rule_by_attribute
  453. def done_ratio
  454. if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
  455. status.default_done_ratio
  456. else
  457. read_attribute(:done_ratio)
  458. end
  459. end
  460. def self.use_status_for_done_ratio?
  461. Setting.issue_done_ratio == 'issue_status'
  462. end
  463. def self.use_field_for_done_ratio?
  464. Setting.issue_done_ratio == 'issue_field'
  465. end
  466. def validate_issue
  467. if due_date && start_date && due_date < start_date
  468. errors.add :due_date, :greater_than_start_date
  469. end
  470. if start_date && soonest_start && start_date < soonest_start
  471. errors.add :start_date, :invalid
  472. end
  473. if fixed_version
  474. if !assignable_versions.include?(fixed_version)
  475. errors.add :fixed_version_id, :inclusion
  476. elsif reopened? && fixed_version.closed?
  477. errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
  478. end
  479. end
  480. # Checks that the issue can not be added/moved to a disabled tracker
  481. if project && (tracker_id_changed? || project_id_changed?)
  482. unless project.trackers.include?(tracker)
  483. errors.add :tracker_id, :inclusion
  484. end
  485. end
  486. # Checks parent issue assignment
  487. if @invalid_parent_issue_id.present?
  488. errors.add :parent_issue_id, :invalid
  489. elsif @parent_issue
  490. if !valid_parent_project?(@parent_issue)
  491. errors.add :parent_issue_id, :invalid
  492. elsif !new_record?
  493. # moving an existing issue
  494. if @parent_issue.root_id != root_id
  495. # we can always move to another tree
  496. elsif move_possible?(@parent_issue)
  497. # move accepted inside tree
  498. else
  499. errors.add :parent_issue_id, :invalid
  500. end
  501. end
  502. end
  503. end
  504. # Validates the issue against additional workflow requirements
  505. def validate_required_fields
  506. user = new_record? ? author : current_journal.try(:user)
  507. required_attribute_names(user).each do |attribute|
  508. if attribute =~ /^\d+$/
  509. attribute = attribute.to_i
  510. v = custom_field_values.detect {|v| v.custom_field_id == attribute }
  511. if v && v.value.blank?
  512. errors.add :base, v.custom_field.name + ' ' + l('activerecord.errors.messages.blank')
  513. end
  514. else
  515. if respond_to?(attribute) && send(attribute).blank?
  516. errors.add attribute, :blank
  517. end
  518. end
  519. end
  520. end
  521. # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
  522. # even if the user turns off the setting later
  523. def update_done_ratio_from_issue_status
  524. if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
  525. self.done_ratio = status.default_done_ratio
  526. end
  527. end
  528. def init_journal(user, notes = "")
  529. @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
  530. if new_record?
  531. @current_journal.notify = false
  532. else
  533. @attributes_before_change = attributes.dup
  534. @custom_values_before_change = {}
  535. self.custom_field_values.each {|c| @custom_values_before_change.store c.custom_field_id, c.value }
  536. end
  537. @current_journal
  538. end
  539. # Returns the id of the last journal or nil
  540. def last_journal_id
  541. if new_record?
  542. nil
  543. else
  544. journals.maximum(:id)
  545. end
  546. end
  547. # Returns a scope for journals that have an id greater than journal_id
  548. def journals_after(journal_id)
  549. scope = journals.reorder("#{Journal.table_name}.id ASC")
  550. if journal_id.present?
  551. scope = scope.where("#{Journal.table_name}.id > ?", journal_id.to_i)
  552. end
  553. scope
  554. end
  555. # Return true if the issue is closed, otherwise false
  556. def closed?
  557. self.status.is_closed?
  558. end
  559. # Return true if the issue is being reopened
  560. def reopened?
  561. if !new_record? && status_id_changed?
  562. status_was = IssueStatus.find_by_id(status_id_was)
  563. status_new = IssueStatus.find_by_id(status_id)
  564. if status_was && status_new && status_was.is_closed? && !status_new.is_closed?
  565. return true
  566. end
  567. end
  568. false
  569. end
  570. # Return true if the issue is being closed
  571. def closing?
  572. if !new_record? && status_id_changed?
  573. status_was = IssueStatus.find_by_id(status_id_was)
  574. status_new = IssueStatus.find_by_id(status_id)
  575. if status_was && status_new && !status_was.is_closed? && status_new.is_closed?
  576. return true
  577. end
  578. end
  579. false
  580. end
  581. # Returns true if the issue is overdue
  582. def overdue?
  583. !due_date.nil? && (due_date < Date.today) && !status.is_closed?
  584. end
  585. # Is the amount of work done less than it should for the due date
  586. def behind_schedule?
  587. return false if start_date.nil? || due_date.nil?
  588. done_date = start_date + ((due_date - start_date+1)* done_ratio/100).floor
  589. return done_date <= Date.today
  590. end
  591. # Does this issue have children?
  592. def children?
  593. !leaf?
  594. end
  595. # Users the issue can be assigned to
  596. def assignable_users
  597. users = project.assignable_users
  598. users << author if author
  599. users << assigned_to if assigned_to
  600. users.uniq.sort
  601. end
  602. # Versions that the issue can be assigned to
  603. def assignable_versions
  604. return @assignable_versions if @assignable_versions
  605. versions = project.shared_versions.open.all
  606. if fixed_version
  607. if fixed_version_id_changed?
  608. # nothing to do
  609. elsif project_id_changed?
  610. if project.shared_versions.include?(fixed_version)
  611. versions << fixed_version
  612. end
  613. else
  614. versions << fixed_version
  615. end
  616. end
  617. @assignable_versions = versions.uniq.sort
  618. end
  619. # Returns true if this issue is blocked by another issue that is still open
  620. def blocked?
  621. !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
  622. end
  623. # Returns an array of statuses that user is able to apply
  624. def new_statuses_allowed_to(user=User.current, include_default=false)
  625. if new_record? && @copied_from
  626. [IssueStatus.default, @copied_from.status].compact.uniq.sort
  627. else
  628. initial_status = nil
  629. if new_record?
  630. initial_status = IssueStatus.default
  631. elsif status_id_was
  632. initial_status = IssueStatus.find_by_id(status_id_was)
  633. end
  634. initial_status ||= status
  635. statuses = initial_status.find_new_statuses_allowed_to(
  636. user.admin ? Role.all : user.roles_for_project(project),
  637. tracker,
  638. author == user,
  639. assigned_to_id_changed? ? assigned_to_id_was == user.id : assigned_to_id == user.id
  640. )
  641. statuses << initial_status unless statuses.empty?
  642. statuses << IssueStatus.default if include_default
  643. statuses = statuses.compact.uniq.sort
  644. blocked? ? statuses.reject {|s| s.is_closed?} : statuses
  645. end
  646. end
  647. def assigned_to_was
  648. if assigned_to_id_changed? && assigned_to_id_was.present?
  649. @assigned_to_was ||= User.find_by_id(assigned_to_id_was)
  650. end
  651. end
  652. # Returns the users that should be notified
  653. def notified_users
  654. notified = []
  655. # Author and assignee are always notified unless they have been
  656. # locked or don't want to be notified
  657. notified << author if author
  658. if assigned_to
  659. notified += (assigned_to.is_a?(Group) ? assigned_to.users : [assigned_to])
  660. end
  661. if assigned_to_was
  662. notified += (assigned_to_was.is_a?(Group) ? assigned_to_was.users : [assigned_to_was])
  663. end
  664. notified = notified.select {|u| u.active? && u.notify_about?(self)}
  665. notified += project.notified_users
  666. notified.uniq!
  667. # Remove users that can not view the issue
  668. notified.reject! {|user| !visible?(user)}
  669. notified
  670. end
  671. # Returns the email addresses that should be notified
  672. def recipients
  673. notified_users.collect(&:mail)
  674. end
  675. # Returns the number of hours spent on this issue
  676. def spent_hours
  677. @spent_hours ||= time_entries.sum(:hours) || 0
  678. end
  679. # Returns the total number of hours spent on this issue and its descendants
  680. #
  681. # Example:
  682. # spent_hours => 0.0
  683. # spent_hours => 50.2
  684. def total_spent_hours
  685. @total_spent_hours ||= self_and_descendants.sum("#{TimeEntry.table_name}.hours",
  686. :joins => "LEFT JOIN #{TimeEntry.table_name} ON #{TimeEntry.table_name}.issue_id = #{Issue.table_name}.id").to_f || 0.0
  687. end
  688. def relations
  689. @relations ||= IssueRelation::Relations.new(self, (relations_from + relations_to).sort)
  690. end
  691. # Preloads relations for a collection of issues
  692. def self.load_relations(issues)
  693. if issues.any?
  694. relations = IssueRelation.all(:conditions => ["issue_from_id IN (:ids) OR issue_to_id IN (:ids)", {:ids => issues.map(&:id)}])
  695. issues.each do |issue|
  696. issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
  697. end
  698. end
  699. end
  700. # Preloads visible spent time for a collection of issues
  701. def self.load_visible_spent_hours(issues, user=User.current)
  702. if issues.any?
  703. hours_by_issue_id = TimeEntry.visible(user).sum(:hours, :group => :issue_id)
  704. issues.each do |issue|
  705. issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0)
  706. end
  707. end
  708. end
  709. # Preloads visible relations for a collection of issues
  710. def self.load_visible_relations(issues, user=User.current)
  711. if issues.any?
  712. issue_ids = issues.map(&:id)
  713. # Relations with issue_from in given issues and visible issue_to
  714. relations_from = IssueRelation.includes(:issue_to => [:status, :project]).where(visible_condition(user)).where(:issue_from_id => issue_ids).all
  715. # Relations with issue_to in given issues and visible issue_from
  716. relations_to = IssueRelation.includes(:issue_from => [:status, :project]).where(visible_condition(user)).where(:issue_to_id => issue_ids).all
  717. issues.each do |issue|
  718. relations =
  719. relations_from.select {|relation| relation.issue_from_id == issue.id} +
  720. relations_to.select {|relation| relation.issue_to_id == issue.id}
  721. issue.instance_variable_set "@relations", IssueRelation::Relations.new(issue, relations.sort)
  722. end
  723. end
  724. end
  725. # Finds an issue relation given its id.
  726. def find_relation(relation_id)
  727. IssueRelation.find(relation_id, :conditions => ["issue_to_id = ? OR issue_from_id = ?", id, id])
  728. end
  729. def all_dependent_issues(except=[])
  730. except << self
  731. dependencies = []
  732. relations_from.each do |relation|
  733. if relation.issue_to && !except.include?(relation.issue_to)
  734. dependencies << relation.issue_to
  735. dependencies += relation.issue_to.all_dependent_issues(except)
  736. end
  737. end
  738. dependencies
  739. end
  740. # Returns an array of issues that duplicate this one
  741. def duplicates
  742. relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
  743. end
  744. # Returns the due date or the target due date if any
  745. # Used on gantt chart
  746. def due_before
  747. due_date || (fixed_version ? fixed_version.effective_date : nil)
  748. end
  749. # Returns the time scheduled for this issue.
  750. #
  751. # Example:
  752. # Start Date: 2/26/09, End Date: 3/04/09
  753. # duration => 6
  754. def duration
  755. (start_date && due_date) ? due_date - start_date : 0
  756. end
  757. # Returns the duration in working days
  758. def working_duration
  759. (start_date && due_date) ? working_days(start_date, due_date) : 0
  760. end
  761. def soonest_start(reload=false)
  762. @soonest_start = nil if reload
  763. @soonest_start ||= (
  764. relations_to(reload).collect{|relation| relation.successor_soonest_start} +
  765. ancestors.collect(&:soonest_start)
  766. ).compact.max
  767. end
  768. # Sets start_date on the given date or the next working day
  769. # and changes due_date to keep the same working duration.
  770. def reschedule_on(date)
  771. wd = working_duration
  772. date = next_working_date(date)
  773. self.start_date = date
  774. self.due_date = add_working_days(date, wd)
  775. end
  776. # Reschedules the issue on the given date or the next working day and saves the record.
  777. # If the issue is a parent task, this is done by rescheduling its subtasks.
  778. def reschedule_on!(date)
  779. return if date.nil?
  780. if leaf?
  781. if start_date.nil? || start_date != date
  782. if start_date && start_date > date
  783. # Issue can not be moved earlier than its soonest start date
  784. date = [soonest_start(true), date].compact.max
  785. end
  786. reschedule_on(date)
  787. begin
  788. save
  789. rescue ActiveRecord::StaleObjectError
  790. reload
  791. reschedule_on(date)
  792. save
  793. end
  794. end
  795. else
  796. leaves.each do |leaf|
  797. if leaf.start_date
  798. # Only move subtask if it starts at the same date as the parent
  799. # or if it starts before the given date
  800. if start_date == leaf.start_date || date > leaf.start_date
  801. leaf.reschedule_on!(date)
  802. end
  803. else
  804. leaf.reschedule_on!(date)
  805. end
  806. end
  807. end
  808. end
  809. def <=>(issue)
  810. if issue.nil?
  811. -1
  812. elsif root_id != issue.root_id
  813. (root_id || 0) <=> (issue.root_id || 0)
  814. else
  815. (lft || 0) <=> (issue.lft || 0)
  816. end
  817. end
  818. def to_s
  819. "#{tracker} ##{id}: #{subject}"
  820. end
  821. # Returns a string of css classes that apply to the issue
  822. def css_classes
  823. s = "issue status-#{status_id} #{priority.try(:css_classes)}"
  824. s << ' closed' if closed?
  825. s << ' overdue' if overdue?
  826. s << ' child' if child?
  827. s << ' parent' unless leaf?
  828. s << ' private' if is_private?
  829. s << ' created-by-me' if User.current.logged? && author_id == User.current.id
  830. s << ' assigned-to-me' if User.current.logged? && assigned_to_id == User.current.id
  831. s
  832. end
  833. # Saves an issue and a time_entry from the parameters
  834. def save_issue_with_child_records(params, existing_time_entry=nil)
  835. Issue.transaction do
  836. if params[:time_entry] && (params[:time_entry][:hours].present? || params[:time_entry][:comments].present?) && User.current.allowed_to?(:log_time, project)
  837. @time_entry = existing_time_entry || TimeEntry.new
  838. @time_entry.project = project
  839. @time_entry.issue = self
  840. @time_entry.user = User.current
  841. @time_entry.spent_on = User.current.today
  842. @time_entry.attributes = params[:time_entry]
  843. self.time_entries << @time_entry
  844. end
  845. # TODO: Rename hook
  846. Redmine::Hook.call_hook(:controller_issues_edit_before_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
  847. if save
  848. # TODO: Rename hook
  849. Redmine::Hook.call_hook(:controller_issues_edit_after_save, { :params => params, :issue => self, :time_entry => @time_entry, :journal => @current_journal})
  850. else
  851. raise ActiveRecord::Rollback
  852. end
  853. end
  854. end
  855. # Unassigns issues from +version+ if it's no longer shared with issue's project
  856. def self.update_versions_from_sharing_change(version)
  857. # Update issues assigned to the version
  858. update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
  859. end
  860. # Unassigns issues from versions that are no longer shared
  861. # after +project+ was moved
  862. def self.update_versions_from_hierarchy_change(project)
  863. moved_project_ids = project.self_and_descendants.reload.collect(&:id)
  864. # Update issues of the moved projects and issues assigned to a version of a moved project
  865. Issue.update_versions(["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)", moved_project_ids, moved_project_ids])
  866. end
  867. def parent_issue_id=(arg)
  868. s = arg.to_s.strip.presence
  869. if s && (m = s.match(%r{\A#?(\d+)\z})) && (@parent_issue = Issue.find_by_id(m[1]))
  870. @parent_issue.id
  871. else
  872. @parent_issue = nil
  873. @invalid_parent_issue_id = arg
  874. end
  875. end
  876. def parent_issue_id
  877. if @invalid_parent_issue_id
  878. @invalid_parent_issue_id
  879. elsif instance_variable_defined? :@parent_issue
  880. @parent_issue.nil? ? nil : @parent_issue.id
  881. else
  882. parent_id
  883. end
  884. end
  885. # Returns true if issue's project is a valid
  886. # parent issue project
  887. def valid_parent_project?(issue=parent)
  888. return true if issue.nil? || issue.project_id == project_id
  889. case Setting.cross_project_subtasks
  890. when 'system'
  891. true
  892. when 'tree'
  893. issue.project.root == project.root
  894. when 'hierarchy'
  895. issue.project.is_or_is_ancestor_of?(project) || issue.project.is_descendant_of?(project)
  896. when 'descendants'
  897. issue.project.is_or_is_ancestor_of?(project)
  898. else
  899. false
  900. end
  901. end
  902. # Extracted from the ReportsController.
  903. def self.by_tracker(project)
  904. count_and_group_by(:project => project,
  905. :field => 'tracker_id',
  906. :joins => Tracker.table_name)
  907. end
  908. def self.by_version(project)
  909. count_and_group_by(:project => project,
  910. :field => 'fixed_version_id',
  911. :joins => Version.table_name)
  912. end
  913. def self.by_priority(project)
  914. count_and_group_by(:project => project,
  915. :field => 'priority_id',
  916. :joins => IssuePriority.table_name)
  917. end
  918. def self.by_category(project)
  919. count_and_group_by(:project => project,
  920. :field => 'category_id',
  921. :joins => IssueCategory.table_name)
  922. end
  923. def self.by_assigned_to(project)
  924. count_and_group_by(:project => project,
  925. :field => 'assigned_to_id',
  926. :joins => User.table_name)
  927. end
  928. def self.by_author(project)
  929. count_and_group_by(:project => project,
  930. :field => 'author_id',
  931. :joins => User.table_name)
  932. end
  933. def self.by_subproject(project)
  934. ActiveRecord::Base.connection.select_all("select s.id as status_id,
  935. s.is_closed as closed,
  936. #{Issue.table_name}.project_id as project_id,
  937. count(#{Issue.table_name}.id) as total
  938. from
  939. #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s
  940. where
  941. #{Issue.table_name}.status_id=s.id
  942. and #{Issue.table_name}.project_id = #{Project.table_name}.id
  943. and #{visible_condition(User.current, :project => project, :with_subprojects => true)}
  944. and #{Issue.table_name}.project_id <> #{project.id}
  945. group by s.id, s.is_closed, #{Issue.table_name}.project_id") if project.descendants.active.any?
  946. end
  947. # End ReportsController extraction
  948. # Returns an array of projects that user can assign the issue to
  949. def allowed_target_projects(user=User.current)
  950. if new_record?
  951. Project.all(:conditions => Project.allowed_to_condition(user, :add_issues))
  952. else
  953. self.class.allowed_target_projects_on_move(user)
  954. end
  955. end
  956. # Returns an array of projects that user can move issues to
  957. def self.allowed_target_projects_on_move(user=User.current)
  958. Project.all(:conditions => Project.allowed_to_condition(user, :move_issues))
  959. end
  960. private
  961. def after_project_change
  962. # Update project_id on related time entries
  963. TimeEntry.update_all(["project_id = ?", project_id], {:issue_id => id})
  964. # Delete issue relations
  965. unless Setting.cross_project_issue_relations?
  966. relations_from.clear
  967. relations_to.clear
  968. end
  969. # Move subtasks that were in the same project
  970. children.each do |child|
  971. next unless child.project_id == project_id_was
  972. # Change project and keep project
  973. child.send :project=, project, true
  974. unless child.save
  975. raise ActiveRecord::Rollback
  976. end
  977. end
  978. end
  979. # Callback for after the creation of an issue by copy
  980. # * adds a "copied to" relation with the copied issue
  981. # * copies subtasks from the copied issue
  982. def after_create_from_copy
  983. return unless copy? && !@after_create_from_copy_handled
  984. if (@copied_from.project_id == project_id || Setting.cross_project_issue_relations?) && @copy_options[:link] != false
  985. relation = IssueRelation.new(:issue_from => @copied_from, :issue_to => self, :relation_type => IssueRelation::TYPE_COPIED_TO)
  986. unless relation.save
  987. logger.error "Could not create relation while copying ##{@copied_from.id} to ##{id} due to validation errors: #{relation.errors.full_messages.join(', ')}" if logger
  988. end
  989. end
  990. unless @copied_from.leaf? || @copy_options[:subtasks] == false
  991. @copied_from.children.each do |child|
  992. unless child.visible?
  993. # Do not copy subtasks that are not visible to avoid potential disclosure of private data
  994. logger.error "Subtask ##{child.id} was not copied during ##{@copied_from.id} copy because it is not visible to the current user" if logger
  995. next
  996. end
  997. copy = Issue.new.copy_from(child, @copy_options)
  998. copy.author = author
  999. copy.project = project
  1000. copy.parent_issue_id = id
  1001. # Children subtasks are copied recursively
  1002. unless copy.save
  1003. logger.error "Could not copy subtask ##{child.id} while copying ##{@copied_from.id} to ##{id} due to validation errors: #{copy.errors.full_messages.join(', ')}" if logger
  1004. end
  1005. end
  1006. end
  1007. @after_create_from_copy_handled = true
  1008. end
  1009. def update_nested_set_attributes
  1010. if root_id.nil?
  1011. # issue was just created
  1012. self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id)
  1013. set_default_left_and_right
  1014. Issue.update_all("root_id = #{root_id}, lft = #{lft}, rgt = #{rgt}", ["id = ?", id])
  1015. if @parent_issue
  1016. move_to_child_of(@parent_issue)
  1017. end
  1018. reload
  1019. elsif parent_issue_id != parent_id
  1020. former_parent_id = parent_id
  1021. # moving an existing issue
  1022. if @parent_issue && @parent_issue.root_id == root_id
  1023. # inside the same tree
  1024. move_to_child_of(@parent_issue)
  1025. else
  1026. # to another tree
  1027. unless root?
  1028. move_to_right_of(root)
  1029. reload
  1030. end
  1031. old_root_id = root_id
  1032. self.root_id = (@parent_issue.nil? ? id : @parent_issue.root_id )
  1033. target_maxright = nested_set_scope.maximum(right_column_name) || 0
  1034. offset = target_maxright + 1 - lft
  1035. Issue.update_all("root_id = #{root_id}, lft = lft + #{offset}, rgt = rgt + #{offset}",
  1036. ["root_id = ? AND lft >= ? AND rgt <= ? ", old_root_id, lft, rgt])
  1037. self[left_column_name] = lft + offset
  1038. self[right_column_name] = rgt + offset
  1039. if @parent_issue
  1040. move_to_child_of(@parent_issue)
  1041. end
  1042. end
  1043. reload
  1044. # delete invalid relations of all descendants
  1045. self_and_descendants.each do |issue|
  1046. issue.relations.each do |relation|
  1047. relation.destroy unless relation.valid?
  1048. end
  1049. end
  1050. # update former parent
  1051. recalculate_attributes_for(former_parent_id) if former_parent_id
  1052. end
  1053. remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
  1054. end
  1055. def update_parent_attributes
  1056. recalculate_attributes_for(parent_id) if parent_id
  1057. end
  1058. def recalculate_attributes_for(issue_id)
  1059. if issue_id && p = Issue.find_by_id(issue_id)
  1060. # priority = highest priority of children
  1061. if priority_position = p.children.maximum("#{IssuePriority.table_name}.position", :joins => :priority)
  1062. p.priority = IssuePriority.find_by_position(priority_position)
  1063. end
  1064. # start/due dates = lowest/highest dates of children
  1065. p.start_date = p.children.minimum(:start_date)
  1066. p.due_date = p.children.maximum(:due_date)
  1067. if p.start_date && p.due_date && p.due_date < p.start_date
  1068. p.start_date, p.due_date = p.due_date, p.start_date
  1069. end
  1070. # done ratio = weighted average ratio of leaves
  1071. unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
  1072. leaves_count = p.leaves.count
  1073. if leaves_count > 0
  1074. average = p.leaves.average(:estimated_hours).to_f
  1075. if average == 0
  1076. average = 1
  1077. end
  1078. 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
  1079. progress = done / (average * leaves_count)
  1080. p.done_ratio = progress.round
  1081. end
  1082. end
  1083. # estimate = sum of leaves estimates
  1084. p.estimated_hours = p.leaves.sum(:estimated_hours).to_f
  1085. p.estimated_hours = nil if p.estimated_hours == 0.0
  1086. # ancestors will be recursively updated
  1087. p.save(:validate => false)
  1088. end
  1089. end
  1090. # Update issues so their versions are not pointing to a
  1091. # fixed_version that is not shared with the issue's project
  1092. def self.update_versions(conditions=nil)
  1093. # Only need to update issues with a fixed_version from
  1094. # a different project and that is not systemwide shared
  1095. Issue.scoped(:conditions => conditions).all(
  1096. :conditions => "#{Issue.table_name}.fixed_version_id IS NOT NULL" +
  1097. " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
  1098. " AND #{Version.table_name}.sharing <> 'system'",
  1099. :include => [:project, :fixed_version]
  1100. ).each do |issue|
  1101. next if issue.project.nil? || issue.fixed_version.nil?
  1102. unless issue.project.shared_versions.include?(issue.fixed_version)
  1103. issue.init_journal(User.current)
  1104. issue.fixed_version = nil
  1105. issue.save
  1106. end
  1107. end
  1108. end
  1109. # Callback on file attachment
  1110. def attachment_added(obj)
  1111. if @current_journal && !obj.new_record?
  1112. @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :value => obj.filename)
  1113. end
  1114. end
  1115. # Callback on attachment deletion
  1116. def attachment_removed(obj)
  1117. if @current_journal && !obj.new_record?
  1118. @current_journal.details << JournalDetail.new(:property => 'attachment', :prop_key => obj.id, :old_value => obj.filename)
  1119. @current_journal.save
  1120. end
  1121. end
  1122. # Default assignment based on category
  1123. def default_assign
  1124. if assigned_to.nil? && category && category.assigned_to
  1125. self.assigned_to = category.assigned_to
  1126. end
  1127. end
  1128. # Updates start/due dates of following issues
  1129. def reschedule_following_issues
  1130. if start_date_changed? || due_date_changed?
  1131. relations_from.each do |relation|
  1132. relation.set_issue_to_dates
  1133. end
  1134. end
  1135. end
  1136. # Closes duplicates if the issue is being closed
  1137. def close_duplicates
  1138. if closing?
  1139. duplicates.each do |duplicate|
  1140. # Reload is need in case the duplicate was updated by a previous duplicate
  1141. duplicate.reload
  1142. # Don't re-close it if it's already closed
  1143. next if duplicate.closed?
  1144. # Same user and notes
  1145. if @current_journal
  1146. duplicate.init_journal(@current_journal.user, @current_journal.notes)
  1147. end
  1148. duplicate.update_attribute :status, self.status
  1149. end
  1150. end
  1151. end
  1152. # Make sure updated_on is updated when adding a note
  1153. def force_updated_on_change
  1154. if @current_journal
  1155. self.updated_on = current_time_from_proper_timezone
  1156. end
  1157. end
  1158. # Saves the changes in a Journal
  1159. # Called after_save
  1160. def create_journal
  1161. if @current_journal
  1162. # attributes changes
  1163. if @attributes_before_change
  1164. (Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on)).each {|c|
  1165. before = @attributes_before_change[c]
  1166. after = send(c)
  1167. next if before == after || (before.blank? && after.blank?)
  1168. @current_journal.details << JournalDetail.new(:property => 'attr',
  1169. :prop_key => c,
  1170. :old_value => before,
  1171. :value => after)
  1172. }
  1173. end
  1174. if @custom_values_before_change
  1175. # custom fields changes
  1176. custom_field_values.each {|c|
  1177. before = @custom_values_before_change[c.custom_field_id]
  1178. after = c.value
  1179. next if before == after || (before.blank? && after.blank?)
  1180. if before.is_a?(Array) || after.is_a?(Array)
  1181. before = [before] unless before.is_a?(Array)
  1182. after = [after] unless after.is_a?(Array)
  1183. # values removed
  1184. (before - after).reject(&:blank?).each do |value|
  1185. @current_journal.details << JournalDetail.new(:property => 'cf',
  1186. :prop_key => c.custom_field_id,
  1187. :old_value => value,
  1188. :value => nil)
  1189. end
  1190. # values added
  1191. (after - before).reject(&:blank?).each do |value|
  1192. @current_journal.details << JournalDetail.new(:property => 'cf',
  1193. :prop_key => c.custom_field_id,
  1194. :old_value => nil,
  1195. :value => value)
  1196. end
  1197. else
  1198. @current_journal.details << JournalDetail.new(:property => 'cf',
  1199. :prop_key => c.custom_field_id,
  1200. :old_value => before,
  1201. :value => after)
  1202. end
  1203. }
  1204. end
  1205. @current_journal.save
  1206. # reset current journal
  1207. init_journal @current_journal.user, @current_journal.notes
  1208. end
  1209. end
  1210. # Query generator for selecting groups of issue counts for a project
  1211. # based on specific criteria
  1212. #
  1213. # Options
  1214. # * project - Project to search in.
  1215. # * field - String. Issue field to key off of in the grouping.
  1216. # * joins - String. The table name to join against.
  1217. def self.count_and_group_by(options)
  1218. project = options.delete(:project)
  1219. select_field = options.delete(:field)
  1220. joins = options.delete(:joins)
  1221. where = "#{Issue.table_name}.#{select_field}=j.id"
  1222. ActiveRecord::Base.connection.select_all("select s.id as status_id,
  1223. s.is_closed as closed,
  1224. j.id as #{select_field},
  1225. count(#{Issue.table_name}.id) as total
  1226. from
  1227. #{Issue.table_name}, #{Project.table_name}, #{IssueStatus.table_name} s, #{joins} j
  1228. where
  1229. #{Issue.table_name}.status_id=s.id
  1230. and #{where}
  1231. and #{Issue.table_name}.project_id=#{Project.table_name}.id
  1232. and #{visible_condition(User.current, :project => project)}
  1233. group by s.id, s.is_closed, j.id")
  1234. end
  1235. end