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

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