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 63KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2019 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. class Issue < ActiveRecord::Base
  19. include Redmine::SafeAttributes
  20. include Redmine::Utils::DateCalculation
  21. include Redmine::I18n
  22. before_save :set_parent_id
  23. include Redmine::NestedSet::IssueNestedSet
  24. belongs_to :project
  25. belongs_to :tracker
  26. belongs_to :status, :class_name => 'IssueStatus'
  27. belongs_to :author, :class_name => 'User'
  28. belongs_to :assigned_to, :class_name => 'Principal'
  29. belongs_to :fixed_version, :class_name => 'Version'
  30. belongs_to :priority, :class_name => 'IssuePriority'
  31. belongs_to :category, :class_name => 'IssueCategory'
  32. has_many :journals, :as => :journalized, :dependent => :destroy, :inverse_of => :journalized
  33. has_many :time_entries, :dependent => :destroy
  34. has_and_belongs_to_many :changesets, lambda {order("#{Changeset.table_name}.committed_on ASC, #{Changeset.table_name}.id ASC")}
  35. has_many :relations_from, :class_name => 'IssueRelation', :foreign_key => 'issue_from_id', :dependent => :delete_all
  36. has_many :relations_to, :class_name => 'IssueRelation', :foreign_key => 'issue_to_id', :dependent => :delete_all
  37. acts_as_attachable :after_add => :attachment_added, :after_remove => :attachment_removed
  38. acts_as_customizable
  39. acts_as_watchable
  40. acts_as_searchable :columns => ['subject', "#{table_name}.description"],
  41. :preload => [:project, :status, :tracker],
  42. :scope => lambda {|options| options[:open_issues] ? self.open : self.all}
  43. acts_as_event :title => Proc.new {|o| "#{o.tracker.name} ##{o.id} (#{o.status}): #{o.subject}"},
  44. :url => Proc.new {|o| {:controller => 'issues', :action => 'show', :id => o.id}},
  45. :type => Proc.new {|o| 'issue' + (o.closed? ? '-closed' : '') }
  46. acts_as_activity_provider :scope => preload(:project, :author, :tracker, :status),
  47. :author_key => :author_id
  48. DONE_RATIO_OPTIONS = %w(issue_field issue_status)
  49. attr_writer :deleted_attachment_ids
  50. delegate :notes, :notes=, :private_notes, :private_notes=, :to => :current_journal, :allow_nil => true
  51. validates_presence_of :subject, :project, :tracker
  52. validates_presence_of :priority, :if => Proc.new {|issue| issue.new_record? || issue.priority_id_changed?}
  53. validates_presence_of :status, :if => Proc.new {|issue| issue.new_record? || issue.status_id_changed?}
  54. validates_presence_of :author, :if => Proc.new {|issue| issue.new_record? || issue.author_id_changed?}
  55. validates_length_of :subject, :maximum => 255
  56. validates_inclusion_of :done_ratio, :in => 0..100
  57. validates :estimated_hours, :numericality => {:greater_than_or_equal_to => 0, :allow_nil => true, :message => :invalid}
  58. validates :start_date, :date => true
  59. validates :due_date, :date => true
  60. validate :validate_issue, :validate_required_fields, :validate_permissions
  61. scope :visible, lambda {|*args|
  62. joins(:project).
  63. where(Issue.visible_condition(args.shift || User.current, *args))
  64. }
  65. scope :open, lambda {|*args|
  66. is_closed = !args.empty? ? !args.first : false
  67. joins(:status).
  68. where(:issue_statuses => {:is_closed => is_closed})
  69. }
  70. scope :recently_updated, lambda { order(:updated_on => :desc) }
  71. scope :on_active_project, lambda {
  72. joins(:project).
  73. where(:projects => {:status => Project::STATUS_ACTIVE})
  74. }
  75. scope :fixed_version, lambda {|versions|
  76. ids = [versions].flatten.compact.map {|v| v.is_a?(Version) ? v.id : v}
  77. ids.any? ? where(:fixed_version_id => ids) : none
  78. }
  79. scope :assigned_to, lambda {|arg|
  80. arg = Array(arg).uniq
  81. ids = arg.map {|p| p.is_a?(Principal) ? p.id : p}
  82. ids += arg.select {|p| p.is_a?(User)}.map(&:group_ids).flatten.uniq
  83. ids.compact!
  84. ids.any? ? where(:assigned_to_id => ids) : none
  85. }
  86. scope :like, lambda {|q|
  87. q = q.to_s
  88. if q.present?
  89. where("LOWER(#{table_name}.subject) LIKE LOWER(?)", "%#{q}%")
  90. end
  91. }
  92. before_validation :default_assign, on: :create
  93. before_validation :clear_disabled_fields
  94. before_save :close_duplicates, :update_done_ratio_from_issue_status,
  95. :force_updated_on_change, :update_closed_on
  96. after_save {|issue| issue.send :after_project_change if !issue.saved_change_to_id? && issue.saved_change_to_project_id?}
  97. after_save :reschedule_following_issues, :update_nested_set_attributes,
  98. :update_parent_attributes, :delete_selected_attachments, :create_journal
  99. # Should be after_create but would be called before previous after_save callbacks
  100. after_save :after_create_from_copy
  101. after_destroy :update_parent_attributes
  102. after_create_commit :send_notification
  103. # Returns a SQL conditions string used to find all issues visible by the specified user
  104. def self.visible_condition(user, options={})
  105. Project.allowed_to_condition(user, :view_issues, options) do |role, user|
  106. sql =
  107. if user.id && user.logged?
  108. case role.issues_visibility
  109. when 'all'
  110. '1=1'
  111. when 'default'
  112. user_ids = [user.id] + user.groups.pluck(:id).compact
  113. "(#{table_name}.is_private = #{connection.quoted_false} OR #{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
  114. when 'own'
  115. user_ids = [user.id] + user.groups.pluck(:id).compact
  116. "(#{table_name}.author_id = #{user.id} OR #{table_name}.assigned_to_id IN (#{user_ids.join(',')}))"
  117. else
  118. '1=0'
  119. end
  120. else
  121. "(#{table_name}.is_private = #{connection.quoted_false})"
  122. end
  123. unless role.permissions_all_trackers?(:view_issues)
  124. tracker_ids = role.permissions_tracker_ids(:view_issues)
  125. if tracker_ids.any?
  126. sql = "(#{sql} AND #{table_name}.tracker_id IN (#{tracker_ids.join(',')}))"
  127. else
  128. sql = '1=0'
  129. end
  130. end
  131. sql
  132. end
  133. end
  134. # Returns true if usr or current user is allowed to view the issue
  135. def visible?(usr=nil)
  136. (usr || User.current).allowed_to?(:view_issues, self.project) do |role, user|
  137. visible =
  138. if user.logged?
  139. case role.issues_visibility
  140. when 'all'
  141. true
  142. when 'default'
  143. !self.is_private? || (self.author == user || user.is_or_belongs_to?(assigned_to))
  144. when 'own'
  145. self.author == user || user.is_or_belongs_to?(assigned_to)
  146. else
  147. false
  148. end
  149. else
  150. !self.is_private?
  151. end
  152. unless role.permissions_all_trackers?(:view_issues)
  153. visible &&= role.permissions_tracker_ids?(:view_issues, tracker_id)
  154. end
  155. visible
  156. end
  157. end
  158. # Returns true if user or current user is allowed to edit or add notes to the issue
  159. def editable?(user=User.current)
  160. attributes_editable?(user) || notes_addable?(user)
  161. end
  162. # Returns true if user or current user is allowed to edit the issue
  163. def attributes_editable?(user=User.current)
  164. user_tracker_permission?(user, :edit_issues) || (
  165. user_tracker_permission?(user, :edit_own_issues) && author == user
  166. )
  167. end
  168. # Overrides Redmine::Acts::Attachable::InstanceMethods#attachments_editable?
  169. def attachments_editable?(user=User.current)
  170. attributes_editable?(user)
  171. end
  172. # Returns true if user or current user is allowed to add notes to the issue
  173. def notes_addable?(user=User.current)
  174. user_tracker_permission?(user, :add_issue_notes)
  175. end
  176. # Returns true if user or current user is allowed to delete the issue
  177. def deletable?(user=User.current)
  178. user_tracker_permission?(user, :delete_issues)
  179. end
  180. def initialize(attributes=nil, *args)
  181. super
  182. if new_record?
  183. # set default values for new records only
  184. self.priority ||= IssuePriority.default
  185. self.watcher_user_ids = []
  186. end
  187. end
  188. def create_or_update(*args)
  189. super
  190. ensure
  191. @status_was = nil
  192. end
  193. private :create_or_update
  194. # AR#Persistence#destroy would raise and RecordNotFound exception
  195. # if the issue was already deleted or updated (non matching lock_version).
  196. # This is a problem when bulk deleting issues or deleting a project
  197. # (because an issue may already be deleted if its parent was deleted
  198. # first).
  199. # The issue is reloaded by the nested_set before being deleted so
  200. # the lock_version condition should not be an issue but we handle it.
  201. def destroy
  202. super
  203. rescue ActiveRecord::StaleObjectError, ActiveRecord::RecordNotFound
  204. # Stale or already deleted
  205. begin
  206. reload
  207. rescue ActiveRecord::RecordNotFound
  208. # The issue was actually already deleted
  209. @destroyed = true
  210. return freeze
  211. end
  212. # The issue was stale, retry to destroy
  213. super
  214. end
  215. alias :base_reload :reload
  216. def reload(*args)
  217. @workflow_rule_by_attribute = nil
  218. @assignable_versions = nil
  219. @relations = nil
  220. @spent_hours = nil
  221. @total_spent_hours = nil
  222. @total_estimated_hours = nil
  223. @last_updated_by = nil
  224. @last_notes = nil
  225. base_reload(*args)
  226. end
  227. # Overrides Redmine::Acts::Customizable::InstanceMethods#available_custom_fields
  228. def available_custom_fields
  229. (project && tracker) ? (project.all_issue_custom_fields & tracker.custom_fields) : []
  230. end
  231. def visible_custom_field_values(user=nil)
  232. user_real = user || User.current
  233. custom_field_values.select do |value|
  234. value.custom_field.visible_by?(project, user_real)
  235. end
  236. end
  237. # Overrides Redmine::Acts::Customizable::InstanceMethods#set_custom_field_default?
  238. def set_custom_field_default?(custom_value)
  239. new_record? || project_id_changed?|| tracker_id_changed?
  240. end
  241. # Copies attributes from another issue, arg can be an id or an Issue
  242. def copy_from(arg, options={})
  243. issue = arg.is_a?(Issue) ? arg : Issue.visible.find(arg)
  244. self.attributes = issue.attributes.dup.except("id", "root_id", "parent_id", "lft", "rgt", "created_on", "updated_on", "status_id", "closed_on")
  245. self.custom_field_values = issue.custom_field_values.inject({}) {|h,v| h[v.custom_field_id] = v.value; h}
  246. if options[:keep_status]
  247. self.status = issue.status
  248. end
  249. self.author = User.current
  250. unless options[:attachments] == false
  251. self.attachments = issue.attachments.map do |attachement|
  252. attachement.copy(:container => self)
  253. end
  254. end
  255. unless options[:watchers] == false
  256. self.watcher_user_ids =
  257. issue.watcher_users.select{|u| u.status == User::STATUS_ACTIVE}.map(&:id)
  258. end
  259. @copied_from = issue
  260. @copy_options = options
  261. self
  262. end
  263. # Returns an unsaved copy of the issue
  264. def copy(attributes=nil, copy_options={})
  265. copy = self.class.new.copy_from(self, copy_options)
  266. copy.attributes = attributes if attributes
  267. copy
  268. end
  269. # Returns true if the issue is a copy
  270. def copy?
  271. @copied_from.present?
  272. end
  273. def status_id=(status_id)
  274. if status_id.to_s != self.status_id.to_s
  275. self.status = (status_id.present? ? IssueStatus.find_by_id(status_id) : nil)
  276. end
  277. self.status_id
  278. end
  279. # Sets the status.
  280. def status=(status)
  281. if status != self.status
  282. @workflow_rule_by_attribute = nil
  283. end
  284. association(:status).writer(status)
  285. end
  286. def priority_id=(pid)
  287. self.priority = nil
  288. write_attribute(:priority_id, pid)
  289. end
  290. def category_id=(cid)
  291. self.category = nil
  292. write_attribute(:category_id, cid)
  293. end
  294. def fixed_version_id=(vid)
  295. self.fixed_version = nil
  296. write_attribute(:fixed_version_id, vid)
  297. end
  298. def tracker_id=(tracker_id)
  299. if tracker_id.to_s != self.tracker_id.to_s
  300. self.tracker = (tracker_id.present? ? Tracker.find_by_id(tracker_id) : nil)
  301. end
  302. self.tracker_id
  303. end
  304. # Sets the tracker.
  305. # This will set the status to the default status of the new tracker if:
  306. # * the status was the default for the previous tracker
  307. # * or if the status was not part of the new tracker statuses
  308. # * or the status was nil
  309. def tracker=(tracker)
  310. tracker_was = self.tracker
  311. association(:tracker).writer(tracker)
  312. if tracker != tracker_was
  313. if status == tracker_was.try(:default_status)
  314. self.status = nil
  315. elsif status && tracker && !tracker.issue_status_ids.include?(status.id)
  316. self.status = nil
  317. end
  318. reassign_custom_field_values
  319. @workflow_rule_by_attribute = nil
  320. end
  321. self.status ||= default_status
  322. self.tracker
  323. end
  324. def project_id=(project_id)
  325. if project_id.to_s != self.project_id.to_s
  326. self.project = (project_id.present? ? Project.find_by_id(project_id) : nil)
  327. end
  328. self.project_id
  329. end
  330. # Sets the project.
  331. # Unless keep_tracker argument is set to true, this will change the tracker
  332. # to the first tracker of the new project if the previous tracker is not part
  333. # of the new project trackers.
  334. # This will:
  335. # * clear the fixed_version is it's no longer valid for the new project.
  336. # * clear the parent issue if it's no longer valid for the new project.
  337. # * set the category to the category with the same name in the new
  338. # project if it exists, or clear it if it doesn't.
  339. # * for new issue, set the fixed_version to the project default version
  340. # if it's a valid fixed_version.
  341. def project=(project, keep_tracker=false)
  342. project_was = self.project
  343. association(:project).writer(project)
  344. if project != project_was
  345. @safe_attribute_names = nil
  346. end
  347. if project_was && project && project_was != project
  348. @assignable_versions = nil
  349. unless keep_tracker || project.trackers.include?(tracker)
  350. self.tracker = project.trackers.first
  351. end
  352. # Reassign to the category with same name if any
  353. if category
  354. self.category = project.issue_categories.find_by_name(category.name)
  355. end
  356. # Clear the assignee if not available in the new project for new issues (eg. copy)
  357. # For existing issue, the previous assignee is still valid, so we keep it
  358. if new_record? && assigned_to && !assignable_users.include?(assigned_to)
  359. self.assigned_to_id = nil
  360. end
  361. # Keep the fixed_version if it's still valid in the new_project
  362. if fixed_version && fixed_version.project != project && !project.shared_versions.include?(fixed_version)
  363. self.fixed_version = nil
  364. end
  365. # Clear the parent task if it's no longer valid
  366. unless valid_parent_project?
  367. self.parent_issue_id = nil
  368. end
  369. reassign_custom_field_values
  370. @workflow_rule_by_attribute = nil
  371. end
  372. # Set fixed_version to the project default version if it's valid
  373. if new_record? && fixed_version.nil? && project && project.default_version_id?
  374. if project.shared_versions.open.exists?(project.default_version_id)
  375. self.fixed_version_id = project.default_version_id
  376. end
  377. end
  378. self.project
  379. end
  380. def description=(arg)
  381. if arg.is_a?(String)
  382. arg = arg.gsub(/(\r\n|\n|\r)/, "\r\n")
  383. end
  384. write_attribute(:description, arg)
  385. end
  386. def deleted_attachment_ids
  387. Array(@deleted_attachment_ids).map(&:to_i)
  388. end
  389. # Overrides assign_attributes so that project and tracker get assigned first
  390. def assign_attributes(new_attributes, *args)
  391. return if new_attributes.nil?
  392. attrs = new_attributes.dup
  393. attrs.stringify_keys!
  394. %w(project project_id tracker tracker_id).each do |attr|
  395. if attrs.has_key?(attr)
  396. send "#{attr}=", attrs.delete(attr)
  397. end
  398. end
  399. super attrs, *args
  400. end
  401. def attributes=(new_attributes)
  402. assign_attributes new_attributes
  403. end
  404. def estimated_hours=(h)
  405. write_attribute :estimated_hours, (h.is_a?(String) ? (h.to_hours || h) : h)
  406. end
  407. safe_attributes 'project_id',
  408. 'tracker_id',
  409. 'status_id',
  410. 'category_id',
  411. 'assigned_to_id',
  412. 'priority_id',
  413. 'fixed_version_id',
  414. 'subject',
  415. 'description',
  416. 'start_date',
  417. 'due_date',
  418. 'done_ratio',
  419. 'estimated_hours',
  420. 'custom_field_values',
  421. 'custom_fields',
  422. 'lock_version',
  423. 'notes',
  424. :if => lambda {|issue, user| issue.new_record? || issue.attributes_editable?(user) }
  425. safe_attributes 'notes',
  426. :if => lambda {|issue, user| issue.notes_addable?(user)}
  427. safe_attributes 'private_notes',
  428. :if => lambda {|issue, user| !issue.new_record? && user.allowed_to?(:set_notes_private, issue.project)}
  429. safe_attributes 'watcher_user_ids',
  430. :if => lambda {|issue, user| issue.new_record? && user.allowed_to?(:add_issue_watchers, issue.project)}
  431. safe_attributes 'is_private',
  432. :if => lambda {|issue, user|
  433. user.allowed_to?(:set_issues_private, issue.project) ||
  434. (issue.author_id == user.id && user.allowed_to?(:set_own_issues_private, issue.project))
  435. }
  436. safe_attributes 'parent_issue_id',
  437. :if => lambda {|issue, user|
  438. (issue.new_record? || issue.attributes_editable?(user)) &&
  439. user.allowed_to?(:manage_subtasks, issue.project)
  440. }
  441. safe_attributes 'deleted_attachment_ids',
  442. :if => lambda {|issue, user| issue.attachments_deletable?(user)}
  443. def safe_attribute_names(user=nil)
  444. names = super
  445. names -= disabled_core_fields
  446. names -= read_only_attribute_names(user)
  447. if new_record?
  448. # Make sure that project_id can always be set for new issues
  449. names |= %w(project_id)
  450. end
  451. if dates_derived?
  452. names -= %w(start_date due_date)
  453. end
  454. if priority_derived?
  455. names -= %w(priority_id)
  456. end
  457. if done_ratio_derived?
  458. names -= %w(done_ratio)
  459. end
  460. names
  461. end
  462. # Safely sets attributes
  463. # Should be called from controllers instead of #attributes=
  464. # attr_accessible is too rough because we still want things like
  465. # Issue.new(:project => foo) to work
  466. def safe_attributes=(attrs, user=User.current)
  467. if attrs.respond_to?(:to_unsafe_hash)
  468. attrs = attrs.to_unsafe_hash
  469. end
  470. @attributes_set_by = user
  471. return unless attrs.is_a?(Hash)
  472. attrs = attrs.deep_dup
  473. # Project and Tracker must be set before since new_statuses_allowed_to depends on it.
  474. if (p = attrs.delete('project_id')) && safe_attribute?('project_id')
  475. if p.is_a?(String) && !/^\d*$/.match?(p)
  476. p_id = Project.find_by_identifier(p).try(:id)
  477. else
  478. p_id = p.to_i
  479. end
  480. if allowed_target_projects(user).where(:id => p_id).exists?
  481. self.project_id = p_id
  482. end
  483. if project_id_changed? && attrs['category_id'].present? && attrs['category_id'].to_s == category_id_was.to_s
  484. # Discard submitted category on previous project
  485. attrs.delete('category_id')
  486. end
  487. end
  488. if (t = attrs.delete('tracker_id')) && safe_attribute?('tracker_id')
  489. if allowed_target_trackers(user).where(:id => t.to_i).exists?
  490. self.tracker_id = t
  491. end
  492. end
  493. if project && tracker.nil?
  494. # Set a default tracker to accept custom field values
  495. # even if tracker is not specified
  496. allowed_trackers = allowed_target_trackers(user)
  497. if attrs['parent_issue_id'].present?
  498. # If parent_issue_id is present, the first tracker for which this field
  499. # is not disabled is chosen as default
  500. self.tracker = allowed_trackers.detect {|t| t.core_fields.include?('parent_issue_id')}
  501. end
  502. self.tracker ||= allowed_trackers.first
  503. end
  504. statuses_allowed = new_statuses_allowed_to(user)
  505. if (s = attrs.delete('status_id')) && safe_attribute?('status_id')
  506. if statuses_allowed.collect(&:id).include?(s.to_i)
  507. self.status_id = s
  508. end
  509. end
  510. if new_record? && !statuses_allowed.include?(status)
  511. self.status = statuses_allowed.first || default_status
  512. end
  513. if (u = attrs.delete('assigned_to_id')) && safe_attribute?('assigned_to_id')
  514. self.assigned_to_id = u
  515. end
  516. attrs = delete_unsafe_attributes(attrs, user)
  517. return if attrs.empty?
  518. if attrs['parent_issue_id'].present?
  519. s = attrs['parent_issue_id'].to_s
  520. unless (m = s.match(%r{\A#?(\d+)\z})) && (m[1] == parent_id.to_s || Issue.visible(user).exists?(m[1]))
  521. @invalid_parent_issue_id = attrs.delete('parent_issue_id')
  522. end
  523. end
  524. if attrs['custom_field_values'].present?
  525. editable_custom_field_ids = editable_custom_field_values(user).map {|v| v.custom_field_id.to_s}
  526. attrs['custom_field_values'].select! {|k, v| editable_custom_field_ids.include?(k.to_s)}
  527. end
  528. if attrs['custom_fields'].present?
  529. editable_custom_field_ids = editable_custom_field_values(user).map {|v| v.custom_field_id.to_s}
  530. attrs['custom_fields'].select! {|c| editable_custom_field_ids.include?(c['id'].to_s)}
  531. end
  532. assign_attributes attrs
  533. end
  534. def disabled_core_fields
  535. tracker ? tracker.disabled_core_fields : []
  536. end
  537. # Returns the custom_field_values that can be edited by the given user
  538. def editable_custom_field_values(user=nil)
  539. read_only = read_only_attribute_names(user)
  540. visible_custom_field_values(user).reject do |value|
  541. read_only.include?(value.custom_field_id.to_s)
  542. end
  543. end
  544. # Returns the custom fields that can be edited by the given user
  545. def editable_custom_fields(user=nil)
  546. editable_custom_field_values(user).map(&:custom_field).uniq
  547. end
  548. # Returns the names of attributes that are read-only for user or the current user
  549. # For users with multiple roles, the read-only fields are the intersection of
  550. # read-only fields of each role
  551. # The result is an array of strings where sustom fields are represented with their ids
  552. #
  553. # Examples:
  554. # issue.read_only_attribute_names # => ['due_date', '2']
  555. # issue.read_only_attribute_names(user) # => []
  556. def read_only_attribute_names(user=nil)
  557. workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'readonly'}.keys
  558. end
  559. # Returns the names of required attributes for user or the current user
  560. # For users with multiple roles, the required fields are the intersection of
  561. # required fields of each role
  562. # The result is an array of strings where sustom fields are represented with their ids
  563. #
  564. # Examples:
  565. # issue.required_attribute_names # => ['due_date', '2']
  566. # issue.required_attribute_names(user) # => []
  567. def required_attribute_names(user=nil)
  568. workflow_rule_by_attribute(user).reject {|attr, rule| rule != 'required'}.keys
  569. end
  570. # Returns true if the attribute is required for user
  571. def required_attribute?(name, user=nil)
  572. required_attribute_names(user).include?(name.to_s)
  573. end
  574. # Returns a hash of the workflow rule by attribute for the given user
  575. #
  576. # Examples:
  577. # issue.workflow_rule_by_attribute # => {'due_date' => 'required', 'start_date' => 'readonly'}
  578. def workflow_rule_by_attribute(user=nil)
  579. return @workflow_rule_by_attribute if @workflow_rule_by_attribute && user.nil?
  580. user_real = user || User.current
  581. roles = user_real.admin ? Role.all.to_a : user_real.roles_for_project(project)
  582. roles = roles.select(&:consider_workflow?)
  583. return {} if roles.empty?
  584. result = {}
  585. workflow_permissions = WorkflowPermission.where(:tracker_id => tracker_id, :old_status_id => status_id, :role_id => roles.map(&:id)).to_a
  586. if workflow_permissions.any?
  587. workflow_rules = workflow_permissions.inject({}) do |h, wp|
  588. h[wp.field_name] ||= {}
  589. h[wp.field_name][wp.role_id] = wp.rule
  590. h
  591. end
  592. fields_with_roles = {}
  593. IssueCustomField.where(:visible => false).joins(:roles).pluck(:id, "role_id").each do |field_id, role_id|
  594. fields_with_roles[field_id] ||= []
  595. fields_with_roles[field_id] << role_id
  596. end
  597. roles.each do |role|
  598. fields_with_roles.each do |field_id, role_ids|
  599. unless role_ids.include?(role.id)
  600. field_name = field_id.to_s
  601. workflow_rules[field_name] ||= {}
  602. workflow_rules[field_name][role.id] = 'readonly'
  603. end
  604. end
  605. end
  606. workflow_rules.each do |attr, rules|
  607. next if rules.size < roles.size
  608. uniq_rules = rules.values.uniq
  609. if uniq_rules.size == 1
  610. result[attr] = uniq_rules.first
  611. else
  612. result[attr] = 'required'
  613. end
  614. end
  615. end
  616. @workflow_rule_by_attribute = result if user.nil?
  617. result
  618. end
  619. private :workflow_rule_by_attribute
  620. def done_ratio
  621. if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
  622. status.default_done_ratio
  623. else
  624. read_attribute(:done_ratio)
  625. end
  626. end
  627. def self.use_status_for_done_ratio?
  628. Setting.issue_done_ratio == 'issue_status'
  629. end
  630. def self.use_field_for_done_ratio?
  631. Setting.issue_done_ratio == 'issue_field'
  632. end
  633. def validate_issue
  634. if due_date && start_date && (start_date_changed? || due_date_changed?) && due_date < start_date
  635. errors.add :due_date, :greater_than_start_date
  636. end
  637. if start_date && start_date_changed? && soonest_start && start_date < soonest_start
  638. errors.add :start_date, :earlier_than_minimum_start_date, :date => format_date(soonest_start)
  639. end
  640. if fixed_version
  641. if !assignable_versions.include?(fixed_version)
  642. errors.add :fixed_version_id, :inclusion
  643. elsif reopening? && fixed_version.closed?
  644. errors.add :base, I18n.t(:error_can_not_reopen_issue_on_closed_version)
  645. end
  646. end
  647. # Checks that the issue can not be added/moved to a disabled tracker
  648. if project && (tracker_id_changed? || project_id_changed?)
  649. if tracker && !project.trackers.include?(tracker)
  650. errors.add :tracker_id, :inclusion
  651. end
  652. end
  653. if assigned_to_id_changed? && assigned_to_id.present?
  654. unless assignable_users.include?(assigned_to)
  655. errors.add :assigned_to_id, :invalid
  656. end
  657. end
  658. # Checks parent issue assignment
  659. if @invalid_parent_issue_id.present?
  660. errors.add :parent_issue_id, :invalid
  661. elsif @parent_issue
  662. if !valid_parent_project?(@parent_issue)
  663. errors.add :parent_issue_id, :invalid
  664. elsif (@parent_issue != parent) && (
  665. self.would_reschedule?(@parent_issue) ||
  666. @parent_issue.self_and_ancestors.any? {|a| a.relations_from.any? {|r| r.relation_type == IssueRelation::TYPE_PRECEDES && r.issue_to.would_reschedule?(self)}}
  667. )
  668. errors.add :parent_issue_id, :invalid
  669. elsif !closed? && @parent_issue.closed?
  670. # cannot attach an open issue to a closed parent
  671. errors.add :base, :open_issue_with_closed_parent
  672. elsif !new_record?
  673. # moving an existing issue
  674. if move_possible?(@parent_issue)
  675. # move accepted
  676. else
  677. errors.add :parent_issue_id, :invalid
  678. end
  679. end
  680. end
  681. end
  682. # Validates the issue against additional workflow requirements
  683. def validate_required_fields
  684. user = new_record? ? author : current_journal.try(:user)
  685. required_attribute_names(user).each do |attribute|
  686. if /^\d+$/.match?(attribute)
  687. attribute = attribute.to_i
  688. v = custom_field_values.detect {|v| v.custom_field_id == attribute }
  689. if v && Array(v.value).detect(&:present?).nil?
  690. errors.add :base, v.custom_field.name + ' ' + l('activerecord.errors.messages.blank')
  691. end
  692. else
  693. if respond_to?(attribute) && send(attribute).blank? && !disabled_core_fields.include?(attribute)
  694. next if attribute == 'category_id' && project.try(:issue_categories).blank?
  695. next if attribute == 'fixed_version_id' && assignable_versions.blank?
  696. errors.add attribute, :blank
  697. end
  698. end
  699. end
  700. end
  701. def validate_permissions
  702. if @attributes_set_by && new_record? && copy?
  703. unless allowed_target_trackers(@attributes_set_by).include?(tracker)
  704. errors.add :tracker, :invalid
  705. end
  706. end
  707. end
  708. # Overrides Redmine::Acts::Customizable::InstanceMethods#validate_custom_field_values
  709. # so that custom values that are not editable are not validated (eg. a custom field that
  710. # is marked as required should not trigger a validation error if the user is not allowed
  711. # to edit this field).
  712. def validate_custom_field_values
  713. user = new_record? ? author : current_journal.try(:user)
  714. if new_record? || custom_field_values_changed?
  715. editable_custom_field_values(user).each(&:validate_value)
  716. end
  717. end
  718. # Set the done_ratio using the status if that setting is set. This will keep the done_ratios
  719. # even if the user turns off the setting later
  720. def update_done_ratio_from_issue_status
  721. if Issue.use_status_for_done_ratio? && status && status.default_done_ratio
  722. self.done_ratio = status.default_done_ratio
  723. end
  724. end
  725. def init_journal(user, notes = "")
  726. @current_journal ||= Journal.new(:journalized => self, :user => user, :notes => notes)
  727. end
  728. # Returns the current journal or nil if it's not initialized
  729. def current_journal
  730. @current_journal
  731. end
  732. # Clears the current journal
  733. def clear_journal
  734. @current_journal = nil
  735. end
  736. # Returns the names of attributes that are journalized when updating the issue
  737. def journalized_attribute_names
  738. names = Issue.column_names - %w(id root_id lft rgt lock_version created_on updated_on closed_on)
  739. if tracker
  740. names -= tracker.disabled_core_fields
  741. end
  742. names
  743. end
  744. # Returns the id of the last journal or nil
  745. def last_journal_id
  746. if new_record?
  747. nil
  748. else
  749. journals.maximum(:id)
  750. end
  751. end
  752. # Returns a scope for journals that have an id greater than journal_id
  753. def journals_after(journal_id)
  754. scope = journals.reorder("#{Journal.table_name}.id ASC")
  755. if journal_id.present?
  756. scope = scope.where("#{Journal.table_name}.id > ?", journal_id.to_i)
  757. end
  758. scope
  759. end
  760. # Returns the journals that are visible to user with their index
  761. # Used to display the issue history
  762. def visible_journals_with_index(user=User.current)
  763. result = journals.
  764. preload(:details).
  765. preload(:user => :email_address).
  766. reorder(:created_on, :id).to_a
  767. result.each_with_index {|j,i| j.indice = i+1}
  768. unless user.allowed_to?(:view_private_notes, project)
  769. result.select! do |journal|
  770. !journal.private_notes? || journal.user == user
  771. end
  772. end
  773. Journal.preload_journals_details_custom_fields(result)
  774. result.select! {|journal| journal.notes? || journal.visible_details.any?}
  775. result
  776. end
  777. # Returns the initial status of the issue
  778. # Returns nil for a new issue
  779. def status_was
  780. if status_id_changed?
  781. if status_id_was.to_i > 0
  782. @status_was ||= IssueStatus.find_by_id(status_id_was)
  783. end
  784. else
  785. @status_was ||= status
  786. end
  787. end
  788. # Return true if the issue is closed, otherwise false
  789. def closed?
  790. status.present? && status.is_closed?
  791. end
  792. # Returns true if the issue was closed when loaded
  793. def was_closed?
  794. status_was.present? && status_was.is_closed?
  795. end
  796. # Return true if the issue is being reopened
  797. def reopening?
  798. if new_record?
  799. false
  800. else
  801. status_id_changed? && !closed? && was_closed?
  802. end
  803. end
  804. alias :reopened? :reopening?
  805. # Return true if the issue is being closed
  806. def closing?
  807. if new_record?
  808. closed?
  809. else
  810. status_id_changed? && closed? && !was_closed?
  811. end
  812. end
  813. # Returns true if the issue is overdue
  814. def overdue?
  815. due_date.present? && (due_date < User.current.today) && !closed?
  816. end
  817. # Is the amount of work done less than it should for the due date
  818. def behind_schedule?
  819. return false if start_date.nil? || due_date.nil?
  820. done_date = start_date + ((due_date - start_date + 1) * done_ratio / 100).floor
  821. return done_date <= User.current.today
  822. end
  823. # Does this issue have children?
  824. def children?
  825. !leaf?
  826. end
  827. # Users the issue can be assigned to
  828. def assignable_users
  829. users = project.assignable_users(tracker).to_a
  830. users << author if author && author.active?
  831. if assigned_to_id_was.present? && assignee = Principal.find_by_id(assigned_to_id_was)
  832. users << assignee
  833. end
  834. users.uniq.sort
  835. end
  836. # Versions that the issue can be assigned to
  837. def assignable_versions
  838. return @assignable_versions if @assignable_versions
  839. versions = project.shared_versions.open.to_a
  840. if fixed_version
  841. if fixed_version_id_changed?
  842. # nothing to do
  843. elsif project_id_changed?
  844. if project.shared_versions.include?(fixed_version)
  845. versions << fixed_version
  846. end
  847. else
  848. versions << fixed_version
  849. end
  850. end
  851. @assignable_versions = versions.uniq.sort
  852. end
  853. # Returns true if this issue is blocked by another issue that is still open
  854. def blocked?
  855. !relations_to.detect {|ir| ir.relation_type == 'blocks' && !ir.issue_from.closed?}.nil?
  856. end
  857. # Returns the default status of the issue based on its tracker
  858. # Returns nil if tracker is nil
  859. def default_status
  860. tracker.try(:default_status)
  861. end
  862. # Returns an array of statuses that user is able to apply
  863. def new_statuses_allowed_to(user=User.current, include_default=false)
  864. initial_status = nil
  865. if new_record?
  866. # nop
  867. elsif tracker_id_changed?
  868. if Tracker.where(:id => tracker_id_was, :default_status_id => status_id_was).any?
  869. initial_status = default_status
  870. elsif tracker.issue_status_ids.include?(status_id_was)
  871. initial_status = IssueStatus.find_by_id(status_id_was)
  872. else
  873. initial_status = default_status
  874. end
  875. else
  876. initial_status = status_was
  877. end
  878. initial_assigned_to_id = assigned_to_id_changed? ? assigned_to_id_was : assigned_to_id
  879. assignee_transitions_allowed = initial_assigned_to_id.present? &&
  880. (user.id == initial_assigned_to_id || user.group_ids.include?(initial_assigned_to_id))
  881. statuses = []
  882. statuses += IssueStatus.new_statuses_allowed(
  883. initial_status,
  884. user.admin ? Role.all.to_a : user.roles_for_project(project),
  885. tracker,
  886. author == user,
  887. assignee_transitions_allowed
  888. )
  889. statuses << initial_status unless statuses.empty?
  890. statuses << default_status if include_default || (new_record? && statuses.empty?)
  891. statuses = statuses.compact.uniq.sort
  892. if blocked? || descendants.open.any?
  893. # cannot close a blocked issue or a parent with open subtasks
  894. statuses.reject!(&:is_closed?)
  895. end
  896. if ancestors.open(false).any?
  897. # cannot reopen a subtask of a closed parent
  898. statuses.select!(&:is_closed?)
  899. end
  900. statuses
  901. end
  902. # Returns the original tracker
  903. def tracker_was
  904. Tracker.find_by_id(tracker_id_in_database)
  905. end
  906. # Returns the previous assignee whenever we're before the save
  907. # or in after_* callbacks
  908. def previous_assignee
  909. if previous_assigned_to_id = assigned_to_id_change_to_be_saved.nil? ? assigned_to_id_before_last_save : assigned_to_id_in_database
  910. Principal.find_by_id(previous_assigned_to_id)
  911. end
  912. end
  913. # Returns the users that should be notified
  914. def notified_users
  915. # Author and assignee are always notified unless they have been
  916. # locked or don't want to be notified
  917. notified = [author, assigned_to, previous_assignee].compact.uniq
  918. notified = notified.map {|n| n.is_a?(Group) ? n.users : n}.flatten
  919. notified.uniq!
  920. notified = notified.select {|u| u.active? && u.notify_about?(self)}
  921. notified += project.notified_users
  922. notified.uniq!
  923. # Remove users that can not view the issue
  924. notified.reject! {|user| !visible?(user)}
  925. notified
  926. end
  927. # Returns the email addresses that should be notified
  928. def recipients
  929. notified_users.collect(&:mail)
  930. end
  931. def notify?
  932. @notify != false
  933. end
  934. def notify=(arg)
  935. @notify = arg
  936. end
  937. # Returns the number of hours spent on this issue
  938. def spent_hours
  939. @spent_hours ||= time_entries.sum(:hours) || 0.0
  940. end
  941. # Returns the total number of hours spent on this issue and its descendants
  942. def total_spent_hours
  943. @total_spent_hours ||=
  944. if leaf?
  945. spent_hours
  946. else
  947. self_and_descendants.joins(:time_entries).sum("#{TimeEntry.table_name}.hours").to_f || 0.0
  948. end
  949. end
  950. def total_estimated_hours
  951. if leaf?
  952. estimated_hours
  953. else
  954. @total_estimated_hours ||= self_and_descendants.visible.sum(:estimated_hours)
  955. end
  956. end
  957. def relations
  958. @relations ||= IssueRelation::Relations.new(self, (relations_from + relations_to).sort)
  959. end
  960. def last_updated_by
  961. if @last_updated_by
  962. @last_updated_by.presence
  963. else
  964. journals.reorder(:id => :desc).first.try(:user)
  965. end
  966. end
  967. def last_notes
  968. if @last_notes
  969. @last_notes
  970. else
  971. journals.where.not(notes: '').reorder(:id => :desc).first.try(:notes)
  972. end
  973. end
  974. # Preloads relations for a collection of issues
  975. def self.load_relations(issues)
  976. if issues.any?
  977. relations = IssueRelation.where("issue_from_id IN (:ids) OR issue_to_id IN (:ids)", :ids => issues.map(&:id)).all
  978. issues.each do |issue|
  979. issue.instance_variable_set "@relations", relations.select {|r| r.issue_from_id == issue.id || r.issue_to_id == issue.id}
  980. end
  981. end
  982. end
  983. # Preloads visible spent time for a collection of issues
  984. def self.load_visible_spent_hours(issues, user=User.current)
  985. if issues.any?
  986. hours_by_issue_id = TimeEntry.visible(user).where(:issue_id => issues.map(&:id)).group(:issue_id).sum(:hours)
  987. issues.each do |issue|
  988. issue.instance_variable_set "@spent_hours", (hours_by_issue_id[issue.id] || 0.0)
  989. end
  990. end
  991. end
  992. # Preloads visible total spent time for a collection of issues
  993. def self.load_visible_total_spent_hours(issues, user=User.current)
  994. if issues.any?
  995. hours_by_issue_id = TimeEntry.visible(user).joins(:issue).
  996. joins("JOIN #{Issue.table_name} parent ON parent.root_id = #{Issue.table_name}.root_id" +
  997. " AND parent.lft <= #{Issue.table_name}.lft AND parent.rgt >= #{Issue.table_name}.rgt").
  998. where("parent.id IN (?)", issues.map(&:id)).group("parent.id").sum(:hours)
  999. issues.each do |issue|
  1000. issue.instance_variable_set "@total_spent_hours", (hours_by_issue_id[issue.id] || 0.0)
  1001. end
  1002. end
  1003. end
  1004. # Preloads visible relations for a collection of issues
  1005. def self.load_visible_relations(issues, user=User.current)
  1006. if issues.any?
  1007. issue_ids = issues.map(&:id)
  1008. # Relations with issue_from in given issues and visible issue_to
  1009. relations_from = IssueRelation.joins(:issue_to => :project).
  1010. where(visible_condition(user)).where(:issue_from_id => issue_ids).to_a
  1011. # Relations with issue_to in given issues and visible issue_from
  1012. relations_to = IssueRelation.joins(:issue_from => :project).
  1013. where(visible_condition(user)).
  1014. where(:issue_to_id => issue_ids).to_a
  1015. issues.each do |issue|
  1016. relations =
  1017. relations_from.select {|relation| relation.issue_from_id == issue.id} +
  1018. relations_to.select {|relation| relation.issue_to_id == issue.id}
  1019. issue.instance_variable_set "@relations", IssueRelation::Relations.new(issue, relations.sort)
  1020. end
  1021. end
  1022. end
  1023. # Returns a scope of the given issues and their descendants
  1024. def self.self_and_descendants(issues)
  1025. Issue.joins("JOIN #{Issue.table_name} ancestors" +
  1026. " ON ancestors.root_id = #{Issue.table_name}.root_id" +
  1027. " AND ancestors.lft <= #{Issue.table_name}.lft AND ancestors.rgt >= #{Issue.table_name}.rgt"
  1028. ).
  1029. where(:ancestors => {:id => issues.map(&:id)})
  1030. end
  1031. # Preloads users who updated last a collection of issues
  1032. def self.load_visible_last_updated_by(issues, user=User.current)
  1033. if issues.any?
  1034. issue_ids = issues.map(&:id)
  1035. journal_ids = Journal.joins(issue: :project).
  1036. where(:journalized_type => 'Issue', :journalized_id => issue_ids).
  1037. where(Journal.visible_notes_condition(user, :skip_pre_condition => true)).
  1038. group(:journalized_id).
  1039. maximum(:id).
  1040. values
  1041. journals = Journal.where(:id => journal_ids).preload(:user).to_a
  1042. issues.each do |issue|
  1043. journal = journals.detect {|j| j.journalized_id == issue.id}
  1044. issue.instance_variable_set("@last_updated_by", journal.try(:user) || '')
  1045. end
  1046. end
  1047. end
  1048. # Preloads visible last notes for a collection of issues
  1049. def self.load_visible_last_notes(issues, user=User.current)
  1050. if issues.any?
  1051. issue_ids = issues.map(&:id)
  1052. journal_ids = Journal.joins(issue: :project).
  1053. where(:journalized_type => 'Issue', :journalized_id => issue_ids).
  1054. where(Journal.visible_notes_condition(user, :skip_pre_condition => true)).
  1055. where.not(notes: '').
  1056. group(:journalized_id).
  1057. maximum(:id).
  1058. values
  1059. journals = Journal.where(:id => journal_ids).to_a
  1060. issues.each do |issue|
  1061. journal = journals.detect {|j| j.journalized_id == issue.id}
  1062. issue.instance_variable_set("@last_notes", journal.try(:notes) || '')
  1063. end
  1064. end
  1065. end
  1066. # Finds an issue relation given its id.
  1067. def find_relation(relation_id)
  1068. IssueRelation.where("issue_to_id = ? OR issue_from_id = ?", id, id).find(relation_id)
  1069. end
  1070. # Returns true if this issue blocks the other issue, otherwise returns false
  1071. def blocks?(other)
  1072. all = [self]
  1073. last = [self]
  1074. while last.any?
  1075. current = last.map {|i| i.relations_from.where(:relation_type => IssueRelation::TYPE_BLOCKS).map(&:issue_to)}.flatten.uniq
  1076. current -= last
  1077. current -= all
  1078. return true if current.include?(other)
  1079. last = current
  1080. all += last
  1081. end
  1082. false
  1083. end
  1084. # Returns true if the other issue might be rescheduled if the start/due dates of this issue change
  1085. def would_reschedule?(other)
  1086. all = [self]
  1087. last = [self]
  1088. while last.any?
  1089. current = last.map {|i|
  1090. i.relations_from.where(:relation_type => IssueRelation::TYPE_PRECEDES).map(&:issue_to) +
  1091. i.leaves.to_a +
  1092. i.ancestors.map {|a| a.relations_from.where(:relation_type => IssueRelation::TYPE_PRECEDES).map(&:issue_to)}
  1093. }.flatten.uniq
  1094. current -= last
  1095. current -= all
  1096. return true if current.include?(other)
  1097. last = current
  1098. all += last
  1099. end
  1100. false
  1101. end
  1102. # Returns an array of issues that duplicate this one
  1103. def duplicates
  1104. relations_to.select {|r| r.relation_type == IssueRelation::TYPE_DUPLICATES}.collect {|r| r.issue_from}
  1105. end
  1106. # Returns the due date or the target due date if any
  1107. # Used on gantt chart
  1108. def due_before
  1109. due_date || (fixed_version ? fixed_version.effective_date : nil)
  1110. end
  1111. # Returns the time scheduled for this issue.
  1112. #
  1113. # Example:
  1114. # Start Date: 2/26/09, End Date: 3/04/09
  1115. # duration => 6
  1116. def duration
  1117. (start_date && due_date) ? due_date - start_date : 0
  1118. end
  1119. # Returns the duration in working days
  1120. def working_duration
  1121. (start_date && due_date) ? working_days(start_date, due_date) : 0
  1122. end
  1123. def soonest_start(reload=false)
  1124. if @soonest_start.nil? || reload
  1125. relations_to.reload if reload
  1126. dates = relations_to.collect{|relation| relation.successor_soonest_start}
  1127. p = @parent_issue || parent
  1128. if p && Setting.parent_issue_dates == 'derived'
  1129. dates << p.soonest_start
  1130. end
  1131. @soonest_start = dates.compact.max
  1132. end
  1133. @soonest_start
  1134. end
  1135. # Sets start_date on the given date or the next working day
  1136. # and changes due_date to keep the same working duration.
  1137. def reschedule_on(date)
  1138. wd = working_duration
  1139. date = next_working_date(date)
  1140. self.start_date = date
  1141. self.due_date = add_working_days(date, wd)
  1142. end
  1143. # Reschedules the issue on the given date or the next working day and saves the record.
  1144. # If the issue is a parent task, this is done by rescheduling its subtasks.
  1145. def reschedule_on!(date, journal=nil)
  1146. return if date.nil?
  1147. if leaf? || !dates_derived?
  1148. if start_date.nil? || start_date != date
  1149. if start_date && start_date > date
  1150. # Issue can not be moved earlier than its soonest start date
  1151. date = [soonest_start(true), date].compact.max
  1152. end
  1153. if journal
  1154. init_journal(journal.user)
  1155. end
  1156. reschedule_on(date)
  1157. begin
  1158. save
  1159. rescue ActiveRecord::StaleObjectError
  1160. reload
  1161. reschedule_on(date)
  1162. save
  1163. end
  1164. end
  1165. else
  1166. leaves.each do |leaf|
  1167. if leaf.start_date
  1168. # Only move subtask if it starts at the same date as the parent
  1169. # or if it starts before the given date
  1170. if start_date == leaf.start_date || date > leaf.start_date
  1171. leaf.reschedule_on!(date)
  1172. end
  1173. else
  1174. leaf.reschedule_on!(date)
  1175. end
  1176. end
  1177. end
  1178. end
  1179. def dates_derived?
  1180. !leaf? && Setting.parent_issue_dates == 'derived'
  1181. end
  1182. def priority_derived?
  1183. !leaf? && Setting.parent_issue_priority == 'derived'
  1184. end
  1185. def done_ratio_derived?
  1186. !leaf? && Setting.parent_issue_done_ratio == 'derived'
  1187. end
  1188. def <=>(issue)
  1189. if issue.nil?
  1190. -1
  1191. elsif root_id != issue.root_id
  1192. (root_id || 0) <=> (issue.root_id || 0)
  1193. else
  1194. (lft || 0) <=> (issue.lft || 0)
  1195. end
  1196. end
  1197. def to_s
  1198. "#{tracker} ##{id}: #{subject}"
  1199. end
  1200. # Returns a string of css classes that apply to the issue
  1201. def css_classes(user=User.current)
  1202. s = +"issue tracker-#{tracker_id} status-#{status_id} #{priority.try(:css_classes)}"
  1203. s << ' closed' if closed?
  1204. s << ' overdue' if overdue?
  1205. s << ' child' if child?
  1206. s << ' parent' unless leaf?
  1207. s << ' private' if is_private?
  1208. if user.logged?
  1209. s << ' created-by-me' if author_id == user.id
  1210. s << ' assigned-to-me' if assigned_to_id == user.id
  1211. s << ' assigned-to-my-group' if user.groups.any? {|g| g.id == assigned_to_id}
  1212. end
  1213. s
  1214. end
  1215. # Unassigns issues from +version+ if it's no longer shared with issue's project
  1216. def self.update_versions_from_sharing_change(version)
  1217. # Update issues assigned to the version
  1218. update_versions(["#{Issue.table_name}.fixed_version_id = ?", version.id])
  1219. end
  1220. # Unassigns issues from versions that are no longer shared
  1221. # after +project+ was moved
  1222. def self.update_versions_from_hierarchy_change(project)
  1223. moved_project_ids = project.self_and_descendants.reload.pluck(:id)
  1224. # Update issues of the moved projects and issues assigned to a version of a moved project
  1225. Issue.update_versions(
  1226. ["#{Version.table_name}.project_id IN (?) OR #{Issue.table_name}.project_id IN (?)",
  1227. moved_project_ids, moved_project_ids]
  1228. )
  1229. end
  1230. def parent_issue_id=(arg)
  1231. s = arg.to_s.strip.presence
  1232. if s && (m = s.match(%r{\A#?(\d+)\z})) && (@parent_issue = Issue.find_by_id(m[1]))
  1233. @invalid_parent_issue_id = nil
  1234. elsif s.blank?
  1235. @parent_issue = nil
  1236. @invalid_parent_issue_id = nil
  1237. else
  1238. @parent_issue = nil
  1239. @invalid_parent_issue_id = arg
  1240. end
  1241. end
  1242. def parent_issue_id
  1243. if @invalid_parent_issue_id
  1244. @invalid_parent_issue_id
  1245. elsif instance_variable_defined? :@parent_issue
  1246. @parent_issue.nil? ? nil : @parent_issue.id
  1247. else
  1248. parent_id
  1249. end
  1250. end
  1251. def set_parent_id
  1252. self.parent_id = parent_issue_id
  1253. end
  1254. # Returns true if issue's project is a valid
  1255. # parent issue project
  1256. def valid_parent_project?(issue=parent)
  1257. return true if issue.nil? || issue.project_id == project_id
  1258. case Setting.cross_project_subtasks
  1259. when 'system'
  1260. true
  1261. when 'tree'
  1262. issue.project.root == project.root
  1263. when 'hierarchy'
  1264. issue.project.is_or_is_ancestor_of?(project) || issue.project.is_descendant_of?(project)
  1265. when 'descendants'
  1266. issue.project.is_or_is_ancestor_of?(project)
  1267. else
  1268. false
  1269. end
  1270. end
  1271. # Returns an issue scope based on project and scope
  1272. def self.cross_project_scope(project, scope=nil)
  1273. if project.nil?
  1274. return Issue
  1275. end
  1276. case scope
  1277. when 'all', 'system'
  1278. Issue
  1279. when 'tree'
  1280. Issue.joins(:project).where("(#{Project.table_name}.lft >= :lft AND #{Project.table_name}.rgt <= :rgt)",
  1281. :lft => project.root.lft, :rgt => project.root.rgt)
  1282. when 'hierarchy'
  1283. Issue.joins(:project).where("(#{Project.table_name}.lft >= :lft AND #{Project.table_name}.rgt <= :rgt) OR (#{Project.table_name}.lft < :lft AND #{Project.table_name}.rgt > :rgt)",
  1284. :lft => project.lft, :rgt => project.rgt)
  1285. when 'descendants'
  1286. Issue.joins(:project).where("(#{Project.table_name}.lft >= :lft AND #{Project.table_name}.rgt <= :rgt)",
  1287. :lft => project.lft, :rgt => project.rgt)
  1288. else
  1289. Issue.where(:project_id => project.id)
  1290. end
  1291. end
  1292. def self.by_tracker(project, with_subprojects=false)
  1293. count_and_group_by(:project => project, :association => :tracker, :with_subprojects => with_subprojects)
  1294. end
  1295. def self.by_version(project, with_subprojects=false)
  1296. count_and_group_by(:project => project, :association => :fixed_version, :with_subprojects => with_subprojects)
  1297. end
  1298. def self.by_priority(project, with_subprojects=false)
  1299. count_and_group_by(:project => project, :association => :priority, :with_subprojects => with_subprojects)
  1300. end
  1301. def self.by_category(project, with_subprojects=false)
  1302. count_and_group_by(:project => project, :association => :category, :with_subprojects => with_subprojects)
  1303. end
  1304. def self.by_assigned_to(project, with_subprojects=false)
  1305. count_and_group_by(:project => project, :association => :assigned_to, :with_subprojects => with_subprojects)
  1306. end
  1307. def self.by_author(project, with_subprojects=false)
  1308. count_and_group_by(:project => project, :association => :author, :with_subprojects => with_subprojects)
  1309. end
  1310. def self.by_subproject(project)
  1311. r = count_and_group_by(:project => project, :with_subprojects => true, :association => :project)
  1312. r.reject {|r| r["project_id"] == project.id.to_s}
  1313. end
  1314. # Query generator for selecting groups of issue counts for a project
  1315. # based on specific criteria
  1316. #
  1317. # Options
  1318. # * project - Project to search in.
  1319. # * with_subprojects - Includes subprojects issues if set to true.
  1320. # * association - Symbol. Association for grouping.
  1321. def self.count_and_group_by(options)
  1322. assoc = reflect_on_association(options[:association])
  1323. select_field = assoc.foreign_key
  1324. Issue.
  1325. visible(User.current, :project => options[:project], :with_subprojects => options[:with_subprojects]).
  1326. joins(:status, assoc.name).
  1327. group(:status_id, :is_closed, select_field).
  1328. count.
  1329. map do |columns, total|
  1330. status_id, is_closed, field_value = columns
  1331. is_closed = ['t', 'true', '1'].include?(is_closed.to_s)
  1332. {
  1333. "status_id" => status_id.to_s,
  1334. "closed" => is_closed,
  1335. select_field => field_value.to_s,
  1336. "total" => total.to_s
  1337. }
  1338. end
  1339. end
  1340. # Returns a scope of projects that user can assign the issue to
  1341. def allowed_target_projects(user=User.current, context=nil)
  1342. if new_record? && context.is_a?(Project) && !copy?
  1343. current_project = context.self_and_descendants
  1344. elsif new_record?
  1345. current_project = nil
  1346. else
  1347. current_project = project
  1348. end
  1349. self.class.allowed_target_projects(user, current_project)
  1350. end
  1351. # Returns a scope of projects that user can assign issues to
  1352. # If current_project is given, it will be included in the scope
  1353. def self.allowed_target_projects(user=User.current, current_project=nil)
  1354. condition = Project.allowed_to_condition(user, :add_issues)
  1355. if current_project.is_a?(Project)
  1356. condition = ["(#{condition}) OR #{Project.table_name}.id = ?", current_project.id]
  1357. elsif current_project
  1358. condition = ["(#{condition}) AND #{Project.table_name}.id IN (?)", current_project.map(&:id)]
  1359. end
  1360. Project.where(condition).having_trackers
  1361. end
  1362. # Returns a scope of trackers that user can assign the issue to
  1363. def allowed_target_trackers(user=User.current)
  1364. self.class.allowed_target_trackers(project, user, tracker_id_was)
  1365. end
  1366. # Returns a scope of trackers that user can assign project issues to
  1367. def self.allowed_target_trackers(project, user=User.current, current_tracker=nil)
  1368. if project
  1369. scope = project.trackers.sorted
  1370. unless user.admin?
  1371. roles = user.roles_for_project(project).select {|r| r.has_permission?(:add_issues)}
  1372. unless roles.any? {|r| r.permissions_all_trackers?(:add_issues)}
  1373. tracker_ids = roles.map {|r| r.permissions_tracker_ids(:add_issues)}.flatten.uniq
  1374. if current_tracker
  1375. tracker_ids << current_tracker
  1376. end
  1377. scope = scope.where(:id => tracker_ids)
  1378. end
  1379. end
  1380. scope
  1381. else
  1382. Tracker.none
  1383. end
  1384. end
  1385. private
  1386. def user_tracker_permission?(user, permission)
  1387. if project && !project.active?
  1388. perm = Redmine::AccessControl.permission(permission)
  1389. return false unless perm && perm.read?
  1390. end
  1391. if user.admin?
  1392. true
  1393. else
  1394. roles = user.roles_for_project(project).select {|r| r.has_permission?(permission)}
  1395. roles.any? {|r| r.permissions_all_trackers?(permission) || r.permissions_tracker_ids?(permission, tracker_id)}
  1396. end
  1397. end
  1398. def after_project_change
  1399. # Update project_id on related time entries
  1400. TimeEntry.where({:issue_id => id}).update_all(["project_id = ?", project_id])
  1401. # Delete issue relations
  1402. unless Setting.cross_project_issue_relations?
  1403. relations_from.clear
  1404. relations_to.clear
  1405. end
  1406. # Move subtasks that were in the same project
  1407. children.each do |child|
  1408. next unless child.project_id == project_id_before_last_save
  1409. # Change project and keep project
  1410. child.send :project=, project, true
  1411. unless child.save
  1412. errors.add :base, l(:error_move_of_child_not_possible, :child => "##{child.id}", :errors => child.errors.full_messages.join(", "))
  1413. raise ActiveRecord::Rollback
  1414. end
  1415. end
  1416. end
  1417. # Callback for after the creation of an issue by copy
  1418. # * adds a "copied to" relation with the copied issue
  1419. # * copies subtasks from the copied issue
  1420. def after_create_from_copy
  1421. return unless copy? && !@after_create_from_copy_handled
  1422. if (@copied_from.project_id == project_id || Setting.cross_project_issue_relations?) && @copy_options[:link] != false
  1423. if @current_journal
  1424. @copied_from.init_journal(@current_journal.user)
  1425. end
  1426. relation = IssueRelation.new(:issue_from => @copied_from, :issue_to => self, :relation_type => IssueRelation::TYPE_COPIED_TO)
  1427. unless relation.save
  1428. logger.error "Could not create relation while copying ##{@copied_from.id} to ##{id} due to validation errors: #{relation.errors.full_messages.join(', ')}" if logger
  1429. end
  1430. end
  1431. unless @copied_from.leaf? || @copy_options[:subtasks] == false
  1432. copy_options = (@copy_options || {}).merge(:subtasks => false)
  1433. copied_issue_ids = {@copied_from.id => self.id}
  1434. @copied_from.reload.descendants.reorder("#{Issue.table_name}.lft").each do |child|
  1435. # Do not copy self when copying an issue as a descendant of the copied issue
  1436. next if child == self
  1437. # Do not copy subtasks of issues that were not copied
  1438. next unless copied_issue_ids[child.parent_id]
  1439. # Do not copy subtasks that are not visible to avoid potential disclosure of private data
  1440. unless child.visible?
  1441. logger.error "Subtask ##{child.id} was not copied during ##{@copied_from.id} copy because it is not visible to the current user" if logger
  1442. next
  1443. end
  1444. copy = Issue.new.copy_from(child, copy_options)
  1445. if @current_journal
  1446. copy.init_journal(@current_journal.user)
  1447. end
  1448. copy.author = author
  1449. copy.project = project
  1450. copy.parent_issue_id = copied_issue_ids[child.parent_id]
  1451. copy.fixed_version_id = nil unless child.fixed_version.present? && child.fixed_version.status == 'open'
  1452. copy.assigned_to = nil unless child.assigned_to_id.present? && child.assigned_to.status == User::STATUS_ACTIVE
  1453. unless copy.save
  1454. 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
  1455. next
  1456. end
  1457. copied_issue_ids[child.id] = copy.id
  1458. end
  1459. end
  1460. @after_create_from_copy_handled = true
  1461. end
  1462. def update_nested_set_attributes
  1463. if saved_change_to_parent_id?
  1464. update_nested_set_attributes_on_parent_change
  1465. end
  1466. remove_instance_variable(:@parent_issue) if instance_variable_defined?(:@parent_issue)
  1467. end
  1468. # Updates the nested set for when an existing issue is moved
  1469. def update_nested_set_attributes_on_parent_change
  1470. former_parent_id = parent_id_before_last_save
  1471. # delete invalid relations of all descendants
  1472. self_and_descendants.each do |issue|
  1473. issue.relations.each do |relation|
  1474. relation.destroy unless relation.valid?
  1475. end
  1476. end
  1477. # update former parent
  1478. recalculate_attributes_for(former_parent_id) if former_parent_id
  1479. end
  1480. def update_parent_attributes
  1481. if parent_id
  1482. recalculate_attributes_for(parent_id)
  1483. association(:parent).reset
  1484. end
  1485. end
  1486. def recalculate_attributes_for(issue_id)
  1487. if issue_id && p = Issue.find_by_id(issue_id)
  1488. if p.priority_derived?
  1489. # priority = highest priority of open children
  1490. # priority is left unchanged if all children are closed and there's no default priority defined
  1491. if priority_position = p.children.open.joins(:priority).maximum("#{IssuePriority.table_name}.position")
  1492. p.priority = IssuePriority.find_by_position(priority_position)
  1493. elsif default_priority = IssuePriority.default
  1494. p.priority = default_priority
  1495. end
  1496. end
  1497. if p.dates_derived?
  1498. # start/due dates = lowest/highest dates of children
  1499. p.start_date = p.children.minimum(:start_date)
  1500. p.due_date = p.children.maximum(:due_date)
  1501. if p.start_date && p.due_date && p.due_date < p.start_date
  1502. p.start_date, p.due_date = p.due_date, p.start_date
  1503. end
  1504. end
  1505. if p.done_ratio_derived?
  1506. # done ratio = average ratio of children weighted with their total estimated hours
  1507. unless Issue.use_status_for_done_ratio? && p.status && p.status.default_done_ratio
  1508. children = p.children.to_a
  1509. if children.any?
  1510. child_with_total_estimated_hours = children.select {|c| c.total_estimated_hours.to_f > 0.0}
  1511. if child_with_total_estimated_hours.any?
  1512. average = child_with_total_estimated_hours.map(&:total_estimated_hours).sum.to_f / child_with_total_estimated_hours.count
  1513. else
  1514. average = 1.0
  1515. end
  1516. done = children.map {|c|
  1517. estimated = c.total_estimated_hours.to_f
  1518. estimated = average unless estimated > 0.0
  1519. ratio = c.closed? ? 100 : (c.done_ratio || 0)
  1520. estimated * ratio
  1521. }.sum
  1522. progress = done / (average * children.count)
  1523. p.done_ratio = progress.floor
  1524. end
  1525. end
  1526. end
  1527. # ancestors will be recursively updated
  1528. p.save(:validate => false)
  1529. end
  1530. end
  1531. # Singleton class method is public
  1532. class << self
  1533. # Update issues so their versions are not pointing to a
  1534. # fixed_version that is not shared with the issue's project
  1535. def update_versions(conditions=nil)
  1536. # Only need to update issues with a fixed_version from
  1537. # a different project and that is not systemwide shared
  1538. Issue.joins(:project, :fixed_version).
  1539. where("#{Issue.table_name}.fixed_version_id IS NOT NULL" +
  1540. " AND #{Issue.table_name}.project_id <> #{Version.table_name}.project_id" +
  1541. " AND #{Version.table_name}.sharing <> 'system'").
  1542. where(conditions).each do |issue|
  1543. next if issue.project.nil? || issue.fixed_version.nil?
  1544. unless issue.project.shared_versions.include?(issue.fixed_version)
  1545. issue.init_journal(User.current)
  1546. issue.fixed_version = nil
  1547. issue.save
  1548. end
  1549. end
  1550. end
  1551. end
  1552. def delete_selected_attachments
  1553. if deleted_attachment_ids.present?
  1554. objects = attachments.where(:id => deleted_attachment_ids.map(&:to_i))
  1555. attachments.delete(objects)
  1556. end
  1557. end
  1558. # Callback on file attachment
  1559. def attachment_added(attachment)
  1560. if current_journal && !attachment.new_record?
  1561. current_journal.journalize_attachment(attachment, :added)
  1562. end
  1563. end
  1564. # Callback on attachment deletion
  1565. def attachment_removed(attachment)
  1566. if current_journal && !attachment.new_record?
  1567. current_journal.journalize_attachment(attachment, :removed)
  1568. current_journal.save
  1569. end
  1570. end
  1571. # Called after a relation is added
  1572. def relation_added(relation)
  1573. if current_journal
  1574. current_journal.journalize_relation(relation, :added)
  1575. current_journal.save
  1576. end
  1577. end
  1578. # Called after a relation is removed
  1579. def relation_removed(relation)
  1580. if current_journal
  1581. current_journal.journalize_relation(relation, :removed)
  1582. current_journal.save
  1583. end
  1584. end
  1585. # Default assignment based on project or category
  1586. def default_assign
  1587. if assigned_to.nil?
  1588. if category && category.assigned_to
  1589. self.assigned_to = category.assigned_to
  1590. elsif project && project.default_assigned_to
  1591. self.assigned_to = project.default_assigned_to
  1592. end
  1593. end
  1594. end
  1595. # Updates start/due dates of following issues
  1596. def reschedule_following_issues
  1597. if saved_change_to_start_date? || saved_change_to_due_date?
  1598. relations_from.each do |relation|
  1599. relation.set_issue_to_dates(@current_journal)
  1600. end
  1601. end
  1602. end
  1603. # Closes duplicates if the issue is being closed
  1604. def close_duplicates
  1605. if Setting.close_duplicate_issues? && closing?
  1606. duplicates.each do |duplicate|
  1607. # Reload is needed in case the duplicate was updated by a previous duplicate
  1608. duplicate.reload
  1609. # Don't re-close it if it's already closed
  1610. next if duplicate.closed?
  1611. # Same user and notes
  1612. if @current_journal
  1613. duplicate.init_journal(@current_journal.user, @current_journal.notes)
  1614. duplicate.private_notes = @current_journal.private_notes
  1615. end
  1616. duplicate.update_attribute :status, self.status
  1617. end
  1618. end
  1619. end
  1620. # Make sure updated_on is updated when adding a note and set updated_on now
  1621. # so we can set closed_on with the same value on closing
  1622. def force_updated_on_change
  1623. if @current_journal || changed?
  1624. self.updated_on = current_time_from_proper_timezone
  1625. if new_record?
  1626. self.created_on = updated_on
  1627. end
  1628. end
  1629. end
  1630. # Callback for setting closed_on when the issue is closed.
  1631. # The closed_on attribute stores the time of the last closing
  1632. # and is preserved when the issue is reopened.
  1633. def update_closed_on
  1634. if closing?
  1635. self.closed_on = updated_on
  1636. end
  1637. end
  1638. # Saves the changes in a Journal
  1639. # Called after_save
  1640. def create_journal
  1641. if current_journal
  1642. current_journal.save
  1643. end
  1644. end
  1645. def send_notification
  1646. if notify? && Setting.notified_events.include?('issue_added')
  1647. Mailer.deliver_issue_add(self)
  1648. end
  1649. end
  1650. def clear_disabled_fields
  1651. if tracker
  1652. tracker.disabled_core_fields.each do |attribute|
  1653. send "#{attribute}=", nil
  1654. end
  1655. self.done_ratio ||= 0
  1656. end
  1657. end
  1658. end