|
class Mission < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: :slugged
validates_presence_of :title, :slug
belongs_to :owner, :class_name => "User"
has_many :mission_agents, :dependent => :destroy
has_many :agent_steps, :through => :mission_agents
accepts_nested_attributes_for :mission_agents, allow_destroy:true
mount_uploader :cover_img, MissionCoverUploader
process_in_background :cover_img
after_initialize do |user|
check_for_completion
end
def agent_count
return self.mission_agents.count
end
def confirmed_agent_count
confirmed_agents = 0
self.mission_agents.each do |agent|
if agent.user != nil
confirmed_agents = confirmed_agents + 1
end
end
return confirmed_agents
end
def agent_count_stats
return String.new("#{self.confirmed_agent_count}/#{self.agent_count}")
end
def step_count
total_steps = 0
self.mission_agents.each do |agent|
total_steps = total_steps + agent.agent_steps.count
end
return total_steps
end
def completed_steps_count
completed_steps = 0
self.mission_agents.each do |agent|
agent.agent_steps.each do |step|
if step.completed
completed_steps = completed_steps + 1
end
end
end
return completed_steps
end
def step_count_stats
return String.new("#{self.completed_steps_count}/#{self.step_count}")
end
def percentage_completed
steps_mod = 0.8
agents_mod = 0.3
completed = (completed_steps_count * steps_mod) + (confirmed_agent_count * agents_mod)
total = (step_count * steps_mod) + (agent_count * agents_mod)
if total > 0
percentage = (100/total) * completed
else
if self.status == 3
percentage = 100
else
percentage = 0
end
end
return percentage
end
def is_agent(user)
if user
if self.mission_agents.find_all_by_user_id(user.id).count > 0
return true
end
end
return false
end
def all_steps_completed
if self.step_count > 0
self.mission_agents.each do |agent|
agent.agent_steps.each do |step|
if step.completed == false || step.completed == nil
return false
end
end
end
return true
else
return false
end
end
def check_for_completion
if self.status == 1 || self.status == 2
if seconds_left > 0
if self.all_steps_completed
self.completed
end
else
self.failed
end
end
end
def completed
self.update(status: 3)
end
def failed
self.update(status: 4)
end
def days_left
if self.status == 3 || self.status == 4
return '0'
elsif self.status == 1 && self.end_date == nil
return '?'
elsif self.end_date
time_dif = self.end_date - Time.now
days_left = time_dif / 60 / 60 / 24
return days_left.round.to_s
else
return '∞'
end
end
def seconds_left
if self.end_date
seconds_left = self.end_date - Time.now
return seconds_left
else
return 0
end
end
end
|