/
workflow.rb
92 lines (71 loc) · 1.7 KB
/
workflow.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class Workflow < ApplicationRecord
include AASM
include Loggable
def self.scopes
%i(robot admin)
end
enum scope: scopes
ransack_alias :state, :aasm_state
belongs_to :issue
has_many :tasks
accepts_nested_attributes_for :tasks, allow_destroy: true
before_destroy :destroy_tasks
def destroy_tasks
tasks.destroy_all
end
scope :running, -> {
joins(:issue)
.where(aasm_state: 'started')
}
scope :failing, -> {
joins(:issue)
.where(aasm_state: 'failed')
}
aasm do
state :new, initial: true
state :started
state :performed
state :failed
state :dismissed
event :start do
transitions from: [:new, :started], to: :started, guard: :lock_issue!
end
event :fail do
transitions from: [:started, :failed], to: :failed
end
event :dismiss do
transitions from: [:new, :started, :dismissed], to: :dismissed
end
event :finish do
transitions from: [:started, :performed], to: :performed, guard: :all_task_in_final_state?
after do
issue.unlock_issue! if aasm.from_state != :performed
end
end
end
def lock_issue!
issue.lock_issue!(false)
end
def name
"Workflow ##{id} - #{workflow_type}"
end
def state
aasm_state
end
def all_task_in_final_state?
tasks.all? {|task| task.performed? || task.failed?}
end
def all_tasks_performed?
tasks.all? {|task| task.performed?}
end
def any_task_failed?
tasks.any? {|task| task.failed? && !task.can_retry?}
end
def completed_tasks
tasks.select{|x| x.performed?}
end
def completness_ratio
return 0 if tasks.empty?
(completed_tasks.count.fdiv(tasks.count) * 100).round
end
end