class Competition < ApplicationRecord has_many :competition_modules, dependent: :destroy has_many :unhidden_competition_modules, -> { where(hidden: false) }, class_name: 'CompetitionModule' has_many :competition_stages, dependent: :destroy has_many :competition_stage_sections, dependent: :destroy has_one :current_stage_section, -> { where('end_time > NOW()') }, class_name: 'CompetitionStageSection' has_many :competition_teams, dependent: :destroy has_many :team_members, dependent: :destroy has_many :chart_rules, dependent: :destroy has_many :competition_scores, dependent: :destroy has_many :competition_staffs, dependent: :destroy has_one :teacher_staff, -> { where(category: :teacher) }, class_name: 'CompetitionStaff' has_one :member_staff, -> { where.not(category: :teacher) }, class_name: 'CompetitionStaff' has_one :competition_mode_setting, dependent: :destroy has_many :informs, as: :container, dependent: :destroy has_many :attachments, as: :container, dependent: :destroy has_many :competition_awards, dependent: :destroy after_create :create_competition_modules def mode_type case mode when 1 "实训" when 2 "课堂" when 3 "教学" when 4 "托管" else "--" end end def teacher_staff_num teacher_staff ? "#{teacher_staff.minimum}~#{teacher_staff.maximum}" : "--" end def member_staff_num member_staff ? "#{member_staff.minimum}~#{member_staff.maximum}" : "--" end # 是否上架 def published? status? end # 是否为个人赛 def personal? competition_staffs.maximum(:maximum) == 1 || max_num == 1 end # 报名是否结束 def enroll_ended? enroll_end_time.blank? || enroll_end_time < Time.now end # 是否已经报名 def enrolled?(user) team_members.exists?(user_id: user.id) end # 是否禁止教师报名 def teacher_enroll_forbidden? teacher_staff.blank? || teacher_staff.maximum.zero? end # 是否禁止学生报名 def member_enroll_forbidden? member_staff.blank? || member_staff.maximum.zero? end # 老师是否能多次报名 def teacher_multiple_limited? teacher_staff&.mutiple_limited? end # 队员是否能多次报名 def member_multiple_limited? member_staff&.mutiple_limited? end def max_min_stage_time CompetitionStageSection.find_by_sql("SELECT MAX(end_time) as max_end_time, MIN(start_time) as min_start_time, competition_stage_id FROM competition_stage_sections WHERE competition_id = #{id} GROUP BY competition_stage_id order by competition_stage_id") end # def awards_count # competition_awards.pluck(:num)&.sum > 0 ? competition_awards.pluck(:num)&.sum : 20 # end private def create_competition_modules CompetitionModule.bulk_insert(*%i[competition_id name position created_at updated_at]) do |worker| %w(首页 报名 通知公告 排行榜 资料下载).each_with_index do |name, index| worker.add(competition_id: id, name: name, position: index + 1) end end end end