item.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Checklist::Item < ApplicationModel
  3. include ChecksClientNotification
  4. include HasHistory
  5. include HasDefaultModelUserRelations
  6. include Checklist::Item::Assets
  7. attr_accessor :initial_clone
  8. belongs_to :checklist
  9. belongs_to :ticket, optional: true
  10. scope :for_user, ->(user) { joins(checklist: :ticket).where(tickets: { group: user.group_ids_access('read') }) }
  11. before_validation :detect_ticket_reference, on: %i[create update], unless: :initial_clone
  12. validate :detect_ticket_loop_reference, on: %i[create update], unless: -> { ticket.blank? || checklist.blank? }
  13. validate :validate_item_count, on: :create
  14. after_create :update_checklist
  15. after_update :update_checklist
  16. after_destroy :update_checklist
  17. validates :text, presence: { allow_blank: true }
  18. def history_log_attributes
  19. {
  20. related_o_id: checklist.ticket_id,
  21. related_history_object: 'Ticket',
  22. }
  23. end
  24. def history_create
  25. history_log('created', created_by_id, { value_to: text })
  26. end
  27. def history_destroy
  28. history_log('removed', updated_by_id, { value_to: text })
  29. end
  30. def notify_clients_data_attributes
  31. {
  32. id: id,
  33. updated_at: updated_at,
  34. updated_by_id: updated_by_id,
  35. }
  36. end
  37. def incomplete?
  38. return ticket_incomplete? if ticket.present?
  39. !checked
  40. end
  41. private
  42. def update_checklist
  43. if persisted?
  44. checklist.sorted_item_ids |= [id.to_s]
  45. else
  46. checklist.sorted_item_ids -= [id.to_s]
  47. end
  48. checklist.updated_at = Time.zone.now
  49. checklist.updated_by_id = UserInfo.current_user_id || updated_by_id
  50. checklist.save!
  51. end
  52. def detect_ticket_reference
  53. return if changes.key?(:ticket_id)
  54. ticket = Ticket::Number.check(text)
  55. return if ticket.blank?
  56. self.ticket = ticket
  57. end
  58. def detect_ticket_loop_reference
  59. return if ticket.id != checklist.ticket.id
  60. errors.add(:ticket, __('reference must not be the checklist ticket.'))
  61. end
  62. def validate_item_count
  63. return if checklist.items.count < 100
  64. errors.add(:base, __('Checklist items are limited to 100 items per checklist.'))
  65. end
  66. def ticket_incomplete?
  67. # Consider the following ticket state types as incomplete:
  68. # - closed
  69. # - merged
  70. !ticket.state.state_type.name.match?(%r{^(closed|merged)$}i)
  71. end
  72. end