checklists.rb 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module Ticket::Checklists
  3. extend ActiveSupport::Concern
  4. included do
  5. has_many :referencing_checklist_items, class_name: 'Checklist::Item', dependent: :nullify
  6. has_many :referencing_checklists, class_name: 'Checklist', through: :referencing_checklist_items, source: :checklist
  7. belongs_to :checklist, dependent: :destroy, optional: true
  8. after_save :update_referenced_checklist_items
  9. association_attributes_ignored :referencing_checklist_items
  10. validates :checklist_id, uniqueness: { allow_nil: true }
  11. validate :ensure_checklist_did_not_exist
  12. end
  13. private
  14. def update_referenced_checklist_items
  15. return if !saved_change_to_state_id?
  16. is_closed = Checklist.ticket_closed?(self)
  17. referencing_checklist_items
  18. .where(checked: !is_closed)
  19. .each { |elem| elem.update! checked: is_closed }
  20. end
  21. def ensure_checklist_did_not_exist
  22. return if !checklist_id_changed?
  23. # All is good if checklist did not exist before or will not exist afterwards
  24. return if !checklist_id || !checklist_id_was
  25. errors.add :base, __('This ticket already has a checklist.')
  26. end
  27. end