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

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