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

issue.rb 63KB

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