diff --git a/.gitignore b/.gitignore index bb4b68554..1b56839ee 100644 --- a/.gitignore +++ b/.gitignore @@ -1,39 +1,39 @@ -*.swp -/.project -/.idea -/.bundle -*.swp -/config/database.yml -/config/configuration.yml -/config/additional_environment.rb -/config/oneapm.yml -/config/environments/production.rb - - -/files/* -/log/* -/public/tmp/* -/tmp/* -/public/cache/* -/config/newrelic.yml -/public/images/avatars/* -/db/schema.rb -/Gemfile.lock -/lib/plugins/acts_as_versioned/test/debug.log -.rbenv-gemsets -.DS_Store -public/api_doc/ -/.metadata -vendor/cache -/files -/public/images/avatars -/public/files -/tags -/config/initializers/gitlab_config.rb -1234567 -public/javascripts/wechat/node_modules/ -.ruby-version -.access_token -tmux*.log -config/wechat.yml -config/oneapm.yml +*.swp +/.project +/.idea/* +/.bundle +*.swp +/config/database.yml +/config/configuration.yml +/config/additional_environment.rb +/config/oneapm.yml +/config/environments/production.rb + + +/files/* +/log/* +/public/tmp/* +/tmp/* +/public/cache/* +/config/newrelic.yml +/public/images/avatars/* +/db/schema.rb +/Gemfile.lock +/lib/plugins/acts_as_versioned/test/debug.log +.rbenv-gemsets +.DS_Store +public/api_doc/ +/.metadata +vendor/cache +/files +/public/images/avatars +/public/files +/tags +/config/initializers/gitlab_config.rb +1234567 +public/javascripts/wechat/node_modules/ +.ruby-version +.access_token +tmux*.log +config/wechat.yml +config/oneapm.yml diff --git a/app/controllers/boards_controller.rb b/app/controllers/boards_controller.rb index 1c0fa35a4..87d68f3c4 100644 --- a/app/controllers/boards_controller.rb +++ b/app/controllers/boards_controller.rb @@ -21,7 +21,7 @@ class BoardsController < ApplicationController before_filter :find_project_by_project_id, :find_board_if_available, :except => [:join_to_org_subfields] before_filter :authorize, :except => [:new, :show, :create, :index, :join_to_org_subfields, :update_position, :update_name, :update_boards_position, :update_boards_name] accept_rss_auth :index, :show - + helper :sort include SortHelper @@ -146,7 +146,7 @@ class BoardsController < ApplicationController if (@board) @topic_count = @board.topics.count(); @topic_pages = 0 #(params[:page] ? params[:page].to_i + 1 : 0) *10 - @topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all(); + @topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.updated_on) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all(); else @board = @contest.boards.build @board.name = " #{l(:label_board_contest) }"#self.name @@ -156,7 +156,7 @@ class BoardsController < ApplicationController if @board.save @topic_count = @board.topics.count(); @topic_pages = 0 #(params[:page] ? params[:page].to_i + 1 : 0) *10 - @topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all(); + @topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.updated_on) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all(); else @topics = [] end @@ -183,7 +183,7 @@ class BoardsController < ApplicationController end #分页 - @limit = 1 + @limit = 10 @is_remote = true @atta_count = @topics.count @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 @@ -370,16 +370,16 @@ class BoardsController < ApplicationController end def update_boards_name - @board.update_attribute("name", params[:name]) - @board.update_attribute("description", params[:name]) + @board.update_attribute("name", params[:name]) + @board.update_attribute("description", params[:name]) - @course_board = @course.boards.where("parent_id is NULL").first - @board = @course_board.children.order("position asc") - @board_count = @board.count + @course_board = @course.boards.where("parent_id is NULL").first + @board = @course_board.children.order("position asc") + @board_count = @board.count - respond_to do |format| - format.js - end + respond_to do |format| + format.js + end end def join_to_org_subfields @@ -392,7 +392,7 @@ class BoardsController < ApplicationController end end -private + private def redirect_to_settings_in_projects redirect_to settings_project_url(@project, :tab => 'boards') end diff --git a/app/controllers/challenges_controller.rb b/app/controllers/challenges_controller.rb index 87fe18a96..20811cab7 100644 --- a/app/controllers/challenges_controller.rb +++ b/app/controllers/challenges_controller.rb @@ -14,7 +14,7 @@ class ChallengesController < ApplicationController def new # 顶部导航 - @st = params[:st] + @st = params[:st].to_i @project_menu_type = 11 respond_to do |format| format.html { render :action => 'new', :layout => 'base_shixun' } @@ -29,17 +29,20 @@ class ChallengesController < ApplicationController @challenge.position = challenge_count + 1 @challenge.shixun = @shixun @challenge.user = User.current - # @challenge.st = params[:st] + @challenge.st = params[:st].to_i if @challenge.save! - # 创建选项 - # params[:question].each do |test| - # ChallengeQuestion.where(:option_name => option_name,:challenges => challenge_id, :positon => 1, :right_key => true) - # end + if params[:st].to_i != 0 + #创建选项 + params[:question][:cnt].each_with_index do |test, index| + answer = params[:choice][:answer][index] == "0" ? false : true + ChallengeQuestion.create(:option_name => test, :challenge_id => @challenge.id, :position => index, :right_key => answer) + end + end end redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun) rescue Exception => e flash[:error] = "#{e.message}" - redirect_to new_shixun_challenge_path(:shixun_id => @shixun) + redirect_to new_shixun_challenge_path(:shixun_id => @shixun, :st => params[:st].to_i) raise ActiveRecord::Rollback end end @@ -103,6 +106,7 @@ class ChallengesController < ApplicationController end def edit + @st = @challenge.st challenge_num = Challenge.where(:shixun_id => @shixun).count challenge_pos = @challenge.position if challenge_pos < challenge_num @@ -120,39 +124,25 @@ class ChallengesController < ApplicationController end def update - @challenge.update_attributes(params[:challenge]) - redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab]) -=begin - respond_to do |format| ActiveRecord::Base.transaction do @challenge.update_attributes(params[:challenge]) - begin - @test_sets.delete_all unless @test_sets.blank? - @challenge_tags.delete_all unless @challenge_tags.blank? - if params[:test_set][:hidden].length > 0 - params[:test_set][:input].each_with_index do |input, index| - unless (input[index] == params[:test_set][:output][index] && input[index].nil?) - params[:test_set][:hidden][index].to_i == 0 ? open = 1 : open = 0 - TestSet.create(:challenge_id => @challenge.id, :input => input, :output => params[:test_set][:output][index], :is_public => open, :position => (index + 1)) - end + if (params[:tab] == "1" || params[:tab].nil?) && @challenge.st != 0 + begin + @challenge.challenge_questions.delete_all + params[:question][:cnt].each_with_index do |test, index| + answer = params[:choice][:answer][index] == "0" ? false : true + ChallengeQuestion.create(:option_name => test, :challenge_id => @challenge.id, :position => index, :right_key => answer) end + redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab]) + rescue Exception => e + flash[:error] = "#{e.message}" + format.html{redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun)} + raise ActiveRecord::Rollback end - unless params[:knowledge].blank? - params[:knowledge][:input].each do |input| - ChallengeTag.create(:name => input, :challenge_id => @challenge.id) - end - end - # 向jenkins端发送请求,构建公共测试用例 - add_shixun_modify_status(@shixun, 1) - format.html {redirect_to shixun_challenge_path(@challenge, :shixun_id => @shixun), notice: '更新成功!'} - rescue Exception => e - flash[:error] = "#{e.message}" - format.html{redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun)} - raise ActiveRecord::Rollback + else + redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab]) end end - end -=end end def update_evaluation diff --git a/app/controllers/courses_controller.rb b/app/controllers/courses_controller.rb index 32fa30536..a0faf463a 100644 --- a/app/controllers/courses_controller.rb +++ b/app/controllers/courses_controller.rb @@ -1328,7 +1328,7 @@ class CoursesController < ApplicationController # course_request_messages = CourseMessage.where("user_id =? and course_id =? and course_message_type =? and viewed =?", User.current.id, @course.id, 'CourseRequestDealResult', false) # course_request_messages.update_all(:viewed => true) - course_activities = @course.course_activities.where("course_act_type in ('HomeworkCommon', 'Attachment', 'Course')") + course_activities = @course.course_activities.where("course_act_type in ('HomeworkCommon', 'Attachment', 'Course', 'Message')") @canShowRealName = User.current.member_of_course? @course @page = params[:page] ? params[:page].to_i + 1 : 0 if params[:type].present? diff --git a/app/controllers/games_controller.rb b/app/controllers/games_controller.rb index b53d6979e..d08e976bf 100644 --- a/app/controllers/games_controller.rb +++ b/app/controllers/games_controller.rb @@ -4,7 +4,7 @@ class GamesController < ApplicationController skip_before_filter :verify_authenticity_token, :only => [:file_update] before_filter :find_myshixun, :only => [:index] before_filter :find_game, :only => [:show, :game_build, :entry,:next_step, :outputs_show, :file_edit, :file_update, - :game_status, :change_status, :answer, :minus_score, :refresh_game_list, :reset_original_code, :reset_new_code] + :game_status, :change_status, :answer, :minus_score, :refresh_game_list, :reset_original_code, :reset_new_code, :evaluating_choice] before_filter :find_repository, :only => [:show, :entry, :file_edit, :file_update, :reset_original_code, :reset_new_code] before_filter :allowd_manager before_filter :allowd_view, :only => [:show] @@ -26,6 +26,7 @@ class GamesController < ApplicationController # @praise 判断是否点赞 # @tread 判断是否踩 # git_repository_url @myshixun, "Myshixun" + # @st 0 实践任务 1 多选任务 2 单选任务 def show # 展示全部实训 if @game.status == 1 @@ -38,12 +39,15 @@ class GamesController < ApplicationController @shixun = @myshixun.shixun # @games_count = @games.count @game_challenge = @game.challenge + @st = @game_challenge.st @had_done = @game.had_done @praise = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?", @game_challenge.id, @game_challenge.class.to_s, User.current.id).first @tread = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?", @game_challenge.id, "ChallengeTread", User.current.id).first @rev = @rev.nil? ? "master" : @rev @type = params[:type] challenge_path = @game_challenge.path + # 用户选项 + @user_answer = @game.outputs.first.actual_output.split("") unless @st == 0 || @game.outputs.blank? # 默认打开文件 logger.info("repository id is #{@repository.try(:id)}, repository's shixun_id =#{@repository.try(:myshixun_id)} shixun_id =#{@repository.try(:shixun_id)}, project_id => #{@repository.try(:project_id)}") # 验证challenge文件名的合法性 @@ -262,6 +266,36 @@ class GamesController < ApplicationController had_done: had_done} end + # 选择题评测(选择题不需要重新评测) + def evaluating_choice + @game_challenge = @game.challenge + user_answer = params[:answer] + correct = true + if !user_answer.blank? + if user_answer.split("").count != @game_challenge.challenge_questions.where(:right_key => true).count + correct = false + else + user_answer.split("").each do |answer| + question = @game_challenge.challenge_questions.where(:position => answer.to_i).first + unless question.right_key + correct = false + break + end + end + end + else + correct = false + end + @game.update_attributes(:status => 2, :end_time => Time.now) + had_done = @game.had_done + User.current.update_attributes(:grade => (User.current.grade + @game.challenge.score), :experience => (User.current.experience + @game.challenge.score)) if correct + if @game.outputs.blank? + Output.create(:game_id => @game.id, :actual_output => user_answer, :result => correct) + end + render :json => {correct: correct, had_done: had_done, :grade => User.current.grade} + end + + def change_status @game.update_attribute(:status, 0) outputs = @game.outputs diff --git a/app/controllers/managements_controller.rb b/app/controllers/managements_controller.rb index 400fad766..f0cb3aacd 100644 --- a/app/controllers/managements_controller.rb +++ b/app/controllers/managements_controller.rb @@ -1,393 +1,755 @@ -# encoding: utf-8 -class ManagementsController < ApplicationController - before_filter :require_admin - layout 'base_management' - include ManagementsHelper - include SortHelper - include UsersHelper - include ApplicationHelper - - # 0 全部;1 活动的; 2 已注册; 3 锁定 - def users - status = params[:user_status].nil? ? 0 : params[:user_status].to_i - @us_order = params[:us_order].blank? ? "desc" : params[:us_order] # 排序 - @order_key = params[:order_key].blank? ? "created_on" : params[:order_key] # 排序关键字 - condition = (params[:research_condition].nil? || params[:research_condition] == "name") ? "concat(lastname, firstname)" : params[:research_condition] - if 0 == status - if params[:research_condition] == "phone" && params[:research_contents].blank? - @users = User.order("#{@order_key} #{@us_order}").all - else - @users = User.where("#{condition} like '%#{params[:research_contents]}%'").order("#{@order_key} #{@us_order}").all - end - else - if params[:research_condition] == "phone" && params[:research_contents].blank? - @users = User.where(:status => status).order("#{@order_key} #{@us_order}").all - else - @users = User.where("status = #{status} and #{condition} like '%#{params[:research_contents]}%'").order("#{@order_key} #{@us_order}").all - end - end - - @users_count = @users.count - @limit = 20 - @is_remote = true - @users_pages = Paginator.new @users_count, @limit, params['page'] || 1 - @offset ||= @users_pages.offset - @users = paginateHelper @users, @limit - - respond_to do |format| - format.js - format.html - end - end - - def shixuns - @menu_type = 3 - sx_status = params[:status].blank? ? [0, 1, 2, 3] : params[:status].to_i # 搜索实训的状态 - keyword = params[:keyword].blank? ? "u_name" : params[:keyword] # 根据姓名/实训名搜索 - search = params[:search] # 搜索的字 - @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order] # 排序 - if "u_name" == keyword - # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user - if search.blank? - @shixuns = Shixun.where(:status => sx_status).order("created_at #{@sx_order}") - else - user_id = User.where("concat(lastname, firstname) like '%#{search}%'") - @shixuns = Shixun.where(:user_id => user_id, :status => sx_status).order("created_at #{@sx_order}") - end - else - @shixuns = Shixun.where("name like '%#{search}%'").where(:status => sx_status).order("created_at #{@sx_order}") - end - @edit_sx_num = Shixun.where(:status => 0).count - @audit_sx_num = Shixun.where(:status => 1).count - @publish_sx_num =Shixun.where(:status => 2).count - @close_sx_num = Shixun.where(:status => 3).count - - @shixuns_count = @shixuns.count - limit = 20 - @shixuns_pages = Paginator.new @shixuns_count, limit, params['page'] || 1 - @offset ||= @shixuns_pages.offset - @shixuns = paginateHelper @shixuns, limit - respond_to do |format| - format.js - format.html - end - end - - # 已发布的实训 - def publish_shixuns - @menu_type = 3 - @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order] # 排序 - search = params[:search] # 搜索字 - keyword = params[:keyword].blank? ? "u_name" : params[:keyword] # 根据姓名/实训名搜索 - close = params[:close] # 关闭实训,参数是实训的Id - unless close.blank? - Shixun.find(close).update_attribute(:status, 3) - end - if "u_name" == keyword - # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user - if search.blank? - @shixuns = Shixun.where(:status => 2).order("created_at #{@sx_order}") - else - user_id = User.where("concat(lastname, firstname) like '%#{search}%'") - @shixuns = Shixun.where(:user_id => user_id, :status => 2).order("created_at #{@sx_order}") - end - else - @shixuns = Shixun.where("name like '%#{search}%'").where(:status => 2).order("created_at #{@sx_order}") - end - @shixuns_count = @shixuns.count - limit = 20 - @shixuns_pages = Paginator.new @shixuns_count, limit, params['page'] || 1 - @offset ||= @shixuns_pages.offset - @shixuns = paginateHelper @shixuns, limit - - respond_to do |format| - format.js - format.html - end - end - - # 已关闭的实训 - def close_shixuns - @menu_type = 3 - @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order] # 排序 - search = params[:search] # 搜索字 - keyword = params[:keyword].blank? ? "u_name" : params[:keyword] # 根据姓名/实训名搜索 - reopen = params[:reopen] # 从新开启实训,参数是实训的Id - - unless reopen.blank? - Shixun.find(reopen).update_attribute(:status, 2) - end - if "u_name" == keyword - # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user - if search.blank? - @shixuns = Shixun.where(:status => 3).order("updated_at #{@sx_order}") - else - user_id = User.where("concat(lastname, firstname) like '%#{search}%'") - @shixuns = Shixun.where(:user_id => user_id, :status => 3).order("updated_at #{@sx_order}") - end - else - @shixuns = Shixun.where("name like '%#{search}%'").where(:status => 3).order("updated_at #{@sx_order}") - end - @shixuns_count = @shixuns.count - limit = 20 - @shixuns_pages = Paginator.new @shixuns_count, limit, params['page'] || 1 - @offset ||= @shixuns_pages.offset - @shixuns = paginateHelper @shixuns, limit - - respond_to do |format| - format.js - format.html - end - end - - def users_trial - @menu_type = 6 - @users = User.where(:status => 1).order("created_on desc").all - @users_count = @users.count - @limit = 20 - @is_remote = true - @users_pages = Paginator.new @users_count, @limit, params['page'] || 1 - @offset ||= @users_pages.offset - @users = paginateHelper @users, @limit - - end - - def search_user - -=begin - auth = ApplyUserAuthentication.where(:status => params[:authentication]) - auth_id = auth.blank? ? User.where(:status => 1).id : "(" + auth.map{|a| a.user_id }.join(",") + ")" -=end - - if params[:member_ids] && params[:trial_whether] == "trial_agree" - params[:member_ids].each do |member| - aUser = ApplyAction.where(:user_id => member, :container_type => "TrialAuthorization") - if aUser.blank? - ApplyAction.create(:user_id => member, :container_type => "TrialAuthorization", :status => 1) - else - aUser.update_all(:status => 1) - end - end - elsif params[:member_ids] && params[:trial_whether] == "trial_cancel" - ApplyAction.where(:user_id => params[:member_ids], :container_type => "TrialAuthorization").update_all(:status => 2) - end - - if params[:member_ids] && (params[:occupation] == "occupation_agree" || params[:realname] == "realname_agree") - User.where(:id => params[:member_ids]).update_all(:authentication => true) - elsif params[:member_ids] && (params[:occupation] == "occupation_agree" || params[:realname] == "realname_cancel") - User.where(:id => params[:member_ids]).update_all(:authentication => false) - end - - if params[:trial] == "-1" - apply = ApplyAction.where(:container_type => "TrialAuthorization") - apply_id = apply.blank? ? -1 : "(" + apply.map{|a| a.user_id}.join(",") + ")" - apply_user_id = User.where("id not in #{apply_id} and status = 1").all - apply_user_id = apply_user_id.blank? ? [-1] : apply_user_id.map{|a| a.id}.split(",")[0] - elsif params[:trial] == "-2" - apply_user_id = User.where(:status => 1).all - apply_user_id = apply_user_id.blank? ? [-1] : apply_user_id.map{|a| a.id}.split(",")[0] - else - apply = ApplyAction.where(:status => params[:trial]) - apply_user_id = apply.blank? ? [-1] : apply.map{|a| a.user_id}.split(",")[0] - end - - if params[:school] == "" - s_user_id = User.where(:status => 1).all - s_user_id = s_user_id.blank? ? [-1] : s_user_id.map{|s| s.id}.split(",")[0] - else - school = School.where("name like '%#{params[:school]}%'") - school_id = school.blank? ? -1 : school.map{|s| s.id }.split(",")[0] - usr = UserExtensions.where(:school_id => school_id) - s_user_id = usr.blank? ? [-1] : usr.map{|u| u.user_id}.split(",")[0] - end - - if params[:department] == "" - d_user_id = User.where(:status => 1).all - d_user_id = d_user_id.blank? ? [-1] : d_user_id.map{|d| d.id}.split(",")[0] - else - department = Department.where("name like '%#{params[:department]}%'").all - dep_id = department.blank? ? -1 : department.map{|d| d.id}.split(",") - usr = UserExtensions.where(:department_id => dep_id) - d_user_id = usr.blank? ? [-1] : usr.map{|u| u.user_id}.split(",")[0] - end - - user_id = s_user_id & d_user_id & apply_user_id - - if params[:research_condition] == "name" - @users = User.where(:id => user_id).where("concat(lastname, firstname) like '%#{params[:research_contents]}%'").order("created_on desc") - elsif params[:research_condition] == "email" - @users = User.where(:id => user_id).where("mail like '%#{params[:research_contents]}%'").order("created_on desc") - elsif params[:research_condition] == "phone" - if params[:research_contents].blank? - @users = User.where(:id => user_id).order("created_on desc") - else - @users = User.where(:id => user_id).where("phone like '%#{params[:research_contents]}%'").order("created_on desc") - end - - end - - @users_count = @users.count - @limit = 20 - @is_remote = true - @users_pages = Paginator.new @users_count, @limit, params['page'] || 1 - @offset ||= @users_pages.offset - @users = paginateHelper @users, @limit - - respond_to do |format| - format.js - end - end - - def update_webssh - webssh = params[:status] == "true" ? true : false - @shixuns = Shixun.find(params[:shixun_id]) - @shixuns.update_column(:webssh, webssh) - respond_to do |format| - format.js - end - end - - def affirm_cancel_auth - user_id = params[:users] - end - - - def trial_authorization - @menu_type = 9 - search = params[:search] - @status = trial_authorization_status(params[:status]) - # @status = (params[:status].blank? || params[:status] == "0") ? 0 : [1,2] - if search.blank? - @authorizations = ApplyAction.where(:container_type => "TrialAuthorization", :status => @status).includes(:user) - else - user_id = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{search}%'") - @authorizations = ApplyAction.where(:container_type => "TrialAuthorization", :status => @status, :user_id => user_id).includes(:user) - end - - @autu_count = @authorizations.count - @limit = 15 - @is_remote = true - @autu_pages = Paginator.new @autu_count, @limit, params['page'] || 1 - @offset ||= @autu_pages.offset - @authorizations = paginateHelper @authorizations, @limit - - end - - # 批量授权 - def batch_authorization - - end - - # params[:type] 1:拒绝 0:同意 - # authentication 会有一个初始值,不同的值代表不同的权限 - # REDO: 后面权限改了后,一并要改 - def trial_authorization_operation - apply_action = ApplyAction.find(params[:apply_id]) - type = params[:type] - search = params[:search] - if type == "0" - authentication_user = AuthenticationsUsers.where(:user_id => apply_action.user_id).first - if authentication_user.blank? - AuthenticationsUsers.create(:user_id => apply_action.user_id, :authentication_id => 1) - end - end - apply_action.update_attributes(:status => (params[:type] == "1" ? 2 : 1), :reason => params[:reject_reason], :dealer_id => User.current.id) - user_id = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{search}%'") - @authorizations = ApplyAction.where(:container_type => "TrialAuthorization", :status => 0, :user_id => user_id).includes(:user) - @autu_count = @authorizations.count - @limit = 15 - @is_remote = true - @autu_pages = Paginator.new @autu_count, @limit, params['page'] || 1 - @offset ||= @autu_pages.offset - @authorizations = paginateHelper @authorizations, @limit - respond_to do |format| - format.js - end - end - - def index - - end - - # copy from admin - def identity_authentication - @menu_type = 9 - @type = trial_authorization_status(params[:type]) - type = params[:type] || 0 # 存在type 就用type 没有就为 0 - user_id = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{params[:name]}%'") - @unapproved_user = ApplyUserAuthentication.where(:status => @type, :user_id => user_id).order("updated_at desc") - respond_to do |format| - format.html - format.js - end - end - - # 拒绝身份认证 - # copy from admin - def reject_authentication - apply_user = ApplyUserAuthentication.find(params[:apply_id]) - reason = apply_user.update_attributes(:status => 2, :remarks => params[:reject_reason]) - render :json => {success: reason} - end - - # 统一身份认证 - # copy from admin - def agree_authentication - apply_user = ApplyUserAuthentication.find(params[:apply_id]) - user = User.find(apply_user.user_id) - apply_user.update_attribute(:status, 1) - user.update_attribute(:authentication, true) - @unapproved_user = ApplyUserAuthentication.where(:status => 0).order("updated_at desc") - respond_to do |format| - format.js - end - end - - def shixun_authorization - @type = trial_authorization_status params[:type] - @authorizations = ApplyAction.where(:container_type => "ApplyShixun", :status => @type).order("created_at desc") - search = params[:search] - unless search.blank? - @authorizations = @authorizations.where(:container_id => Shixun.where(:id => @authorizations.map(&:container_id)).where("name like '%#{search}%'").map(&:id)).order("created_at desc") - end - - @authorizations_count = @authorizations.count - @limit = 15 - @is_remote = true - @authorizations_pages = Paginator.new @authorizations_count, @limit, params['page'] || 1 - @offset ||= @authorizations_pages.offset - @authorizations = paginateHelper @authorizations, @limit - respond_to do |format| - format.js - format.html - end - end - - def deal_shixun_authorization - apply_action = ApplyAction.find(params[:apply_id]) - type = params[:type].to_i - shixun = Shixun.find apply_action.container_id - if type == 0 - shixun.update_column('status', 0) - apply_action.update_attributes(:status => 2, :reason => params[:reject_reason], :dealer_id => User.current.id) - notes = "您所在团队提交的项目实训发布申请:#{shixun.name},审核未通过。
原因:#{params[:reject_reason]}" - shixun.shixun_members.each do |member| - JournalsForMessage.create(:jour_id => member.user_id, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0) - end - else - shixun.update_column('status', 2) - apply_action.update_attributes(:status => 1, :dealer_id => User.current.id) - shixun_modify_status_without_publish shixun, 1 - end - @authorizations = ApplyAction.where(:container_type => "ApplyShixun", :status => 0) - @authorizations_count = @authorizations.count - @limit = 15 - @is_remote = true - @authorizations_pages = Paginator.new @authorizations_count, @limit, params['page'] || 1 - @offset ||= @authorizations_pages.offset - @authorizations = paginateHelper @authorizations, @limit - respond_to do |format| - format.js - end - end -end +# encoding: utf-8 +class ManagementsController < ApplicationController + before_filter :require_admin + layout 'base_management' + include ManagementsHelper + include SortHelper + include UsersHelper + include ApplicationHelper + # 专业列表 + def profession + @syllabus=Syllabus.where("0=0") + @menu_type=11 + @sub_type=1 + major_level_option=params[:major_level_option] + discipline_category_option=params[:discipline_category_option] + first_level_discipline_option=params[:first_level_discipline_option] + if major_level_option!='0' + @syllabus=@syllabus.where(:major_level=>major_level_option) + else + @syllabus=@syllabus + end + + if discipline_category_option !=nil + @syllabus=@syllabus.where(:discipline_category_id=>discipline_category_option) + end + + if first_level_discipline_option!=nil + @syllabus=@syllabus.where(:first_level_discipline_id=>first_level_discipline_option) + end + @syllabus_count = @syllabus.count + limit = 20 + @is_remote = true + @syllabus_pages = Paginator.new @syllabus_count, limit, params['page'] || 1 + @offset ||= @syllabus_pages.offset + @syllabus = paginateHelper @syllabus, limit + + respond_to do |format| + format.js + format.html + end + + end + + # 实训适用课程 + def applicable_course + @majorcourse=MajorCourse.where("0=0") + + end + # 单位部门列表 + def departments + @menu_type = 6 + @sub_type = 2 + @department =Department.where("0=0") + search=params[:search] + if search.blank? + @department = @department + else + @department = @department.where("name like '%#{search}%'") + end + @department_count =@department.count + limit = 20 + @is_remote = true + @department_pages = Paginator.new @department_count, limit, params['page'] || 1 + @offset ||=@department_pages.offset + @department = paginateHelper @department, limit + respond_to do |format| + format.js + format.html + end + + end + # 单位列表 + def departments_part + @menu_type = 6 + @sub_type = 1 + @schools = School.where("0=0") + search=params[:search] + if search.blank? + @schools = @schools + else + @schools = @schools.where("name like '%#{search}%'") + end + @schools_count = @schools.count + limit = 20 + @is_remote = true + @schools_pages = Paginator.new @schools_count, limit, params['page'] || 1 + @offset ||= @schools_pages.offset + @schools= paginateHelper @schools, limit + + respond_to do |format| + format.js + format.html + end + end + + # 部门审核 + def depart + @menu_type = 10 + @sub_type = 3 + search = params[:search] + @apply_status = ApplyAddDepartment.where("0=0") + if search.blank? + @apply_status = @apply_status.where("0=0") + else + @apply_status= @apply_status.where("name like '%#{search}%'") + end + @apply_status_count = @apply_status.count + limit = 20 + @is_remote = true + @apply_status_pages = Paginator.new @apply_status_count, limit, params['page'] || 1 + @offset ||=@apply_status_pages.offset + @apply_status = paginateHelper @apply_status, limit + respond_to do |format| + format.js + format.html + end + end + + # 单位审批 + def unit + @menu_type = 10 + @sub_type = 4 + search = params[:search] + @apply_status = ApplyAddSchools.where("0=0") + if search.blank? + @apply_status = @apply_status.where("0=0") + else + @apply_status= @apply_status.where("name like '%#{search}%'") + end + @apply_status_count = @apply_status.count + limit = 20 + @is_remote = true + @apply_status_pages = Paginator.new @apply_status_count, limit, params['page'] || 1 + @offset ||= @apply_status_pages.offset + @apply_status = paginateHelper @apply_status, limit + + respond_to do |format| + format.js + format.html + end + end + + # 课堂列表 + def classroom + @menu_type = 2 + @sub_type = 1 + @syllabus = Syllabus.where("0=0") + + @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order] + unless params[:school_id] || params[:search] || params[:keyword] || params[:status] + user_exs=UserExtensions.where(:user_id=> @syllabus.map(&:user_id)) + @schools = School.where(:id =>user_exs.map(&:school_id)) + end + + major_level_option=params[:major_level_option] + discipline_category_option=params[:discipline_category_option] + first_level_discipline_option=params[:first_level_discipline_option] + syllabus_major_option=params[:syllabus_major_option] + keyword=params[:keyword] + search=params[:search] + if major_level_option!='0' + @syllabus=@syllabus.where(:major_level=>major_level_option) + else + @syllabus=@syllabus + end + + if discipline_category_option !=nil + @syllabus=@syllabus.where(:discipline_category_id=>discipline_category_option) + end + + if first_level_discipline_option!=nil + @syllabus=@syllabus.where(:first_level_discipline_id=>first_level_discipline_option) + end + + if syllabus_major_option!=nil + @syllabus=@syllabus.where(:major_id=>syllabus_major_option) + end + + if params[:school_id] && params[:school_id] != '0' + @syllabus = Syllabus.includes(:user => {:user_extensions => []}).where("user_extensions.school_id = #{params[:school_id]}") + else + @syllabus = @syllabus.where("0=0") + end + + if search.blank? + @syllabus = @syllabus + else + if "u_name" == keyword + user_id = User.where("concat(lastname, firstname) like '%#{search}%'") + @syllabus = @syllabus.includes(:user).where("concat(users.lastname, users.firstname) like '%#{search}%'") + else + @syllabus= @syllabus.where("user_id like '%#{search}%'") + end + end + @syllabus_count = @syllabus.count + limit = 20 + @is_remote = true + @syllabus_pages = Paginator.new @syllabus_count, limit, params['page'] || 1 + @offset ||= @syllabus_pages.offset + @syllabus = paginateHelper @syllabus, limit + respond_to do |format| + format.html + format.js + end + end + + # 班级列表 + def classroom_classment + @menu_type = 2 + @sub_type = 2 + @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order] + @courses = Course.where("0=0") + # @courses = @courses.select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS updatetime").order("updatetime desc") + @timing=Course.where(:is_end=>false).count + @end=Course.where(:is_end=>true).count + unless params[:school_id] || params[:search] || params[:keyword] || params[:status] + user_exs=UserExtensions.where(:school_id=> @courses.map(&:school_id)) + @schools = School.where(:id =>user_exs.map(&:school_id)) + end + search = params[:search] # 搜索字 + keyword = params[:keyword].blank? ? "u_name" : params[:keyword] # 根据姓名/课程名搜索 + status = params[:status].to_i + if params[:school_id] && params[:school_id] != '0' + @courses =Course.joins("join users u on courses.tea_id = u.id").joins("join user_extensions ue on u.id = ue.user_id").where("ue.school_id = #{params[:school_id]}").order("created_at #{@sx_order}") + else + @courses = Course.where("0=0").order("created_at #{@sx_order}") + end + if params[:status] && params[:status]!='' + @courses =@courses.where(:is_end =>status).order("created_at #{@sx_order}") + end + if "u_name" == keyword + if search.blank? + @courses = @courses.order("created_at #{@sx_order}") + else + user_id = User.where("concat(lastname, firstname) like '%#{search}%'") + @courses = @courses.joins("join users u on courses.tea_id = u.id").where("concat(u.lastname, u.firstname) like '%#{search}%'").order("created_at #{@sx_order}") + end + else + @courses= @courses.where("name like '%#{search}%'").order("created_at #{@sx_order}") + end + @courses = @courses.select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS updatetime").reorder("updatetime desc") + @courses_count = @courses.count + limit = 20 + @is_remote = true + @courses_pages = Paginator.new @courses_count, limit, params['page'] || 1 + @offset ||= @courses_pages.offset + @courses = paginateHelper @courses, limit + respond_to do |format| + format.js + format.html + end + end + + # 课程实训 + def class_shixuns + @menu_type = 4 + @sub_type = 1 + @edit_class_sx_num=Subject.where(:status => 0).count + @audit_class_sx_num=Subject.where(:status => 1).count + @publish_class_sx_num=Subject.where(:status => 2).count + search = params[:search] # 搜索字 + keyword = params[:keyword].blank? ? "u_name" : params[:keyword] # 根据姓名/课程名搜索 + status = params[:status].to_i + if params[:school_id] && params[:school_id] != '0' + @c_shixuns = Subject.includes(:user => {:user_extensions => []}).where("user_extensions.school_id = #{params[:school_id]}") + else + @c_shixuns = Subject.where("0=0") + end + if params[:status] && params[:status]!='' + @c_shixuns= @c_shixuns.where(:status =>status) + end + if search.blank? + @c_shixuns = @c_shixuns + else + if "u_name" == keyword + user_id = User.where("concat(lastname, firstname) like '%#{search}%'") + @c_shixuns = @c_shixuns.includes(:user).where("concat(users.lastname, users.firstname) like '%#{search}%'") + else + @c_shixuns= @c_shixuns.where("name like '%#{search}%'") + end + end + @c_shixuns = @c_shixuns.reorder("created_at desc") + unless params[:school_id] || params[:search] || params[:keyword] || params[:status] + user_exs = UserExtensions.where(:user_id => @c_shixuns.map(&:user_id)) + @schools = School.where(:id => user_exs.map(&:school_id)) + end + respond_to do |format| + format.js + format.html + end + end + + # 已发布课程实训 + def class_publish_shixuns + @menu_type = 4 + @sub_type = 2 + search = params[:search] # 搜索字 + keyword = params[:keyword].blank? ? "u_name" : params[:keyword] # 根据姓名/课程名搜索 + if params[:school_id] && params[:school_id] != '0' + @c_shixuns = Subject.includes(:user => {:user_extensions => []}).where("subjects.status = 2 and user_extensions.school_id = #{params[:school_id]}") + else + @c_shixuns = Subject.where(:status => 2) + end + if search.blank? + @c_shixuns = @c_shixuns + else + if "u_name" == keyword + # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user + user_id = User.where("concat(lastname, firstname) like '%#{search}%'") + @c_shixuns = @c_shixuns.includes(:user).where("concat(users.lastname, users.firstname) like '%#{search}%'") + else + @c_shixuns= @c_shixuns.where("name like '%#{search}%'") + end + end + unless params[:school_id] || params[:search] || params[:keyword] + user_exs = UserExtensions.where(:user_id => @c_shixuns.map(&:user_id)) + @schools = School.where(:id => user_exs.map(&:school_id)) + end + respond_to do |format| + format.js + format.html + end + end + + # 0 全部;1 活动的; 2 已注册; 3 锁定 + def users + @menu_type =7 + @sub_type = 1 + status = params[:user_status].nil? ? 0 : params[:user_status].to_i + @us_order = params[:us_order].blank? ? "desc" : params[:us_order] # 排序 + @order_key = params[:order_key].blank? ? "created_on" : params[:order_key] # 排序关键字 + condition = (params[:research_condition].nil? || params[:research_condition] == "name") ? "concat(lastname, firstname)" : params[:research_condition] + if 0 == status + if params[:research_condition] == "phone" && params[:research_contents].blank? + @users = User.order("#{@order_key} #{@us_order}").all + else + @users = User.where("#{condition} like '%#{params[:research_contents]}%'").order("#{@order_key} #{@us_order}").all + end + else + if params[:research_condition] == "phone" && params[:research_contents].blank? + @users = User.where(:status => status).order("#{@order_key} #{@us_order}").all + else + @users = User.where("status = #{status} and #{condition} like '%#{params[:research_contents]}%'").order("#{@order_key} #{@us_order}").all + end + end + @users_count = @users.count + @limit = 20 + @is_remote = true + @users_pages = Paginator.new @users_count, @limit, params['page'] || 1 + @offset ||= @users_pages.offset + @users = paginateHelper @users, @limit + respond_to do |format| + format.js + format.html + end + end + + def shixuns + @menu_type = 3 + @sub_type = 1 + sx_status = params[:status].blank? ? [0, 1, 2, 3] : params[:status].to_i # 搜索实训的状态 + keyword = params[:keyword].blank? ? "u_name" : params[:keyword] # 根据姓名/实训名搜索 + search = params[:search] # 搜索的字 + @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order] # 排序 + if "u_name" == keyword + # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user + if search.blank? + @shixuns = Shixun.where(:status => sx_status).order("created_at #{@sx_order}") + else + user_id = User.where("concat(lastname, firstname) like '%#{search}%'") + @shixuns = Shixun.where(:user_id => user_id, :status => sx_status).order("created_at #{@sx_order}") + end + else + @shixuns = Shixun.where("name like '%#{search}%'").where(:status => sx_status).order("created_at #{@sx_order}") + end + @edit_sx_num = Shixun.where(:status => 0).count + @audit_sx_num = Shixun.where(:status => 1).count + @publish_sx_num =Shixun.where(:status => 2).count + @close_sx_num = Shixun.where(:status => 3).count + @shixuns_count = @shixuns.count + limit = 20 + @shixuns_pages = Paginator.new @shixuns_count, limit, params['page'] || 1 + @offset ||= @shixuns_pages.offset + @shixuns = paginateHelper @shixuns, limit + respond_to do |format| + format.js + format.html + end + end + + # 已发布的实训 + def publish_shixuns + @menu_type = 3 + @sub_type = 2 + @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order] # 排序 + search = params[:search] # 搜索字 + keyword = params[:keyword].blank? ? "u_name" : params[:keyword] # 根据姓名/实训名搜索 + close = params[:close] # 关闭实训,参数是实训的Id + unless close.blank? + Shixun.find(close).update_attribute(:status, 3) + end + if "u_name" == keyword + # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user + if search.blank? + @shixuns = Shixun.where(:status => 2).order("created_at #{@sx_order}") + else + user_id = User.where("concat(lastname, firstname) like '%#{search}%'") + @shixuns = Shixun.where(:user_id => user_id, :status => 2).order("created_at #{@sx_order}") + end + else + @shixuns = Shixun.where("name like '%#{search}%'").where(:status => 2).order("created_at #{@sx_order}") + end + @shixuns_count = @shixuns.count + limit = 20 + @shixuns_pages = Paginator.new @shixuns_count, limit, params['page'] || 1 + @offset ||= @shixuns_pages.offset + @shixuns = paginateHelper @shixuns, limit + respond_to do |format| + format.js + format.html + end + end + + # 已关闭的实训 + def close_shixuns + @menu_type = 3 + @sub_type = 3 + @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order] # 排序 + search = params[:search] # 搜索字 + keyword = params[:keyword].blank? ? "u_name" : params[:keyword] # 根据姓名/实训名搜索 + reopen = params[:reopen] # 从新开启实训,参数是实训的Id + unless reopen.blank? + Shixun.find(reopen).update_attribute(:status, 2) + end + if "u_name" == keyword + # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user + if search.blank? + @shixuns = Shixun.where(:status => 3).order("updated_at #{@sx_order}") + else + user_id = User.where("concat(lastname, firstname) like '%#{search}%'") + @shixuns = Shixun.where(:user_id => user_id, :status => 3).order("updated_at #{@sx_order}") + end + else + @shixuns = Shixun.where("name like '%#{search}%'").where(:status => 3).order("updated_at #{@sx_order}") + end + @shixuns_count = @shixuns.count + limit = 20 + @shixuns_pages = Paginator.new @shixuns_count, limit, params['page'] || 1 + @offset ||= @shixuns_pages.offset + @shixuns = paginateHelper @shixuns, limit + respond_to do |format| + format.js + format.html + end + end + + def users_trial + @menu_type = 7 + @sub_type = 2 + @users = User.where(:status => 1).order("created_on desc").all + @users_count = @users.count + @limit = 20 + @is_remote = true + @users_pages = Paginator.new @users_count, @limit, params['page'] || 1 + @offset ||= @users_pages.offset + @users = paginateHelper @users, @limit + end + + def search_user + +=begin + auth = ApplyUserAuthentication.where(:status => params[:authentication]) + auth_id = auth.blank? ? User.where(:status => 1).id : "(" + auth.map{|a| a.user_id }.join(",") + ")" +=end + + if params[:member_ids] && params[:trial_whether] == "trial_agree" + params[:member_ids].each do |member| + aUser = ApplyAction.where(:user_id => member, :container_type => "TrialAuthorization") + if aUser.blank? + ApplyAction.create(:user_id => member, :container_type => "TrialAuthorization", :status => 1) + else + aUser.update_all(:status => 1) + end + end + elsif params[:member_ids] && params[:trial_whether] == "trial_cancel" + ApplyAction.where(:user_id => params[:member_ids], :container_type => "TrialAuthorization").update_all(:status => 2) + end + + if params[:member_ids] && (params[:occupation] == "occupation_agree" || params[:realname] == "realname_agree") + User.where(:id => params[:member_ids]).update_all(:authentication => true) + elsif params[:member_ids] && (params[:occupation] == "occupation_agree" || params[:realname] == "realname_cancel") + User.where(:id => params[:member_ids]).update_all(:authentication => false) + end + + if params[:trial] == "-1" + apply = ApplyAction.where(:container_type => "TrialAuthorization") + apply_id = apply.blank? ? -1 : "(" + apply.map{|a| a.user_id}.join(",") + ")" + apply_user_id = User.where("id not in #{apply_id} and status = 1").all + apply_user_id = apply_user_id.blank? ? [-1] : apply_user_id.map{|a| a.id}.split(",")[0] + elsif params[:trial] == "-2" + apply_user_id = User.where(:status => 1).all + apply_user_id = apply_user_id.blank? ? [-1] : apply_user_id.map{|a| a.id}.split(",")[0] + else + apply = ApplyAction.where(:status => params[:trial]) + apply_user_id = apply.blank? ? [-1] : apply.map{|a| a.user_id}.split(",")[0] + end + + if params[:school] == "" + s_user_id = User.where(:status => 1).all + s_user_id = s_user_id.blank? ? [-1] : s_user_id.map{|s| s.id}.split(",")[0] + else + school = School.where("name like '%#{params[:school]}%'") + school_id = school.blank? ? -1 : school.map{|s| s.id }.split(",")[0] + usr = UserExtensions.where(:school_id => school_id) + s_user_id = usr.blank? ? [-1] : usr.map{|u| u.user_id}.split(",")[0] + end + + if params[:department] == "" + d_user_id = User.where(:status => 1).all + d_user_id = d_user_id.blank? ? [-1] : d_user_id.map{|d| d.id}.split(",")[0] + else + department = Department.where("name like '%#{params[:department]}%'").all + dep_id = department.blank? ? -1 : department.map{|d| d.id}.split(",") + usr = UserExtensions.where(:department_id => dep_id) + d_user_id = usr.blank? ? [-1] : usr.map{|u| u.user_id}.split(",")[0] + end + + user_id = s_user_id & d_user_id & apply_user_id + + if params[:research_condition] == "name" + @users = User.where(:id => user_id).where("concat(lastname, firstname) like '%#{params[:research_contents]}%'").order("created_on desc") + elsif params[:research_condition] == "email" + @users = User.where(:id => user_id).where("mail like '%#{params[:research_contents]}%'").order("created_on desc") + elsif params[:research_condition] == "phone" + if params[:research_contents].blank? + @users = User.where(:id => user_id).order("created_on desc") + else + @users = User.where(:id => user_id).where("phone like '%#{params[:research_contents]}%'").order("created_on desc") + end + + end + + @users_count = @users.count + @limit = 20 + @is_remote = true + @users_pages = Paginator.new @users_count, @limit, params['page'] || 1 + @offset ||= @users_pages.offset + @users = paginateHelper @users, @limit + + respond_to do |format| + format.js + end + end + + def update_webssh + webssh = params[:status] == "true" ? true : false + @shixuns = Shixun.find(params[:shixun_id]) + @shixuns.update_column(:webssh, webssh) + respond_to do |format| + format.js + end + end + + def affirm_cancel_auth + user_id = params[:users] + end + + + def trial_authorization + @menu_type =10 + @sub_type = 2 + search = params[:search] + @status = trial_authorization_status(params[:status]) + # @status = (params[:status].blank? || params[:status] == "0") ? 0 : [1,2] + if search.blank? + @authorizations = ApplyAction.where(:container_type => "TrialAuthorization", :status => @status).includes(:user) + else + user_id = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{search}%'") + @authorizations = ApplyAction.where(:container_type => "TrialAuthorization", :status => @status, :user_id => user_id).includes(:user) + end + + @autu_count = @authorizations.count + @limit = 15 + @is_remote = true + @autu_pages = Paginator.new @autu_count, @limit, params['page'] || 1 + @offset ||= @autu_pages.offset + @authorizations = paginateHelper @authorizations, @limit + + end + + # 批量授权 + def batch_authorization + + end + + # params[:type] 1:拒绝 0:同意 + # authentication 会有一个初始值,不同的值代表不同的权限 + # REDO: 后面权限改了后,一并要改 + def trial_authorization_operation + apply_action = ApplyAction.find(params[:apply_id]) + type = params[:type] + search = params[:search] + if type == "0" + authentication_user = AuthenticationsUsers.where(:user_id => apply_action.user_id).first + if authentication_user.blank? + AuthenticationsUsers.create(:user_id => apply_action.user_id, :authentication_id => 1) + end + end + apply_action.update_attributes(:status => (params[:type] == "1" ? 2 : 1), :reason => params[:reject_reason], :dealer_id => User.current.id) + user_id = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{search}%'") + @authorizations = ApplyAction.where(:container_type => "TrialAuthorization", :status => 0, :user_id => user_id).includes(:user) + @autu_count = @authorizations.count + @limit = 15 + @is_remote = true + @autu_pages = Paginator.new @autu_count, @limit, params['page'] || 1 + @offset ||= @autu_pages.offset + @authorizations = paginateHelper @authorizations, @limit + respond_to do |format| + format.js + end + end + + def index + + end + + # copy from admin + def identity_authentication + @menu_type = 10 + @sub_type = 1 + @type = trial_authorization_status(params[:type]) + type = params[:type] || 0 # 存在type 就用type 没有就为 0 + user_id = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{params[:name]}%'") + @unapproved_user = ApplyUserAuthentication.where(:status => @type, :user_id => user_id).order("updated_at desc") + respond_to do |format| + format.html + format.js + end + end + + # 拒绝身份认证 + # copy from admin + def reject_authentication + apply_user = ApplyUserAuthentication.find(params[:apply_id]) + reason = apply_user.update_attributes(:status => 2, :remarks => params[:reject_reason]) + render :json => {success: reason} + end + + # 统一身份认证 + # copy from admin + def agree_authentication + apply_user = ApplyUserAuthentication.find(params[:apply_id]) + user = User.find(apply_user.user_id) + apply_user.update_attribute(:status, 1) + user.update_attribute(:authentication, true) + @unapproved_user = ApplyUserAuthentication.where(:status => 0).order("updated_at desc") + respond_to do |format| + format.js + end + end + + def subject_authorization + @menu_type = 10 + @sub_type == 6 + @type = trial_authorization_status params[:type] + @authorizations = ApplyAction.where(:container_type => "ApplySubject", :status => @type).order("created_at desc") + # @subject=Subject.all + + @authorizations_count = @authorizations.count + @limit = 15 + @is_remote = true + @authorizations_pages = Paginator.new @authorizations_count, @limit, params['page'] || 1 + @offset ||= @authorizations_pages.offset + @authorizations = paginateHelper @authorizations, @limit + respond_to do |format| + format.js + format.html + end + end + + def shixun_authorization + @menu_type = 10 + @sub_type == 5 + @type = trial_authorization_status params[:type] + @authorizations = ApplyAction.where(:container_type => "ApplyShixun", :status => @type).order("created_at desc") + search = params[:search] + unless search.blank? + @authorizations = @authorizations.where(:container_id => Shixun.where(:id => @authorizations.map(&:container_id)).where("name like '%#{search}%'").map(&:id)).order("created_at desc") + end + + @authorizations_count = @authorizations.count + @limit = 15 + @is_remote = true + @authorizations_pages = Paginator.new @authorizations_count, @limit, params['page'] || 1 + @offset ||= @authorizations_pages.offset + @authorizations = paginateHelper @authorizations, @limit + respond_to do |format| + format.js + format.html + end + end + # 课程实训发布审批 + def deal_subject_authorization + apply_action = ApplyAction.find(params[:apply_id]) + type = params[:type].to_i + subject = Subject.find apply_action.container_id + if type == 0 #拒绝 + subject.update_column('status', 0) + apply_action.update_attributes(:status => 2, :reason => params[:reject_reason], :dealer_id => User.current.id) + notes = "您所在团队提交的课程实训发布申请:#{subject.name},审核未通过。
原因:#{params[:reject_reason]}" + JournalsForMessage.create(:jour_id => subject.user_id, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0) + else #同意 + subject.update_column('status', 2) + apply_action.update_attributes(:status => 1, :dealer_id => User.current.id) + end + @authorizations = ApplyAction.where(:container_type => "ApplySubject", :status => 0) + @authorizations_count = @authorizations.count + @limit = 15 + @is_remote = true + @authorizations_pages = Paginator.new @authorizations_count, @limit, params['page'] || 1 + @offset ||= @authorizations_pages.offset + @authorizations = paginateHelper @authorizations, @limit + respond_to do |format| + format.js + end + end + # 项目实训发布审批 + def deal_shixun_authorization + apply_action = ApplyAction.find(params[:apply_id]) + type = params[:type].to_i + shixun = Shixun.find apply_action.container_id + if type == 0 #拒绝 + shixun.update_column('status', 0) + apply_action.update_attributes(:status => 2, :reason => params[:reject_reason], :dealer_id => User.current.id) + notes = "您所在团队提交的项目实训发布申请:#{shixun.name},审核未通过。
原因:#{params[:reject_reason]}" + shixun.shixun_members.each do |member| + JournalsForMessage.create(:jour_id => member.user_id, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0) + end + else #同意 + shixun.update_column('status', 2) + apply_action.update_attributes(:status => 1, :dealer_id => User.current.id) + shixun_modify_status_without_publish shixun, 1 + end + @authorizations = ApplyAction.where(:container_type => "ApplyShixun", :status => 0) + @authorizations_count = @authorizations.count + @limit = 15 + @is_remote = true + @authorizations_pages = Paginator.new @authorizations_count, @limit, params['page'] || 1 + @offset ||= @authorizations_pages.offset + @authorizations = paginateHelper @authorizations, @limit + respond_to do |format| + format.js + end + end +end diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb index c9f826c57..c2bce7a27 100644 --- a/app/controllers/messages_controller.rb +++ b/app/controllers/messages_controller.rb @@ -20,10 +20,10 @@ class MessagesController < ApplicationController before_filter :authorize1, :only => [:show] menu_item :boards default_search_scope :messages - before_filter :find_board, :only => [:new, :preview,:edit] + before_filter :find_board, :only => [:new, :create, :preview, :edit, :update, :sticky_topic] before_filter :find_attachments, :only => [:preview] - before_filter :find_message, :except => [:new, :preview, :join_org_subfield, :get_subfield_on_click_org, :join_org_subfields] - before_filter :authorize, :except => [:preview, :edit, :destroy, :new,:join_org_subfield, :get_subfield_on_click_org, :join_org_subfields] + before_filter :find_message, :except => [:new, :create, :preview, :join_org_subfield, :get_subfield_on_click_org, :join_org_subfields] + before_filter :authorize, :except => [:preview, :edit, :update, :destroy, :message_replies, :new, :create, :join_org_subfield, :get_subfield_on_click_org, :join_org_subfields, :sticky_topic] helper :boards helper :watchers @@ -39,7 +39,7 @@ class MessagesController < ApplicationController def show # 顶部导航 @project_menu_type = 3 - + @topic.update_column('visits', @topic.visits + 1) @isReply = true # page = params[:page] # # Find the page of the requested reply @@ -51,31 +51,32 @@ class MessagesController < ApplicationController @replies = Message.where("root_id = #{@topic.id}").reorder("created_on desc") @reply_count = @replies.count @replies = get_no_children_comments_all @replies - @limit_count = @replies.count - @page = params[:page] ? params[:page].to_i + 1 : 0 - @limit = 10 - @replies = @replies[@page * @limit..@page * @limit + 9] - @reply = Message.new(:subject => "RE: #{@message.subject}") + #@limit_count = @replies.count + #@page = params[:page] ? params[:page].to_i + 1 : 0 + #@limit = 10 + #@replies = @replies[@page * @limit..@page * @limit + 9] + @reply = Message.new if @course #帖子消息状态更新 course_messages = CourseMessage.where("user_id =? and course_message_type =? and course_message_id =? and course_id =? and viewed =?", User.current.id, 'Message', @topic.id, @course.id, 0) course_messages.update_all(:viewed => true) #@replies = @topic.children. - #includes(:author, :attachments, :praise_tread_cache, {:board => :project}). - #reorder("#{Message.table_name}.created_on DESC"). - #limit(@reply_pages.per_page). - #offset(@reply_pages.offset). - #all + #includes(:author, :attachments, :praise_tread_cache, {:board => :project}). + #reorder("#{Message.table_name}.created_on DESC"). + #limit(@reply_pages.per_page). + #offset(@reply_pages.offset). + #all #@replies = paginateHelper messages_replies,10 # 班级帖子回复消息设为已读 + @replies.each do |comment| - course_message = CourseMessage.where(:course_message_type => 'Message', :course_message_id => comment.id, :user_id => User.current.id, :viewed => 0) - course_message.update_all(:viewed => 1) + course_message = CourseMessage.where(:course_message_type => 'Message', :course_message_id => comment.id, :user_id => User.current.id, :viewed => 0) + course_message.update_all(:viewed => 1) end @left_nav_type = 2 respond_to do |format| format.js - format.html {render :layout => 'base_courses'} + format.html {render :layout => 'base_edu'} end #render :action => "show", :layout => "base_courses"#by young elsif @project @@ -133,11 +134,19 @@ class MessagesController < ApplicationController # Create a new topic def new + @message = Message.new + respond_to do |format| + format.html { render :layout => 'base_edu' } + end + end + + def create if User.current.logged? @message = Message.new @message.author = User.current @message.board = @board @message.safe_attributes = params[:message] + @message.sticky = params[:message][:sticky] ? 1 : 0 if request.post? if @project is_public = @project.is_public @@ -157,16 +166,18 @@ class MessagesController < ApplicationController call_hook(:controller_messages_new_after_save, { :params => params, :message => @message}) render_attachment_warning_if_needed(@message) - if params[:is_board] - if @project - redirect_to project_boards_path(@project) - elsif @course - redirect_to course_boards_path(@course, :board_id => @board.id) - elsif @contest - redirect_to contest_boards_path(@contest, :board_id => @board.id) - end - else + if @course redirect_to board_message_url(@board, @message) + else + if params[:is_board] + if @project + redirect_to project_boards_path(@project) + elsif @contest + redirect_to contest_boards_path(@contest, :board_id => @board.id) + end + else + redirect_to board_message_url(@board, @message) + end end else if params[:is_board] @@ -178,7 +189,7 @@ class MessagesController < ApplicationController redirect_to contest_boards_path(@contest, :board_id => @board.id, :flag => true) end else - layout_file = @project ? 'base_projects' : (@course ? 'base_courses' : 'base_contests') + layout_file = @project ? 'base_projects' : (@course ? 'base_edu' : 'base_contests') render :action => 'new', :layout => layout_file end @@ -187,7 +198,7 @@ class MessagesController < ApplicationController @left_nav_type = 2 respond_to do |format| format.html { - layout_file = @project ? 'base_projects' : (@course ? 'base_courses' : 'base_contests') + layout_file = @project ? 'base_projects' : (@course ? 'base_edu' : 'base_contests') render :layout => layout_file } end @@ -201,7 +212,7 @@ class MessagesController < ApplicationController def reply if params[:parent_id] parent = Message.find params[:parent_id] - @topic = params[:activity_id].nil? ? parent : Message.find(params[:activity_id].to_i) + @topic = params[:activity_id].blank? ? parent : Message.find(params[:activity_id].to_i) @reply = Message.new @reply.author = User.current @reply.board = parent.board @@ -232,37 +243,53 @@ class MessagesController < ApplicationController update_forge_activity(@topic.class,@topic.id) update_org_activity(@topic.class,@topic.id) + redirect_to message_replies_board_message_path(@topic, :board_id => @board.id, :user_activity_id => params[:user_activity_id]) #@topic.update_attribute(:updated_on, Time.now) - if !@reply.new_record? - if params[:asset_id] - ids = params[:asset_id].split(',') - update_kindeditor_assets_owner ids,@reply.id,OwnerTypeHelper::MESSAGE - end + # if !@reply.new_record? + # if params[:asset_id] + # ids = params[:asset_id].split(',') + # update_kindeditor_assets_owner ids,@reply.id,OwnerTypeHelper::MESSAGE + # end + # + # call_hook(:controller_messages_reply_after_save, { :params => params, :message => @reply}) + # attachments = Attachment.attach_files(@reply, params[:attachments]) + # render_attachment_warning_if_needed(@reply) + # else + # #render file: 'messages#show', layout: 'base_courses' + # end - call_hook(:controller_messages_reply_after_save, { :params => params, :message => @reply}) - attachments = Attachment.attach_files(@reply, params[:attachments]) - render_attachment_warning_if_needed(@reply) - else - #render file: 'messages#show', layout: 'base_courses' - end - if params[:user_activity_id] - @user_activity_id = params[:user_activity_id] - @is_course = params[:is_course] if params[:is_course] - @is_board = params[:is_board] if params[:is_board] - respond_to do |format| - format.js - end - return - else - redirect_to board_message_url(@board, @topic) - return - end + # if params[:user_activity_id] + # @user_activity_id = params[:user_activity_id] + # @is_course = params[:is_course] if params[:is_course] + # @is_board = params[:is_board] if params[:is_board] + # respond_to do |format| + # format.js + # end + # return + # else + # redirect_to board_message_url(@board, @topic) + # return + # end end + def message_replies + @replies = Message.where("root_id = #{@topic.id}").reorder("created_on desc") + @reply_count = @replies.count + @replies = get_no_children_comments_all @replies + #@limit_count = @replies.count + #@page = params[:page] ? params[:page].to_i + 1 : 0 + #@limit = 10 + #@replies = @replies[@page * @limit..@page * @limit + 9] + @reply = Message.new() + @user_activity_id = params[:user_activity_id].blank? ? @topic.id : params[:user_activity_id].to_i + respond_to do |format| + format.js + end + end + # Edit a message def edit - @isReply = false if @project (render_403; return false) unless @message.editable_by?(User.current) elsif @course @@ -273,55 +300,34 @@ class MessagesController < ApplicationController (render_403; return false) unless @message.org_subfield_editable_by?(User.current) end + respond_to do |format| + format.html { + if @project + layout_file = 'base_projects' + elsif @course + @left_nav_type = 2 + layout_file = 'base_edu' + elsif @contest + @left_nav_type = 4 + layout_file = 'base_contests' + elsif @org_subfield + @organization = @org_subfield.organization + layout_file = 'base_org' + end + render :layout => layout_file + } + end + end + + def update @message.safe_attributes = params[:message] - if request.post? && @message.save + @message.sticky = params[:message][:sticky] ? 1 : 0 + if @message.save attachments = Attachment.attach_files(@message, params[:attachments]) render_attachment_warning_if_needed(@message) #flash[:notice] = l(:notice_successful_update) @message.reload - if params[:is_course] && params[:is_course].to_i == 0 - redirect_to user_activities_path(User.current.id) - elsif params[:is_course] && params[:is_course].to_i == 1 && params[:is_board] && params[:is_board].to_i == 0 - if @project - redirect_to project_path(@project) - elsif @course - redirect_to course_activity_path(@course) - elsif @contest - redirect_to contest_path(@contest) - end - elsif params[:is_course] && params[:is_course].to_i == 1 && params[:is_board] && params[:is_board].to_i == 1 - if @project - redirect_to project_boards_path(@project) - elsif @course - redirect_to course_boards_path(@course) - elsif @contest - redirect_to contest_boards_path(@contest) - end - else - redirect_to board_message_url(@message.board, @message.root, :r => (@message.parent_id && @message.id)) - end - elsif request.get? || request.post? - if params[:is_course] && params[:is_board] - @is_course = params[:is_course] - @is_board = params[:is_board] - end - respond_to do |format| - format.html { - if @project - layout_file = 'base_projects' - elsif @course - @left_nav_type = 2 - layout_file = 'base_courses' - elsif @contest - @left_nav_type = 4 - layout_file = 'base_contests' - elsif @org_subfield - @organization = @org_subfield.organization - layout_file = 'base_org' - end - render :layout => layout_file - } - end + redirect_to board_message_url(@message.board, @message.root, :r => (@message.parent_id && @message.id)) end end @@ -333,9 +339,7 @@ class MessagesController < ApplicationController @user_activity_id = params[:user_activity_id] @is_course = params[:is_course] if params[:is_course] @is_board = params[:is_board] if params[:is_board] - respond_to do |format| - format.js - end + redirect_to message_replies_board_message_path(@topic, :board_id => @board.id, :user_activity_id => params[:user_activity_id]) return end if @project @@ -399,6 +403,12 @@ class MessagesController < ApplicationController end end + def sticky_topic + (render_403; return false) unless (User.current.admin? || User.current.allowed_to?(:as_teacher, @course)) + @topic.update_attributes(:sticky => @topic.sticky == 1 ? 0 : 1) + redirect_to board_message_path(@topic.board_id, @topic) + end + def quote # @subject = @message.subject # @subject = "RE: #{@subject}" unless @subject.starts_with?('RE:') @@ -437,8 +447,8 @@ class MessagesController < ApplicationController :created_on => Time.now, :updated_on => Time.now, :locked => @message.locked, :sticky => @message.sticky) @message.attachments.each do |attach| mes.attachments << Attachment.new(:filename => attach.filename, :disk_filename => attach.disk_filename, :filesize => attach.filesize, :content_type => attach.content_type, :digest => attach.digest, - :downloads => 0, :author_id => User.current.id, :created_on => Time.now, :description => attach.description, :disk_directory => attach.disk_directory, :attachtype => attach.attachtype, - :is_public => attach.is_public, :quotes => 0) + :downloads => 0, :author_id => User.current.id, :created_on => Time.now, :description => attach.description, :disk_directory => attach.disk_directory, :attachtype => attach.attachtype, + :is_public => attach.is_public, :quotes => 0) end # OrgSubfieldMessage.create(:org_subfield_id => field_id.to_i, :message_id => mes.id, :message_type => type) # org_acts = OrgActivity.where("container_type='OrgSubfield' and container_id=? and org_act_type='Message' and org_act_id=?", field_id.to_i, @message.id) diff --git a/app/controllers/myshixuns_controller.rb b/app/controllers/myshixuns_controller.rb index abab48f3b..e69e9fd9f 100644 --- a/app/controllers/myshixuns_controller.rb +++ b/app/controllers/myshixuns_controller.rb @@ -27,7 +27,7 @@ class MyshixunsController < ApplicationController jenkins_shixuns = Redmine::Configuration['jenkins_shixuns'] uri = URI("#{jenkins_shixuns}/jenkins-exec/webssh/getConnectInfo") user_id = User.current.id - params = {gameID:@myshixun.id} + params = {gameID:@myshixun.id, operationEnvironment:@myshixun.shixun.try(:language)} res = uri_exec uri, params if res && res['code'].to_i != 0 raise("实训云平台繁忙(繁忙等级:92)") diff --git a/app/controllers/school_controller.rb b/app/controllers/school_controller.rb index b6e34a185..ef053bb16 100644 --- a/app/controllers/school_controller.rb +++ b/app/controllers/school_controller.rb @@ -1,285 +1,286 @@ -class SchoolController < ApplicationController - layout 'course_base' - before_filter :require_admin, :only => :upload_logo - - def upload - uploaded_io = params[:logo] - school_id ||= params[:id] - s1 = School.find(school_id) - unless uploaded_io.nil? - File.open(Rails.root.join('public', 'images', 'school', school_id.to_s+'.png'), 'wb') do |file| - file.write(uploaded_io.read) - end - - s1.logo_link = '/images/school/'+school_id.to_s+'.png' - - end - s1.name = params[:name] unless params[:name].blank? - s1.province = params[:province] unless params[:province].blank? - s1.save - redirect_to admin_schools_url(:school_name => params[:school_name]) - end - - def upload_logo - @school = School.find params[:id] - @school_name = params[:school_name] - end - - #获取制定学校开设的课程数 - def course_count school_id - School.find(school_id).courses.count - end - - - def index - - end - - def get_province - @provinces = School.find_by_sql("select distinct province from schools") - - options = "" - - @provinces.each do |p| - options << "" - end - - # 取id取学校名 - # 连接子表: 查询已添加用户的学校 - school = School.select("id, name"). - joins("RIGHT JOIN ( - SELECT DISTINCT school_id - FROM #{UserExtensions.table_name} - WHERE school_id IS NOT NULL) AS sids ON schools.id = sids.school_id"). - where("#{School.table_name}.id IS NOT NULL") - - options_s = "" - school.each do |s| - options_s << "
  • #{s.name}
  • " - end - - res = Hash.new - res[:text] = options - res[:text_s] = options_s - - render :json => res - - - end - - def get_options - @school = School.where("province = ?", params[:province]) - p = params[:province] - ##@school = School.all - options = "" - - @school.each do |s| - #options << "" - options << "
  • #{s.name}
  • " - end - - - render :text => options - - end - - def get_schoollist - @school = School.where("province = ?", params[:province]) - - options = "" - @school.each do |s| - options << "
  • #{s.name}
  • " - end - - render :text => options - end - - def search_school - q = "%#{params[:key_word].strip}%" - - @school = School.where("name LIKE ?", q) - @school = @school.where("province = ?", params[:province]) if (params[:province] != '0' ) - - options = "" - @school.each do |s| - options << "
  • #{s.name}
  • " - end - - options = "
    #{l(:label_school_not_fount)}
    " if options.blank? - - render :text => options - end - - #根据学校名字或者拼音来查询 - def on_search - condition = "#{params[:name].strip}".gsub(" ","") - #将条件截断为汉字和拼音(全汉字 或者 全拼音 或者 汉字和拼音), - #获取拼音的第一次出现的位置 - chinese = [] - pinyin = [] - condition.scan(/./).each_with_index do |char,index| - if char =~ /[a-zA-Z0-9]/ - pinyin << char - elsif char =~ /\'/ - else - chinese << char - end - end - if(condition == '') - @school = School.reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100) - @school_count = School.count - else - @school = School.where("name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100) - @school_count = School.where("name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").count - end - - result = [] - # @school.each do |sc| - # result << {:value=>sc.name,:data=>sc.id} - # end - render :json =>{ :schools => @school,:count=>@school_count}.to_json - end - - #添加学校 - def add_school - @school = School.new - @school.name = params[:name].strip - @school.pinyin = Pinyin.t(params[:name].strip, splitter: '') - @school.save - respond_to do |format| - format.js - end - end - - #申请高校(单位) name:名称 province:省 city:市 address:地址 remarks:备注 - def apply_add_school - - data = {result:0,name:params[:name],school_id:0} - #0 成功 1参数错误 2名称已存在 3.失败 - data[:result] = 0 - - #检验参数 - if params[:name] == "" || params[:province] == "" || params[:city] == "" || params[:address] == "" - data[:result] = 1 - else - school = School.where("name = '#{params[:name]}'").first - if school - data[:result] = 2 - else - school = School.new - school.name = params[:name].strip - school.pinyin = Pinyin.t(params[:name].strip, splitter: '') - school.province = params[:province] - - #status 0未处理 1通过 2拒绝 - applyschool = ApplyAddSchools.new - - #用belongs_to 可以一起存数据库 - applyschool.school = school - applyschool.name = school.name - applyschool.province = params[:province] - applyschool.city = params[:city] - applyschool.address = params[:address] - applyschool.remarks = params[:remarks] - applyschool.user_id = User.current.id - if applyschool.save - data[:school_id] = school.id - user_extention= User.current.extensions - user_extention.school_id = school.id - user_extention.save! - - # 向管理员发送信息 - users = User.where(:admin => 1) - users.each do |user| - AppliedMessage.create(:user_id => user.id, :status => 0, :applied_user_id => User.current.id, :viewed => 0, :applied_id => school.id, :applied_type => "ApplyAddSchools", :name => school.name ) - end - - else - data[:result] = 3 - end - end - end - render :json =>data - end - - def search_repeat_schoolname - status = 0 #没有重复的 - name = params[:name] - - if name - school = School.where("name = '#{name}'").first - - if school - status = 1 #有重复的 - end - end - - - render :json =>status - end - - def edit_apply_name - name = params[:name] || "" - status = -1 - - if name != "" - applyschool = ApplyAddSchools.where("id=?",params[:id]).first - - applyschool.name = name.strip - - if applyschool.school - applyschool.school.name = name - applyschool.school.pinyin = Pinyin.t(name.strip, splitter: '') - applyschool.school.save! - end - applyschool.save! - status = 0 - end - - render :json=>{:status=>status,:id=>params[:id],:name=>name} - end - - def edit_apply_address - address = params[:address] || "" - - status = -1 - - if address != "" - applyschool = ApplyAddSchools.where("id=?",params[:id]).first - applyschool.address = address - applyschool.save! - status = 0 - end - - render :json=>{:status=>status,:id=>params[:id],:address=>address} - end - - def edit_apply_province - province = params[:province] || "" - city = params[:city] || "" - status = -1 - - if(province != "") &&(city != "") - applyschool = ApplyAddSchools.where("id=?",params[:id]).first - applyschool.province = province - applyschool.city = city - - if applyschool.school - applyschool.school.province = province - applyschool.school.save! - end - applyschool.save! - - if applyschool.user_id && applyschool.user_id != 0 - user = User.find(applyschool.user_id) - user_extention= user.extensions - user_extention.location = province - user_extention.location_city = city - user_extention.save! - end - status = 0 - end - - render :json=>{:status=>status,:id=>params[:id],:province=>province,:city=>city} - end -end +class SchoolController < ApplicationController + layout 'course_base' + before_filter :require_admin, :only => :upload_logo + + def upload + uploaded_io = params[:logo] + school_id ||= params[:id] + s1 = School.find(school_id) + unless uploaded_io.nil? + File.open(Rails.root.join('public', 'images', 'school', school_id.to_s+'.png'), 'wb') do |file| + file.write(uploaded_io.read) + end + + s1.logo_link = '/images/school/'+school_id.to_s+'.png' + + end + s1.name = params[:name] unless params[:name].blank? + s1.province = params[:province] unless params[:province].blank? + s1.save + redirect_to departments_part_managements_path + end + + def upload_logo + @school = School.find params[:id] + @school_name = params[:school_name] + render :layout => "base_management" + end + + #获取制定学校开设的课程数 + def course_count school_id + School.find(school_id).courses.count + end + + + def index + + end + + def get_province + @provinces = School.find_by_sql("select distinct province from schools") + + options = "" + + @provinces.each do |p| + options << "" + end + + # 取id取学校名 + # 连接子表: 查询已添加用户的学校 + school = School.select("id, name"). + joins("RIGHT JOIN ( + SELECT DISTINCT school_id + FROM #{UserExtensions.table_name} + WHERE school_id IS NOT NULL) AS sids ON schools.id = sids.school_id"). + where("#{School.table_name}.id IS NOT NULL") + + options_s = "" + school.each do |s| + options_s << "
  • #{s.name}
  • " + end + + res = Hash.new + res[:text] = options + res[:text_s] = options_s + + render :json => res + + + end + + def get_options + @school = School.where("province = ?", params[:province]) + p = params[:province] + ##@school = School.all + options = "" + + @school.each do |s| + #options << "" + options << "
  • #{s.name}
  • " + end + + + render :text => options + + end + + def get_schoollist + @school = School.where("province = ?", params[:province]) + + options = "" + @school.each do |s| + options << "
  • #{s.name}
  • " + end + + render :text => options + end + + def search_school + q = "%#{params[:key_word].strip}%" + + @school = School.where("name LIKE ?", q) + @school = @school.where("province = ?", params[:province]) if (params[:province] != '0' ) + + options = "" + @school.each do |s| + options << "
  • #{s.name}
  • " + end + + options = "
    #{l(:label_school_not_fount)}
    " if options.blank? + + render :text => options + end + + #根据学校名字或者拼音来查询 + def on_search + condition = "#{params[:name].strip}".gsub(" ","") + #将条件截断为汉字和拼音(全汉字 或者 全拼音 或者 汉字和拼音), + #获取拼音的第一次出现的位置 + chinese = [] + pinyin = [] + condition.scan(/./).each_with_index do |char,index| + if char =~ /[a-zA-Z0-9]/ + pinyin << char + elsif char =~ /\'/ + else + chinese << char + end + end + if(condition == '') + @school = School.reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100) + @school_count = School.count + else + @school = School.where("name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100) + @school_count = School.where("name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").count + end + + result = [] + # @school.each do |sc| + # result << {:value=>sc.name,:data=>sc.id} + # end + render :json =>{ :schools => @school,:count=>@school_count}.to_json + end + + #添加学校 + def add_school + @school = School.new + @school.name = params[:name].strip + @school.pinyin = Pinyin.t(params[:name].strip, splitter: '') + @school.save + respond_to do |format| + format.js + end + end + + #申请高校(单位) name:名称 province:省 city:市 address:地址 remarks:备注 + def apply_add_school + + data = {result:0,name:params[:name],school_id:0} + #0 成功 1参数错误 2名称已存在 3.失败 + data[:result] = 0 + + #检验参数 + if params[:name] == "" || params[:province] == "" || params[:city] == "" || params[:address] == "" + data[:result] = 1 + else + school = School.where("name = '#{params[:name]}'").first + if school + data[:result] = 2 + else + school = School.new + school.name = params[:name].strip + school.pinyin = Pinyin.t(params[:name].strip, splitter: '') + school.province = params[:province] + + #status 0未处理 1通过 2拒绝 + applyschool = ApplyAddSchools.new + + #用belongs_to 可以一起存数据库 + applyschool.school = school + applyschool.name = school.name + applyschool.province = params[:province] + applyschool.city = params[:city] + applyschool.address = params[:address] + applyschool.remarks = params[:remarks] + applyschool.user_id = User.current.id + if applyschool.save + data[:school_id] = school.id + user_extention= User.current.extensions + user_extention.school_id = school.id + user_extention.save! + + # 向管理员发送信息 + users = User.where(:admin => 1) + users.each do |user| + AppliedMessage.create(:user_id => user.id, :status => 0, :applied_user_id => User.current.id, :viewed => 0, :applied_id => school.id, :applied_type => "ApplyAddSchools", :name => school.name ) + end + + else + data[:result] = 3 + end + end + end + render :json =>data + end + + def search_repeat_schoolname + status = 0 #没有重复的 + name = params[:name] + + if name + school = School.where("name = '#{name}'").first + + if school + status = 1 #有重复的 + end + end + + + render :json =>status + end + + def edit_apply_name + name = params[:name] || "" + status = -1 + + if name != "" + applyschool = ApplyAddSchools.where("id=?",params[:id]).first + + applyschool.name = name.strip + + if applyschool.school + applyschool.school.name = name + applyschool.school.pinyin = Pinyin.t(name.strip, splitter: '') + applyschool.school.save! + end + applyschool.save! + status = 0 + end + + render :json=>{:status=>status,:id=>params[:id],:name=>name} + end + + def edit_apply_address + address = params[:address] || "" + + status = -1 + + if address != "" + applyschool = ApplyAddSchools.where("id=?",params[:id]).first + applyschool.address = address + applyschool.save! + status = 0 + end + + render :json=>{:status=>status,:id=>params[:id],:address=>address} + end + + def edit_apply_province + province = params[:province] || "" + city = params[:city] || "" + status = -1 + + if(province != "") &&(city != "") + applyschool = ApplyAddSchools.where("id=?",params[:id]).first + applyschool.province = province + applyschool.city = city + + if applyschool.school + applyschool.school.province = province + applyschool.school.save! + end + applyschool.save! + + if applyschool.user_id && applyschool.user_id != 0 + user = User.find(applyschool.user_id) + user_extention= user.extensions + user_extention.location = province + user_extention.location_city = city + user_extention.save! + end + status = 0 + end + + render :json=>{:status=>status,:id=>params[:id],:province=>province,:city=>city} + end +end diff --git a/app/controllers/shixuns_controller.rb b/app/controllers/shixuns_controller.rb index c214b6acc..eab591a15 100644 --- a/app/controllers/shixuns_controller.rb +++ b/app/controllers/shixuns_controller.rb @@ -116,10 +116,6 @@ class ShixunsController < ApplicationController @collaborators = @shixun.collaborators end - def new_disscuss - render :layout => 'base_edu' - end - def collaborators_delete user_id = params[:c_id] shixun_member = ShixunMember.where(:user_id => user_id, :shixun_id => @shixun.id, :role => 2).first diff --git a/app/controllers/stages_controller.rb b/app/controllers/stages_controller.rb index cdb8712df..d653d33a3 100644 --- a/app/controllers/stages_controller.rb +++ b/app/controllers/stages_controller.rb @@ -5,14 +5,15 @@ class StagesController < ApplicationController include ApplicationHelper def create - if params[:stage_name] && params[:shixun_id] + if params[:stage_name] stage = Stage.new stage.name = params[:stage_name] + stage.description = params[:stage_des] stage.subject_id = @subject.id stage.user_id = User.current.id stage.position = @subject.stages.count + 1 ActiveRecord::Base.transaction do - if stage.save + if stage.save && params[:shixun_id] begin params[:shixun_id].each do |shixun_id| shixun = Shixun.find shixun_id @@ -34,10 +35,11 @@ class StagesController < ApplicationController end def update - if params[:stage_name] && params[:shixun_id] + if params[:stage_name] @stage.name = params[:stage_name] + @stage.description = params[:stage_des] ActiveRecord::Base.transaction do - if @stage.save + if @stage.save && params[:shixun_id] begin @stage.stage_shixuns.destroy_all params[:shixun_id].each do |shixun_id| diff --git a/app/controllers/subjects_controller.rb b/app/controllers/subjects_controller.rb index 6da59d62b..76c6d4808 100644 --- a/app/controllers/subjects_controller.rb +++ b/app/controllers/subjects_controller.rb @@ -3,7 +3,7 @@ class SubjectsController < ApplicationController layout 'base_subject' before_filter :require_login before_filter :check_authentication - before_filter :find_subject, :except => [:index, :create_subject, :new_subject, :append_to_stage] + before_filter :find_subject, :except => [:index, :new, :create, :create_subject, :new_subject, :append_to_stage] include ApplicationHelper @@ -30,6 +30,37 @@ class SubjectsController < ApplicationController @stages = @subject.stages end + def new + @subject = Subject.new + render :layout => "base_edu" + end + + def create + if params[:subject] + subject = Subject.create(:name => params[:subject][:name], :description => params[:subject][:description], :user_id => User.current.id, :visits => 0, :status => 0) + end + redirect_to subject_path(subject) + end + + def edit + render :layout => "base_edu" + end + + def update + if params[:subject] + subject = @subject.update_attributes(:name => params[:subject][:name], :description => params[:subject][:description]) + end + redirect_to subject_path(@subject) + end + + def update_attr + if params[:name] + @subject.update_attributes(:name => params[:name]) + elsif params[:description] + @subject.update_attributes(:description => params[:description]) + end + end + def new_subject if Course.where(:tea_id => User.current.id).count > 0 @status = 1 @@ -53,8 +84,9 @@ class SubjectsController < ApplicationController end def choose_subject_shixun - course_list = @subject.course_list - @shixuns = Shixun.where(:user_id => User.current.id, :status => [0, 1, 2], :id => course_list.shixun_major_courses.map(&:shixun_id)) + #course_list = @subject.course_list + @shixuns = User.current.shixuns.where(:status => [0, 1, 2]).reorder("created_at desc") + #@shixuns = Shixun.where(:user_id => User.current.id, :status => [0, 1, 2], :id => course_list.shixun_major_courses.map(&:shixun_id)) @shixuns_count = @shixuns.count @limit = 8 @shixuns_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1 @@ -67,15 +99,19 @@ class SubjectsController < ApplicationController end def publish - @subject.update_attributes(:status => 1) apply = ApplyAction.where(:container_type => "ApplySubject", :container_id => @subject.id).order("created_at desc").first if apply && apply.status == 0 @status = 0 else - ApplyAction.create(:container_type => "ApplySubject", :container_id => @subject.id, :user_id => User.current.id, :status => 0) - notes = User.current.show_name.to_s + " 申请发布课程实训:#{@subject.name}" - JournalsForMessage.create(:jour_id => 1, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0) - @status = 1 + if Shixun.where(:id => @subject.stage_shixuns.map(&:shixun_id), :status => [0, 1]).count > 0 + @status = 2 + else + @subject.update_attributes(:status => 1) + ApplyAction.create(:container_type => "ApplySubject", :container_id => @subject.id, :user_id => User.current.id, :status => 0) + notes = User.current.show_name.to_s + " 申请发布课程实训:#{@subject.name}" + JournalsForMessage.create(:jour_id => 1, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0) + @status = 1 + end end end @@ -83,11 +119,21 @@ class SubjectsController < ApplicationController apply = ApplyAction.where(:container_type => "ApplySubject", :container_id => @subject.id).order("created_at desc").first if apply && apply.status == 0 apply.update_attributes(:status => 3) - @subject.update_column('status', 0) end + @subject.update_attributes(:status => 0) redirect_to subject_path(@subject) end + def destroy + if @subject + ApplyAction.where(:container_type => "ApplySubject", :container_id => @subject.id).destroy_all + @subject.destroy + respond_to do |format| + format.js + end + end + end + private # Find subject of id params[:id] def find_subject diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 002ed0db7..3adf2cc17 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -164,7 +164,7 @@ module ApplicationHelper # 实训语言的种类 def shixun_language - ["Java", "C", "C++", "Python", "MySQL/Java","JFinal","Docker","Ethoernet","Dynamips"] + ["Java", "C", "C++", "Python2.7", "Python3.6", "MySQL/Java","JFinal","Docker","Ethereum","Dynamips"] end # 实训试用专业 @@ -225,11 +225,27 @@ module ApplicationHelper myshixun = Myshixun.where(:shixun_id => shixun.id, :user_id => user.id).first if myshixun.nil? 0 + elsif !myshixun.nil? && myshixun.games.select{|game| game.status == 2}.count == 0 + -1 + elsif myshixun.games.select{|game| game.status == 0}.count > 0 + [myshixun.games.select{|game| game.status == 0}.count + 1] else myshixun.games.select{|game| game.status == 2}.count end end + # TPI状态 :已通关、未通关、未开启 + def my_shixun_status shixun, user + status = "" + myshixun = Myshixun.where(:shixun_id => shixun.id, :user_id => user.id).first + if myshixun.nil? + status = "未开启" + else + status = myshixun.status == 1 ? "已通关" : "未通关" + end + status + end + # 定义实训相关方法 def sum_final_score Game.find_by_sql("SELECT sum(final_score) as total_score FROM `games` where user_id=#{User.current.id}").first.try(:total_score) @@ -1918,23 +1934,25 @@ module ApplicationHelper elsif @welcome title << "创新源于实践" elsif @course - title << (@course.name.nil? ? "实训课堂" : @course.name) + title << (@course.name.nil? ? "在线课堂" : @course.name) elsif params[:controller] == "homework_bank" title << ("题库") + elsif params[:controller] == "managements" + title << ("后台管理") elsif params[:controller] == "courses" && params[:action] == "index" - title << ("实训课堂") + title << ("在线课堂") elsif @contest title << (@contest.name.nil? ? "创新源于实践" : @contest.name) elsif @shixun - title << (@shixun.name.nil? ? "实训分类" : @shixun.name) + title << (@shixun.name.nil? ? "全部实训" : @shixun.name) elsif @my_shixun title << ("我的实训") elsif params[:controller] == "shixuns" && params[:action] == "index" - title << ("实训分类") + title << ("全部实训") elsif @subject - title << (@subject.name.nil? ? "课程实训" : @subject.name) + title << (@subject.name.nil? ? "实训套件" : @subject.name) elsif params[:controller] == "subjects" && params[:action] == "index" - title << ("课程实训") + title << ("实训套件") elsif @organization title << (@organization.name.nil? ? "创新源于实践" : @organization.name) elsif @forum || params[:controller] == "forums" @@ -1945,7 +1963,7 @@ module ApplicationHelper if !@project_community.blank? || !@user_projectlist.blank? title << "项目" elsif !@course_community.blank? || !@user_courselist.blank? - title << "实训课堂" + title << "在线课堂" elsif !@contest_community.blank? title << @contest_community elsif !@manage_issues.blank? @@ -1960,8 +1978,7 @@ module ApplicationHelper title << @user.show_name end elsif @syllabus - title << (@syllabus.title.nil? ? "实训课堂" : @syllabus.title) - else + title << (@syllabus.title.nil? ? "在线课堂" : @syllabus.title) else title << (User.current.id == 2 ? "未登录" : User.current.try(:realname)) end # if first_page.nil? || first_page.web_title.nil? @@ -5179,3 +5196,69 @@ def quote_homework_bank homework, course end end +def major_level_option + content = [] + option0 = [] + option0 << "选择课程所属专业层级" + option0 << 0 + option1 = [] + option1 << "专科" + option1 << 3 + option2 = [] + option2 << "本科" + option2 << 2 + option3 = [] + option3 << "研究生" + option3 << 1 + content << option0 + content << option1 + content << option2 + content << option3 + content +end + +def discipline_category_option major_level = 3 + content = [] + option0 = [] + option0 << "选择课程所属学科门类" + option0 << 0 + content << option0 + DisciplineCategory.where(:major_level => major_level).each do |dis| + option = [] + option << dis.name.to_s + option << dis.id + content << option + end + content +end + +def first_level_discipline_option disc_ca = 27 + content = [] + option0 = [] + option0 << "选择课程所属一级学科" + option0 << 0 + content << option0 + FirstLevelDiscipline.where(:discipline_category_id => disc_ca).each do |fir_dis| + option = [] + option << fir_dis.name.to_s + option << fir_dis.id + content << option + end + content +end + +def syllabus_major_option fir_dis = 213 + content = [] + option0 = [] + option0 << "选择课程所属专业" + option0 << 0 + content << option0 + Major.where(:first_level_discipline_id => fir_dis).each do |major| + option = [] + option << major.name.to_s + option << major.id + content << option + end + content +end + diff --git a/app/helpers/syllabuses_helper.rb b/app/helpers/syllabuses_helper.rb index bfb5b199b..91b951d46 100644 --- a/app/helpers/syllabuses_helper.rb +++ b/app/helpers/syllabuses_helper.rb @@ -51,72 +51,6 @@ module SyllabusesHelper count end - def major_level_option - content = [] - option0 = [] - option0 << "选择课程所属专业层级" - option0 << 0 - option1 = [] - option1 << "专科" - option1 << 3 - option2 = [] - option2 << "本科" - option2 << 2 - option3 = [] - option3 << "研究生" - option3 << 1 - content << option0 - content << option1 - content << option2 - content << option3 - content - end - - def discipline_category_option major_level = 3 - content = [] - option0 = [] - option0 << "选择课程所属学科门类" - option0 << 0 - content << option0 - DisciplineCategory.where(:major_level => major_level).each do |dis| - option = [] - option << dis.name.to_s - option << dis.id - content << option - end - content - end - - def first_level_discipline_option disc_ca = 27 - content = [] - option0 = [] - option0 << "选择课程所属一级学科" - option0 << 0 - content << option0 - FirstLevelDiscipline.where(:discipline_category_id => disc_ca).each do |fir_dis| - option = [] - option << fir_dis.name.to_s - option << fir_dis.id - content << option - end - content - end - - def syllabus_major_option fir_dis = 213 - content = [] - option0 = [] - option0 << "选择课程所属专业" - option0 << 0 - content << option0 - Major.where(:first_level_discipline_id => fir_dis).each do |major| - option = [] - option << major.name.to_s - option << major.id - content << option - end - content - end - def syllabus_type_option content = [] option0 = [] diff --git a/app/models/challenge.rb b/app/models/challenge.rb index 6779b345e..58b860765 100644 --- a/app/models/challenge.rb +++ b/app/models/challenge.rb @@ -1,5 +1,5 @@ #coding=utf-8 -# st 0:编程任务;1:多选任务;2:单选任务 +# st 0:实践任务;1:多选任务;2:单选任务 class Challenge < ActiveRecord::Base default_scope :order => 'position' belongs_to :shixun,:touch=> true @@ -8,6 +8,7 @@ class Challenge < ActiveRecord::Base has_many :test_sets, :dependent => :destroy has_many :challenge_tags, :dependent => :destroy has_many :games, :dependent => :destroy + has_many :challenge_questions, :dependent => :destroy validates_presence_of :subject # validates_presence_of :score @@ -43,4 +44,15 @@ class Challenge < ActiveRecord::Base myshixun = Myshixun.where(:shixun_id => self.shixun.id, :user_id => User.current.id).first game = Game.where(:myshixun_id => myshixun.id, :challenge_id => self.id).first end + + # 正确答案 + def right_answers + answer = "" + self.challenge_questions.each do |ans| + if ans.right_key + answer << (ans.position + 65).chr + end + end + return answer + end end diff --git a/app/models/challenge_question.rb b/app/models/challenge_question.rb index bda6780ce..eb835c32e 100644 --- a/app/models/challenge_question.rb +++ b/app/models/challenge_question.rb @@ -1,3 +1,4 @@ class ChallengeQuestion < ActiveRecord::Base - attr_accessible :challenge_id, :option, :position, :right_key + belongs_to :challenge + attr_accessible :challenge_id, :option_name, :position, :right_key end diff --git a/app/models/course.rb b/app/models/course.rb index 77bc0e757..ccb4579a3 100644 --- a/app/models/course.rb +++ b/app/models/course.rb @@ -1,552 +1,552 @@ -#coding=utf-8 - -require 'elasticsearch/model' -class Course < ActiveRecord::Base - include Redmine::SafeAttributes - - include CoursesHelper - - STATUS_ACTIVE = 1 - STATUS_CLOSED = 5 - STATUS_ARCHIVED = 9 - - #elasticsearch - include Elasticsearch::Model - - #elasticsearch kaminari init - Kaminari::Hooks.init - Elasticsearch::Model::Response::Response.__send__ :include, Elasticsearch::Model::Response::Pagination::Kaminari - settings index: { number_of_shards: 5 } do - mappings dynamic: 'false' do - indexes :name, analyzer: 'smartcn',index_options: 'offsets' - indexes :description, analyzer: 'smartcn',index_options: 'offsets' - indexes :updated_at, index:"not_analyzed",type:"date" - end - end - - attr_accessible :code, :extra, :name, :state, :tea_id, :time , :location, :state, :term, :password,:is_public,:description,:class_period, :open_student, :enterprise_name, :is_delete, :syllabus_id, :end_time, :end_term, :choose_group_allow, :is_end - #belongs_to :project, :class_name => 'Course', :foreign_key => :extra, primary_key: :identifier - belongs_to :teacher, :class_name => 'User', :foreign_key => :tea_id # 定义一个方法teacher,该方法通过tea_id来调用User表 - belongs_to :school, :class_name => 'School', :foreign_key => :school_id #定义一个方法school,该方法通过school_id来调用School表 - belongs_to :syllabus - # has_many :bid - has_many :members, :include => [:principal, :roles], :conditions => "#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{Principal::STATUS_ACTIVE}" - has_many :memberships, :class_name => 'Member' - has_many :member_principals, :class_name => 'Member', - :include => :principal, - :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{Principal::STATUS_ACTIVE})" - has_many :principals, :through => :member_principals, :source => :principal - has_many :users, :through => :members - has_many :org_courses, :dependent => :destroy - has_many :organizations, :through => :org_courses - # has_many :homeworks, :through => :homework_for_courses, :source => :bid, :dependent => :destroy - has_many :journals_for_messages, :as => :jour, :dependent => :destroy - # has_many :homework_for_courses, :dependent => :destroy - has_many :student, :class_name => 'StudentsForCourse', :source => :user - has_many :course_infos, :class_name => 'CourseInfos',:dependent => :destroy - has_many :enabled_modules, :dependent => :delete_all - has_many :boards, :dependent => :destroy, :order => "position ASC" - #has_many :course_journals_for_messages, :class_name => 'CourseJournalsForMessage', :as => :jour, :dependent => :destroy - has_many :news, :dependent => :destroy, :include => :author - has_one :course_status, :class_name => "CourseStatus", :dependent => :destroy - has_many :student_work_projects, :dependent => :destroy - - has_many :homework_commons, :dependent => :destroy - has_many :student_works, :through => :homework_commons, :dependent => :destroy - - has_many :course_groups, :dependent => :destroy, :order => "name ASC" - has_many :course_homework_statisticss, :dependent => :destroy - # 课程动态 - has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy - - has_many :course_activities - # 课程消息 - has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy - has_many :exercises, :dependent => :destroy - # 课程贡献榜 - has_many :course_contributor_scores, :dependent => :destroy - - #课程模块 - has_many :course_modules, :dependent => :destroy - acts_as_taggable - acts_as_nested_set :order => 'name', :dependent => :destroy - acts_as_attachable :view_permission => :view_course_files, - :delete_permission => :manage_files - - validates_presence_of :name - #validates_format_of :class_period, :with =>/^[1-9]\d*$/ - #validates_format_of :time, :with => /^\d{4}$/ - validates_format_of :name,:with =>/^[^ ]+[a-zA-Z0-9_\u4e00-\u9fa5\s\S]*$/ - validates_length_of :description, :maximum => 10000 - - before_save :self_validate - # 公开课程变成私有课程,所有资源都变成私有 - after_update :update_files_public,:update_course_ealasticsearch_index - after_create :create_board_sync, :act_as_course_activity, :act_as_course_message,:create_course_ealasticsearch_index - before_destroy :delete_all_members,:delete_course_ealasticsearch_index - after_save :log_infor - - safe_attributes 'extra', - 'time', - 'name', - 'extra', - 'code', - 'location', - 'tea_id', - 'password', - 'term', - 'is_public', - 'description', - 'class_period', - 'open_student', - 'is_delete', - 'syllabus_id', - 'end_time', - 'end_term', - 'os_allow', - 'choose_group_allow', - 'credit' - - acts_as_customizable - - scope :not_deleted, lambda{where(is_delete: 0)} - scope :not_deleted_not_end, lambda{where(is_delete: 0, is_end: 0)} - scope :not_deleted_but_is_end, lambda{where(is_end: 1, is_delete: 0)} - scope :all_course - scope :active, lambda { where(:status => STATUS_ACTIVE) } - scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) } - scope :all_public, lambda { where(:is_public => true) } - scope :visible, lambda {|*args| where(Course.where("is_delete =?", 0).visible_condition(args.shift || User.current, *args)) } - scope :allowed_to, lambda {|*args| - user = User.current - permission = nil - if args.first.is_a?(Symbol) - permission = args.shift - else - user = args.shift - permission = args.shift - end - where(Course.allowed_to_condition(user, permission, *args)) - } - scope :like, lambda {|arg| - if arg.blank? - where(nil) - else - pattern = "%#{arg.to_s.strip.downcase}%" - where(" LOWER(name) LIKE :p ", :p => pattern) - end - } - scope :indexable,lambda { where('is_public = 1 and is_delete = 0') } - def self.search(query) - __elasticsearch__.search( - { - query: { - multi_match: { - query: query, - type:"most_fields", - operator: "or", - fields: ['name', 'description^0.5'] - } - }, - sort: { - _score:{order: "desc" }, - updated_at:{order:"desc"} - - }, - highlight: { - pre_tags: [''], - post_tags: [''], - fields: { - name: {}, - description: {} - } - } - } - ) - end - - def self.e_search(query) - __elasticsearch__.search( - { - query: { - multi_match: { - query: query, - type:"most_fields", - operator: "or", - fields: ['name', 'description^0.5'] - } - }, - sort: { - _score:{order: "desc" }, - updated_at:{order:"desc"} - - } - } - ) - end - - def delete! - update_attribute(:is_delete, true) - end - - def visible?(user=User.current) - user.allowed_to?(:view_course, self) - end - - def parent_id_changed? - false - end - - # Returns the mail adresses of users that should be always notified on project events - def recipients - notified_users.collect {|user| user.mail} - end - - # Returns the users that should be notified on project events - def notified_users - # TODO: User part should be extracted to User#notify_about? - members.select {|m| m.principal.present? && (m.mail_notification? || m.principal.mail_notification == 'all')}.collect {|m| m.principal} - end - - - # 课程的短描述信息 - def short_description(length = 255) - description.gsub(/<\/?.*?>/,"").html_safe if description - #description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description - end - - # 课程的短名称信息 - def short_name(length = 8) - name.gsub(/<\/?.*?>/,"").html_safe if name - end - - def strip_html(html) - return html if html.empty? || !html.include?('<') - output = "" - tokenizer = HTML::Tokenizer.new(html) - while token = tokenizer.next - node = HTML::Node.parse(nil, 0, 0, token, false) - output += token unless (node.kind_of? HTML::Tag) or (token =~ /^ ["#{Attachmentstype.table_name}.typeId= ?",self.attachmenttype ]) - end - - - # 获取资源后缀名列表 - def contenttypes - attachmenttypes - if @attachmenttypes.length >0 - @attachmenttypes.last().suffixArr - end - end - - def active? - self.status == STATUS_ACTIVE - end - - #课程权限判断 - def allows_to?(action) - if archived? - # No action allowed on archived projects - return false - end - unless active? || Redmine::AccessControl.read_action?(action) - # No write action allowed on closed projects - return false - end - # No action allowed on disabled modules - if action.is_a? Hash - allowed_actions.include? "#{action[:controller]}/#{action[:action]}" - else - allowed_permissions.include? action - end - end - - # 课程允许的权限集合 - def allowed_permissions - @allowed_permissions ||= begin - module_names = enabled_modules.all(:select => :name).collect {|m| m.name} - Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name} - end - end - - # 课程允许的动作集合 - def allowed_actions - @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten - end - - # 返回用户组可以访问的课程 - def users_by_role - members.includes(:user, :roles).all.inject({}) do |h, m| - m.roles.each do |r| - h[r] ||= [] - h[r] << m.user - end - h - end - end - - #自定义验证 - def self_validate - - end - - def update_files_public - unless self.is_public? - self.attachments.each do |a| - a.update_attributes(:is_public => false) - end - end - end - - - def update_default_value - self.time = Time.now.year unless time - self.term = cur_course_term unless term - self.class_period = 10 unless class_period - end - - # 创建课程讨论区 - def create_board_sync - @board = self.boards.build - #self.name=" #{l(:label_borad_course) }" - @board.name = " #{l(:label_borad_course) }"#self.name - @board.description = self.name.to_s - @board.project_id = -1 - if @board.save - logger.debug "[Course Model] ===> #{@board.to_json}" - else - logger.error "[Course Model] ===> Auto create board when course saved, because #{@board.full_messages}" - end - end - - # 新增课程留言 - # add by nwb - def self.add_new_jour(user, notes, id, options={}) - course = Course.find(id) - if options.count == 0 - pjfm = course.journals_for_messages.build(:user_id => user.id, :notes => notes, :reply_id => 0) - else - pjfm = course.journals_for_messages.build(options) - end - pjfm.save - pjfm - end - - # 删除课程所有成员 - def delete_all_members - if self.members && self.members.count > 0 - me, mr = Member.table_name, MemberRole.table_name - connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.course_id = #{id})") - Member.delete_all(['course_id = ?', id]) - end - end - - # 创建课程模块 - def create_course_modules - mod = self.course_modules - if mod.blank? - type = ["news", "boards", "attachment", "homework", "poll", "exercises", "statistics"] - for i in 0..6 - CourseModule.create(:course_id => self.id, :module_type => type[i], :position => i + 1, :hidden => 0 ) - end - mod = self.course_modules - end - return mod - end - - def get_endup_time - begin - end_time = Time.parse(self.endup_time) - rescue Exception => e - end_time = Time.parse("3000-01-01") - Rails.logger.error "[Error] course endup_time error. ===> #{e}" - ensure - return end_time - end - end - - def get_time - begin - time = Date.new(self.time).to_time - rescue Exception => e - time = Time.parse("3000-01-01") - Rails.logger.error "[Error] course time error. ===> #{e}" - ensure - return time - end - end - - def self.allowed_to_condition(user, permission, options={}) - perm = Redmine::AccessControl.permission(permission) - base_statement = (perm && perm.read? ? "#{Course.table_name}.status <> #{Course::STATUS_ARCHIVED}" : "#{Course.table_name}.status = #{Course::STATUS_ACTIVE}") - if perm && perm.course_module - base_statement << " AND #{Course.table_name}.id IN (SELECT em.course_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.course_module}')" - end - - if options[:course] - course_statement = "#{Course.table_name}.id = #{options[:course].id}" - course_statement << " OR (#{Course.table_name}.lft > #{options[:course].lft} AND #{Course.table_name}.rgt < #{options[:course].rgt})" if options[:with_subcourses] - base_statement = "(#{course_statement}) AND (#{base_statement})" - end - - if user.admin? - base_statement - else - statement_by_role = {} - unless options[:member] - role = user.logged? ? Role.non_member : Role.anonymous - if role.allowed_to?(permission) - statement_by_role[role] = "#{Course.table_name}.is_public = #{connection.quoted_true}" - end - end - if user.logged? - user.courses_by_role.each do |role, courses| - if role.allowed_to?(permission) && courses.any? - statement_by_role[role] = "#{Course.table_name}.id IN (#{courses.collect(&:id).join(',')})" - end - end - end - if statement_by_role.empty? - "1=0" - else - if block_given? - statement_by_role.each do |role, statement| - if s = yield(role, user) - statement_by_role[role] = "(#{statement} AND (#{s}))" - end - end - end - "((#{base_statement}) AND (#{statement_by_role.values.join(' OR ')}))" - end - end - end - - #课程动态公共表记录 - def act_as_course_activity - self.course_acts << CourseActivity.new(:user_id => self.tea_id,:course_id => self.id) - end - - #创建课程后,给该用户发送消息 - def act_as_course_message - self.course_messages << CourseMessage.new(:user_id => self.tea_id, :course_id => self.id, :viewed => false) - end - - - #项目与课程分离后,很多课程的名称等信息为空,这些数据信息存储在项目表中!!就是数据兼容的问题 - #def name - # read_attribute('name') || Project.find_by_identifier(self.extra).try(:name) - #end - - # after_commit on: [:create] do - # __elasticsearch__.index_document - # end - # - # after_commit on: [:update] do - # __elasticsearch__.update_document - # end - # - # after_commit on: [:destroy] do - # __elasticsearch__.delete_document - # end - def create_course_ealasticsearch_index - return if Rails.env.development? - if self.is_public == 1 and self.is_delete == 0 #公开 和 没有被删除的课程才被索引 - self.__elasticsearch__.index_document - end - end - - def update_course_ealasticsearch_index - return if Rails.env.development? - if self.is_public == 1 and self.is_delete == 0 #如果是初次更新成为公开或者恢复被删除的情况,会报错,那么这条记录尚未被索引过。没有报错就是更新的其他属性 - begin - self.__elasticsearch__.update_document - rescue => e - self.__elasticsearch__.index_document - end - else #如果是更新成为私有的,那么索引就要被删除 - begin - self.__elasticsearch__.delete_document - rescue => e - - end - end - end - - def delete_course_ealasticsearch_index - return if Rails.env.development? - begin - self.__elasticsearch__.delete_document - rescue => e - - end - end - - # 延迟生成邀请码 - def invite_code - return generate_invite_code - end - - # 生成邀请码 - CODES = %W(2 3 4 5 6 7 8 9 A B C D E F G H J K L N M O P Q R S T U V W X Y Z) - def generate_invite_code - code = read_attribute(:invite_code) - if !code || code.size <5 - code = CODES.sample(5).join - return generate_invite_code if Course.where(invite_code: code).present? - update_attribute(:invite_code, code) - end - code - end - - - def generate_qrcode - ticket = self.qrcode - if !ticket || ticket.size < 10 || (Time.now.to_i > self.qrcode_expiretime) - response = Wechat.api.qrcode_create_scene(invite_code, 2592000) - logger.debug "response = #{response}" - self.qrcode = response['ticket'] - self.qrcode_expiretime = Time.now.to_i+response['expire_seconds'] - save! && reload - ticket = qrcode - end - ticket - end - - def log_infor - Rails.logger.info "##########################################################course's syllabus_id is #{self.syllabus_id}." - end - -end - - - -# Delete the previous articles index in Elasticsearch -# Course.__elasticsearch__.client.indices.delete index: Course.index_name rescue nil -# -# # Create the new index with the new mapping -# Course.__elasticsearch__.client.indices.create \ -# index: Course.index_name, -# body: { settings: Course.settings.to_hash, mappings: Course.mappings.to_hash } - -# Index all article records from the DB to Elasticsearch -#Course.where('is_public = 1').import :force=>true - - +#coding=utf-8 + +require 'elasticsearch/model' +class Course < ActiveRecord::Base + include Redmine::SafeAttributes + + include CoursesHelper + + STATUS_ACTIVE = 1 + STATUS_CLOSED = 5 + STATUS_ARCHIVED = 9 + + #elasticsearch + include Elasticsearch::Model + + #elasticsearch kaminari init + Kaminari::Hooks.init + Elasticsearch::Model::Response::Response.__send__ :include, Elasticsearch::Model::Response::Pagination::Kaminari + settings index: { number_of_shards: 5 } do + mappings dynamic: 'false' do + indexes :name, analyzer: 'smartcn',index_options: 'offsets' + indexes :description, analyzer: 'smartcn',index_options: 'offsets' + indexes :updated_at, index:"not_analyzed",type:"date" + end + end + + attr_accessible :code, :extra, :name, :state, :tea_id, :time , :location, :state, :term, :password,:is_public,:description,:class_period, :open_student, :enterprise_name, :is_delete, :syllabus_id, :end_time, :end_term, :choose_group_allow, :is_end + #belongs_to :project, :class_name => 'Course', :foreign_key => :extra, primary_key: :identifier + belongs_to :teacher, :class_name => 'User', :foreign_key => :tea_id, :dependent => :destroy # 定义一个方法teacher,该方法通过tea_id来调用User表 + belongs_to :school, :class_name => 'School', :foreign_key => :school_id #定义一个方法school,该方法通过school_id来调用School表 + belongs_to :syllabus + # has_many :bid + has_many :members, :include => [:principal, :roles], :conditions => "#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{Principal::STATUS_ACTIVE}" + has_many :memberships, :class_name => 'Member' + has_many :member_principals, :class_name => 'Member', + :include => :principal, + :conditions => "#{Principal.table_name}.type='Group' OR (#{Principal.table_name}.type='User' AND #{Principal.table_name}.status=#{Principal::STATUS_ACTIVE})" + has_many :principals, :through => :member_principals, :source => :principal + has_many :users, :through => :members + has_many :org_courses, :dependent => :destroy + has_many :organizations, :through => :org_courses + # has_many :homeworks, :through => :homework_for_courses, :source => :bid, :dependent => :destroy + has_many :journals_for_messages, :as => :jour, :dependent => :destroy + # has_many :homework_for_courses, :dependent => :destroy + has_many :student, :class_name => 'StudentsForCourse', :source => :user + has_many :course_infos, :class_name => 'CourseInfos',:dependent => :destroy + has_many :enabled_modules, :dependent => :delete_all + has_many :boards, :dependent => :destroy, :order => "position ASC" + #has_many :course_journals_for_messages, :class_name => 'CourseJournalsForMessage', :as => :jour, :dependent => :destroy + has_many :news, :dependent => :destroy, :include => :author + has_one :course_status, :class_name => "CourseStatus", :dependent => :destroy + has_many :student_work_projects, :dependent => :destroy + + has_many :homework_commons, :dependent => :destroy + has_many :student_works, :through => :homework_commons, :dependent => :destroy + + has_many :course_groups, :dependent => :destroy, :order => "name ASC" + has_many :course_homework_statisticss, :dependent => :destroy + # 课程动态 + has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy + + has_many :course_activities + # 课程消息 + has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy + has_many :exercises, :dependent => :destroy + # 课程贡献榜 + has_many :course_contributor_scores, :dependent => :destroy + + #课程模块 + has_many :course_modules, :dependent => :destroy + acts_as_taggable + acts_as_nested_set :order => 'name', :dependent => :destroy + acts_as_attachable :view_permission => :view_course_files, + :delete_permission => :manage_files + + validates_presence_of :name + #validates_format_of :class_period, :with =>/^[1-9]\d*$/ + #validates_format_of :time, :with => /^\d{4}$/ + validates_format_of :name,:with =>/^[^ ]+[a-zA-Z0-9_\u4e00-\u9fa5\s\S]*$/ + validates_length_of :description, :maximum => 10000 + + before_save :self_validate + # 公开课程变成私有课程,所有资源都变成私有 + after_update :update_files_public,:update_course_ealasticsearch_index + after_create :create_board_sync, :act_as_course_activity, :act_as_course_message,:create_course_ealasticsearch_index + before_destroy :delete_all_members,:delete_course_ealasticsearch_index + after_save :log_infor + + safe_attributes 'extra', + 'time', + 'name', + 'extra', + 'code', + 'location', + 'tea_id', + 'password', + 'term', + 'is_public', + 'description', + 'class_period', + 'open_student', + 'is_delete', + 'syllabus_id', + 'end_time', + 'end_term', + 'os_allow', + 'choose_group_allow', + 'credit' + + acts_as_customizable + + scope :not_deleted, lambda{where(is_delete: 0)} + scope :not_deleted_not_end, lambda{where(is_delete: 0, is_end: 0)} + scope :not_deleted_but_is_end, lambda{where(is_end: 1, is_delete: 0)} + scope :all_course + scope :active, lambda { where(:status => STATUS_ACTIVE) } + scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) } + scope :all_public, lambda { where(:is_public => true) } + scope :visible, lambda {|*args| where(Course.where("is_delete =?", 0).visible_condition(args.shift || User.current, *args)) } + scope :allowed_to, lambda {|*args| + user = User.current + permission = nil + if args.first.is_a?(Symbol) + permission = args.shift + else + user = args.shift + permission = args.shift + end + where(Course.allowed_to_condition(user, permission, *args)) + } + scope :like, lambda {|arg| + if arg.blank? + where(nil) + else + pattern = "%#{arg.to_s.strip.downcase}%" + where(" LOWER(name) LIKE :p ", :p => pattern) + end + } + scope :indexable,lambda { where('is_public = 1 and is_delete = 0') } + def self.search(query) + __elasticsearch__.search( + { + query: { + multi_match: { + query: query, + type:"most_fields", + operator: "or", + fields: ['name', 'description^0.5'] + } + }, + sort: { + _score:{order: "desc" }, + updated_at:{order:"desc"} + + }, + highlight: { + pre_tags: [''], + post_tags: [''], + fields: { + name: {}, + description: {} + } + } + } + ) + end + + def self.e_search(query) + __elasticsearch__.search( + { + query: { + multi_match: { + query: query, + type:"most_fields", + operator: "or", + fields: ['name', 'description^0.5'] + } + }, + sort: { + _score:{order: "desc" }, + updated_at:{order:"desc"} + + } + } + ) + end + + def delete! + update_attribute(:is_delete, true) + end + + def visible?(user=User.current) + user.allowed_to?(:view_course, self) + end + + def parent_id_changed? + false + end + + # Returns the mail adresses of users that should be always notified on project events + def recipients + notified_users.collect {|user| user.mail} + end + + # Returns the users that should be notified on project events + def notified_users + # TODO: User part should be extracted to User#notify_about? + members.select {|m| m.principal.present? && (m.mail_notification? || m.principal.mail_notification == 'all')}.collect {|m| m.principal} + end + + + # 课程的短描述信息 + def short_description(length = 255) + description.gsub(/<\/?.*?>/,"").html_safe if description + #description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description + end + + # 课程的短名称信息 + def short_name(length = 8) + name.gsub(/<\/?.*?>/,"").html_safe if name + end + + def strip_html(html) + return html if html.empty? || !html.include?('<') + output = "" + tokenizer = HTML::Tokenizer.new(html) + while token = tokenizer.next + node = HTML::Node.parse(nil, 0, 0, token, false) + output += token unless (node.kind_of? HTML::Tag) or (token =~ /^ ["#{Attachmentstype.table_name}.typeId= ?",self.attachmenttype ]) + end + + + # 获取资源后缀名列表 + def contenttypes + attachmenttypes + if @attachmenttypes.length >0 + @attachmenttypes.last().suffixArr + end + end + + def active? + self.status == STATUS_ACTIVE + end + + #课程权限判断 + def allows_to?(action) + if archived? + # No action allowed on archived projects + return false + end + unless active? || Redmine::AccessControl.read_action?(action) + # No write action allowed on closed projects + return false + end + # No action allowed on disabled modules + if action.is_a? Hash + allowed_actions.include? "#{action[:controller]}/#{action[:action]}" + else + allowed_permissions.include? action + end + end + + # 课程允许的权限集合 + def allowed_permissions + @allowed_permissions ||= begin + module_names = enabled_modules.all(:select => :name).collect {|m| m.name} + Redmine::AccessControl.modules_permissions(module_names).collect {|p| p.name} + end + end + + # 课程允许的动作集合 + def allowed_actions + @actions_allowed ||= allowed_permissions.inject([]) { |actions, permission| actions += Redmine::AccessControl.allowed_actions(permission) }.flatten + end + + # 返回用户组可以访问的课程 + def users_by_role + members.includes(:user, :roles).all.inject({}) do |h, m| + m.roles.each do |r| + h[r] ||= [] + h[r] << m.user + end + h + end + end + + #自定义验证 + def self_validate + + end + + def update_files_public + unless self.is_public? + self.attachments.each do |a| + a.update_attributes(:is_public => false) + end + end + end + + + def update_default_value + self.time = Time.now.year unless time + self.term = cur_course_term unless term + self.class_period = 10 unless class_period + end + + # 创建课程讨论区 + def create_board_sync + @board = self.boards.build + #self.name=" #{l(:label_borad_course) }" + @board.name = " #{l(:label_borad_course) }"#self.name + @board.description = self.name.to_s + @board.project_id = -1 + if @board.save + logger.debug "[Course Model] ===> #{@board.to_json}" + else + logger.error "[Course Model] ===> Auto create board when course saved, because #{@board.full_messages}" + end + end + + # 新增课程留言 + # add by nwb + def self.add_new_jour(user, notes, id, options={}) + course = Course.find(id) + if options.count == 0 + pjfm = course.journals_for_messages.build(:user_id => user.id, :notes => notes, :reply_id => 0) + else + pjfm = course.journals_for_messages.build(options) + end + pjfm.save + pjfm + end + + # 删除课程所有成员 + def delete_all_members + if self.members && self.members.count > 0 + me, mr = Member.table_name, MemberRole.table_name + connection.delete("DELETE FROM #{mr} WHERE #{mr}.member_id IN (SELECT #{me}.id FROM #{me} WHERE #{me}.course_id = #{id})") + Member.delete_all(['course_id = ?', id]) + end + end + + # 创建课程模块 + def create_course_modules + mod = self.course_modules + if mod.blank? + type = ["news", "boards", "attachment", "homework", "poll", "exercises", "statistics"] + for i in 0..6 + CourseModule.create(:course_id => self.id, :module_type => type[i], :position => i + 1, :hidden => 0 ) + end + mod = self.course_modules + end + return mod + end + + def get_endup_time + begin + end_time = Time.parse(self.endup_time) + rescue Exception => e + end_time = Time.parse("3000-01-01") + Rails.logger.error "[Error] course endup_time error. ===> #{e}" + ensure + return end_time + end + end + + def get_time + begin + time = Date.new(self.time).to_time + rescue Exception => e + time = Time.parse("3000-01-01") + Rails.logger.error "[Error] course time error. ===> #{e}" + ensure + return time + end + end + + def self.allowed_to_condition(user, permission, options={}) + perm = Redmine::AccessControl.permission(permission) + base_statement = (perm && perm.read? ? "#{Course.table_name}.status <> #{Course::STATUS_ARCHIVED}" : "#{Course.table_name}.status = #{Course::STATUS_ACTIVE}") + if perm && perm.course_module + base_statement << " AND #{Course.table_name}.id IN (SELECT em.course_id FROM #{EnabledModule.table_name} em WHERE em.name='#{perm.course_module}')" + end + + if options[:course] + course_statement = "#{Course.table_name}.id = #{options[:course].id}" + course_statement << " OR (#{Course.table_name}.lft > #{options[:course].lft} AND #{Course.table_name}.rgt < #{options[:course].rgt})" if options[:with_subcourses] + base_statement = "(#{course_statement}) AND (#{base_statement})" + end + + if user.admin? + base_statement + else + statement_by_role = {} + unless options[:member] + role = user.logged? ? Role.non_member : Role.anonymous + if role.allowed_to?(permission) + statement_by_role[role] = "#{Course.table_name}.is_public = #{connection.quoted_true}" + end + end + if user.logged? + user.courses_by_role.each do |role, courses| + if role.allowed_to?(permission) && courses.any? + statement_by_role[role] = "#{Course.table_name}.id IN (#{courses.collect(&:id).join(',')})" + end + end + end + if statement_by_role.empty? + "1=0" + else + if block_given? + statement_by_role.each do |role, statement| + if s = yield(role, user) + statement_by_role[role] = "(#{statement} AND (#{s}))" + end + end + end + "((#{base_statement}) AND (#{statement_by_role.values.join(' OR ')}))" + end + end + end + + #课程动态公共表记录 + def act_as_course_activity + self.course_acts << CourseActivity.new(:user_id => self.tea_id,:course_id => self.id) + end + + #创建课程后,给该用户发送消息 + def act_as_course_message + self.course_messages << CourseMessage.new(:user_id => self.tea_id, :course_id => self.id, :viewed => false) + end + + + #项目与课程分离后,很多课程的名称等信息为空,这些数据信息存储在项目表中!!就是数据兼容的问题 + #def name + # read_attribute('name') || Project.find_by_identifier(self.extra).try(:name) + #end + + # after_commit on: [:create] do + # __elasticsearch__.index_document + # end + # + # after_commit on: [:update] do + # __elasticsearch__.update_document + # end + # + # after_commit on: [:destroy] do + # __elasticsearch__.delete_document + # end + def create_course_ealasticsearch_index + return if Rails.env.development? + if self.is_public == 1 and self.is_delete == 0 #公开 和 没有被删除的课程才被索引 + self.__elasticsearch__.index_document + end + end + + def update_course_ealasticsearch_index + return if Rails.env.development? + if self.is_public == 1 and self.is_delete == 0 #如果是初次更新成为公开或者恢复被删除的情况,会报错,那么这条记录尚未被索引过。没有报错就是更新的其他属性 + begin + self.__elasticsearch__.update_document + rescue => e + self.__elasticsearch__.index_document + end + else #如果是更新成为私有的,那么索引就要被删除 + begin + self.__elasticsearch__.delete_document + rescue => e + + end + end + end + + def delete_course_ealasticsearch_index + return if Rails.env.development? + begin + self.__elasticsearch__.delete_document + rescue => e + + end + end + + # 延迟生成邀请码 + def invite_code + return generate_invite_code + end + + # 生成邀请码 + CODES = %W(2 3 4 5 6 7 8 9 A B C D E F G H J K L N M O P Q R S T U V W X Y Z) + def generate_invite_code + code = read_attribute(:invite_code) + if !code || code.size <5 + code = CODES.sample(5).join + return generate_invite_code if Course.where(invite_code: code).present? + update_attribute(:invite_code, code) + end + code + end + + + def generate_qrcode + ticket = self.qrcode + if !ticket || ticket.size < 10 || (Time.now.to_i > self.qrcode_expiretime) + response = Wechat.api.qrcode_create_scene(invite_code, 2592000) + logger.debug "response = #{response}" + self.qrcode = response['ticket'] + self.qrcode_expiretime = Time.now.to_i+response['expire_seconds'] + save! && reload + ticket = qrcode + end + ticket + end + + def log_infor + Rails.logger.info "##########################################################course's syllabus_id is #{self.syllabus_id}." + end + +end + + + +# Delete the previous articles index in Elasticsearch +# Course.__elasticsearch__.client.indices.delete index: Course.index_name rescue nil +# +# # Create the new index with the new mapping +# Course.__elasticsearch__.client.indices.create \ +# index: Course.index_name, +# body: { settings: Course.settings.to_hash, mappings: Course.mappings.to_hash } + +# Index all article records from the DB to Elasticsearch +#Course.where('is_public = 1').import :force=>true + + diff --git a/app/models/message.rb b/app/models/message.rb index e5c1f7205..e5c4e0788 100644 --- a/app/models/message.rb +++ b/app/models/message.rb @@ -98,7 +98,7 @@ class Message < ActiveRecord::Base } - safe_attributes 'subject', 'content', 'reply_id', 'root_id' + safe_attributes 'subject', 'content', 'reply_id', 'root_id', 'visits' safe_attributes 'board_id','locked', 'sticky', :if => lambda {|message, user| if message.project diff --git a/app/models/output.rb b/app/models/output.rb index b6edbb602..68ba45061 100644 --- a/app/models/output.rb +++ b/app/models/output.rb @@ -1,5 +1,6 @@ class Output < ActiveRecord::Base # attr_accessible :title, :body + # actual_output 编程题:实际输出, 选择题: 用户提交的答案(如: 014 对应用户选择为A B E) default_scope :order => 'test_set_position desc' belongs_to :game end diff --git a/app/models/school.rb b/app/models/school.rb index 81e1743b2..63d180e9f 100644 --- a/app/models/school.rb +++ b/app/models/school.rb @@ -1,10 +1,10 @@ -class School < ActiveRecord::Base - attr_accessible :name, :province,:pinyin - has_many :courses - has_many :departments, :dependent => :destroy - - def to_s - self.name.to_s - end - -end +class School < ActiveRecord::Base + default_scope :order => 'created_at desc' + attr_accessible :name, :province,:pinyin + has_many :courses + has_many :departments, :dependent => :destroy + + def to_s + self.name.to_s + end +end diff --git a/app/models/syllabus.rb b/app/models/syllabus.rb index f1d9cb34e..e893d9791 100644 --- a/app/models/syllabus.rb +++ b/app/models/syllabus.rb @@ -1,161 +1,165 @@ -# encoding: utf-8 -class Syllabus < ActiveRecord::Base - include Redmine::SafeAttributes - include ApplicationHelper - #elasticsearch - include Elasticsearch::Model - #elasticsearch kaminari init - Kaminari::Hooks.init - Elasticsearch::Model::Response::Response.__send__ :include, Elasticsearch::Model::Response::Pagination::Kaminari - settings index: { number_of_shards: 5 } do - mappings dynamic: 'false' do - indexes :title, analyzer: 'smartcn',index_options: 'offsets' - indexes :description, analyzer: 'smartcn',index_options: 'offsets' - indexes :updated_at, index:"not_analyzed", type:'date' - end - end - acts_as_taggable - acts_as_attachable - has_many_kindeditor_assets :assets, :dependent => :destroy - - belongs_to :user - has_many :courses - has_many :homework_banks - has_many :reference_materials, :dependent => :destroy - has_many :syllabus_update_records, :dependent => :destroy - has_many :journals_for_messages, :as => :jour, :dependent => :destroy - has_many :syllabus_members, :dependent => :destroy - has_many :praise_tread, as: :praise_tread_object, dependent: :destroy - has_one :praise_tread_cache, as: :object, dependent: :destroy - belongs_to :discipline_category - belongs_to :first_level_discipline - belongs_to :major - attr_accessible :description, :user_id, :title, :eng_name, :syllabus_type, :credit, :hours, :theory_hours, :practice_hours, :applicable_major, :pre_course, :major_level, :discipline_category_id, :first_level_discipline_id, :major_id - safe_attributes 'title','user', 'description', 'eng_name', 'syllabus_type', 'credit', 'hours', 'theory_hours', 'practice_hours', 'credit', 'applicable_major', 'pre_course', 'major_level', 'discipline_category_id', "first_level_discipline_id" - - validates :title, :user_id, presence: true - - after_update :update_syllabus_ealasticsearch_index - after_create :create_syllabus_ealasticsearch_index - before_destroy :delete_syllabus_ealasticsearch_index - - scope :indexable,lambda { where(nil) }#用于elastic建索引的scope - - scope :like, lambda {|arg| - if arg.blank? - where(nil) - else - pattern = "%#{arg.to_s.strip.downcase}%" - where(" LOWER(title) LIKE :p ", :p => pattern) - end - } - - def delete_kindeditor_assets - delete_kindeditor_assets_from_disk self.id,OwnerTypeHelper::SYLLABUS - end - - def syllabus_major_level - type = "" - case self.major_level - when 1 - type = "研究生" - when 2 - type = "本科" - when 3 - type = "专科" - end - type - end - - def syllabus_type_str - type = "" - case self.syllabus_type - when 1 - type = "公共必修课" - when 2 - type = "学科必修课" - when 3 - type = "专业选修课" - when 4 - type = "实践必修课" - when 5 - type = "实践选修课" - end - type - end - - def syllabus_discipline_category - self.discipline_category ? self.discipline_category.name : '' - end - - def syllabus_first_level_discipline - self.first_level_discipline ? self.first_level_discipline.name : '' - end - - def syllabus_major - self.major ? self.major.name : '' - end - - ###添加回复 - def self.add_syllabus_jour(user, notes, id, root_id, options = {}) - syllabus = Syllabus.find(id) - if options.count == 0 - jfm = syllabus.journals_for_messages.build(:user_id => user.id, :notes => notes, :reply_id => 0, :root_id => root_id) - else - jfm = syllabus.journals_for_messages.build(options) - end - jfm.save - jfm - end - - def create_syllabus_ealasticsearch_index - return if Rails.env.development? - self.__elasticsearch__.index_document - end - - def update_syllabus_ealasticsearch_index - return if Rails.env.development? - begin - self.__elasticsearch__.update_document - rescue => e - self.__elasticsearch__.index_document - end - end - - def delete_syllabus_ealasticsearch_index - return if Rails.env.development? - begin - self.__elasticsearch__.delete_document - rescue => e - - end - end - - def self.search(query) - __elasticsearch__.search( - { - query: { - multi_match: { - query: query, - type:"most_fields", - operator: "or", - fields: ['title'] - } - }, - sort: { - _score:{order: "desc" }, - updated_at:{order:"desc"} - - }, - highlight: { - pre_tags: [''], - post_tags: [''], - fields: { - title: {}, - description: {} - } - } - } - ) - end -end +# encoding: utf-8 +class Syllabus < ActiveRecord::Base + include Redmine::SafeAttributes + include ApplicationHelper + #elasticsearch + include Elasticsearch::Model + #elasticsearch kaminari init + Kaminari::Hooks.init + Elasticsearch::Model::Response::Response.__send__ :include, Elasticsearch::Model::Response::Pagination::Kaminari + settings index: { number_of_shards: 5 } do + mappings dynamic: 'false' do + indexes :title, analyzer: 'smartcn',index_options: 'offsets' + indexes :description, analyzer: 'smartcn',index_options: 'offsets' + indexes :updated_at, index:"not_analyzed", type:'date' + end + end + acts_as_taggable + acts_as_attachable + has_many_kindeditor_assets :assets, :dependent => :destroy + + belongs_to :user + has_many :courses + has_many :homework_banks + has_many :reference_materials, :dependent => :destroy + has_many :syllabus_update_records, :dependent => :destroy + has_many :journals_for_messages, :as => :jour, :dependent => :destroy + has_many :syllabus_members, :dependent => :destroy + has_many :praise_tread, as: :praise_tread_object, dependent: :destroy + has_one :praise_tread_cache, as: :object, dependent: :destroy + belongs_to :discipline_category + belongs_to :first_level_discipline + belongs_to :major + attr_accessible :description, :user_id, :title, :eng_name, :syllabus_type, :credit, :hours, :theory_hours, :practice_hours, :applicable_major, :pre_course, :major_level, :discipline_category_id, :first_level_discipline_id, :major_id + safe_attributes 'title','user', 'description', 'eng_name', 'syllabus_type', 'credit', 'hours', 'theory_hours', 'practice_hours', 'credit', 'applicable_major', 'pre_course', 'major_level', 'discipline_category_id', "first_level_discipline_id" + + validates :title, :user_id, presence: true + + after_update :update_syllabus_ealasticsearch_index + after_create :create_syllabus_ealasticsearch_index + before_destroy :delete_syllabus_ealasticsearch_index + + scope :indexable,lambda { where(nil) }#用于elastic建索引的scope + + scope :like, lambda {|arg| + if arg.blank? + where(nil) + else + pattern = "%#{arg.to_s.strip.downcase}%" + where(" LOWER(title) LIKE :p ", :p => pattern) + end + } + + def delete_kindeditor_assets + delete_kindeditor_assets_from_disk self.id,OwnerTypeHelper::SYLLABUS + end + + # 课程层级 + def syllabus_major_level + type = "" + case self.major_level + when 1 + type = "研究生" + when 2 + type = "本科" + when 3 + type = "专科" + end + type + end + + def syllabus_type_str + type = "" + case self.syllabus_type + when 1 + type = "公共必修课" + when 2 + type = "学科必修课" + when 3 + type = "专业选修课" + when 4 + type = "实践必修课" + when 5 + type = "实践选修课" + end + type + end + + # 课程的学科门类 + def syllabus_discipline_category + self.discipline_category ? self.discipline_category.name : '' + end + + # 课程的一级学科 + def syllabus_first_level_discipline + self.first_level_discipline ? self.first_level_discipline.name : '' + end + + # 课程的专业 + def syllabus_major + self.major ? self.major.name : '' + end + + ###添加回复 + def self.add_syllabus_jour(user, notes, id, root_id, options = {}) + syllabus = Syllabus.find(id) + if options.count == 0 + jfm = syllabus.journals_for_messages.build(:user_id => user.id, :notes => notes, :reply_id => 0, :root_id => root_id) + else + jfm = syllabus.journals_for_messages.build(options) + end + jfm.save + jfm + end + + def create_syllabus_ealasticsearch_index + return if Rails.env.development? + self.__elasticsearch__.index_document + end + + def update_syllabus_ealasticsearch_index + return if Rails.env.development? + begin + self.__elasticsearch__.update_document + rescue => e + self.__elasticsearch__.index_document + end + end + + def delete_syllabus_ealasticsearch_index + return if Rails.env.development? + begin + self.__elasticsearch__.delete_document + rescue => e + + end + end + + def self.search(query) + __elasticsearch__.search( + { + query: { + multi_match: { + query: query, + type:"most_fields", + operator: "or", + fields: ['title'] + } + }, + sort: { + _score:{order: "desc" }, + updated_at:{order:"desc"} + + }, + highlight: { + pre_tags: [''], + post_tags: [''], + fields: { + title: {}, + description: {} + } + } + } + ) + end +end diff --git a/app/views/admin/projects.html.erb b/app/views/admin/projects.html.erb index e7d796e6f..ed173930a 100644 --- a/app/views/admin/projects.html.erb +++ b/app/views/admin/projects.html.erb @@ -1,92 +1,92 @@ -
    - <%= link_to l(:label_project_new), {:controller => 'projects', :action => 'new'}, :class => 'icon icon-add' %> -
    - -

    - <%=l(:label_project_plural)%> -

    - -<%= form_tag({}, :method => :get) do %> -
    - - <%= l(:label_filter_plural) %> - - - <%= select_tag 'status', project_status_options_for_select(@status), :class => "small", :onchange => "this.form.submit(); return false;" %> - - <%= text_field_tag 'name', params[:name], :size => 30, :placeholder => '输入项目名称进行搜索' %> - <%= submit_tag l(:button_apply), :class => "small", :name => nil %> - <%= link_to l(:button_clear), {:controller => 'admin', :action => 'projects'}, :class => 'icon icon-reload' %> -
    -<% end %> -  - -
    - - - - - - - - - - - - <% @projects.each do |project| %> - "> - - - - - - - <% end %> - -
    - 序号 - - <%=l(:label_project)%> - - <%=l(:field_is_public)%> - - <%=l(:field_created_on)%> -
    - <%= project.id %> - - - <%= link_to_project_settings(project, {}) %> - - - <%= checked_image project.is_public? %> - - <%= format_date(project.created_on) %> - - <%= link_to(l(:button_archive), { :controller => 'projects', :action => 'archive', :id => project, :status => params[:status] }, :data => {:confirm => l(:text_are_you_sure)}, :method => :post, :class => 'icon icon-lock') unless project.archived? %> - <%= link_to(l(:button_unarchive), { :controller => 'projects', :action => 'unarchive', :id => project, :status => params[:status] }, :method => :post, :class => 'icon icon-unlock') if project.archived? && (project.parent.nil? || !project.parent.archived?) %> - <%= link_to(l(:button_delete), project_path(project), :method => :delete, :class => 'icon icon-del', :onClick=>"delcfm()" ) %> -
    -
    - - - -<% html_title(l(:label_project_plural)) -%> -
    项目代码/提交数统计: - <%= link_to "最近一周", {:controller => 'admin', :action => 'export_rep_static_users', :format => 'xls', :cycle => "admin_week" }, :confirm => l(:label_rep_admin_export_tip), :class => "linkBlue2" %> | - <%= link_to "最近一月", {:controller => 'admin', :action => 'export_rep_static_users', :format => 'xls', :cycle => "admin_month" }, :confirm => l(:label_rep_admin_export_tip), :class => "linkBlue2" %>| - <%= link_to "所有", {:controller => 'admin', :action => 'export_rep_static_users', :format => 'xls', :cycle => "admin_all" }, :confirm => l(:label_rep_admin_export_tip), :class => "linkBlue2" %> -
    - - \ No newline at end of file diff --git a/app/views/attachments/_activity_attach.html.erb b/app/views/attachments/_activity_attach.html.erb index 8baf1deb3..fd6eb661f 100644 --- a/app/views/attachments/_activity_attach.html.erb +++ b/app/views/attachments/_activity_attach.html.erb @@ -1,6 +1,6 @@ <% if activity.attachments.any? %> <% activity.attachments.each do |attachment| %> -
  • +
  • <%= link_to_short_attachment attachment,:length=> 58, :class => 'link-color-grey', :download => true %> diff --git a/app/views/boards/_course_show.html.erb b/app/views/boards/_course_show.html.erb index 4ca7f618c..0ba6af1f3 100644 --- a/app/views/boards/_course_show.html.erb +++ b/app/views/boards/_course_show.html.erb @@ -1,60 +1,60 @@ - - - - <% if false %> - + <% if @is_new%> + $(function(){ + $("#message_subject").focus(); + }); + <%end%> + -
    -
    -
    - <%= @board.parent_id.nil? ? "班级讨论区" : "#{@board.name}" %> +
    +
    +
    + <%= @board.parent_id.nil? ? "班级讨论区" : "#{@board.name}" %> +
    + + <% is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@board.course)) %> + <% if is_teacher %> + <%= link_to "添加子栏目", settings_course_path(@board.course.id,'boards'), :class => "link-blue fr mt5" %> + <% end %> +
    +
    + <% if User.current.logged? %> + <%= labelled_form_for @message, :url =>{:controller=>'messages',:action => 'new', :board_id => @board.id, :is_board => 'true'}, + :html => {:nhname=>'form',:multipart => true, :id => 'message-form'} do |f| %> + <%= render :partial => 'course_new', :locals => {:f => f, :topic => @message, :edit_mode => false, :course => @board.course} %> + <% end %> + <% end %> +
    + <%= render :partial=> 'course_show_detail',:locals =>{:topics => @topics, :page => 0} %>
    - - <% is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@board.course)) %> - <% if is_teacher %> - <%= link_to "添加子栏目", settings_course_path(@board.course.id,'boards'), :class => "link-blue fr mt5" %> - <% end %> -
    -
    - <% if User.current.logged? %> - <%= labelled_form_for @message, :url =>{:controller=>'messages',:action => 'new', :board_id => @board.id, :is_board => 'true'}, - :html => {:nhname=>'form',:multipart => true, :id => 'message-form'} do |f| %> - <%= render :partial => 'course_new', :locals => {:f => f, :topic => @message, :edit_mode => false, :course => @board.course} %> - <% end %> - <% end %> -
    - <%= render :partial=> 'course_show_detail',:locals =>{:topics => @topics, :page => 0} %> -
    <% end %> -
    - -
    - <%= render :partial => "course_show_detail", :locals => {:topics => @topics, :page => 0} %> +
    +
    +
    +

    全部帖子

    <%= @topics.count %> + <% if User.current.logged? %> + + 我要发布 + <% end %> +
    +
    + <%= render :partial => "course_show_detail", :locals => {:topics => @topics, :page => 0} %> +
    \ No newline at end of file diff --git a/app/views/boards/_course_show_detail.html.erb b/app/views/boards/_course_show_detail.html.erb index 39df6331e..5930d76df 100644 --- a/app/views/boards/_course_show_detail.html.erb +++ b/app/views/boards/_course_show_detail.html.erb @@ -3,8 +3,8 @@ <%= javascript_include_tag "create_kindeditor" %> <% end %> -<% if @topics %> - <%= render :partial => 'users/course_boardlist', :locals => {:topics => @topics ? @topics: topics , :is_course => 1, :is_board=>1} %> +<% if @topics.count > 0 %> + <%= render :partial => 'users/course_boardlist', :locals => {:topics => @topics, :is_course => 1, :is_board=>1} %> <% else %> <%= render :partial => "welcome/no_data" %> <% end %> \ No newline at end of file diff --git a/app/views/challenges/_answer_form.html.erb b/app/views/challenges/_answer_form.html.erb index 11007ca74..98f3a8e7b 100644 --- a/app/views/challenges/_answer_form.html.erb +++ b/app/views/challenges/_answer_form.html.erb @@ -47,7 +47,7 @@ saveHTMLToTextarea : true, // 用于增加自定义工具栏的功能,可以直接插入HTML标签,不使用默认的元素创建图标 dialogMaskOpacity : 0.6, - placeholder: "请输入完成当前任务依赖的知识点或者其它相关信息", + placeholder: "<%= @st == 0 ? '' : "请输入各个选项的具体解析或其他相关信息" %>", imageUpload : true, imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp", "JPG", "JPEG", "GIF", "PNG", "BMP", "WEBP"], imageUploadURL : "<%= upload_with_markdown_path(:container_id => @shixun.id, :container_type => @shixun.class) %>"//url diff --git a/app/views/challenges/_content_list.html.erb b/app/views/challenges/_content_list.html.erb index 3b199c484..4fa08e9b8 100644 --- a/app/views/challenges/_content_list.html.erb +++ b/app/views/challenges/_content_list.html.erb @@ -5,18 +5,29 @@ <%= @challenges.count %> <% end %> <% if User.current.manager_of_shixun?(@shixun) && @shixun.status == 0 %> - - - - 新建阶段 + +实践任务 + +多选任务 + +单选任务 + <% end %>
    <% @challenges.each_with_index do |challenge, index| -%>
    -

    第<%= challenge.position %>关 +

    + + <% if challenge.st == 0 %> + + <% elsif challenge.st == 1 %> + + <% elsif challenge.st == 2 %> + + <% end%> + + + 第<%= challenge.position %>关 <%#= link_to challenge.subject, shixun_challenge_path(@shixun.id, challenge), :target => "_blank" %> <% if User.current.manager_of_shixun?(@shixun) %> - <%= link_to challenge.subject, shixun_challenge_path(@shixun, challenge), :target => "_blank" %> + <%= link_to challenge.subject, edit_shixun_challenge_path(challenge, :shixun_id => @shixun), :target => "_blank" %> <% else %> <% if allow_to_view_challenge(challenge, @shixun) %> <%= link_to challenge.subject, myshixun_game_path(challenge.current_user_game, :myshixun_id => challenge.current_user_game.try(:myshixun)), :target => "_blank" %> diff --git a/app/views/challenges/_edit_answer.html.erb b/app/views/challenges/_edit_answer.html.erb index 4dc249b46..1fd0f9522 100644 --- a/app/views/challenges/_edit_answer.html.erb +++ b/app/views/challenges/_edit_answer.html.erb @@ -3,7 +3,7 @@

    - <% if @shixun.status == 0 && User.current.manager_of_shixun?(@shixun) %> + <% if User.current.manager_of_shixun?(@shixun) %> 编辑 <% end %>

    diff --git a/app/views/challenges/_edit_propaedeutics.html.erb b/app/views/challenges/_edit_propaedeutics.html.erb new file mode 100644 index 000000000..d3a5af201 --- /dev/null +++ b/app/views/challenges/_edit_propaedeutics.html.erb @@ -0,0 +1,44 @@ +
    + <% if @editor.blank? && !@challenge.ready_knowledge.blank? %> +
    +
    +

    + <% if User.current.manager_of_shixun?(@shixun) %> + 编辑 + <% end %> +

    +
    +
      +
    • + +
      + +
      + +
    • +
    +
    + <% end %> + <% if @challenge.ready_knowledge.blank? || !@editor.blank? %> +
      + <%= labelled_form_for @challenge, :url => shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => 6), :html => {:id => "challenge_shixun_propaedeutics"} do |f| %> + <%= render :partial => "propaedeutics_form", :locals => {:f => f} %> + <% end %> +
    + <% end %> +
    + \ No newline at end of file diff --git a/app/views/challenges/_edit_scoring.html.erb b/app/views/challenges/_edit_scoring.html.erb index 307f8d74c..3eab2d79b 100644 --- a/app/views/challenges/_edit_scoring.html.erb +++ b/app/views/challenges/_edit_scoring.html.erb @@ -3,7 +3,7 @@
    ">

    - <% if @shixun.status == 0 && User.current.manager_of_shixun?(@shixun) %> + <% if User.current.manager_of_shixun?(@shixun) %> 编辑 <% end %>

    diff --git a/app/views/challenges/_edit_skill.html.erb b/app/views/challenges/_edit_skill.html.erb index 2a00676bd..64c4556b6 100644 --- a/app/views/challenges/_edit_skill.html.erb +++ b/app/views/challenges/_edit_skill.html.erb @@ -2,7 +2,7 @@
    ">

    - <% if @shixun.status == 0 && User.current.manager_of_shixun?(@shixun) %> + <% if User.current.manager_of_shixun?(@shixun) %> 编辑 <% end %>

    diff --git a/app/views/challenges/_edit_task_pass.html.erb b/app/views/challenges/_edit_task_pass.html.erb index 0e602d69d..75473897c 100644 --- a/app/views/challenges/_edit_task_pass.html.erb +++ b/app/views/challenges/_edit_task_pass.html.erb @@ -3,7 +3,7 @@

    - <% if @shixun.status == 0 && User.current.manager_of_shixun?(@shixun) %> + <% if User.current.manager_of_shixun?(@shixun) %> 编辑 <% end %>

    @@ -23,6 +23,31 @@

  • + <% if @challenge.st == 1 %> + + <% elsif @challenge.st == 2 %> + + <% end %> <% end %> <% if @challenge.subject.blank? || !@editor.blank? %> <% end %> -<%# if @challenge.st == 1 %> - +<%# if @challenge.st == 1 %> <%# end %> \ No newline at end of file diff --git a/app/views/challenges/_score_form.html.erb b/app/views/challenges/_score_form.html.erb index 8dbcd49d3..989eb74ce 100644 --- a/app/views/challenges/_score_form.html.erb +++ b/app/views/challenges/_score_form.html.erb @@ -29,8 +29,13 @@
      -
    1. 如果学员查看了参考答案,则不能得到相应的经验值
    2. -
    3. 如果学员成功得到经验值,那么将同时获得等值的金币奖励,如:+100经验值、+100金币
    4. + <% if @st == 0 %> +
    5. 如果学员查看了参考答案,则不能得到相应的经验值
    6. +
    7. 如果学员成功得到经验值,那么将同时获得等值的金币奖励,如:+100经验值、+100金币
    8. + <% else %> +
    9. 如果学员答题错误,则不能得到相应的经验值
    10. +
    11. 如果学员成功得到经验值,那么将同时获得等值的金币奖励,如:+10经验值、+10金币
    12. + <% end %>
    @@ -44,40 +49,41 @@
  • @@ -25,13 +32,66 @@
  • - - - - - + <% if @st != 0 %> + <% if params[:action] == "edit" && @challenge.challenge_questions.count > 0 %> + <% @challenge.challenge_questions.each_with_index do |question, index| %> +
  • + + + + +
  • + <% end %> + <% elsif @st == 2 %> +
  • + + + + +
  • +
  • + + + + +
  • + <% else %> +
  • + + + + +
  • +
  • + + + + +
  • +
  • + + + + +
  • +
  • + + + + +
  • + <% end %> + + <% end %>
  • - 保存 + 保存 <% if params[:action] == "new" %> 取消 <% else %> @@ -63,12 +123,121 @@ saveHTMLToTextarea : true, // 用于增加自定义工具栏的功能,可以直接插入HTML标签,不使用默认的元素创建图标 dialogMaskOpacity : 0.6, - placeholder: "请输入完成当前任务依赖的知识点或者其它相关信息", + placeholder: "<%= @st == 0 ? "请输入完成当前任务依赖的知识点或者其它相关信息" : "请输入选择题的题干内容" %>", imageUpload : true, imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp", "JPG", "JPEG", "GIF", "PNG", "BMP", "WEBP"], imageUploadURL : "<%= upload_with_markdown_path(:container_id => @shixun.id, :container_type => @shixun.class) %>"//url }); + + var bt = baidu.template; + bt.LEFT_DELIMITER = ''; + + $("#shixun_form").on('click', 'a.option_icon_add', function () { + var html = bt('t:set-option-list', null); + $(this).parent().parent('.clearfix').before(html); + var inputs = document.getElementsByName("question[cnt][]"); + var inputs_spans = document.getElementsByName("option_span"); + for (var j = 0; j < inputs_spans.length; j++) { + if(j >= 0 && j <= 26){ + $(inputs_spans[j]).html(String.fromCharCode(65 + j)); + } + } + for (var i = 0; i < inputs.length; i++) { + autoTextarea(inputs[i], 0, 140); + } + $(inputs[inputs.length - 1]).focus(); + }); + $("#shixun_form").on('click', 'a.option_icon_remove', function () { + $(this).parent('.clearfix').remove(); + var inputs_spans = document.getElementsByName("option_span"); + for (var j = 0; j < inputs_spans.length; j++) { + if(j >= 0 && j <= 26){ + if(j >= 0 && j <= 26){ + $(inputs_spans[j]).html(String.fromCharCode(65 + j)); + } + } + } + $("#current-option").html(""); + if($(".check-option-bg").length>0){ + for(var i=0;i<$(".check-option-bg").length;i++){ + $("#current-option").html($("#current-option").html()+$(".check-option-bg").eq(i).html()); + } + }else{ + $("#current-option").html("请点击正确选项"); + } + }); }); + //设置选项答案 + function selectchoice(item, st){ + //判断是否选中,如果选中,再次点击的时候取消选中 + if($(item).hasClass('check-option-bg')){ + $(item).removeClass('check-option-bg'); + }else{ + if(st == 2){ + //单选 + $(".select-choice").removeClass('check-option-bg'); + $(item).addClass('check-option-bg'); + }else{ + //多选 + $(item).addClass('check-option-bg'); + } + } + $("#current-option").html(""); + if($(".check-option-bg").length>0){ + for(var i=0;i<$(".check-option-bg").length;i++){ + $("#current-option").html($("#current-option").html()+$(".check-option-bg").eq(i).html()); + } + }else{ + $("#current-option").html("请点击正确选项"); + } + } + // 判断选择题的答案 + function set_choice_answer(){ + var answer = document.getElementsByName("choice[answer][]"); + var choice = document.getElementsByName("option_span"); + for(var o = 0; o < choice.length; o++){ + if($(choice[o]).hasClass("check-option-bg")){ + $(answer[o]).val(String.fromCharCode(65 + o)); + }else{ + $(answer[o]).val(0); + } + } + } + + // 判断选择题内容是否为空 + function judge_choice_contents(){ + var answer = document.getElementsByName("choice[answer][]"); + var contents = document.getElementsByName("question[cnt][]"); + var lens = contents.length; + for(var i = 0; i < lens; i++){ + if($(contents[i]).val().trim() == ""){ + return true; + } + } + return false; + } + + // 判断选择题选择答案的个数 + function judge_choice_answer(){ + var answer = document.getElementsByName("choice[answer][]"); + var lens = answer.length; + var num = 0; + for(var i= 0; i < lens; i++){ + if($(answer[i]).val() != "0"){ + num += 1; + } + } + return num; + } + + // 选择题选项的个数 + function choice_num(){ + var answer = document.getElementsByName("choice[answer][]"); + var lens = answer.length; + return lens; + } + window.onload = function(){ $("#challenge_task_pass [type=\"latex\"]").bind("click", function(){ taskpass_editormd.cm.replaceSelection("```latex"); @@ -100,15 +269,41 @@ $("#task_pass_show").show(); $("#task_pass_edit").hide(); }); - function challenge_update(){ + function challenge_update(st){ + set_choice_answer(); + var error = $("#choice_error_tip"); if($('#challenge_subject').val().trim() == ""){ $("#challenge_subject").focus(); $("#new_shixun_name").show(); }else if($("#challenge_task_pass textarea").val().trim() == ""){ $("#challenge_task_pass textarea").focus(); $("#new_shixun_pass").show(); + }else if(judge_choice_contents()){ + error.html("选项不能为空").show(); }else{ - $('#challenge_shixun_update').submit(); + if(st == "2"){ + if(judge_choice_contents()) { + error.html("选项内容不能为空").show(); + }else if(choice_num() < 2){ + error.html("单选题选项不能少于2个").show(); + }else if(judge_choice_answer() == 0){ + error.html("请设置答案").show(); + }else{ + $('#challenge_shixun_update').submit(); + } + }else if(st == "1"){ + if(judge_choice_contents()) { + error.html("选项内容不能为空").show(); + }else if(choice_num() < 3){ + error.html("多选题选项不能少于3个").show(); + }else if(judge_choice_answer() < 2){ + error.html("答案不能少于2个").show(); + }else{ + $('#challenge_shixun_update').submit(); + } + }else{ + $('#challenge_shixun_update').submit(); + } } } diff --git a/app/views/challenges/edit.html.erb b/app/views/challenges/edit.html.erb index a415faf65..46080141c 100644 --- a/app/views/challenges/edit.html.erb +++ b/app/views/challenges/edit.html.erb @@ -17,13 +17,29 @@
    -
    +
    + <% if @st == 0 %> + + + + <% elsif @st == 1 %> + + + + <% elsif @st == 2%> + + + + <% end %>

    阶段详情(第<%= @challenge.position %>关)

    <% unless @next_challenge.blank? %> 下一阶段 <% end %> <% if @shixun.status == 0 && User.current.manager_of_shixun?(@shixun) %> - 新建阶段 + + +实践任务 + +多选任务 + +单选任务 <% end %>
    @@ -31,14 +47,17 @@
  • "> 本关任务
  • - <%# if @challenge.st == 0 %> + <% if @challenge.st == 0 %>
  • "> 评测设置
  • - <%# end %> + <% end %>
  • "> 参考答案
  • +
  • "> + 预备知识 +
  • "> 评分设置
  • @@ -57,6 +76,8 @@ <%= render :partial => "edit_scoring" %> <% elsif @tab == 5 %> <%= render :partial => "edit_skill" %> + <% elsif @tab == 6 %> + <%= render :partial => "edit_propaedeutics" %> <% end %> diff --git a/app/views/challenges/show.html.erb b/app/views/challenges/show.html.erb index 2901d38cc..eee1eeb49 100644 --- a/app/views/challenges/show.html.erb +++ b/app/views/challenges/show.html.erb @@ -25,7 +25,10 @@ 下一阶段 <% end %> <% if @shixun.status == 0 && User.current.manager_of_shixun?(@shixun) %> - 新建阶段 + + +单选任务 + +多选任务 + +实践任务 <% end %>
    diff --git a/app/views/courses/_member_all_student_list.html.erb b/app/views/courses/_member_all_student_list.html.erb index b7286f7b5..d0b32777b 100644 --- a/app/views/courses/_member_all_student_list.html.erb +++ b/app/views/courses/_member_all_student_list.html.erb @@ -27,14 +27,14 @@ <% end %>
    -
    +
    -
    +

    @@ -44,39 +44,44 @@

    -
      -
    • - 序号 - 姓名 - 用户ID - 学号 - 分班 - 操作 -
    • + + + + + + + + + + + + + <% unless @members.blank? %> <% @members.each_with_index do |member, index| %> <% user = member.user %> -
    • - <%= index + 1 + (@page - 1) * 20 %> - <%= link_to user.show_real_name, user_path(user), :target => '_blank' %> - <%= user.login %> - <%= user.user_extensions ? user.user_extensions.student_id : '' %> - <%= member.course_group_id == 0 ? '未分班' : member.course_group.name %> - +
    • + + + + + + + <% end %> <% end %> - + +
      序号姓名用户ID学号分班操作
      <%= index + 1 + (@page - 1) * 20 %><%= link_to user.show_real_name, user_path(user), :class => 'edu-txt-w140 task-hide mt5', :target => '_blank' %><%= user.login %><%= user.user_extensions ? user.user_extensions.student_id : '' %><%= member.course_group_id == 0 ? '未分班' : member.course_group.name %> <% if user == User.current %> - 删除 + 删除 <% else %> -- <% end %> - - +
    -
    +
      <%= pagination_links_full @member_pages, @member_count, :per_page_links => false, :remote => @is_remote, :flag => true, :is_new => true%>
    diff --git a/app/views/courses/_member_group_student_list.html.erb b/app/views/courses/_member_group_student_list.html.erb index 14b0be8ea..d139d5bc6 100644 --- a/app/views/courses/_member_group_student_list.html.erb +++ b/app/views/courses/_member_group_student_list.html.erb @@ -31,14 +31,14 @@ <% end %>
    -
    -