class CustomWorkflow < ActiveRecord::Base belongs_to :tracker, optional: true belongs_to :project, optional: true has_many :workflow_steps, -> { order(:position) }, dependent: :destroy has_many :issue_workflow_states, dependent: :destroy validates :name, presence: true scope :active, -> { where(active: true) } scope :for_tracker, ->(tracker_id) { where(tracker_id: [tracker_id, nil]) } scope :for_project, ->(project_id) { where(project_id: [project_id, nil]) } def start_step workflow_steps.find_by(is_start: true) || workflow_steps.first end def end_step workflow_steps.find_by(is_end: true) || workflow_steps.last end def step_count workflow_steps.count end def self.find_for_issue(issue) # 프로젝트 + 트래커 매칭 먼저 wf = active.where(project_id: issue.project_id, tracker_id: issue.tracker_id).first return wf if wf # 트래커만 매칭 wf = active.where(project_id: nil, tracker_id: issue.tracker_id).first return wf if wf # 프로젝트만 매칭 wf = active.where(project_id: issue.project_id, tracker_id: nil).first return wf if wf # 기본 워크플로우 active.where(is_default: true).first end end