diff --git a/.gitignore b/.gitignore
new file mode 100644
index 000000000..1b56839ee
--- /dev/null
+++ b/.gitignore
@@ -0,0 +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
diff --git a/.idea/bigdate.iml b/.idea/bigdate.iml
new file mode 100644
index 000000000..2cc9fe5eb
--- /dev/null
+++ b/.idea/bigdate.iml
@@ -0,0 +1,288 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Gemfile b/Gemfile
index 8033bf210..2a11f7477 100644
--- a/Gemfile
+++ b/Gemfile
@@ -6,6 +6,7 @@ unless RUBY_PLATFORM =~ /w32/
if RUBY_PLATFORM =~ /darwin/
gem "rmagick", "= 2.15.4" ## osx must be this version
elsif RUBY_PLATFORM =~ /linux/
+ gem 'simple_xlsx_reader'
gem "rmagick", "~> 2.13.1" ## centos yum install ImageMagick-devel
end
gem 'certified'
@@ -14,6 +15,7 @@ unless RUBY_PLATFORM =~ /w32/
gem 'nokogiri'
end
+#gem 'simple_xlsx_reader'
gem 'wechat',path: 'lib/wechat'
gem 'grack', path:'lib/grack'
gem 'gitlab', path: 'lib/gitlab-cli'
@@ -75,7 +77,7 @@ group :development, :test do
gem 'pry-byebug'
gem "test-unit", "~>3.0"
end
- gem 'rspec-rails', '~> 3.0'
+ # gem 'rspec-rails', '~> 3.0'
gem 'factory_girl_rails'
end
diff --git a/app/assets/javascripts/debates.js.coffee b/app/assets/javascripts/debates.js.coffee
new file mode 100644
index 000000000..761567942
--- /dev/null
+++ b/app/assets/javascripts/debates.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/app/assets/javascripts/department.js.coffee b/app/assets/javascripts/department.js.coffee
new file mode 100644
index 000000000..761567942
--- /dev/null
+++ b/app/assets/javascripts/department.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/app/assets/javascripts/discusses.js.coffee b/app/assets/javascripts/discusses.js.coffee
new file mode 100644
index 000000000..761567942
--- /dev/null
+++ b/app/assets/javascripts/discusses.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/app/assets/javascripts/homework_bank.js.coffee b/app/assets/javascripts/homework_bank.js.coffee
new file mode 100644
index 000000000..761567942
--- /dev/null
+++ b/app/assets/javascripts/homework_bank.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/app/assets/javascripts/iframes.js.coffee b/app/assets/javascripts/iframes.js.coffee
new file mode 100644
index 000000000..761567942
--- /dev/null
+++ b/app/assets/javascripts/iframes.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/app/assets/javascripts/kubernete.js.coffee b/app/assets/javascripts/kubernete.js.coffee
new file mode 100644
index 000000000..761567942
--- /dev/null
+++ b/app/assets/javascripts/kubernete.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/app/assets/javascripts/management.js.coffee b/app/assets/javascripts/management.js.coffee
new file mode 100644
index 000000000..761567942
--- /dev/null
+++ b/app/assets/javascripts/management.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/app/assets/javascripts/managements.js.coffee b/app/assets/javascripts/managements.js.coffee
new file mode 100644
index 000000000..761567942
--- /dev/null
+++ b/app/assets/javascripts/managements.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/app/assets/javascripts/stages.js.coffee b/app/assets/javascripts/stages.js.coffee
new file mode 100644
index 000000000..761567942
--- /dev/null
+++ b/app/assets/javascripts/stages.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/app/assets/javascripts/subjects.js.coffee b/app/assets/javascripts/subjects.js.coffee
new file mode 100644
index 000000000..761567942
--- /dev/null
+++ b/app/assets/javascripts/subjects.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/app/assets/stylesheets/debates.css.scss b/app/assets/stylesheets/debates.css.scss
new file mode 100644
index 000000000..6c45b3be9
--- /dev/null
+++ b/app/assets/stylesheets/debates.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the debates controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/assets/stylesheets/department.css.scss b/app/assets/stylesheets/department.css.scss
new file mode 100644
index 000000000..b31882b3b
--- /dev/null
+++ b/app/assets/stylesheets/department.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the Department controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/assets/stylesheets/discusses.css.scss b/app/assets/stylesheets/discusses.css.scss
new file mode 100644
index 000000000..3b4264c09
--- /dev/null
+++ b/app/assets/stylesheets/discusses.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the discusses controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/assets/stylesheets/homework_bank.css.scss b/app/assets/stylesheets/homework_bank.css.scss
new file mode 100644
index 000000000..d8be9e5ef
--- /dev/null
+++ b/app/assets/stylesheets/homework_bank.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the HomeworkBank controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/assets/stylesheets/iframes.css.scss b/app/assets/stylesheets/iframes.css.scss
new file mode 100644
index 000000000..58755a300
--- /dev/null
+++ b/app/assets/stylesheets/iframes.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the iframes controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/assets/stylesheets/kubernete.css.scss b/app/assets/stylesheets/kubernete.css.scss
new file mode 100644
index 000000000..3a633505e
--- /dev/null
+++ b/app/assets/stylesheets/kubernete.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the kubernete controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/assets/stylesheets/management.css.scss b/app/assets/stylesheets/management.css.scss
new file mode 100644
index 000000000..6d4f81abc
--- /dev/null
+++ b/app/assets/stylesheets/management.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the management controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/assets/stylesheets/managements.css.scss b/app/assets/stylesheets/managements.css.scss
new file mode 100644
index 000000000..00a467eed
--- /dev/null
+++ b/app/assets/stylesheets/managements.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the managements controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/assets/stylesheets/stages.css.scss b/app/assets/stylesheets/stages.css.scss
new file mode 100644
index 000000000..3784335fe
--- /dev/null
+++ b/app/assets/stylesheets/stages.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the stages controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/assets/stylesheets/subjects.css.scss b/app/assets/stylesheets/subjects.css.scss
new file mode 100644
index 000000000..454072191
--- /dev/null
+++ b/app/assets/stylesheets/subjects.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the subjects controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/controllers/account_controller.rb b/app/controllers/account_controller.rb
index d7db4c1bb..f2ae14598 100644
--- a/app/controllers/account_controller.rb
+++ b/app/controllers/account_controller.rb
@@ -22,7 +22,13 @@ class AccountController < ApplicationController
# prevents login action to be filtered by check_if_login_required application scope filter
skip_before_filter :check_if_login_required
+ skip_before_filter :check_authentication, :only => [:login, :logout, :user_join, :avatar, :authentication, :professional_certification, :security_settings, :change_psd]
+ before_filter :auth_login1, :only => [:avatar, :authentication, :professional_certification, :security_settings, :change_psd]
+ skip_before_filter :verify_authenticity_token, :only =>[:codepedia_login]
+ before_filter :require_login, only: [:avatar, :authentication, :professional_certification, :security_settings, :change_psd, :user_auth, :apply_auth, :apply_pro_certification, :check_student_id]
+ include ApplicationHelper
# Login request and validation
+
def login
if params[:type] == "activated"
@message = l(:notice_account_activated)
@@ -43,13 +49,25 @@ class AccountController < ApplicationController
redirect_to user_path(User.current)
end
else
- render :layout => 'login_bigdata'
+ render :layout => 'login_bigdata'
end
else
authenticate_user
end
end
+ def codepedia_login
+ logger.info("codepedia_login#########################################")
+ logger.info("#{params}")
+ user, last_login_on = User.try_to_login(params[:username], params[:password])
+ logger.info(user)
+ if user.blank?
+ render :json => { status: 0 }
+ else
+ render :json => { status: 1, user: user}
+ end
+ end
+
def user_join
if params[:type] == "activated"
@message = l(:notice_account_activated)
@@ -79,7 +97,7 @@ class AccountController < ApplicationController
# 服务协议
def agreement
- render :layout => 'static_base'
+ render :layout => 'base_edu'
end
def about_us
@@ -90,8 +108,10 @@ class AccountController < ApplicationController
def logout
if User.current.anonymous?
redirect_to signin_path
- elsif request.post?
+ else
+ UserActions.create(:action_id => User.current.id, :action_type => "Logout", :user_id => User.current.id)
logout_user
+ # 记录用户登出行为
redirect_to signin_path
end
# display the logout form
@@ -169,7 +189,7 @@ class AccountController < ApplicationController
session[:auth_source_registration] = nil
self.logged_user = @user
flash[:notice] = l(:notice_account_activated)
- redirect_to my_account_path(:tip=>1)
+ redirect_to my_account_path(:tip => 1)
end
else
us = UsersService.new
@@ -202,6 +222,11 @@ class AccountController < ApplicationController
account_pending
end
end
+ if params[:user][:mail].nil?
+ reward_grade(@user, @user.id, 'Phone', 500)
+ else
+ reward_grade(@user, @user.id, 'Mail', 500)
+ end
end
end
end
@@ -317,24 +342,25 @@ class AccountController < ApplicationController
req = Hash.new(false)
req[:valid] = false
type = params[:type].to_i
- if type == 1 || type == 2 || params[:phone] =~ /^1\d{10}$/
- code = VerificationCode.where(:phone => params[:phone], :code => params[:code], :code_type => (params[:type].to_i != 1 && params[:type].to_i != 2) ? 2 : params[:type].to_i ).last
+ if type == 1 || type == 2 || type == 4 || params[:phone] =~ /^1\d{10}$/
+ code = VerificationCode.where(:phone => params[:phone], :code => params[:code], :code_type => (params[:type].to_i != 1 && params[:type].to_i != 2 && params[:type].to_i != 4) ? 2 : params[:type].to_i ).last
else
- code = VerificationCode.where(:email => params[:phone], :code => params[:code], :code_type => 3).last
+ code = VerificationCode.where(:email => params[:phone], :code => params[:code], :code_type => params[:type].to_i).last
end
req[:valid] = !code.nil? && (Time.now.to_i - code.created_at.to_i) <= 10*60
render :json => req
end
- # 发送验证码:type 1:注册手机验证码 2:找回密码手机验证码 3:找回密码邮箱验证码
+ # 发送验证码:type 1:注册手机验证码 2:找回密码手机验证码 3:找回密码邮箱验证码 4:绑定手机 5:绑定邮箱
def get_verification_code
code = %W(0 1 2 3 4 5 6 7 8 9)
type = params[:type].to_i
req = Hash.new(false)
req[:status] = 0
+ req[:msg] = ''
if type == 1
if User.where(:phone => params[:value]).count > 0
- req[:status] = 2
+ req[:status] = 2 #已注册
else
begin
verification_code = code.sample(6).join
@@ -347,10 +373,10 @@ class AccountController < ApplicationController
end
req[:status] = 1
end
- else
+ elsif type == 2 || type == 3
if params[:value] =~ /^[a-zA-Z0-9]+([._\\]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
if User.where(:mail => params[:value]).count == 0
- req[:status] = 2
+ req[:status] = 2 #未注册
else
begin
verification_code = code.sample(6).join
@@ -384,11 +410,283 @@ class AccountController < ApplicationController
else
req[:status] = 2
end
+ else
+ if params[:value] =~ /^[a-zA-Z0-9]+([._\\]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
+ if User.where(:mail => params[:value]).count > 0
+ req[:status] = 2 #已绑定
+ req[:msg] = '该邮箱已被绑定'
+ else
+ begin
+ verification_code = code.sample(6).join
+ user = User.current
+ token = Token.new(:user => user, :action => "bind")
+ if token.save
+ Mailer.run.bind_email(token, verification_code, params[:value])
+ VerificationCode.create(:email => params[:value], :status => 1, :code_type => 5, :code => verification_code)
+ end
+ rescue => e
+ Rails.logger.error "发送验证码出错: #{e}"
+ end
+ req[:status] = 3
+ req[:link] = params[:value].split("@")[1]
+ end
+ elsif params[:value] =~ /^1\d{10}$/
+ if User.where(:phone => params[:value]).count > 0
+ req[:status] = 2
+ req[:msg] = '该手机号已被绑定'
+ else
+ begin
+ verification_code = code.sample(6).join
+ status = Trustie::Sms.send(mobile: params[:value], code: verification_code)
+ if status
+ VerificationCode.create(:phone => params[:value], :status => 1, :code_type => 4, :code => verification_code)
+ end
+ rescue => e
+ Rails.logger.error "发送验证码出错: #{e}"
+ end
+ req[:status] = 1
+ end
+ else
+ req[:status] = 2
+ end
end
render :json => req
end
+ def avatar
+ @user = params[:user_id].nil? ? User.current : User.find(params[:user_id])
+ @setting_type = 2
+ render :layout => 'base_edu_account'
+ end
+
+ # 实名认证
+ def authentication
+ @user = User.current
+ @apply_user_auth = ApplyUserAuthentication.where(:user_id => @user.id, :auth_type => 1, :status => [0, 2]).order("created_at asc").last
+ @setting_type = 3
+ render :layout => 'base_edu_account'
+ end
+
+ # 职业认证
+ def professional_certification
+ @user = User.current
+ @apply_user_auth = ApplyUserAuthentication.where(:user_id => @user.id, :auth_type => 2, :status => [0, 2]).order("created_at asc").last
+ @setting_type = 4
+ render :layout => 'base_edu_account'
+ end
+
+ def apply_auth
+ @user = User.current
+ @user.lastname = params[:lastname]
+ @user.firstname = ""
+ @user.ID_number = params[:ID_number]
+ @se = @user.extensions
+ @se.gender = params[:sex]
+
+ if @user.save && @se.save
+ @user.update_attributes(:authentication => 0)
+ diskfile1 = disk_auth_filename('UserAuthentication', @user.id, 'ID')
+ diskfileID = diskfile1 + 'temp'
+ begin
+ FileUtils.mv diskfileID, diskfile1, force: true if File.exist? diskfileID
+ ensure
+ File.delete(diskfileID) if File.exist?(diskfileID)
+ end
+ if File.exist?(diskfile1)
+ ApplyUserAuthentication.create(:user_id => @user.id, :status => 0, :auth_type => 1)
+ end
+ end
+ redirect_to authentication_account_path
+ end
+
+ def apply_pro_certification
+ @user = User.current
+ @se = @user.extensions
+ @se.school_id = params[:occupation]
+ @se.department_id = params[:department_id]
+ @se.identity = params[:identity].to_i if params[:identity]
+ if @se.identity == 0
+ @se.technical_title = params[:te_technical_title] if params[:te_technical_title]
+ @se.student_id = nil
+ elsif @se.identity == 1
+ @se.student_id = params[:no] if params[:no]
+ @se.technical_title = nil
+ elsif @se.identity == 2
+ @se.technical_title = params[:pro_technical_title] if params[:pro_technical_title]
+ @se.student_id = nil
+ end
+ if @user.save && @se.save
+ @user.update_attributes(:professional_certification => 0)
+ if @se.identity == 1
+ ApplyUserAuthentication.create(:user_id => @user.id, :status => 0, :auth_type => 2)
+ else
+ diskfile2 = disk_auth_filename('UserAuthentication', @user.id, 'PRO')
+ diskfilePRO = diskfile2 + 'temp'
+ begin
+ FileUtils.mv diskfilePRO, diskfile2, force: true if File.exist? diskfilePRO
+ ensure
+ File.delete(diskfilePRO) if File.exist?(diskfilePRO)
+ end
+ if File.exist?(diskfile2)
+ ApplyUserAuthentication.create(:user_id => @user.id, :status => 0, :auth_type => 2)
+ end
+ end
+ end
+ redirect_to professional_certification_account_path
+ end
+
+ # 修改资料时判断学号是否已使用
+ def check_user_student_id
+ data = {result:0, account:""}
+ if params[:student_id] && params[:school_id]
+ if UserExtensions.where("student_id = '#{params[:student_id]}' and school_id = #{params[:school_id]} and user_id != #{User.current.id}").count > 0
+ user = User.where(:id => UserExtensions.where("student_id = '#{params[:student_id]}' and school_id = #{params[:school_id]} and user_id != #{User.current.id}").map(&:user_id)).first
+ data[:account] = user.mail.blank? ? user.user_phone : user.user_mail
+ else
+ data[:result] = 1
+ end
+ end
+ render :json => data
+ end
+
+ # 实名认证时判断学号是否已使用
+ def check_student_id
+ data = {result:0, account:""}
+ if params[:student_id] && params[:school_id]
+ auth_count = User.where(:id => UserExtensions.where(:student_id => params[:student_id], :school_id => params[:school_id]).map(&:user_id), :professional_certification => 1).count
+ apply_count = ApplyUserAuthentication.where(:status => 0, :user_id => User.where(:id => UserExtensions.where(:student_id => params[:student_id], :school_id => params[:school_id]).map(&:user_id), :professional_certification => 0).map(&:id)).count
+ if auth_count == 0 && apply_count == 0
+ data[:result] = 1
+ else
+ user = auth_count != 0 ? User.where(:id => UserExtensions.where(:student_id => params[:student_id], :school_id => params[:school_id]).map(&:user_id)).first : ApplyUserAuthentication.where(:status => 0, :user_id => User.where(:id => UserExtensions.where(:student_id => params[:student_id], :school_id => params[:school_id]).map(&:user_id), :professional_certification => 0).map(&:id)).first.user
+ if user != User.current
+ data[:account] = user.mail.blank? ? user.user_phone : user.user_mail
+ else
+ data[:result] = 1
+ end
+ end
+ end
+ render :json => data
+ end
+
+ # 实名认证时判断证件号码是否已使用
+ def check_id_number
+ data = {result:0, account:""}
+ if params[:id_number]
+ auth_count = User.where(:ID_number => params[:id_number], :authentication => 1).count
+ apply_count = ApplyUserAuthentication.where(:status => 0, :user_id => User.where(:ID_number => params[:id_number], :authentication => 0).map(&:id)).count
+ if auth_count == 0 && apply_count == 0
+ data[:result] = 1
+ else
+ user = auth_count != 0 ? User.where(:ID_number => params[:id_number], :authentication => 1).first : ApplyUserAuthentication.where(:status => 0, :user_id => User.where(:ID_number => params[:id_number], :authentication => 0).map(&:id)).first.user
+ if user != User.current
+ data[:account] = user.mail.blank? ? user.user_phone : user.user_mail
+ else
+ data[:result] = 1
+ end
+ end
+ end
+ render :json => data
+ end
+
+ def cancel_pro_apply
+ @apply_user_auth = ApplyUserAuthentication.where(:user_id => User.current.id, :auth_type => params[:auth_type], :status => 0).update_all(:status => 3)
+
+ if params[:auth_type] == "1"
+ redirect_to authentication_account_path
+ else
+ redirect_to professional_certification_account_path
+ end
+ end
+
+ def apply_trail
+ apply_action = ApplyAction.where(:user_id => User.current.id, :container_type => "TrialAuthorization", :status => 0).first
+ school_ids = School.where(:auto_users_trial => 1).map(&:id)
+ if User.current.user_extensions.identity == 1 && !User.current.user_extensions.student_id.nil? && User.current.user_extensions.student_id != "" && !User.current.user_extensions.school.nil? && school_ids.include?(User.current.user_extensions.school_id)
+ User.current.update_attributes(:certification => 1)
+ @tip = "申请成功,我们将在一分钟内完成审核"
+ if apply_action.blank?
+ ApplyAction.create(:user_id => User.current.id, :status => 1, :container_type => "TrialAuthorization", :apply_reason => params[:apply_reason])
+ else
+ apply_action.update_attributes(:status => 1)
+ end
+ else
+ @tip = "申请成功,我们将在一个工作日内完成审核"
+ ApplyAction.create(:user_id => User.current.id, :status => 0, :container_type => "TrialAuthorization", :apply_reason => params[:apply_reason])
+ end
+
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def user_auth
+ @user = User.current
+ diskfile1 = disk_auth_filename('UserAuthentication', @user.id, 'ID')
+ diskfile2 = disk_auth_filename('UserAuthentication', @user.id, 'PRO')
+ diskfileID = diskfile1 + 'temp'
+ diskfilePRO = diskfile2 + 'temp'
+ begin
+ FileUtils.mv diskfileID, diskfile1, force: true if File.exist? diskfileID
+ FileUtils.mv diskfilePRO, diskfile2, force: true if File.exist? diskfilePRO
+ ensure
+ File.delete(diskfileID) if File.exist?(diskfileID)
+ File.delete(diskfilePRO) if File.exist?(diskfilePRO)
+ end
+ if File.exist?(diskfile1) && File.exist?(diskfile2)
+ ApplyUserAuthentication.create(:user_id => @user.id, :status => 0)
+ end
+
+ redirect_to authentication_account_path
+ end
+
+ def security_settings
+ @user = User.current
+ @setting_type = 5
+ render :layout => 'base_edu_account'
+ end
+
+ def change_psd
+ @user = User.current
+ @setting_type = 6
+ render :layout => 'base_edu_account'
+ end
+
+ # 修改密码时判断密码是否输入正确
+ def valid_psd
+ @user = User.current
+ req = Hash.new(false)
+ req[:valid] = false
+ req[:valid] = @user.check_password?(params[:value])
+ render :json => req
+ end
+
+ def change_or_bind
+ @user = User.current
+ @type = params[:type]
+ @setting_type = 5
+ render :layout => 'base_edu_account'
+ end
+
+ def bind_email_or_phone
+ @user = User.current
+ begin
+ ActiveRecord::Base.transaction do
+ if params[:type] == "phone"
+ @user.update_attributes!(:phone => params[:value])
+ reward_grade(@user, @user.id, 'Phone', 500)
+ else
+ @user.update_attributes!(:mail => params[:value])
+ reward_grade(@user, @user.id, 'Mail', 500)
+ end
+ end
+ rescue
+ raise ActiveRecord::Rollback
+ end
+ redirect_to security_settings_path
+ end
+
def wechat_bind
respond_to do |format|
format.html { render :layout => "login_bigdata"}
@@ -547,6 +845,8 @@ class AccountController < ApplicationController
call_hook(:controller_account_success_authentication_after, {:user => user })
code = /\d*/
+ # 记录用户登录行为
+ UserActions.create(:action_id => User.current.id, :action_type => "Login", :user_id => User.current.id)
#根据home_url生产正则表达式
eval("code = " + "/^" + home_url.gsub(/\//,"\\\/") + "\\\/*(welcome)?\\\/*(\\\/index\\\/*.*)?\$/")
if (code=~params[:back_url] || params[:back_url].to_s.include?('lost_password')) && last_login_on != ''
diff --git a/app/controllers/admin_controller.rb b/app/controllers/admin_controller.rb
index 001195bba..a3d1a387e 100644
--- a/app/controllers/admin_controller.rb
+++ b/app/controllers/admin_controller.rb
@@ -1,1051 +1,1173 @@
-
-# Redmine - project management software
-# Copyright (C) 2006-2013 Jean-Philippe Lang
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-
-class AdminController < ApplicationController
- layout 'admin'
- menu_item :projects, :only => :projects
- menu_item :plugins, :only => :plugins
- menu_item :info, :only => :info
-
- before_filter :require_admin
- helper :sort
- helper :Users
- helper :Settings,SchoolHelper
- include SortHelper
-
- def index
- @no_configuration_data = Redmine::DefaultData::Loader::no_data?
- end
-
- def export_rep_static_users
- rev = params[:rev]
- cycle = params[:cycle]
- cycle_name = (params[:cycle] == "admin_week" ? l(:label_per_week) : (params[:cycle] == "admin_month" ? l(:label_per_month) : l(:label_per_all)))
- respond_to do |format|
- format.html
- format.xls{
- filename = "#{l(:label_user_rep_xls)}_#{cycle_name}.xls"
- send_data(admin_export_rep_xls(:rev => rev, :cycle => "1"), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
- }
- end
- end
-
- # 管理员界面导出所有项目代码、提交次数统计
- def admin_export_rep_xls (options = {})
- cycle = params[:cycle]
- g = Gitlab.client
- users_results = []
- User.all.each do |user|
- unless user.mail.nil?
- user_mail = user.mail
- user.projects.where("gpid is not null").each do |project|
- begin
- g.branches(project.gpid).each do |branch|
- if cycle == "admin_week"
- statics = g.admin_rep_stats_week(project.gpid, :rev => branch.name, :user_mail => user_mail)
- elsif cycle == "admin_month"
- statics = g.admin_rep_stats_month(project.gpid, :rev => branch.name, :user_mail => user_mail)
- elsif cycle == "admin_all"
- statics = g.admin_rep_stats_all(project.gpid, :rev => branch.name, :user_mail => user_mail)
- end
- unless statics.first.commits_num == "0"
- user_details = {:user_id => user.id, :user_name => user.show_name, :project_id => project.id, :project_name => project.name,
- :commits_num => statics.first.commits_num, :add => statics.first.add, :del => statics.first.del, :changes => statics.first.changes, :branch => branch.name}
- users_results << user_details
- end
- end
- rescue Exception => e
- puts e
- end
- end
- end
- end
-
- xls_report = StringIO.new
- book = Spreadsheet::Workbook.new
- sheet1 = book.create_worksheet :name => l(:project_module_repository)
- blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
- sheet1.row(0).default_format = blue
- sheet1.row(0).concat([l(:label_rep_user_id),l(:label_rep_user_name),l(:label_rep_project_id),l(:label_rep_project_name),l(:rep_branch),l(:rep_changeset),l(:rep_code_add),l(:rep_code_delete),l(:rep_code_modified),l(:rep_sode_time)])
- count_row = 1
- users_results.each do |static|
- sheet1[count_row,0] = static[:user_id]
- sheet1[count_row,1] = static[:user_name]
- sheet1[count_row,2] = static[:project_id]
- sheet1[count_row,3] = static[:project_name]
- sheet1[count_row,4] = static[:branch]
- sheet1[count_row,5] = static[:commits_num]
- sheet1[count_row,6] = static[:add]
- sheet1[count_row,7] = static[:del]
- sheet1[count_row,8] = static[:changes]
- sheet1[count_row,9] = Time.now.strftime('%Y-%m-%d %H:%M:%S')
- count_row += 1
- end
- book.write xls_report
- xls_report.string
- end
-
- # 管理员界面 项目列表
- def projects
-=begin
- @status = params[:status] || 1
-
- scope = Project.status(@status)
- scope = scope.like(params[:name]) if params[:name].present?
- @projects = scope.where(project_type: Project::ProjectType_project).reorder("created_on desc").all
-=end
- # 搜索功能
- @name = params[:name] || ""
- condition = "#{@name.strip}".gsub(" ","")
- @status = params[:status] || ""
- unless @status.empty?
- @projects = Project.where(:status=>@status).like(condition).order('created_on desc')
- else
- @projects = Project.like(condition).order('created_on desc')
- end
- # 分页
- @projects = paginateHelper @projects,30
- @page = (params['page'] || 1).to_i - 1
- render :action => "projects", :layout => false if request.xhr?
- end
-
- def contests
- @name = params[:name]
- @contests = Contest.where("id >= 780 and name like '%#{@name}%'").order('created_at desc')
- @contests = paginateHelper @contests,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- def syllabuses
- @name = params[:name]
- @syllabuses = Syllabus.like(@name).order('created_at desc')
- @syllabuses = paginateHelper @syllabuses,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #为班级选择课程
- def select_course_syllabus
- @flag = false
- if params[:syllabus_id] && params[:course_id]
- course = Course.where("id = #{params[:course_id].to_i}").first
- unless course.nil?
- course.update_attribute(:syllabus_id, params[:syllabus_id].to_i)
- @flag = true
- end
- end
- if @flag
- render :text=> "succ"
- else
- render :text=>'fail'
- end
- end
-
- #新建课程
- def create_syllabus
- if params[:course_id]
- course = Course.where("id = #{params[:course_id]}").first
- if course
- @user = course.teacher
- syllabus = Syllabus.new
- syllabus.update_attributes(:title => params[:title], :eng_name => params[:eng_name], :user_id => @user.id)
- syllabus.description = Message.where("id = 19412").first.nil? ? nil : Message.where("id = 19412").first.content
- if syllabus.save
- course.update_attribute(:syllabus_id, params[:syllabus_id].to_i)
- @flag = params[:flag].to_i
- @course = course
- respond_to do |format|
- format.js
- end
- end
- end
- end
- end
-
- def courses
- @name = params[:name].to_s.strip.downcase
- if @name && @name != ""
- all_user_ids = Course.all.map{|course| course.tea_id}
- user_str_ids = search_user_by_name all_user_ids, @name
- user_ids = user_str_ids.empty? ? "(-1)" : "(" + user_str_ids.join(",") + ")"
- @courses = Course.where("tea_id in #{user_ids} or name like '%#{@name}%'").reorder("created_at desc")
- else
- @courses = Course.order('created_at desc')
- end
- @courses = paginateHelper @courses,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #未配置班级列表
- def non_syllabus_courses
- @name = params[:name].to_s.strip.downcase
- if @name && @name != ""
- @courses = Course.where("syllabus_id is null and is_delete = 0").select{ |course| (course.teacher[:lastname].to_s.downcase + course.teacher[:firstname].to_s.downcase).include?(@name) || course.name.include?(@name)}
- @courses = @courses.sort{|x, y| y.created_at <=> x.created_at}
- else
- @courses = Course.where("syllabus_id is null and is_delete = 0").order('created_at desc')
- end
- @courses = paginateHelper @courses,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #修改班级名称
- def update_course_name
- @course = Course.where("id = #{params[:course_id].to_i}").first
- unless @course.nil?
- @course.update_column("name", params[:name])
- respond_to do |format|
- format.js
- end
- end
- end
-
- #修改课程名称
- def update_syllabus_title
- @syllabus = Syllabus.where("id = #{params[:syllabus_id].to_i}").first
- unless @syllabus.nil?
- @syllabus.update_column("title", params[:name])
- respond_to do |format|
- format.js
- end
- end
- end
-
- #管理员界面精品课程列表
- def excellent_courses
- @courses = Course.where("is_excellent =? or excellent_option =?", 1, 1 )
- respond_to do |format|
- format.html
- end
- end
-
- # 单位名称列表下的已审批按照名字排序
- def apply_shcool_sort
- @order = ""
- @sort = ""
- if params[:sort] && (params[:order] == 'name')
- # courses = School.find_by_sql("SELECT c.*,count(c.id) FROM courses c,course_activities ca WHERE c.id = ca.course_id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY count(c.id) #{params[:sort]}, c.id desc")
- school = School.find_by_sql(" SELECT aas.name FROM apply_add_schools aas where aas.status = '0' ORDER BY CONVERT(aas.name USING gbk) #{params[:sort]}, aas.id asc ")
- @order = params[:order]
- @sort = params[:sort]
- end
- redirect_to unapplied_schools_url
- end
-
- #精品课程下的全部课程
- def excellent_all_courses
- name = params[:name]
- @order = ""
- @sort = ""
- if params[:sort] && (params[:order] == 'act')
- courses = Course.find_by_sql("SELECT c.*,count(c.id) FROM courses c,course_activities ca WHERE c.id = ca.course_id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY count(c.id) #{params[:sort]}, c.id desc")
- @order = params[:order]
- @sort = params[:sort]
-
- elsif params[:sort] && (params[:order] == 'time')
- courses = Course.find_by_sql("SELECT * FROM courses WHERE name like '%#{name}%' ORDER BY time #{params[:sort]}, id desc")
- @order = params[:order]
- @sort = params[:sort]
-
- elsif params[:sort] && (params[:order] == 'post')
- courses = Course.find_by_sql("SELECT c.*, count(m.id) count FROM boards b, courses c, messages m WHERE m.board_id = b.id AND b.course_id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY count #{params[:sort]}, c.id desc")
- @order = params[:order]
- @sort = params[:sort]
-
- elsif params[:sort] && (params[:order] == 'res')
- courses = Course.find_by_sql("SELECT c.*, count(at.container_id) cat FROM attachments at, courses c WHERE at.container_type = 'Course' AND at.container_id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY cat #{params[:sort]}, id desc")
- @order = params[:order]
- @sort = params[:sort]
-
- elsif params[:sort] && (params[:order] == 'works')
- courses = Course.find_by_sql("SELECT c.*, count(hc.id) chc FROM courses c, homework_commons hc,student_works sw WHERE c.id = hc.course_id AND sw.homework_common_id = hc.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY chc #{params[:sort]}, id desc")
- @order = params[:order]
- @sort = params[:sort]
-
- elsif params[:sort] && (params[:order] == 'homework')
- courses = Course.find_by_sql("SELECT c.*, count(sw.id) csw FROM student_works sw, courses c, homework_commons hc WHERE c.id = hc.course_id AND sw.id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY csw #{params[:sort]}, id desc")
- @order = params[:order]
- @sort = params[:sort]
-
- elsif params[:sort] && (params[:order] == 'std')
- courses = Course.find_by_sql("SELECT c.*, count(sfc.id) sfc FROM courses c, students_for_courses sfc WHERE sfc.course_id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY sfc #{params[:sort]}, id desc")
- @order = params[:order]
- @sort = params[:sort]
-
- elsif params[:sort] && (params[:order] == 'open')
- courses = Course.find_by_sql("SELECT * FROM courses WHERE name like '%#{name}%' ORDER BY is_public #{params[:sort]},id desc")
- @order = params[:order]
- @sort = params[:sort]
-
- else
- courses = Course.like(name).order('created_at desc')
- end
- @courses = paginateHelper courses,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #设为精品
- def set_excellent_course
- @course = Course.find params[:id]
- unless @course.nil?
- if @course.is_excellent == 1 || @course.excellent_option == 1
- @course.update_column('is_excellent', 0)
- @course.update_column('excellent_option', 0)
- else
- @course.update_column('is_excellent', 1)
- end
- respond_to do |format|
- format.js
- end
- end
- end
-
- #取消精品
- def cancel_excellent_course
- @course = Course.find params[:id]
- unless @course.nil?
- if @course.is_excellent == 1 || @course.excellent_option == 1
- @course.update_column('is_excellent', 0)
- @course.update_column('excellent_option', 0)
- end
- end
- respond_to do |format|
- format.html{
- redirect_to excellent_courses_url
- }
- end
- end
-
- #管理员界面课程资源列表
- def course_resource_list
-
- if params[:sort] == 'file_size'
- @resource = Attachment.where(:container_type => 'Course').order("filesize desc")
- elsif params[:sort] == 'file_upload'
- @resource = Attachment.where(:container_type => 'Course').order("created_on desc")
- elsif params[:sort] == 'file_download_times'
- @resource = Attachment.where(:container_type => 'Course').order("downloads desc")
- else
- @resource = Attachment.where(:container_type => 'Course').order("created_on desc")
- end
-
- @resource = paginateHelper @resource,30
- @page = (params['page'] || 1).to_i - 1
-
- respond_to do |format|
- format.html
- end
- end
-
- #管理员界面項目资源列表
- def project_resource_list
-
- if params[:sort] == 'file_size'
- @pro_resource = Attachment.where(:container_type => 'Project').order("filesize desc")
- elsif params[:sort] == 'file_upload'
- @pro_resource = Attachment.where(:container_type => 'Project').order("created_on desc")
- elsif params[:sort] == 'file_download_times'
- @pro_resource = Attachment.where(:container_type => 'Project').order("downloads desc")
- else
- @pro_resource = Attachment.where(:container_type => 'Project').order("created_on desc")
- end
-
- @pro_resource = paginateHelper @pro_resource,30
- @page = (params['page'] || 1).to_i - 1
-
- respond_to do |format|
- format.html
- end
- end
-
-
- def users
- sort_init 'login', 'asc'
- sort_update %w(login firstname lastname mail admin created_on last_login_on)
-
- case params[:format]
- when 'xml', 'json'
- @offset, @limit = api_offset_and_limit({:limit => 50})
- else
- @limit = 50 #per_page_option
- end
-
- @status = params[:status] || 1
- scope = User.logged.status(@status)
- scope = User.like(params[:name]) if params[:name].present?
- scope = scope.in_group(params[:group_id]) if params[:group_id].present?
-
- @user_count = scope.count
- @user_pages = Paginator.new @user_count, @limit, params['page']
- @offset ||= @user_pages.offset
- @users = scope.order(sort_clause).limit(@limit).offset(@offset).all
-
-
- respond_to do |format|
- format.html {
- @groups = Group.all.sort
- }
- format.api
- end
- end
-
- # 系统消息
- def messages
- @admin_messages = SystemMessage.new
- end
-
- def plugins
- @plugins = Redmine::Plugin.all
- end
-
- # Loads the default configuration
- # (roles, trackers, statuses, workflow, enumerations)
- def default_configuration
- if request.post?
- begin
- Redmine::DefaultData::Loader::load(params[:lang])
- flash[:notice] = l(:notice_default_data_loaded)
- rescue Exception => e
- flash[:error] = l(:error_can_t_load_default_data, e.message)
- end
- end
- redirect_to admin_url
- end
-
- def test_email
- raise_delivery_errors = ActionMailer::Base.raise_delivery_errors
- # Force ActionMailer to raise delivery errors so we can catch it
- ActionMailer::Base.raise_delivery_errors = true
- begin
- @test = Mailer.test_email(User.current).deliver
- flash[:notice] = l(:notice_email_sent, User.current.mail)
- rescue Exception => e
- flash[:error] = l(:notice_email_error, e.message)
- end
- ActionMailer::Base.raise_delivery_errors = raise_delivery_errors
- redirect_to settings_url(:tab => 'notifications')
- end
-
- def info
- @db_adapter_name = ActiveRecord::Base.connection.adapter_name
- @checklist = [
- [:text_default_administrator_account_changed, User.default_admin_account_changed?],
- [:text_file_repository_writable, File.writable?(Attachment.storage_path)],
- [:text_plugin_assets_writable, File.writable?(Redmine::Plugin.public_directory)],
- [:text_rmagick_available, Object.const_defined?(:Magick)]
- ]
- end
- #管理功能用户列表的搜索
- def search
- sort_init 'login', 'asc'
- sort_update %w(login firstname lastname mail admin created_on last_login_on)
-
- case params[:format]
- when 'xml', 'json'
- @offset, @limit = api_offset_and_limit({:limit => 15})
- else
- @limit = 15#per_page_option
- end
- @status = params[:status] || 1
- scope = User.logged.status(@status)
- scope = scope.like(params[:name],params[:search_by][:id]) if params[:name].present?
- @user_count = scope.count
- @user_pages = Paginator.new @user_count, @limit, params['page']
- @user_base_tag = params[:id] ? 'base_users':'base'
-
- @users = scope.order(sort_clause).offset(@user_pages.offset).limit(@user_pages.per_page).all
- respond_to do |format|
- format.html {
- @groups = Group.all.sort
- }
- format.api
- end
- end
-
- #首页定制
- def first_page_made
- if request.get?
- @first_page = FirstPage.find_by_page_type('project')
- elsif request.post?
- @first_page = FirstPage.find_by_page_type('project')
- @first_page.web_title = params[:web_title]
- @first_page.description = params[:first_page][:description]
- #@first_page.title = params[:title]
- @first_page.image_width = params[:image_width]
- @first_page.image_height = params[:image_height]
- @first_page.sort_type = params[:sort_type]
- @first_page.show_course = params[:show_course]
- @first_page.show_contest = params[:show_contest]
- if @first_page.save
- respond_to do |format|
- flash[:notice] = l(:notice_successful_update)
- format.html {
- redirect_to first_page_made_url
- }
- format.api { render_api_ok }
- #format.json { render json: @first_page, status: :created, location: @first_page }
- end
- else
- respond_to do |format|
- flash.now[:error] = "#{l :label_first_page_create_fail}: #{@first_page.errors.full_messages[0]}"
- format.html {
- render :action => 'first_page_made'
- }
- format.api { render_validation_errors(@first_page) }
- #format.json { render json: @first_page.errors, status: :unprocessable_entity }
- end
- end
- end
- end
-
- def course_page_made
- if request.get?
- @course_page = FirstPage.find_by_page_type('course')
- @first_page = FirstPage.find_by_page_type('project')
- elsif request.post?
- @first_page = FirstPage.find_by_page_type('project')
- @course_page = FirstPage.find_by_page_type('course')
- @first_page.web_title = params[:web_title]
- @course_page.web_title = params[:web_title]
- @course_page.title = params[:course_title]
- @course_page.image_width = params[:image_width]
- @course_page.image_height = params[:image_height]
- @course_page.description = params[:course_description]
- if @first_page.save && @course_page.save
- respond_to do |format|
- format.html {
- flash[:notice] = l(:notice_successful_update)
- redirect_to course_page_made_url
- }
- format.api { render_api_ok }
- end
- else
- respond_to do |format|
- flash.now[:error] = "#{l :label_first_page_create_fail}: #{@first_page.errors.full_messages[0]}\n\t#{@course_page.errors.full_messages[0]}"
- #flash.now[:error] = "#{l :label_first_page_create_fail}: #{@course_page.errors.full_messages[0]}"
- format.html {
-
- render :action => 'course_page_made'
- }
- format.api { render_validation_errors(@first_page) }
- format.api { render_validation_errors(@course_page) }
- end
- end
- end
- end
-
- def contest_page_made
- if request.get?
- @contest_page = FirstPage.find_by_page_type('contest')
- @first_page = FirstPage.find_by_page_type('project')
- elsif request.post?
- @first_page = FirstPage.find_by_page_type('project')
- @contest_page = FirstPage.find_by_page_type('contest')
- @first_page.web_title = params[:web_title]
- @contest_page.web_title = params[:web_title]
- @contest_page.title = params[:contest_title]
- @contest_page.image_width = params[:image_width]
- @contest_page.image_height = params[:image_height]
- @contest_page.description = params[:contest_description]
-
- if @first_page.save && @contest_page.save
- respond_to do |format|
- format.html {
- flash[:notice] = l(:notice_successful_update)
- redirect_to contest_page_made_url
- }
- format.api { render_api_ok }
- end
- else
- respond_to do |format|
- flash.now[:error] = "#{l :label_first_page_create_fail}: #{@first_page.errors.full_messages[0]}\n\t#{@contest_page.errors.full_messages[0]}\n\t#{@notification.errors.full_messages[0]}"
- format.html {
- render :action => 'contest_page_made'
- }
- format.api { render_validation_errors(@first_page) }
- format.api { render_validation_errors(@contest_page) }
- end
- end
- end
- end
-
- def web_footer_made
- if request.get?
- @organizer = WebFooterOranizer.first
- @first_page = FirstPage.find_by_page_type('project')
- #@notification = ContestNotification.all.first;
- elsif request.post?
- @first_page = FirstPage.find_by_page_type('project')
- @first_page.web_title = params[:web_title]
- @organizer = WebFooterOranizer.first
- if @organizer.nil?
- @organizer = WebFooterOranizer.new
- end
- @organizer.name = params[:organizer_name]
- @organizer.description = params[:web_footer_oranizer][:description]
- if @first_page.save && @organizer.save
- respond_to do |format|
- format.html {
- flash[:notice] = l(:notice_successful_update)
- redirect_to web_footer_made_url
- }
- format.api { render_api_ok }
- end
- else
- respond_to do |format|
- flash.now[:error] = "#{l :label_first_page_create_fail}: #{@first_page.errors.full_messages[0]}\n\t#{@organizer.errors.full_messages[0]}}"
- format.html {
- render :action => 'web_footer_made'
- }
- format.api { render_validation_errors(@first_page) }
- format.api { render_validation_errors(@contest_page) }
- end
- end
- end
- end
-
- #企业主页定制
- def enterprise_page_made
- @enterprise_page = FirstPage.find_by_page_type('enterprise')
- if @enterprise_page.nil?
- @enterprise_page = FirstPage.new
- @enterprise_page.page_type = 'enterprise'
- end
- if request.get?
- @first_page = FirstPage.find_by_page_type('project')
- elsif request.post?
- @first_page = FirstPage.find_by_page_type('project')
- @first_page.web_title = params[:web_title]
- @enterprise_page.web_title = params[:web_title]
- @enterprise_page.title = params[:course_title]
- @enterprise_page.image_width = params[:image_width]
- @enterprise_page.image_height = params[:image_height]
- @enterprise_page.description = params[:course_description]
- if @first_page.save && @enterprise_page.save
- respond_to do |format|
- format.html {
- flash[:notice] = l(:notice_successful_update)
- redirect_to enterprise_page_made_url
- }
- format.api { render_api_ok }
- end
- else
- respond_to do |format|
- flash.now[:error] = "#{l :label_first_page_create_fail}: #{@first_page.errors.full_messages[0]}\n\t#{@enterprise_page.errors.full_messages[0]}"
- #flash.now[:error] = "#{l :label_first_page_create_fail}: #{@course_page.errors.full_messages[0]}"
- format.html {
- render :action => 'enterprise_page_made'
- }
- format.api { render_validation_errors(@first_page) }
- format.api { render_validation_errors(@enterprise_page) }
- end
- end
- end
- end
-
- #组织
- def organization
- @organizations = Organization.find_by_sql("SELECT * FROM organizations ORDER BY created_at DESC")
- #@organizations = Organization.all.order("created_at desc")
- @organization_count = @organizations.count
- @organization_pages = Paginator.new @organization_count, 30, params['page'] || 1
- @organizations = paginateHelper @organizations,30
-
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #学校列表
- def schools
- @order = ""
- @sort = ""
- @schools = School.find_by_sql("SELECT * FROM schools ORDER BY created_at DESC")
- if params[:sort] && (params[:order] == 'num')
- @order = params[:order]
- @sort = params[:sort]
- @schools.each do |school|
- count = UserExtensions.where("school_id = #{school.id} or occupation = '#{school.name}'").count
- school[:infocount] = count.to_i
- end
- @sort == 'asc' ? (@schools = @schools.sort{|x,y| x[:infocount] <=> y[:infocount] }) : (@schools = @schools.sort{|x,y| y[:infocount] <=> x[:infocount]})
- end
-
- @school_count = @schools.count
-
- @school_pages = Paginator.new @school_count, 30, params['page'] || 1
- @schools = paginateHelper @schools,30
-
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- # 单位审核
- # 未审批tab页
- # status: 0 未审批; 1 已批阅; 2已更改; 3拒绝;
- def applied_schools
- # 更新消息状态
- if params[:flag]
- applied_message = AppliedMessage.where(:id => params[:applied_message_id]).first
- applied_message.update_attribute(:viewed, true)
- end
-
- @name = params[:name] || ""
- condition = "#{@name.strip}".gsub(" ","")
- @apply_status = ApplyAddSchools.where("status = 0 and name like '%#{condition}%'").order('created_at desc')
- @apply_count = @apply_status.count
- @apply_pages = Paginator.new @apply_count, 30, params['page'] || 1
- @apply_status = paginateHelper @apply_status, 30
- @page = (params['page'] || 1).to_i - 1
-
- respond_to do |format|
- format.html
- end
- end
-
- # 单位审核
- # 已审批tab页
- def has_applied_schools
- @name = params[:name] || ""
- condition = "#{@name.strip}".gsub(" ","")
-
- @has_apply_status = ApplyAddSchools.where("(status = 1 or status = 2) and name like '%#{condition}%'").order('created_at desc')
- @has_apply_count = @has_apply_status.count
- @has_apply_pages = Paginator.new @has_apply_count, 30, params['page'] || 1
- @has_apply_status = paginateHelper @has_apply_status, 30
- @page = (params['page'] || 1).to_i - 1
-
- respond_to do |format|
- format.html
- end
- end
-
- # 单位审核:批准
- # 消息发送,发送对象为申请人
- # status: 0表示未批准; status:1表示已批准; status: 2表示已更改; status: 3表示已拒绝; status: 4表示已更改后废除的高校
- def approve_applied_schools
- applied_school = ApplyAddSchools.find params[:id]
- applied_message_id = applied_school.school_id
- applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
- applied_message.update_all(:status => 1)
- applied_school.update_column('status', 1) unless applied_school.nil?
- school = applied_school.school
- school.update_attribute("province", applied_school.province)
- AppliedMessage.create(:user_id => applied_school.user_id, :status => 1, :viewed => 0, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
- # School.create(:user_id => applied_school.user_id, :status => 1, :viewed => true, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
- respond_to do |format|
- format.html{ redirect_to unapplied_schools_url }
- end
- end
-
- # 单位审核:更改
- # 修改该字段
- # 同步修改使用了改名称的用户单位
- def edit_applied_schools
- aas = ApplyAddSchools.find(params[:applied_id])
- # aas.update_attribute(:name, params[:name])
- #applied_add_school = ApplyAddSchools.where(:name => aas.name)
- school = School.find params[:school_id]
- begin
- #更新消息表的status
- applied_message_id = aas.school_id
- applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
- applied_message.update_all(:status => 4)
- aas.update_attribute(:status, 2)
- AppliedMessage.create(:user_id => aas.user_id, :status => 2, :viewed => 0, :applied_id => aas.id, :applied_type => "ApplyAddSchools", :name => school[0].name )
- users = UserExtensions.where("school_id = #{aas.school_id}")
- users.update_all(:school_id => school[0].id)
- if aas.school_id != school[0].id.to_i
- aas.school.destroy
- end
- aas.update_attribute(:school_id, school[0].id)
- rescue Exception => e
- puts e
- end
- # applied_schools = ApplyAddSchools.find params[:applied_id]
- # applied_schools.update_column('name', params[:name])
- redirect_to unapplied_schools_url
- end
-
- # 单位审核:更改功能搜索合法学校弹框
- def all_schools
- apply_schools = ApplyAddSchools.where("status = 0")
- apply_school_ids = apply_schools.empty? ? "(-1)" : "(" + apply_schools.map{|sc| sc.school_id}.join(',') + ")"
- if !params[:search].nil?
- search = "%#{params[:search].to_s.strip.downcase}%"
- @schools = School.where("id not in #{apply_school_ids} and #{School.table_name}.name like :p", :p => search)
- #@schools = School.all
- else
- #@course = @user.courses.where("is_delete = 0 and #{Course.table_name}.id != #{homework.course_id}").select { |course| @user.allowed_to?(:as_teacher,course)}
- @schools = School.where("id not in #{apply_school_ids}")
- end
- @edit_id = params[:school_id]
- @search = params[:search]
- respond_to do |format|
- format.js
- end
- end
-
- # 单位审核:删除
- def delete_applied_schools
- applied_school = ApplyAddSchools.find(params[:id])
- applied_message_id = applied_school.school_id
- applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
- applied_message.update_all(:status => 3)
- applied_school.update_attribute(:status, 3)
- # 未审批删除
- if params[:tip] == "unapplied"
- AppliedMessage.create(:user_id => applied_school.user_id, :status => 3, :viewed => 0, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
- # 删除学校的用户
- users = UserExtensions.where("school_id = #{applied_school.school_id}")
- users.update_all(:school_id => nil)
- applied_school.school.destroy
- redirect_to unapplied_schools_url
- # 已审批删除
- elsif params[:tip] == "applied"
- applied_school.destroy
- redirect_to applied_schools_url
- end
- end
-
- #移动端版本管理
- def mobile_version
- @versions = PhoneAppVersion.reorder('created_at desc')
- @new_version = PhoneAppVersion.new
-
- end
-
- def create_version
- @versions = PhoneAppVersion.reorder('created_at desc')
- @new_version = PhoneAppVersion.new
- @new_version.version = params[:version]
- @new_version.description = params[:description]
- if params[:attachments][:dummy][:file].nil? || params[:attachments][:dummy][:file] == ""
- respond_to do |format|
- flash.now[:error] = "#{l :label_version_create_fail}: #{l(:label_client_need)}"
- #flash.now[:error] = "#{l :label_first_page_create_fail}: #{@course_page.errors.full_messages[0]}"
- format.html {
- render :action => 'mobile_version'
- }
- format.api { render_validation_errors(@new_version) }
- end
- else
- @new_version.save_attachments(params[:attachments] || (params[:version] && params[:version][:uploads]))
- if @new_version.save
- respond_to do |format|
- format.html {
- flash[:notice] = l(:notice_successful_create)
- redirect_to mobile_version_url
- }
- format.api { render_api_ok }
- end
- else
- respond_to do |format|
- flash.now[:error] = "#{l :label_version_create_fail}: #{@new_version.errors.full_messages[0]}"
- #flash.now[:error] = "#{l :label_first_page_create_fail}: #{@course_page.errors.full_messages[0]}"
- format.html {
- render :action => 'mobile_version'
- }
- format.api { render_validation_errors(@new_version) }
- end
- end
- end
-
- end
-
- #留言列表
- def leave_messages
- notes1, notes2, notes3 = '', '', ''
- begin
- notes1 = Message.find(19292).content
- notes2 = Message.find(19291).content
- notes3 = Message.find(19504).content
- rescue => e
- end
- @jour = JournalsForMessage.find_by_sql("SELECT * FROM journals_for_messages AS j1
- WHERE j1.jour_type IN ('Course','Principal') AND (j1.m_parent_id IS NULL OR (j1.m_parent_id IN (SELECT id FROM journals_for_messages WHERE jour_type IN ('Course','Principal')))) AND j1.notes !='#{notes1}' AND j1.notes !='#{notes2}' AND j1.notes !='#{notes3}' order by created_on desc")
- @jour = paginateHelper @jour,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #帖子
- def messages_list
- @memo = Memo.reorder("created_at desc")
- @memo = paginateHelper @memo,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #课程讨论区的帖子
- def course_messages
- @course_ms=Message.joins("join boards on messages.board_id=boards.id where boards.course_id is not NULL").reorder('created_on desc')
- @course_ms = paginateHelper @course_ms,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #项目讨论区的帖子
- def project_messages
- @project_ms=Message.joins("join boards on messages.board_id=boards.id where boards.project_id != -1").reorder('created_on desc')
- @project_ms = paginateHelper @project_ms,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #通知
- def notices
- @news = News.where('course_id is not NULL').order('created_on desc')
- @news = paginateHelper @news,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #最近登录用户列表
- def latest_login_users
- scope = User.order('last_login_on desc')
- scope = scope.where("last_login_on>= '#{params[:startdate]} 00:00:00'") if params[:startdate].present?
- scope =scope.where("last_login_on <= '#{params[:enddate]} 23:59:59'") if params[:enddate].present?
- @users = scope
- @users = paginateHelper @users,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #最近登录老师列表
- def latest_login_teachers
- scope = User.find_by_sql("SELECT * FROM users,user_extensions WHERE users.id = user_extensions.user_id AND user_extensions.identity=0 ORDER BY last_login_on DESC")
- if params[:startdate].present?
- scope = User.find_by_sql("SELECT * FROM users,user_extensions WHERE users.id = user_extensions.user_id AND user_extensions.identity=0 and last_login_on>= '#{params[:startdate]} 00:00:00' ORDER BY last_login_on DESC")
- end
- if params[:enddate].present?
- scope = User.find_by_sql("SELECT * FROM users,user_extensions WHERE users.id = user_extensions.user_id AND user_extensions.identity=0 and last_login_on <= '#{params[:enddate]} 23:59:59' ORDER BY last_login_on DESC")
- end
- @teachers = scope
- @teachers = paginateHelper @teachers,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
- #作业
- def homework
- #@homework = HomeworkCommon.order('end_time desc')
- if params[:type] == "2"
- @homework = HomeworkCommon.where(:homework_type => 2).order( 'created_at desc ')
- else
- @homework = HomeworkCommon.order( 'created_at desc ')
- end
- @homework = paginateHelper @homework,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-
-#代码测试列表
- def code_work_tests
- #求出所有条数
- tCount = CodeTests.count()
-
- #设置个空的数组 以便paginateHelper来分页
- @code_work_tests = []
- if tCount >= 1
- @code_work_tests[tCount-1] = {}
- end
- @code_work_tests = paginateHelper @code_work_tests,30
- @page = (params['page'] || 1).to_i - 1
-
- #取出需要的那一页数据
- tStart = @page*30
- @code_work_tests = CodeTests.find_by_sql("select * from code_tests order by id desc limit #{tStart},30 ")
-
- #取出各个作品是否是模拟答题的
- is_test = {}
- #作品是否存在
- link_swork = {}
- #作业是否存在
- link_hwork = {}
- @code_work_tests.each do |test|
- #作品是否存在
- if is_test[test['student_work_id']] != nil
- test['link_swork'] = link_swork[test['student_work_id']]
- test['is_test'] = is_test[test['student_work_id']]
- else
- work = StudentWork.where("id=?",test['student_work_id']).first
- test['link_swork'] = !work.nil?
- test['is_test'] = work.nil? ? false : work.is_test
- #test['is_test'] = CodeTests.find_by_sql("select is_test from student_works where id = #{test['student_work_id']}").first['is_test']
- is_test[test['student_work_id']] = test['is_test']
- link_swork[test['student_work_id']] = test['link_swork']
- end
-
- #作业是否存在
- if link_hwork[test['homework_id']] != nil
- test['link_hwork'] = link_hwork[test['homework_id']]
- else
- hwork = HomeworkCommon.where("id=?",test['homework_id']).first
- test['link_hwork'] = !hwork.nil?
- link_hwork[test['homework_id']] = test['link_hwork']
- end
- end
-
- respond_to do |format|
- format.html
- end
- end
- #分享作业申请
- def apply_for_homework
- homeworks = ApplyHomework.where("user_id != 0")
- @homework = paginateHelper homeworks,30
- @page = (params['page'] || 1).to_i - 1
- respond_to do |format|
- format.html
- end
- end
-end
+
+# Redmine - project management software
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+class AdminController < ApplicationController
+ layout 'admin'
+ menu_item :projects, :only => :projects
+ menu_item :plugins, :only => :plugins
+ menu_item :info, :only => :info
+
+ before_filter :require_admin
+ helper :sort
+ helper :Users
+ helper :Settings,SchoolHelper
+ include SortHelper
+
+ def index
+ @no_configuration_data = Redmine::DefaultData::Loader::no_data?
+ end
+
+ def export_rep_static_users
+ rev = params[:rev]
+ cycle = params[:cycle]
+ cycle_name = (params[:cycle] == "admin_week" ? l(:label_per_week) : (params[:cycle] == "admin_month" ? l(:label_per_month) : l(:label_per_all)))
+ respond_to do |format|
+ format.html
+ format.xls{
+ filename = "#{l(:label_user_rep_xls)}_#{cycle_name}.xls"
+ send_data(admin_export_rep_xls(:rev => rev, :cycle => "1"), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
+ }
+ end
+ end
+
+ # 管理员界面导出所有项目代码、提交次数统计
+ def admin_export_rep_xls (options = {})
+ cycle = params[:cycle]
+ g = Gitlab.client
+ users_results = []
+ User.all.each do |user|
+ unless user.mail.nil?
+ user_mail = user.mail
+ user.projects.where("gpid is not null").each do |project|
+ begin
+ g.branches(project.gpid).each do |branch|
+ if cycle == "admin_week"
+ statics = g.admin_rep_stats_week(project.gpid, :rev => branch.name, :user_mail => user_mail)
+ elsif cycle == "admin_month"
+ statics = g.admin_rep_stats_month(project.gpid, :rev => branch.name, :user_mail => user_mail)
+ elsif cycle == "admin_all"
+ statics = g.admin_rep_stats_all(project.gpid, :rev => branch.name, :user_mail => user_mail)
+ end
+ unless statics.first.commits_num == "0"
+ user_details = {:user_id => user.id, :user_name => user.show_name, :project_id => project.id, :project_name => project.name,
+ :commits_num => statics.first.commits_num, :add => statics.first.add, :del => statics.first.del, :changes => statics.first.changes, :branch => branch.name}
+ users_results << user_details
+ end
+ end
+ rescue Exception => e
+ puts e
+ end
+ end
+ end
+ end
+
+ xls_report = StringIO.new
+ book = Spreadsheet::Workbook.new
+ sheet1 = book.create_worksheet :name => l(:project_module_repository)
+ blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
+ sheet1.row(0).default_format = blue
+ sheet1.row(0).concat([l(:label_rep_user_id),l(:label_rep_user_name),l(:label_rep_project_id),l(:label_rep_project_name),l(:rep_branch),l(:rep_changeset),l(:rep_code_add),l(:rep_code_delete),l(:rep_code_modified),l(:rep_sode_time)])
+ count_row = 1
+ users_results.each do |static|
+ sheet1[count_row,0] = static[:user_id]
+ sheet1[count_row,1] = static[:user_name]
+ sheet1[count_row,2] = static[:project_id]
+ sheet1[count_row,3] = static[:project_name]
+ sheet1[count_row,4] = static[:branch]
+ sheet1[count_row,5] = static[:commits_num]
+ sheet1[count_row,6] = static[:add]
+ sheet1[count_row,7] = static[:del]
+ sheet1[count_row,8] = static[:changes]
+ sheet1[count_row,9] = Time.now.strftime('%Y-%m-%d %H:%M:%S')
+ count_row += 1
+ end
+ book.write xls_report
+ xls_report.string
+ end
+
+ # 管理员界面 项目列表
+ def projects
+=begin
+ @status = params[:status] || 1
+
+ scope = Project.status(@status)
+ scope = scope.like(params[:name]) if params[:name].present?
+ @projects = scope.where(project_type: Project::ProjectType_project).reorder("created_on desc").all
+=end
+ # 搜索功能
+ @name = params[:name] || ""
+ condition = "#{@name.strip}".gsub(" ","")
+ @status = params[:status] || ""
+ unless @status.empty?
+ @projects = Project.where(:status=>@status).like(condition).order('created_on desc')
+ else
+ @projects = Project.like(condition).order('created_on desc')
+ end
+ # 分页
+ @projects = paginateHelper @projects,30
+ @page = (params['page'] || 1).to_i - 1
+ render :action => "projects", :layout => false if request.xhr?
+ end
+
+ def contests
+ @name = params[:name]
+ @contests = Contest.where("id >= 780 and name like '%#{@name}%'").order('created_at desc')
+ @contests = paginateHelper @contests,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ def syllabuses
+ @name = params[:name]
+ @syllabuses = Syllabus.like(@name).order('created_at desc')
+ @syllabuses = paginateHelper @syllabuses,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #为班级选择课程
+ def select_course_syllabus
+ @flag = false
+ if params[:syllabus_id] && params[:course_id]
+ course = Course.where("id = #{params[:course_id].to_i}").first
+ unless course.nil?
+ course.update_attribute(:syllabus_id, params[:syllabus_id].to_i)
+ @flag = true
+ end
+ end
+ if @flag
+ render :text=> "succ"
+ else
+ render :text=>'fail'
+ end
+ end
+
+ #新建课程
+ def create_syllabus
+ if params[:course_id]
+ course = Course.where("id = #{params[:course_id]}").first
+ if course
+ @user = course.teacher
+ syllabus = Syllabus.new
+ syllabus.update_attributes(:title => params[:title], :eng_name => params[:eng_name], :user_id => @user.id)
+ syllabus.description = Message.where("id = 19412").first.nil? ? nil : Message.where("id = 19412").first.content
+ if syllabus.save
+ course.update_attribute(:syllabus_id, params[:syllabus_id].to_i)
+ @flag = params[:flag].to_i
+ @course = course
+ respond_to do |format|
+ format.js
+ end
+ end
+ end
+ end
+ end
+
+ def courses
+ @name = params[:name].to_s.strip.downcase
+ if @name && @name != ""
+ all_user_ids = Course.all.map{|course| course.tea_id}
+ user_str_ids = search_user_by_name all_user_ids, @name
+ user_ids = user_str_ids.empty? ? "(-1)" : "(" + user_str_ids.join(",") + ")"
+ @courses = Course.where("tea_id in #{user_ids} or name like '%#{@name}%'").reorder("created_at desc")
+ else
+ @courses = Course.order('created_at desc')
+ end
+ @courses = paginateHelper @courses,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #未配置班级列表
+ def non_syllabus_courses
+ @name = params[:name].to_s.strip.downcase
+ if @name && @name != ""
+ @courses = Course.where("syllabus_id is null and is_delete = 0").select{ |course| (course.teacher[:lastname].to_s.downcase + course.teacher[:firstname].to_s.downcase).include?(@name) || course.name.include?(@name)}
+ @courses = @courses.sort{|x, y| y.created_at <=> x.created_at}
+ else
+ @courses = Course.where("syllabus_id is null and is_delete = 0").order('created_at desc')
+ end
+ @courses = paginateHelper @courses,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #修改班级名称
+ def update_course_name
+ @course = Course.where("id = #{params[:course_id].to_i}").first
+ unless @course.nil?
+ @course.update_column("name", params[:name])
+ respond_to do |format|
+ format.js
+ end
+ end
+ end
+
+ #修改课程名称
+ def update_syllabus_title
+ @syllabus = Syllabus.where("id = #{params[:syllabus_id].to_i}").first
+ unless @syllabus.nil?
+ @syllabus.update_column("title", params[:name])
+ respond_to do |format|
+ format.js
+ end
+ end
+ end
+
+ #管理员界面精品课程列表
+ def excellent_courses
+ @courses = Course.where("is_excellent =? or excellent_option =?", 1, 1 )
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ def shixuns
+ @shixuns = Shixun.all
+ end
+
+ #实训认证
+ def shixun_authentication
+ @shixun = Shixun.find(params[:id])
+ @shixun.update_attribute(:authentication, !@shixun.authentication)
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ # 单位名称列表下的已审批按照名字排序
+ def apply_shcool_sort
+ @order = ""
+ @sort = ""
+ if params[:sort] && (params[:order] == 'name')
+ # courses = School.find_by_sql("SELECT c.*,count(c.id) FROM courses c,course_activities ca WHERE c.id = ca.course_id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY count(c.id) #{params[:sort]}, c.id desc")
+ school = School.find_by_sql(" SELECT aas.name FROM apply_add_schools aas where aas.status = '0' ORDER BY CONVERT(aas.name USING gbk) #{params[:sort]}, aas.id asc ")
+ @order = params[:order]
+ @sort = params[:sort]
+ end
+ redirect_to unapplied_schools_url
+ end
+
+ #精品课程下的全部课程
+ def excellent_all_courses
+ name = params[:name]
+ @order = ""
+ @sort = ""
+ if params[:sort] && (params[:order] == 'act')
+ courses = Course.find_by_sql("SELECT c.*,count(c.id) FROM courses c,course_activities ca WHERE c.id = ca.course_id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY count(c.id) #{params[:sort]}, c.id desc")
+ @order = params[:order]
+ @sort = params[:sort]
+
+ elsif params[:sort] && (params[:order] == 'time')
+ courses = Course.find_by_sql("SELECT * FROM courses WHERE name like '%#{name}%' ORDER BY time #{params[:sort]}, id desc")
+ @order = params[:order]
+ @sort = params[:sort]
+
+ elsif params[:sort] && (params[:order] == 'post')
+ courses = Course.find_by_sql("SELECT c.*, count(m.id) count FROM boards b, courses c, messages m WHERE m.board_id = b.id AND b.course_id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY count #{params[:sort]}, c.id desc")
+ @order = params[:order]
+ @sort = params[:sort]
+
+ elsif params[:sort] && (params[:order] == 'res')
+ courses = Course.find_by_sql("SELECT c.*, count(at.container_id) cat FROM attachments at, courses c WHERE at.container_type = 'Course' AND at.container_id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY cat #{params[:sort]}, id desc")
+ @order = params[:order]
+ @sort = params[:sort]
+
+ elsif params[:sort] && (params[:order] == 'works')
+ courses = Course.find_by_sql("SELECT c.*, count(hc.id) chc FROM courses c, homework_commons hc,student_works sw WHERE c.id = hc.course_id AND sw.homework_common_id = hc.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY chc #{params[:sort]}, id desc")
+ @order = params[:order]
+ @sort = params[:sort]
+
+ elsif params[:sort] && (params[:order] == 'homework')
+ courses = Course.find_by_sql("SELECT c.*, count(sw.id) csw FROM student_works sw, courses c, homework_commons hc WHERE c.id = hc.course_id AND sw.id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY csw #{params[:sort]}, id desc")
+ @order = params[:order]
+ @sort = params[:sort]
+
+ elsif params[:sort] && (params[:order] == 'std')
+ courses = Course.find_by_sql("SELECT c.*, count(sfc.id) sfc FROM courses c, students_for_courses sfc WHERE sfc.course_id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY sfc #{params[:sort]}, id desc")
+ @order = params[:order]
+ @sort = params[:sort]
+
+ elsif params[:sort] && (params[:order] == 'open')
+ courses = Course.find_by_sql("SELECT * FROM courses WHERE name like '%#{name}%' ORDER BY is_public #{params[:sort]},id desc")
+ @order = params[:order]
+ @sort = params[:sort]
+
+ else
+ courses = Course.like(name).order('created_at desc')
+ end
+ @courses = paginateHelper courses,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #设为精品
+ def set_excellent_course
+ @course = Course.find params[:id]
+ unless @course.nil?
+ if @course.is_excellent == 1 || @course.excellent_option == 1
+ @course.update_column('is_excellent', 0)
+ @course.update_column('excellent_option', 0)
+ else
+ @course.update_column('is_excellent', 1)
+ end
+ respond_to do |format|
+ format.js
+ end
+ end
+ end
+
+ #取消精品
+ def cancel_excellent_course
+ @course = Course.find params[:id]
+ unless @course.nil?
+ if @course.is_excellent == 1 || @course.excellent_option == 1
+ @course.update_column('is_excellent', 0)
+ @course.update_column('excellent_option', 0)
+ end
+ end
+ respond_to do |format|
+ format.html{
+ redirect_to excellent_courses_url
+ }
+ end
+ end
+
+ #管理员界面课程资源列表
+ def course_resource_list
+
+ if params[:sort] == 'file_size'
+ @resource = Attachment.where(:container_type => 'Course').order("filesize desc")
+ elsif params[:sort] == 'file_upload'
+ @resource = Attachment.where(:container_type => 'Course').order("created_on desc")
+ elsif params[:sort] == 'file_download_times'
+ @resource = Attachment.where(:container_type => 'Course').order("downloads desc")
+ else
+ @resource = Attachment.where(:container_type => 'Course').order("created_on desc")
+ end
+
+ @resource = paginateHelper @resource,30
+ @page = (params['page'] || 1).to_i - 1
+
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #管理员界面項目资源列表
+ def project_resource_list
+
+ if params[:sort] == 'file_size'
+ @pro_resource = Attachment.where(:container_type => 'Project').order("filesize desc")
+ elsif params[:sort] == 'file_upload'
+ @pro_resource = Attachment.where(:container_type => 'Project').order("created_on desc")
+ elsif params[:sort] == 'file_download_times'
+ @pro_resource = Attachment.where(:container_type => 'Project').order("downloads desc")
+ else
+ @pro_resource = Attachment.where(:container_type => 'Project').order("created_on desc")
+ end
+
+ @pro_resource = paginateHelper @pro_resource,30
+ @page = (params['page'] || 1).to_i - 1
+
+ respond_to do |format|
+ format.html
+ end
+ end
+
+
+ def users
+ sort_init 'login', 'asc'
+ sort_update %w(login firstname lastname mail admin created_on last_login_on)
+
+ case params[:format]
+ when 'xml', 'json'
+ @offset, @limit = api_offset_and_limit({:limit => 50})
+ else
+ @limit = 50 #per_page_option
+ end
+
+ @status = params[:status] || 1
+ scope = User.logged.status(@status)
+ scope = User.like(params[:name]) if params[:name].present?
+ scope = scope.in_group(params[:group_id]) if params[:group_id].present?
+
+ @user_count = scope.count
+ @user_pages = Paginator.new @user_count, @limit, params['page']
+ @offset ||= @user_pages.offset
+ @users = scope.order(sort_clause).limit(@limit).offset(@offset).all
+
+
+ respond_to do |format|
+ format.html {
+ @groups = Group.all.sort
+ }
+ format.api
+ end
+ end
+
+ # 系统消息
+ def messages
+ @admin_messages = SystemMessage.new
+ end
+
+ def plugins
+ @plugins = Redmine::Plugin.all
+ end
+
+ # Loads the default configuration
+ # (roles, trackers, statuses, workflow, enumerations)
+ def default_configuration
+ if request.post?
+ begin
+ Redmine::DefaultData::Loader::load(params[:lang])
+ flash[:notice] = l(:notice_default_data_loaded)
+ rescue Exception => e
+ flash[:error] = l(:error_can_t_load_default_data, e.message)
+ end
+ end
+ redirect_to admin_url
+ end
+
+ def test_email
+ raise_delivery_errors = ActionMailer::Base.raise_delivery_errors
+ # Force ActionMailer to raise delivery errors so we can catch it
+ ActionMailer::Base.raise_delivery_errors = true
+ begin
+ @test = Mailer.test_email(User.current).deliver
+ flash[:notice] = l(:notice_email_sent, User.current.mail)
+ rescue Exception => e
+ flash[:error] = l(:notice_email_error, e.message)
+ end
+ ActionMailer::Base.raise_delivery_errors = raise_delivery_errors
+ redirect_to settings_url(:tab => 'notifications')
+ end
+
+ def info
+ @db_adapter_name = ActiveRecord::Base.connection.adapter_name
+ @checklist = [
+ [:text_default_administrator_account_changed, User.default_admin_account_changed?],
+ [:text_file_repository_writable, File.writable?(Attachment.storage_path)],
+ [:text_plugin_assets_writable, File.writable?(Redmine::Plugin.public_directory)],
+ [:text_rmagick_available, Object.const_defined?(:Magick)]
+ ]
+ end
+ #管理功能用户列表的搜索
+ def search
+ sort_init 'login', 'asc'
+ sort_update %w(login firstname lastname mail admin created_on last_login_on)
+
+ case params[:format]
+ when 'xml', 'json'
+ @offset, @limit = api_offset_and_limit({:limit => 15})
+ else
+ @limit = 15#per_page_option
+ end
+ @status = params[:status] || 1
+ scope = User.logged.status(@status)
+ scope = scope.like(params[:name],params[:search_by][:id]) if params[:name].present?
+ @user_count = scope.count
+ @user_pages = Paginator.new @user_count, @limit, params['page']
+ @user_base_tag = params[:id] ? 'base_users':'base'
+
+ @users = scope.order(sort_clause).offset(@user_pages.offset).limit(@user_pages.per_page).all
+ respond_to do |format|
+ format.html {
+ @groups = Group.all.sort
+ }
+ format.api
+ end
+ end
+
+ #首页定制
+ def first_page_made
+ if request.get?
+ @first_page = FirstPage.find_by_page_type('project')
+ elsif request.post?
+ @first_page = FirstPage.find_by_page_type('project')
+ @first_page.web_title = params[:web_title]
+ @first_page.description = params[:first_page][:description]
+ #@first_page.title = params[:title]
+ @first_page.image_width = params[:image_width]
+ @first_page.image_height = params[:image_height]
+ @first_page.sort_type = params[:sort_type]
+ @first_page.show_course = params[:show_course]
+ @first_page.show_contest = params[:show_contest]
+ if @first_page.save
+ respond_to do |format|
+ flash[:notice] = l(:notice_successful_update)
+ format.html {
+ redirect_to first_page_made_url
+ }
+ format.api { render_api_ok }
+ #format.json { render json: @first_page, status: :created, location: @first_page }
+ end
+ else
+ respond_to do |format|
+ flash.now[:error] = "#{l :label_first_page_create_fail}: #{@first_page.errors.full_messages[0]}"
+ format.html {
+ render :action => 'first_page_made'
+ }
+ format.api { render_validation_errors(@first_page) }
+ #format.json { render json: @first_page.errors, status: :unprocessable_entity }
+ end
+ end
+ end
+ end
+
+ def course_page_made
+ if request.get?
+ @course_page = FirstPage.find_by_page_type('course')
+ @first_page = FirstPage.find_by_page_type('project')
+ elsif request.post?
+ @first_page = FirstPage.find_by_page_type('project')
+ @course_page = FirstPage.find_by_page_type('course')
+ @first_page.web_title = params[:web_title]
+ @course_page.web_title = params[:web_title]
+ @course_page.title = params[:course_title]
+ @course_page.image_width = params[:image_width]
+ @course_page.image_height = params[:image_height]
+ @course_page.description = params[:course_description]
+ if @first_page.save && @course_page.save
+ respond_to do |format|
+ format.html {
+ flash[:notice] = l(:notice_successful_update)
+ redirect_to course_page_made_url
+ }
+ format.api { render_api_ok }
+ end
+ else
+ respond_to do |format|
+ flash.now[:error] = "#{l :label_first_page_create_fail}: #{@first_page.errors.full_messages[0]}\n\t#{@course_page.errors.full_messages[0]}"
+ #flash.now[:error] = "#{l :label_first_page_create_fail}: #{@course_page.errors.full_messages[0]}"
+ format.html {
+
+ render :action => 'course_page_made'
+ }
+ format.api { render_validation_errors(@first_page) }
+ format.api { render_validation_errors(@course_page) }
+ end
+ end
+ end
+ end
+
+ def contest_page_made
+ if request.get?
+ @contest_page = FirstPage.find_by_page_type('contest')
+ @first_page = FirstPage.find_by_page_type('project')
+ elsif request.post?
+ @first_page = FirstPage.find_by_page_type('project')
+ @contest_page = FirstPage.find_by_page_type('contest')
+ @first_page.web_title = params[:web_title]
+ @contest_page.web_title = params[:web_title]
+ @contest_page.title = params[:contest_title]
+ @contest_page.image_width = params[:image_width]
+ @contest_page.image_height = params[:image_height]
+ @contest_page.description = params[:contest_description]
+
+ if @first_page.save && @contest_page.save
+ respond_to do |format|
+ format.html {
+ flash[:notice] = l(:notice_successful_update)
+ redirect_to contest_page_made_url
+ }
+ format.api { render_api_ok }
+ end
+ else
+ respond_to do |format|
+ flash.now[:error] = "#{l :label_first_page_create_fail}: #{@first_page.errors.full_messages[0]}\n\t#{@contest_page.errors.full_messages[0]}\n\t#{@notification.errors.full_messages[0]}"
+ format.html {
+ render :action => 'contest_page_made'
+ }
+ format.api { render_validation_errors(@first_page) }
+ format.api { render_validation_errors(@contest_page) }
+ end
+ end
+ end
+ end
+
+ def web_footer_made
+ if request.get?
+ @organizer = WebFooterOranizer.first
+ @first_page = FirstPage.find_by_page_type('project')
+ #@notification = ContestNotification.all.first;
+ elsif request.post?
+ @first_page = FirstPage.find_by_page_type('project')
+ @first_page.web_title = params[:web_title]
+ @organizer = WebFooterOranizer.first
+ if @organizer.nil?
+ @organizer = WebFooterOranizer.new
+ end
+ @organizer.name = params[:organizer_name]
+ @organizer.description = params[:web_footer_oranizer][:description]
+ if @first_page.save && @organizer.save
+ respond_to do |format|
+ format.html {
+ flash[:notice] = l(:notice_successful_update)
+ redirect_to web_footer_made_url
+ }
+ format.api { render_api_ok }
+ end
+ else
+ respond_to do |format|
+ flash.now[:error] = "#{l :label_first_page_create_fail}: #{@first_page.errors.full_messages[0]}\n\t#{@organizer.errors.full_messages[0]}}"
+ format.html {
+ render :action => 'web_footer_made'
+ }
+ format.api { render_validation_errors(@first_page) }
+ format.api { render_validation_errors(@contest_page) }
+ end
+ end
+ end
+ end
+
+ #企业主页定制
+ def enterprise_page_made
+ @enterprise_page = FirstPage.find_by_page_type('enterprise')
+ if @enterprise_page.nil?
+ @enterprise_page = FirstPage.new
+ @enterprise_page.page_type = 'enterprise'
+ end
+ if request.get?
+ @first_page = FirstPage.find_by_page_type('project')
+ elsif request.post?
+ @first_page = FirstPage.find_by_page_type('project')
+ @first_page.web_title = params[:web_title]
+ @enterprise_page.web_title = params[:web_title]
+ @enterprise_page.title = params[:course_title]
+ @enterprise_page.image_width = params[:image_width]
+ @enterprise_page.image_height = params[:image_height]
+ @enterprise_page.description = params[:course_description]
+ if @first_page.save && @enterprise_page.save
+ respond_to do |format|
+ format.html {
+ flash[:notice] = l(:notice_successful_update)
+ redirect_to enterprise_page_made_url
+ }
+ format.api { render_api_ok }
+ end
+ else
+ respond_to do |format|
+ flash.now[:error] = "#{l :label_first_page_create_fail}: #{@first_page.errors.full_messages[0]}\n\t#{@enterprise_page.errors.full_messages[0]}"
+ #flash.now[:error] = "#{l :label_first_page_create_fail}: #{@course_page.errors.full_messages[0]}"
+ format.html {
+ render :action => 'enterprise_page_made'
+ }
+ format.api { render_validation_errors(@first_page) }
+ format.api { render_validation_errors(@enterprise_page) }
+ end
+ end
+ end
+ end
+
+ #组织
+ def organization
+ @organizations = Organization.find_by_sql("SELECT * FROM organizations ORDER BY created_at DESC")
+ #@organizations = Organization.all.order("created_at desc")
+ @organization_count = @organizations.count
+ @organization_pages = Paginator.new @organization_count, 30, params['page'] || 1
+ @organizations = paginateHelper @organizations,30
+
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #学校列表
+ def schools
+ @order = ""
+ @sort = ""
+ @schools = School.find_by_sql("SELECT * FROM schools ORDER BY created_at DESC")
+ if params[:sort] && (params[:order] == 'num')
+ @order = params[:order]
+ @sort = params[:sort]
+ @schools.each do |school|
+ count = UserExtensions.where("school_id = #{school.id} or occupation = '#{school.name}'").count
+ school[:infocount] = count.to_i
+ end
+ @sort == 'asc' ? (@schools = @schools.sort{|x,y| x[:infocount] <=> y[:infocount] }) : (@schools = @schools.sort{|x,y| y[:infocount] <=> x[:infocount]})
+ end
+
+ @school_count = @schools.count
+
+ @school_pages = Paginator.new @school_count, 30, params['page'] || 1
+ @schools = paginateHelper @schools,30
+
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ # 单位审核
+ # 未审批tab页
+ # status: 0 未审批; 1 已批阅; 2已更改; 3拒绝;
+ def applied_schools
+ # 更新消息状态
+ if params[:flag]
+ applied_message = AppliedMessage.where(:id => params[:applied_message_id], :applied_type => 'ApplyAddSchools').first
+ applied_message.update_attribute(:viewed, true)
+ end
+
+ @name = params[:name] || ""
+ condition = "#{@name.strip}".gsub(" ","")
+ @apply_status = ApplyAddSchools.where("status = 0 and name like '%#{condition}%'").order('created_at desc')
+ @apply_count = @apply_status.count
+ @apply_pages = Paginator.new @apply_count, 30, params['page'] || 1
+ @apply_status = paginateHelper @apply_status, 30
+ @page = (params['page'] || 1).to_i - 1
+
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ # 单位审核
+ # 已审批tab页
+ def has_applied_schools
+ @name = params[:name] || ""
+ condition = "#{@name.strip}".gsub(" ","")
+
+ @has_apply_status = ApplyAddSchools.where("(status = 1 or status = 2) and name like '%#{condition}%'").order('created_at desc')
+ @has_apply_count = @has_apply_status.count
+ @has_apply_pages = Paginator.new @has_apply_count, 30, params['page'] || 1
+ @has_apply_status = paginateHelper @has_apply_status, 30
+ @page = (params['page'] || 1).to_i - 1
+
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ # 单位审核:批准
+ # 消息发送,发送对象为申请人
+ # status: 0表示未批准; status:1表示已批准; status: 2表示已更改; status: 3表示已拒绝; status: 4表示已更改后废除的高校
+ def approve_applied_schools
+ applied_school = ApplyAddSchools.find params[:id]
+ applied_message_id = applied_school.school_id
+ applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
+ applied_message.update_all(:status => 1)
+ applied_school.update_column('status', 1) unless applied_school.nil?
+ school = applied_school.school
+ school.update_attribute("province", applied_school.province)
+ AppliedMessage.create(:user_id => applied_school.user_id, :status => 1, :viewed => 0, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
+ # School.create(:user_id => applied_school.user_id, :status => 1, :viewed => true, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
+ respond_to do |format|
+ format.html{ redirect_to unapplied_schools_url }
+ end
+ end
+
+ # 单位审核:更改
+ # 修改该字段
+ # 同步修改使用了改名称的用户单位
+ def edit_applied_schools
+ aas = ApplyAddSchools.find(params[:applied_id])
+ # aas.update_attribute(:name, params[:name])
+ #applied_add_school = ApplyAddSchools.where(:name => aas.name)
+ school = School.find params[:school_id]
+ begin
+ #更新消息表的status
+ applied_message_id = aas.school_id
+ applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
+ applied_message.update_all(:status => 4)
+ aas.update_attribute(:status, 2)
+ AppliedMessage.create(:user_id => aas.user_id, :status => 2, :viewed => 0, :applied_id => aas.id, :applied_type => "ApplyAddSchools", :name => school[0].name )
+ users = UserExtensions.where("school_id = #{aas.school_id}")
+ users.update_all(:school_id => school[0].id)
+ if aas.school_id != school[0].id.to_i
+ aas.school.destroy
+ end
+ ApplyAddDepartment.where(:school_id => aas.school_id).update_all(:school_id => school[0].id)
+ Department.where(:school_id => aas.school_id).update_all(:school_id => school[0].id)
+ aas.update_attribute(:school_id, school[0].id)
+ rescue Exception => e
+ puts e
+ end
+ # applied_schools = ApplyAddSchools.find params[:applied_id]
+ # applied_schools.update_column('name', params[:name])
+ redirect_to unapplied_schools_url
+ end
+
+ # 单位审核:更改功能搜索合法学校弹框
+ def all_schools
+ apply_schools = ApplyAddSchools.where("status = 0")
+ apply_school_ids = apply_schools.empty? ? "(-1)" : "(" + apply_schools.map{|sc| sc.school_id}.join(',') + ")"
+ if !params[:search].nil?
+ search = "%#{params[:search].to_s.strip.downcase}%"
+ @schools = School.where("id not in #{apply_school_ids} and #{School.table_name}.name like :p", :p => search)
+ #@schools = School.all
+ else
+ #@course = @user.courses.where("is_delete = 0 and #{Course.table_name}.id != #{homework.course_id}").select { |course| @user.allowed_to?(:as_teacher,course)}
+ @schools = School.where("id not in #{apply_school_ids}")
+ end
+ @edit_id = params[:school_id]
+ @search = params[:search]
+ respond_to do |format|
+ format.js
+ end
+ end
+ # 单位审核:删除
+ def delete_applied_schools
+ applied_school = ApplyAddSchools.find(params[:id])
+ applied_message_id = applied_school.school_id
+ applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
+ applied_message.update_all(:status => 3)
+ applied_school.update_attribute(:status, 3)
+ # 单位对应的部门审核也应做删除处理
+ applied_departments = ApplyAddDepartment.where(:school_id => applied_school.school_id)
+ applied_departments.update_all(:status => 3)
+ AppliedMessage.where(:applied_id => applied_departments.map(&:id), :applied_type => "ApplyAddDepartment").update_all(:status => 3)
+ # 未审批删除
+ if params[:tip] == "unapplied"
+ AppliedMessage.create(:user_id => applied_school.user_id, :status => 3, :viewed => 0, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
+ if applied_departments.first
+ AppliedMessage.create(:user_id => applied_departments.first.user_id, :status => 3, :viewed => 0, :applied_id => applied_departments.first.id, :applied_type => "ApplyAddDepartment", :name => applied_departments.first.name )
+ end
+# 删除学校的用户
+ users = UserExtensions.where("school_id = #{applied_school.school_id}")
+ users.update_all(:school_id => nil, :department_id => nil)
+ applied_school.school.destroy
+ applied_school.school.departments.destroy_all
+ redirect_to unit_managements_path
+ # 已审批删除
+ elsif params[:tip] == "applied"
+ applied_school.destroy
+ redirect_to unit_managements_path
+ end
+ end
+
+ # 部门审核
+ # 未审批tab页
+ # status: 0 未审批; 1 已批阅; 2已更改; 3拒绝;
+ def applied_departments
+ # 更新消息状态
+ if params[:flag]
+ applied_message = AppliedMessage.where(:id => params[:applied_message_id], :applied_type => 'ApplyAddDepartment').first
+ applied_message.update_attribute(:viewed, true)
+ end
+
+ @name = params[:name] || ""
+ condition = "#{@name.strip}".gsub(" ","")
+ @apply_status = ApplyAddDepartment.where("status = 0 and name like '%#{condition}%'").order('created_at desc')
+ @apply_count = @apply_status.count
+ @apply_pages = Paginator.new @apply_count, 30, params['page'] || 1
+ @apply_status = paginateHelper @apply_status, 30
+ @page = (params['page'] || 1).to_i - 1
+
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ def has_applied_departments
+ @name = params[:name] || ""
+ condition = "#{@name.strip}".gsub(" ","")
+ @has_apply_status = ApplyAddDepartment.where("(status = 1 or status = 2) and name like '%#{condition}%'").order('created_at desc')
+ @has_apply_count = @has_apply_status.count
+ @has_apply_pages = Paginator.new @has_apply_count, 30, params['page'] || 1
+ @has_apply_status = paginateHelper @has_apply_status, 30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ def approve_applied_departments
+ applied_department = ApplyAddDepartment.find params[:id]
+ applied_message = AppliedMessage.where(:applied_id => applied_department.id, :applied_type => "ApplyAddDepartment")
+ applied_message.update_all(:status => 1)
+ applied_department.update_column('status', 1) unless applied_department.nil?
+ AppliedMessage.create(:user_id => applied_department.user_id, :status => 1, :viewed => 0, :applied_id => applied_department.id, :applied_type => "ApplyAddDepartment", :name => applied_department.name )
+ respond_to do |format|
+ format.html{ redirect_to depart_managements_path }
+ end
+ end
+
+ def delete_applied_departments
+ applied_department = ApplyAddDepartment.find params[:id]
+ applied_message = AppliedMessage.where(:applied_id => applied_department.id, :applied_type => "ApplyAddDepartment")
+ applied_message.update_all(:status => 3)
+ applied_department.update_attribute(:status, 3)
+ # 未审批删除
+ if params[:tip] == "unapplied"
+ AppliedMessage.create(:user_id => applied_department.user_id, :status => 3, :viewed => 0, :applied_id => applied_department.id, :applied_type => "ApplyAddDepartment", :name => applied_department.name )
+ # 删除学校的用户
+ users = UserExtensions.where("department_id = #{applied_department.department_id}")
+ users.update_all(:department_id => nil)
+ applied_department.department.destroy
+ redirect_to depart_managements_path
+ # 已审批删除
+ elsif params[:tip] == "applied"
+ applied_department.destroy
+ redirect_to depart_managements_path
+ end
+ end
+
+ #移动端版本管理
+ def mobile_version
+ @versions = PhoneAppVersion.reorder('created_at desc')
+ @new_version = PhoneAppVersion.new
+
+ end
+
+ # 身份认证
+ def identity_authentication
+ 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{ render :layout => 'base_edu' }
+ format.js
+ end
+ end
+
+ # 拒绝身份认证
+ 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
+
+ # 统一身份认证
+ 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 create_version
+ @versions = PhoneAppVersion.reorder('created_at desc')
+ @new_version = PhoneAppVersion.new
+ @new_version.version = params[:version]
+ @new_version.description = params[:description]
+ if params[:attachments][:dummy][:file].nil? || params[:attachments][:dummy][:file] == ""
+ respond_to do |format|
+ flash.now[:error] = "#{l :label_version_create_fail}: #{l(:label_client_need)}"
+ #flash.now[:error] = "#{l :label_first_page_create_fail}: #{@course_page.errors.full_messages[0]}"
+ format.html {
+ render :action => 'mobile_version'
+ }
+ format.api { render_validation_errors(@new_version) }
+ end
+ else
+ @new_version.save_attachments(params[:attachments] || (params[:version] && params[:version][:uploads]))
+ if @new_version.save
+ respond_to do |format|
+ format.html {
+ flash[:notice] = l(:notice_successful_create)
+ redirect_to mobile_version_url
+ }
+ format.api { render_api_ok }
+ end
+ else
+ respond_to do |format|
+ flash.now[:error] = "#{l :label_version_create_fail}: #{@new_version.errors.full_messages[0]}"
+ #flash.now[:error] = "#{l :label_first_page_create_fail}: #{@course_page.errors.full_messages[0]}"
+ format.html {
+ render :action => 'mobile_version'
+ }
+ format.api { render_validation_errors(@new_version) }
+ end
+ end
+ end
+
+ end
+
+ #留言列表
+ def leave_messages
+ notes1, notes2, notes3 = '', '', ''
+ begin
+ notes1 = Message.find(19292).content
+ notes2 = Message.find(19291).content
+ notes3 = Message.find(19504).content
+ rescue => e
+ end
+ @jour = JournalsForMessage.find_by_sql("SELECT * FROM journals_for_messages AS j1
+ WHERE j1.jour_type IN ('Course','Principal') AND (j1.m_parent_id IS NULL OR (j1.m_parent_id IN (SELECT id FROM journals_for_messages WHERE jour_type IN ('Course','Principal')))) AND j1.notes !='#{notes1}' AND j1.notes !='#{notes2}' AND j1.notes !='#{notes3}' order by created_on desc")
+ @jour = paginateHelper @jour,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #帖子
+ def messages_list
+ @memo = Memo.reorder("created_at desc")
+ @memo = paginateHelper @memo,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #课程讨论区的帖子
+ def course_messages
+ @course_ms=Message.joins("join boards on messages.board_id=boards.id where boards.course_id is not NULL").reorder('created_on desc')
+ @course_ms = paginateHelper @course_ms,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #项目讨论区的帖子
+ def project_messages
+ @project_ms=Message.joins("join boards on messages.board_id=boards.id where boards.project_id != -1").reorder('created_on desc')
+ @project_ms = paginateHelper @project_ms,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #通知
+ def notices
+ @news = News.where('course_id is not NULL').order('created_on desc')
+ @news = paginateHelper @news,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #最近登录用户列表
+ def latest_login_users
+ scope = User.order('last_login_on desc')
+ scope = scope.where("last_login_on>= '#{params[:startdate]} 00:00:00'") if params[:startdate].present?
+ scope =scope.where("last_login_on <= '#{params[:enddate]} 23:59:59'") if params[:enddate].present?
+ @users = scope
+ @users = paginateHelper @users,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #最近登录老师列表
+ def latest_login_teachers
+ scope = User.find_by_sql("SELECT * FROM users,user_extensions WHERE users.id = user_extensions.user_id AND user_extensions.identity=0 ORDER BY last_login_on DESC")
+ if params[:startdate].present?
+ scope = User.find_by_sql("SELECT * FROM users,user_extensions WHERE users.id = user_extensions.user_id AND user_extensions.identity=0 and last_login_on>= '#{params[:startdate]} 00:00:00' ORDER BY last_login_on DESC")
+ end
+ if params[:enddate].present?
+ scope = User.find_by_sql("SELECT * FROM users,user_extensions WHERE users.id = user_extensions.user_id AND user_extensions.identity=0 and last_login_on <= '#{params[:enddate]} 23:59:59' ORDER BY last_login_on DESC")
+ end
+ @teachers = scope
+ @teachers = paginateHelper @teachers,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ #作业
+ def homework
+ #@homework = HomeworkCommon.order('end_time desc')
+ if params[:type] == "2"
+ @homework = HomeworkCommon.where(:homework_type => 2).order( 'created_at desc ')
+ else
+ @homework = HomeworkCommon.order( 'created_at desc ')
+ end
+ @homework = paginateHelper @homework,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+
+#代码测试列表
+ def code_work_tests
+ #求出所有条数
+ tCount = CodeTests.count()
+
+ #设置个空的数组 以便paginateHelper来分页
+ @code_work_tests = []
+ if tCount >= 1
+ @code_work_tests[tCount-1] = {}
+ end
+ @code_work_tests = paginateHelper @code_work_tests,30
+ @page = (params['page'] || 1).to_i - 1
+
+ #取出需要的那一页数据
+ tStart = @page*30
+ @code_work_tests = CodeTests.find_by_sql("select * from code_tests order by id desc limit #{tStart},30 ")
+
+ #取出各个作品是否是模拟答题的
+ is_test = {}
+ #作品是否存在
+ link_swork = {}
+ #作业是否存在
+ link_hwork = {}
+ @code_work_tests.each do |test|
+ #作品是否存在
+ if is_test[test['student_work_id']] != nil
+ test['link_swork'] = link_swork[test['student_work_id']]
+ test['is_test'] = is_test[test['student_work_id']]
+ else
+ work = StudentWork.where("id=?",test['student_work_id']).first
+ test['link_swork'] = !work.nil?
+ test['is_test'] = work.nil? ? false : work.is_test
+ #test['is_test'] = CodeTests.find_by_sql("select is_test from student_works where id = #{test['student_work_id']}").first['is_test']
+ is_test[test['student_work_id']] = test['is_test']
+ link_swork[test['student_work_id']] = test['link_swork']
+ end
+
+ #作业是否存在
+ if link_hwork[test['homework_id']] != nil
+ test['link_hwork'] = link_hwork[test['homework_id']]
+ else
+ hwork = HomeworkCommon.where("id=?",test['homework_id']).first
+ test['link_hwork'] = !hwork.nil?
+ link_hwork[test['homework_id']] = test['link_hwork']
+ end
+ end
+
+ respond_to do |format|
+ format.html
+ end
+ end
+ #分享作业申请
+ def apply_for_homework
+ homeworks = ApplyHomework.where("user_id != 0")
+ @homework = paginateHelper homeworks,30
+ @page = (params['page'] || 1).to_i - 1
+ respond_to do |format|
+ format.html
+ end
+ end
+end
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index de9c1b713..e8e548c26 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -60,6 +60,20 @@ class ApplicationController < ActionController::Base
logger.info "HTTP_USER_AGENT #{request.env["HTTP_USER_AGENT"]}"
end
+ # 判断用户是否认证
+ # def check_authentication
+ # # return true
+ # if params[:action] == "on_search" || params[:action] == "apply_trail" # 之所以这样处理是为了避开account页面ajax加载
+ # return true
+ # end
+ # authentication = ApplyAction.where(:user_id => User.current.id, :status => 1).first
+ # user_identity = User.current.try(:user_extensions).try(:identity)
+ # if user_identity.blank? || authentication.blank?
+ # redirect_to my_account_path
+ # return
+ # end
+ # end
+
def session_expiration
if session[:user_id]
if session_expired? && !try_to_autologin
@@ -106,6 +120,7 @@ class ApplicationController < ActionController::Base
def current_user
find_current_user
end
+
def find_current_user
user = nil
unless api_request?
@@ -205,6 +220,7 @@ class ApplicationController < ActionController::Base
def logout_user
if User.current.logged?
if Redmine::Configuration['cookie_domain'].present?
+ logger.info("##########################{Redmine::Configuration['cookie_domain']}")
cookies.delete(autologin_cookie_name, domain: Redmine::Configuration['cookie_domain'])
else
cookies.delete autologin_cookie_name
@@ -433,7 +449,7 @@ class ApplicationController < ActionController::Base
if params[:project_id]
@project = Project.find(params[:project_id])
elsif params[:shixun_id]
- @shixun = Shixun.find(params[:shixun_id])
+ @shixun = Shixun.find_by_identifier(params[:shixun_id])
elsif params[:course_id]
@course = Course.find(params[:course_id])
elsif params[:org_subfield_id]
@@ -624,6 +640,10 @@ class ApplicationController < ActionController::Base
end
def render_403(options={})
+ if User.current.id == 2
+ redirect_to signin_url
+ return
+ end
@project = nil
render_error({:message => :notice_not_authorized, :status => 403}.merge(options),'common/403')
#render :template => 'common/403'
@@ -631,6 +651,10 @@ class ApplicationController < ActionController::Base
end
def render_404(options={})
+ if User.current.id == 2
+ redirect_to signin_url
+ return
+ end
render_error({:message => :notice_file_not_found, :status => 404}.merge(options),'common/404')
#render :template => 'common/404'
return false
@@ -948,6 +972,20 @@ class ApplicationController < ActionController::Base
end
end
+ # gitlab分页定制
+ def paginateHelperForGitlab obj, pre_size=15
+ @obj_count = obj.count
+ @obj_pages = Paginator.new @obj_count, pre_size, params['page']
+ if obj.kind_of? ActiveRecord::Base or obj.kind_of? ActiveRecord::Relation
+ obj.limit(@obj_pages.per_page).offset(@obj_pages.offset)
+ elsif obj.kind_of? Array
+ obj[0, @obj_pages.per_page]
+ else
+ logger.error "[ApplicationController] Error : application_controller#paginateHelper ===> unknow category: #{obj.class}"
+ raise RuntimeError, 'unknow type, Please input you type into this helper.'
+ end
+ end
+
#查找首页相关信息
def find_first_page
@first_page = FirstPage.find_by_page_type('project')
diff --git a/app/controllers/attachments_controller.rb b/app/controllers/attachments_controller.rb
index 35abc1a5e..ddce8496d 100644
--- a/app/controllers/attachments_controller.rb
+++ b/app/controllers/attachments_controller.rb
@@ -79,6 +79,51 @@ class AttachmentsController < ApplicationController
:disposition => 'attachment' #inline can open in browser
end
+ def direct_download_resource
+ @resource = ResourceBank.find(params[:id])
+ storage_path = Redmine::Configuration['attachments_storage_path'] || File.join(Rails.root, "files")
+ file = File.join(storage_path, @resource.disk_directory.to_s, @resource.disk_filename.to_s)
+ send_file file, :filename => filename_for_content_disposition(@resource.filename),
+ :type => detect_content_type(@resource),
+ :disposition => 'attachment' #inline can open in browser
+ @resource.increment!(:downloads)
+ end
+
+ def download_resource
+ @resource = ResourceBank.find(params[:id])
+ candown = resource_bank_candown @resource, params[:type]
+ if candown
+ if stale?(:etag => @resource.digest)
+ if params[:preview] == 'true'
+ storage_path = Redmine::Configuration['attachments_storage_path'] || File.join(Rails.root, "files")
+ convered_file = File.join(storage_path, @resource.disk_directory.to_s, @resource.disk_filename.to_s)
+ #如果本身不是pdf文件,则先寻找是不是已转换化,如果没有则转化
+ unless pdf?(convered_file)
+ convered_file = File.join(Rails.root, "files", "convered_office", @attachment.disk_filename + ".pdf")
+ unless File.exist?(convered_file)
+ office = Trustie::Utils::Office.new(File.join(storage_path, @resource.disk_directory.to_s, @resource.disk_filename.to_s))
+ office.conver(convered_file)
+ end
+ end
+ if File.exist?(convered_file) && pdf?(convered_file)
+ send_file convered_file, :type => 'application/pdf; charset=utf-8', :disposition => 'inline'
+ else
+ direct_download_resource
+ end
+ else
+ # 记录用户行为
+ record_user_actions(params[:id])
+ # 直接下载历史版本
+ direct_download_resource
+ end
+ end
+ else
+ render_403 :message => :notice_not_authorized
+ end
+ rescue => e
+ redirect_to "http://" + (Setting.host_name.to_s) +"/file_not_found.html"
+ end
+
def direct_download_history
@attachment_history = AttachmentHistory.find(params[:id])
@attachment_history.increment_download
@@ -126,6 +171,8 @@ class AttachmentsController < ApplicationController
UserActions.create(:action_id => id, :action_type => "AttachmentHistory", :user_id => User.current.id) unless id.nil?
elsif params[:action] == "download"
UserActions.create(:action_id => id, :action_type => "Attachment", :user_id => User.current.id) unless id.nil?
+ elsif params[:action] == "download_resource"
+ UserActions.create(:action_id => id, :action_type => "ResourceBank", :user_id => User.current.id) unless id.nil?
end
end
@@ -268,6 +315,8 @@ class AttachmentsController < ApplicationController
def upload
+
+
# Make sure that API users get used to set this content type
# as it won't trigger Rails' automatic parsing of the request body for parameters
unless request.content_type == 'application/octet-stream'
@@ -295,6 +344,25 @@ class AttachmentsController < ApplicationController
end
end
+ def upload_with_markdown
+ logger.debug "upload_with_markdown"
+ @attachment = Attachment.new(:file => params["editormd-image-file"])
+ @attachment.author = User.current
+ # 如果其它类型的条用md,必须传类型,elsif判断
+ if params[:container_type] == 'Shixun'
+ @attachment.container_type = 'Shixun'
+ @attachment.container_id = params[:container_id]
+ end
+ @attachment.filename = params[:filename].presence || Redmine::Utils.random_hex(16)
+ saved = @attachment.save
+ saved
+ render json: {
+ success: saved ? 1 : 0, # | 1, // 0 表示上传失败,1 表示上传成功
+ message: "上传失败:#{ @attachment.errors.full_messages.join(',') }",
+ url: download_attachment_path(@attachment.id) # 上传成功时才返回
+ }
+ end
+
def upload_attachment_version
@flag = false
Attachment.transaction do
@@ -303,7 +371,7 @@ class AttachmentsController < ApplicationController
@attachment = Attachment.find(params[:attachments ].first[1][:attachment_id])
#将需要修改的记录保存到历史记录
@history = AttachmentHistory.new
- @history.attributes = @old_attachment.attributes.dup.except("id")
+ @history.attributes = @old_attachment.attributes.dup.except("id", "resource_bank_id")
@history.attachment_id = params[:old_attachment_id]
#需要更新版本号,需要拿到原来该文件最大的历史版本号
@old_history = @old_attachment.attachment_histories.reorder('version desc').first
@@ -706,6 +774,8 @@ class AttachmentsController < ApplicationController
elsif !@attachment.container.nil? && ((@attachment.container.has_attribute?(:board) || @attachment.container.has_attribute?(:board_id)) && @attachment.container.board &&
@attachment.container.board.contest)
@contest = @attachment.container.board.contest
+ elsif @attachment.container_type == 'Shixun'
+ @shixun
else
unless @attachment.container_type == 'Syllabus' || @attachment.container_type == 'Bid' || @attachment.container_type == 'Organization' || @attachment.container_type == 'HomeworkAttach' || @attachment.container_type == 'Memo' || @attachment.container_type == 'Softapplication' || @attachment.container_type == 'PhoneAppVersion' || @attachment.container_type == 'StudentWorksScore'|| @attachment.container_type == 'StudentWork' || @attachment.container_type == 'Work'|| @attachment.container_type == 'ContestantWork'|| @attachment.container_type == 'Contest' || @attachment.container_type == 'HomeworkBank'
@project = @attachment.project
diff --git a/app/controllers/avatar_controller.rb b/app/controllers/avatar_controller.rb
index 22f0ad84d..409fdc43f 100644
--- a/app/controllers/avatar_controller.rb
+++ b/app/controllers/avatar_controller.rb
@@ -1,3 +1,4 @@
+#encoding: utf-8
class AvatarController < ApplicationController
include ActionView::Helpers::NumberHelper
@@ -10,15 +11,32 @@ class AvatarController < ApplicationController
unless request.content_type == 'application/octet-stream'
@source_type = params[:source_type]
@source_id = params[:source_id]
- @temp_file = params[:avatar][:image]
- @image_file = @temp_file.original_filename
+ @temp_file = params[:img] || params[:avatar][:image]
+
+ if @temp_file.respond_to?(:original_filename)
+ @image_file = @temp_file.original_filename
+ #image_file.force_encoding("UTF-8") if filename.respond_to?(:force_encoding)
+ else
+ @image_file=params[:filename]
+ end
+
@is_direct = params[:is_direct]
+ @auth_type = params[:auth_type]
+
+
+ #base64转换
+ img_base64_head = 'data:image/jpeg;base64,'
+ if @temp_file && @temp_file.start_with?(img_base64_head)
+ @temp_file = StringIO.new(Base64.decode64(@temp_file[img_base64_head.size,@temp_file.size-img_base64_head.size]))
+ end
+
else
unless request.raw_post.nil?
@source_type = params[:source_type]
@source_id = params[:source_id]
@temp_file = request.raw_post
@is_direct = params[:is_direct]
+ @auth_type = params[:auth_type]
if @temp_file.size > 0
if @temp_file.respond_to?(:original_filename)
@image_file = @temp_file.original_filename
@@ -31,17 +49,26 @@ class AvatarController < ApplicationController
end
end
+
+
size = @temp_file.size
- if @temp_file && (@temp_file.size > 0)
+ if @temp_file && (@temp_file.size > 0)
if @temp_file.size > Setting.upload_avatar_max_size.to_i
@status = 1
@msg = l(:error_upload_avatar_to_large, :max_size => number_to_human_size(Setting.upload_avatar_max_size.to_i))
elsif Trustie::Utils::Image.new(@temp_file).image?
diskfile=disk_filename(@source_type,@source_id)
- @urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),avatar_filename(@source_id,@image_file))
+ if @source_type == 'UserAuthentication'
+ diskfile = disk_auth_filename('UserAuthentication', @source_id, @auth_type)
+ diskfile1 = diskfile + 'temp'
+ File.delete(diskfile1) if File.exist?(diskfile1)
+ @urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),auth_filename(@source_id,@auth_type))
+ else
+ @urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),avatar_filename(@source_id,@image_file))
+ end
# 用户头像上传时进行特别处理
- if @is_direct == '1' && (@source_type == 'User' || @source_type == 'Course' || @source_type == 'Project' || @source_type == 'Organization'|| @source_type == 'Contest')
+ if @is_direct == '1' && (@source_type == 'User' || @source_type == 'Course' || @source_type == 'Project' || @source_type == 'Organization'|| @source_type == 'Contest' || @source_type == 'UserAuthentication')
diskfile += "temp"
@urlfile += "temp"
end
@@ -66,7 +93,9 @@ class AvatarController < ApplicationController
end
end
- if @source_type == 'Contest'
+ if @source_type == 'UserAuthentication'
+
+ elsif @source_type == 'Contest'
Trustie::Utils::Image.new(diskfile,true).compress(900)
else
Trustie::Utils::Image.new(diskfile,true).compress(300)
@@ -76,19 +105,11 @@ class AvatarController < ApplicationController
else
@status = 2
@msg = l(:not_valid_image_file)
+ logger.error "上传失败: "+@msg
end
end
@temp_file = nil
- sleep(3)
-
- unless File.size(diskfile) < size
- logger.info("###############################################################sleep")
- sleep(0.5)
- end
-
- #@src_file = diskfile
-
respond_to do |format|
format.json{
render :inline => {status: @status, message:@msg, url:"#{@urlfile.to_s}?#{Time.now.to_i}"}.to_json,:content_type => 'text/html'
diff --git a/app/controllers/blog_comments_controller.rb b/app/controllers/blog_comments_controller.rb
index 88d4c4d53..6605170f1 100644
--- a/app/controllers/blog_comments_controller.rb
+++ b/app/controllers/blog_comments_controller.rb
@@ -43,6 +43,7 @@ class BlogCommentsController < ApplicationController
update_messsages_to_viewed("BlogMessage", params[:blog_id])
@article = BlogComment.find(params[:id])
+ update_visiti_count @article
@replies = BlogComment.where("root_id = #{@article.id}").reorder("created_on desc")
@reply_count = @replies.count
@replies = get_no_children_comments_all @replies
diff --git a/app/controllers/boards_controller.rb b/app/controllers/boards_controller.rb
index d1ef60a12..3d9f5a18a 100644
--- a/app/controllers/boards_controller.rb
+++ b/app/controllers/boards_controller.rb
@@ -19,9 +19,9 @@ class BoardsController < ApplicationController
layout 'base_projects'#by young
default_search_scope :messages
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]
+ 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
@@ -49,7 +49,7 @@ class BoardsController < ApplicationController
@boards = @course.boards.includes(:last_message => :author).all
if @course.boards.empty?
@board = @course.boards.build
- @board.name = " #{l(:label_borad_course) }"
+ @board.name = "#{l(:label_borad_course)}"
@board.description = @course.name.to_s
@board.project_id = -1
if @board.save
@@ -107,6 +107,8 @@ class BoardsController < ApplicationController
end
sort_name = "updated_on"
sort_type = @b_sort == 1 ? "asc" : "desc"
+ @q = params[:name]
+ q = "%#{@q}%"
# 讨论区消息状态更新(已读和未读)
if @project
@@ -122,7 +124,7 @@ class BoardsController < ApplicationController
# 'replies' => "#{Message.table_name}.replies_count",
# 'updated_on' => "COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on)"
- @is_new = params[:is_new]
+ # @is_new = params[:is_new]
@topic_count = @board ? @board.topics.count : 0
if @project
if @board
@@ -138,7 +140,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.where("#{Message.table_name}.subject like '#{q}'").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();
else
@topics = [];
end
@@ -146,7 +148,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 +158,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
@@ -182,6 +184,7 @@ class BoardsController < ApplicationController
@type = 1
end
+ @all_count = @topics.count
#分页
@limit = 15
@is_remote = true
@@ -260,6 +263,10 @@ class BoardsController < ApplicationController
board.project_id = -1
board.position = parent.children.count + 1
parent.children << board
+
+ @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
@@ -298,6 +305,11 @@ class BoardsController < ApplicationController
after_boards = @board.parent.children.where("position > #{@board.position}")
after_boards.update_all("position = position - 1")
@board.destroy
+
+ @course_board = @course.boards.where("parent_id is NULL").first
+ @board = @course_board.children.order("position asc")
+ @board_count = @board.count
+
if @course || @contest
respond_to do |format|
format.js
@@ -327,6 +339,29 @@ class BoardsController < ApplicationController
end
end
+ def update_boards_position
+ boards = @board.parent.children
+ if params[:opr] == 'up' && @board.position > 1
+ before_board = boards.where("position = #{@board.position - 1}").first
+ if before_board && @board.update_attribute('position', @board.position - 1)
+ before_board.update_attribute('position', before_board.position + 1)
+ end
+ elsif params[:opr] == 'down' && @board.position < boards.count
+ after_board = boards.where("position = #{@board.position + 1}").first
+ if after_board && @board.update_attribute('position', @board.position + 1)
+ after_board.update_attribute('position', after_board.position - 1)
+ end
+ end
+
+ @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
+ end
+
def update_name
if @course || @contest
@board.update_attribute("name", params[:name])
@@ -337,6 +372,19 @@ class BoardsController < ApplicationController
end
end
+ def update_boards_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
+
+ respond_to do |format|
+ format.js
+ end
+ end
+
def join_to_org_subfields
if params[:id]
@board = Board.find(params[:id])
@@ -347,7 +395,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 5c29976e4..375596075 100644
--- a/app/controllers/challenges_controller.rb
+++ b/app/controllers/challenges_controller.rb
@@ -1,17 +1,23 @@
# encoding: utf-8
class ChallengesController < ApplicationController
layout "base_shixun"
- before_filter :find_shixun, :only => [:index, :new, :create, :destroy, :challenge_build]
- before_filter :find_challenge, :only => [:show, :edit, :update, :challenge_build, :index_up, :index_down, :destroy]
+ before_filter :check_authentication
+ before_filter :find_shixun, :only => [:index, :new, :create, :destroy, :challenge_build, :update_evaluation, :add_choose_question, :new_choose_question, :choose_type_show, :edit_choose_question, :update_choose_question, :destroy_challenge_choose]
+ before_filter :find_challenge, :only => [:show, :edit, :update, :challenge_build, :index_up, :index_down, :destroy, :update_evaluation, :add_choose_question, :new_choose_question, :choose_type_show, :edit_choose_question, :update_choose_question, :destroy_challenge_choose]
before_filter :build_challege_from_params, :only => [:new, :create]
- before_filter :tpi_manager_allowed, :only => [:challenge_build, :destroy, :show, :edit, :new, :create]
- before_filter :query_challeges, :only => [:show, :edit, :update]
+ before_filter :tpi_manager_allowed, :only => [:challenge_build, :destroy, :edit, :new, :create]
+ before_filter :allowed_view, :only => [:show]
+ before_filter :query_challeges, :only => [:show, :edit, :update, :update_evaluation]
before_filter :find_shixun_language, :only => [:show, :new, :edit]
+ #before_filter :default_format_js, only: :new_or_edit_choose_question
+
+ #skip_before_filter :verify_authenticity_token, :only => [:new_or_edit_choose_question]
include ApplicationHelper
def new
# 顶部导航
+ @st = params[:st].to_i
@project_menu_type = 11
respond_to do |format|
format.html { render :action => 'new', :layout => 'base_shixun' }
@@ -19,43 +25,50 @@ class ChallengesController < ApplicationController
end
def create
- challenge_count = @shixun.challenges.count
- @challenge = Challenge.new(params[:challenge])
- @challenge.position = challenge_count + 1
- @challenge.shixun = @shixun
- @challenge.user = User.current
- if @challenge.save
- if params[:sample][:input].length > 0
- params[:sample][:input].each_with_index do |value, index|
- unless (value == params[:sample][:output][index] && value.blank?)
- ChallengeSample.create(:challenge_id => @challenge.id, :input => value, :output => params[:sample][:output][index])
+ ActiveRecord::Base.transaction do
+ begin
+ challenge_count = @shixun.challenges.count
+ @challenge = Challenge.new(params[:challenge])
+ @challenge.position = challenge_count + 1
+ @challenge.shixun = @shixun
+ @challenge.user = User.current
+ @challenge.st = params[:st].to_i
+ @challenge.save!
+=begin
+ if @challenge.save!
+ 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
- end
- if params[:program][:output].length > 0
- params[:program][:output].each do |output|
- TestSet.create(:challenge_id => @challenge.id, :input => nil, :output => output)
+=end
+ # 实训是否需要重启
+ # 非实践任务创建第一个阶段时调用 publishGame, 避免不包含实践任务的实训进行模拟实战时报错
+ if @challenge.position == 1 && params[:st].to_i != 0
+ add_shixun_modify_status @shixun, 1
+ else
+ shixun_modify_status_without_publish(@shixun, 1)
end
- end
- unless params[:knowledge].blank?
- params[:knowledge][:input].each do |input|
- ChallengeTag.create(:name => input, :challenge_id => @challenge.id)
- end
- end
- respond_to do |format|
- format.html {redirect_to shixun_challenge_path(@challenge, :shixun_id => @shixun), notice: '创建成功!'}
- end
- else
- respond_to do |format|
- format.html { render :action => 'new' }
+ 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, :st => params[:st].to_i)
+ raise ActiveRecord::Rollback
end
end
end
+ # 处理新建challenge返回的pipeline片段
+ def fragment_from_jenkins
+
+ end
+
def index
# 顶部导航
- @challenges = @shixun.challenges.order("position desc")
-
+ @challenges = @shixun.challenges.order("position asc")
respond_to do |format|
format.js
format.html
@@ -65,6 +78,12 @@ class ChallengesController < ApplicationController
end
def show
+ challenge_num = Challenge.where(:shixun_id => @shixun).count
+ challenge_pos = @challenge.position
+ if challenge_pos < challenge_num
+ @next_challenge = Challenge.where(:shixun_id => @shixun, :position => challenge_pos + 1).first
+ end
+ @prev_challenge = Challenge.where(:shixun_id => @shixun, :position => challenge_pos - 1).first if challenge_pos - 1 > 0
respond_to do |format|
format.html
format.js
@@ -72,56 +91,205 @@ class ChallengesController < ApplicationController
end
def edit
- end
-
- def destroy
- @challenge.destroy
+ @st = @challenge.st
+ challenge_num = Challenge.where(:shixun_id => @shixun).count
+ challenge_pos = @challenge.position
+ if challenge_pos < challenge_num
+ @next_challenge = Challenge.where(:shixun_id => @shixun, :position => challenge_pos+1).first
+ end
+ @prev_challenge = Challenge.where(:shixun_id => @shixun, :position => challenge_pos - 1).first if (challenge_pos - 1) > 0
+ @tab = params[:tab].blank? ? 1 : params[:tab].to_i
+ @editor = params[:editor] # 编辑模式
respond_to do |format|
- format.html{redirect_to shixun_challenges_path(@shixun)}
+ format.html
+ format.js
end
end
- def update
+ def new_choose_question
+ ActiveRecord::Base.transaction do
+ begin
+ @challenge_choose = ChallengeChoose.new
+ @challenge_choose.challenge_id = @challenge.id
+ @challenge_choose.subject = params[:choose][:subject]
+ @challenge_choose.answer = params[:choose][:answer]
+ @challenge_choose.standard_answer = params[:standard_answer]
+ @challenge_choose.score = params[:challenge][:score].to_i
+ @challenge_choose.difficult = params[:challenge][:difficulty].to_i
+ @challenge_choose.position = params[:position].to_i
+ @challenge_choose.category = params[:category].to_i
+ if @challenge_choose.save!
+ # 创建选项
+ params[:question][:cnt].each_with_index do |test, index|
+ answer = params[:choice][:answer][index] == "0" ? false : true
+ ChallengeQuestion.create(:option_name => test, :challenge_choose_id => @challenge_choose.id, :position => index, :right_key => answer)
+ end
+ # 创建单选多选的技能标签
+ unless params[:knowledge].blank?
+ params[:knowledge][:input].each do |input|
+ ChallengeTag.create(:name => input, :challenge_choose_id => @challenge_choose.id, :challenge_id => @challenge.id)
+ end
+ end
+ end
+ @index = params[:position].to_i - 1
+ # 发起重置请求
+ shixun_modify_status_without_publish(@shixun, 1)
+ respond_to do |format|
+ format.js
+ end
+ rescue Exception => e
+ flash[:error] = "#{e.message}"
+ redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun)
+ raise ActiveRecord::Rollback
+ end
+ end
+ end
+
+ def update_choose_question
+ @challenge_choose = ChallengeChoose.where(:id => params[:choose_id]).first
+ ActiveRecord::Base.transaction do
+ @challenge_choose.update_attributes(:subject => params[:choose][:subject],
+ :answer => params[:choose][:answer],
+ :standard_answer => params[:standard_answer],
+ :score => params[:challenge][:score].to_i,
+ :difficult => params[:challenge][:difficulty].to_i)
+ begin
+ @challenge_choose.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_choose_id => @challenge_choose.id, :position => index, :right_key => answer)
+ end
+ # 发起重置请求
+ shixun_modify_status_without_publish(@shixun, 1)
+ @challenge_choose.challenge_tags.delete_all unless @challenge_choose.challenge_tags.blank?
+ unless params[:knowledge].blank?
+ params[:knowledge][:input].each do |input|
+ ChallengeTag.create(:name => input, :challenge_choose_id => @challenge_choose.id, :challenge_id => @challenge.id)
+ end
+ end
+ @challenge_choose = ChallengeChoose.where(:id => params[:choose_id]).first
+ @index = params[:index].to_i
+ respond_to do |format|
+ format.js
+ end
+ rescue Exception => e
+ flash[:error] = "#{e.message}"
+ format.html{redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun)}
+ raise ActiveRecord::Rollback
+ end
+ end
+ end
+
+ def edit_choose_question
+ @challenge_choose = ChallengeChoose.where(:id => params[:choose_id]).first
+ @category = @challenge_choose.category
+ @position = @challenge_choose.position.to_i
+ @index = params[:index].to_i
respond_to do |format|
- if @challenge.update_attributes(params[:challenge])
- ActiveRecord::Base.transaction do
- @challenge_samples.delete_all unless @challenge_samples.blank?
+ format.js
+ end
+ end
+
+ def choose_type_show
+ @challenge_choose = ChallengeChoose.where(:id => params[:choose_id]).first
+ @index = params[:index].to_i
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def destroy_challenge_choose
+ @challenge_choose = ChallengeChoose.where(:id => params[:choose_id]).first
+ @challenge_choose.destroy
+ # 发起重置请求
+ shixun_modify_status_without_publish(@shixun, 1)
+ redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun)
+ end
+
+ def add_choose_question
+ @category = params[:category].to_i
+ @position = params[:position].to_i
+ #@challenge_choose = @challenge.challenge_chooses
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def destroy
+ next_challenges = @shixun.challenges.where("position > #{@challenge.position}")
+ next_challenges.update_all("position = position - 1")
+ @challenges = @shixun.challenges
+ add_shixun_modify_status(@shixun, 1)
+ @challenge.destroy
+ end
+
+ def update
+ ActiveRecord::Base.transaction do
+ @challenge.update_attributes(params[:challenge])
+ #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
+ #else
+ redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab])
+ #end
+ end
+ end
+
+ def update_evaluation
+ ActiveRecord::Base.transaction do
+ @challenge.update_attributes(params[:challenge])
+ begin
+ if params[:tab].to_i == 2
@test_sets.delete_all unless @test_sets.blank?
- @challenge_tags.delete_all unless @challenge_tags.blank?
- if params[:sample][:input].length > 0
- params[:sample][:input].each_with_index do |value, index|
- unless (value == params[:sample][:output][index] && value.blank?)
- ChallengeSample.create(:challenge_id => @challenge.id, :input => value, :output => params[:sample][:output][index])
+ 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
end
end
- if params[:program][:output].length > 0
- params[:program][:output].each do |output|
- TestSet.create(:challenge_id => @challenge.id, :input => nil, :output => output)
- end
- end
+ # 向jenkins端发送请求,构建公共测试用例
+ shixun_modify_status_publish(@shixun, 1)
+ elsif params[:tab].to_i == 5
+ @challenge_tags.delete_all unless @challenge_tags.blank?
unless params[:knowledge].blank?
params[:knowledge][:input].each do |input|
ChallengeTag.create(:name => input, :challenge_id => @challenge.id)
end
end
end
- format.html {redirect_to shixun_challenge_path(@challenge, :shixun_id => @shixun), notice: '更新成功!'}
- format.json { head :no_content }
- else
- format.html { render action: "edit" }
- format.json { render json: @challenge.errors }
+ if params[:tab].to_i == 5
+ redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab]), notice: 'Succeed'
+ else
+ redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab])
+ end
+ rescue Exception => e
+ flash[:error] = "#{e.message}"
+ redirect_to edit_shixun_challenge_path(@challenge, :shixun_id => @shixun, :tab => params[:tab])
+ raise ActiveRecord::Rollback
end
end
end
-
def index_down
next_challenge = @challenge.next_challenge
position = @challenge.position
@challenge.update_attribute(:position, (position + 1))
next_challenge.update_attribute(:position, next_challenge.position - 1)
@challenges = @shixun.challenges
+ # 向jenkins端发送请求,构建公共测试用例
+ add_shixun_modify_status(@shixun, 1)
end
def index_up
@@ -130,12 +298,14 @@ class ChallengesController < ApplicationController
@challenge.update_attribute(:position, (position - 1))
last_challenge.update_attribute(:position, last_challenge.position + 1)
@challenges = @shixun.challenges
+ # 向jenkins端发送请求,构建公共测试用例
+ add_shixun_modify_status(@shixun, 1)
end
# build job 只负责发送请求
def challenge_build
gitUrl = git_repository_url(@shixun, "Shixun")
- gitUrl = Base64.encode64(gitUrl)
+ gitUrl = Base64.urlsafe_encode64(gitUrl)
taskId = params[:id]
jobName = @shixun.forked_form
step = @challenge.position
@@ -168,6 +338,12 @@ class ChallengesController < ApplicationController
end
end
+ def allowed_view
+ unless (allow_to_view_challenge(@challenge, @shixun) || User.current.manager_of_shixun?(@shixun))
+ render_403
+ end
+ end
+
def build_challege_from_params
if params[:id].blank?
@challenge = Challenge.new
@@ -181,7 +357,6 @@ class ChallengesController < ApplicationController
end
def query_challeges
- @challenge_samples = @challenge.challenge_samples
@test_sets = @challenge.test_sets
@challenge_tags = @challenge.challenge_tags
end
@@ -196,7 +371,16 @@ class ChallengesController < ApplicationController
# Find project of id params[:id]
def find_shixun
shixun_id = params[:shixun_id] || (params[:challenge] && params[:challenge][:shixun_id])
- @shixun = Shixun.find(shixun_id)
+ @shixun = Shixun.find_by_identifier(shixun_id)
+ if @shixun.nil?
+ render_404
+ return
+ else
+ if (@shixun.status == 0 && !(User.current.manager_of_shixun?(@shixun) || User.current.admin?))
+ render_403
+ return
+ end
+ end
rescue ActiveRecord::RecordNotFound
render_404
end
@@ -206,4 +390,8 @@ class ChallengesController < ApplicationController
@language = language_switch language
end
+ def default_format_js
+ response.headers['content--type'] = 'text/javascript'
+ request.format = 'js'
+ end
end
diff --git a/app/controllers/courses_controller.rb b/app/controllers/courses_controller.rb
index a6937cf21..2fcb119fc 100644
--- a/app/controllers/courses_controller.rb
+++ b/app/controllers/courses_controller.rb
@@ -10,8 +10,11 @@ class CoursesController < ApplicationController
helper :files
helper :activity_notifys
include ApplicationHelper
+ helper SyllabusesHelper
before_filter :auth_login1, :only => [:show, :course_activity, :feedback]
+ skip_before_filter :verify_authenticity_token, :only => [:update_position]
+ before_filter :check_authentication, :except => [:update_position]
menu_item :overview
menu_item :feedback, :only => :feedback
menu_item :homework, :only => :homework
@@ -22,9 +25,9 @@ class CoursesController < ApplicationController
menu_item l(:label_sort_by_active), :only => :index
menu_item l(:label_sort_by_influence), :only => :index
- before_filter :can_show_course, :except => []
+ #before_filter :can_show_course, :except => []
before_filter :logged_user_by_apptoken,:only => [:show,:feedback]
- before_filter :find_course, :except => [ :index, :search, :new, :join, :unjoin, :create, :new_join, :course, :join_private_courses, :join_course_multi_role]
+ before_filter :find_course, :except => [ :index, :search, :new, :join, :unjoin, :create, :new_join, :course, :join_private_courses, :join_course_multi_role, :unjoin_group, :search_course_list]
before_filter :authorize_course, :only => [:show, :settings, :update, :course]
before_filter :authorize_course_global, :only => [:new,:create]
before_filter :toggleCourse, :only => [:finishcourse, :restartcourse]
@@ -32,6 +35,140 @@ class CoursesController < ApplicationController
before_filter :require_login, :only => [:join, :unjoin]
#before_filter :allow_join, :only => [:join]
+ require 'bundler/setup'
+ if RUBY_PLATFORM =~ /linux/
+ require 'simple_xlsx_reader'
+ end
+ # params[:search] 搜索课程的名称
+ # params[:select] "join" "create" "all" 参与的 创建的 所有的课程
+ #
+ def index
+ @user = User.current
+ @search = params[:search].nil? ? '' : params[:search]
+ @select = params[:select].nil? ? '' : params[:select]
+ @is_over = params[:is_over] # 是否是新建课程页面跳转的查看归档
+ @syllabuses_num = Course.all.count
+ #@syllabus_count = all_syllabuses.count
+ # 我创建的课堂
+ #create_syllabuses = Course.where(:tea_id => @user.id)
+ # 我参与的课堂
+ #join_syllabuses = @user.courses.where("is_delete = 0 and tea_id != #{@user.id}")
+ # @join_syllabuses_count = @user.courses.not_deleted_not_end.order("updated_at desc").select{ |course| !@user.has_teacher_role(course)}.count
+ # @create_syllabuses_count = @user.courses.not_deleted_not_end.order("updated_at desc").select{ |course| @user.has_teacher_role(course)}.count
+ @my_courses_count = @user.courses.not_deleted_not_end.count
+
+ # 页面筛选的课程
+ if @select == "create"
+ @syllabuses = @user.courses.not_deleted_not_end.where("name like '%#{@search}%'").order("updated_at desc").select{ |course| @user.has_teacher_role(course)}
+ elsif @select == "join"
+ @syllabuses = @user.courses.not_deleted_not_end.where("name like '%#{@search}%'").order("updated_at desc").select{ |course| !@user.has_teacher_role(course)}
+ elsif @select == "end"
+ # 归档的课堂
+ end_syllabuses = Course.where("is_end = 1 and name like '%#{@search}%'")
+
+ @syllabuses = end_syllabuses
+ else
+ # 全部课堂
+ all_syllabuses = Course.where("is_end = 0 and is_delete = 0 and name like '%#{@search}%'")
+ @syllabuses = all_syllabuses
+ end
+
+ @syllabuses.each do |course|
+ course[:infocount] = course.members.count
+ #course[:infocount] = (User.current.admin? || User.current.allowed_to?(:as_teacher,course)) ? (course.homework_commons.count + visable_attachemnts_incourse(course).count + course.members.count) : (course.homework_commons.where("publish_time <= '#{Time.now}'").count + visable_attachemnts_incourse(course).count + course.members.count)
+ if course[:infocount] < 0
+ course[:infocount] = 0
+ end
+ end
+ @syllabuses = @syllabuses.sort{|x,y| y[:infocount] <=> x[:infocount] }
+
+ @syllabuses_count = @syllabuses.count
+ @limit = 16
+ @is_remote = true
+ @syllabuses_pages = Paginator.new @syllabuses_count, @limit, params['page'] || 1
+ @offset ||= @syllabuses_pages.offset
+ @syllabuses = paginateHelper @syllabuses, @limit
+ respond_to do |format|
+ format.js
+ format.html { render :layout => "base_edu" }
+ end
+ end
+
+ def import_excel
+ attachments = params[:attachments]
+ attachments.each do |attachment|
+ attachment = Attachment.find_by_token_only(attachment[1]['token'])
+ attachment.container_id = @course.id
+ attachment.container_type = "ImportStudent"
+ attachment.save
+ end
+ @import_attachments = Attachment.where(:container_id => @course.id, :container_type => "ImportStudent")
+ end
+
+ def shixun_statistics
+ @homeworks = @course.homework_commons.where("homework_type = 4 and publish_time < '#{Time.now}'").order("publish_time desc")
+ filename="#{format_date(Time.now)}_#{@course.teacher.show_real_name.to_s}_#{@course.name}_实训数据报告";
+
+ respond_to do |format|
+ format.xls {
+ send_data(shixun_xls(@homeworks,@course), :type => 'application/octet-stream', :filename => filename_for_content_disposition("#{filename}.xls"))
+ }
+ end
+ end
+
+ # REDO:性能需要优化,这块是管理员后台任务,不影响用户使用
+ def sync_students
+ school_id = User.find(@course.tea_id).try(:user_extensions).try(:school_id)
+ @import_attachments = Attachment.where(:container_id => @course.id, :container_type => "ImportStudent")
+ @had_import_count = 0
+ @list_count = 0
+ if @import_attachments.present?
+ @import_attachments.each do |attachment|
+ path = attachment.disk_directory
+ name = attachment.disk_filename
+ if name.split(".").last == "xls" || name.split(".").last == "xlsx"
+ lists = readData("files/#{path}/#{name}")
+ @list_count += lists.count
+ lists.each do |list|
+ logger.info("#{list[0]}---#{list[1]}")
+ user = User.find_by_sql("SELECT u.* FROM `users` u, `user_extensions` ue where u.id = ue.user_id and CONCAT(u.lastname,u.firstname) ='#{list[1]}' and ue.school_id='#{school_id}' and ue.student_id='#{list[0]}'").first
+ # 用户存在并且用户是非课程成员
+ if user.present? && Member.where(:course_id => @course, :user_id => user.id).blank?
+ members = []
+ members << Member.new(:role_ids => [10], :user_id => user.id)
+ @course.members << members
+ StudentsForCourse.create(:student_id => user.id, :course_id => @course.id)
+ @had_import_count += 1
+ end
+ end
+ end
+ end
+ end
+ @members = @course.members.joins("join user_extensions on members.user_id = user_extensions.user_id").order("student_id asc").select{|m| m.roles.to_s.include?("Student")}
+ @member_count = @members.count
+ @limit = 20
+ @is_remote = true
+ @page = (params['page'] || 1).to_i
+ @member_pages = Paginator.new @member_count, @limit, params['page'] || 1
+ @offset ||= @member_pages.offset
+ @members = paginateHelper @members,@limit
+
+ @teacher_count = TeacherAndAssistantCount @course
+ @student_count = studentCount(@course)
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
+ end
+
+ def readData(xlsx)
+ doc = SimpleXlsxReader.open(xlsx)
+ sheet = doc.sheets.first
+ sheet.rows.inject([]) { |l, row|
+ if row.size >= 3 && row[1] && row[2]
+ l << [row[1], row[2]]
+ else
+ l
+ end
+ }
+ end
# 邀请码停用/启用
def set_invite_code_halt
@@ -96,6 +233,16 @@ class CoursesController < ApplicationController
join = cs.join_course_roles params,@user
@state = join[:state]
@course = join[:course]
+ if @state == 6
+ # 给课堂老师发留言
+ if params[:role].include?("7") || params[:role].include?("9")
+ notes = @user.show_real_name.to_s + " 申请以#{params[:role].include?('7') ? '教辅' : '教师'}的身份加入班级:#{@course.name} "
+ @course.course_teachers.each do |mem|
+ user = mem.user
+ user.journals_for_messages << JournalsForMessage.new(:user_id => @user.id, :notes => notes, :private => 1, :reply_id => 0)
+ end
+ end
+ end
else
@state = 5 #未登录
end
@@ -110,9 +257,7 @@ class CoursesController < ApplicationController
cs = CoursesService.new
cs.exit_course params,User.current
end
- respond_to do |format|
- format.js { render :partial => 'set_join', :locals => {:user => User.current, :course => Course.find(params[:object_id]), :object_id => params[:object_id]} }
- end
+ redirect_to user_path(User.current)
end
@@ -129,18 +274,18 @@ class CoursesController < ApplicationController
@course = c[:course]
if @course.errors.full_messages.count <= 0
respond_to do |format|
- format.html {
+ format.js {
# render :layout => 'base_courses'
- flash[:notice] = l(:notice_successful_update)
- redirect_to settings_course_url(@course)
+ #flash[:notice] = l(:notice_successful_update)
+ #redirect_to settings_course_url(@course)
}
format.api { render_api_ok }
end
else
respond_to do |format|
- format.html {
- settings
- redirect_to settings_course_url(@course)
+ format.js {
+ # settings
+ # redirect_to settings_course_url(@course)
}
format.api { render_validation_errors(@course) }
end
@@ -214,28 +359,23 @@ class CoursesController < ApplicationController
end
def addgroups
+ data = {:result=>1}
@subPage_title = l :label_student_list
if params[:group_name]
- group = CourseGroup.new
- group.name = params[:group_name]
- group.course_id = @course.id
- group.save
+ if @course.course_groups.where(:name => params[:group_name]).count > 0
+ data[:result] = 0
+ else
+ group = CourseGroup.new
+ group.name = params[:group_name]
+ group.course_id = @course.id
+ group.save
+ end
end
- @sort_type = 'score'
- @score_sort_by = "desc"
- @canShowCode = User.current.allowed_to?(:as_teacher,@course) && params[:role] != '1'
- @is_remote = true
- @members = student_homework_score(0,0, 10,@score_sort_by)
- @course_groups = @course.course_groups
- @limit = 50
- @page = params[:page].nil? ? 1 : params['page'].to_i
- @members_count = @members.count
- @no_group_count = @members_count - @course.members.where("course_group_id != 0").count
- @mem_pages = Paginator.new @members_count, @limit, @page
- @members = paginateHelper @members, @limit
+ render :json => data
end
def deletegroup
+ data = {:result=>1}
group = CourseGroup.find params[:group_id]
if group
if group.members.count == 0
@@ -245,38 +385,26 @@ class CoursesController < ApplicationController
CourseGroup.delete(params[:group_id])
end
end
- @subPage_title = l :label_student_list
- @canShowCode = isCourseTeacher(User.current.id,@course) && params[:role] != '1'
- @is_remote = true
- @sort_type = 'score'
- @score_sort_by = "desc"
- @members = student_homework_score(0,0, 10,@score_sort_by)
- @course_groups = @course.course_groups
- @limit = 50
- @page = params[:page].nil? ? 1 : params['page'].to_i
- @members_count = @members.count
- @no_group_count = @members_count - @course.members.where("course_group_id != 0").count
- @mem_pages = Paginator.new @members_count, @limit, @page
- @members = paginateHelper @members, @limit
+ render :json => data
end
def updategroupname
+ data = {:result=>1}
@subPage_title = l :label_student_list
- if params[:group_name]
+ if params[:group_name] && params[:group_id]
group = CourseGroup.find(params[:group_id])
- group.name = params[:group_name]
- group.save
+ if @course.course_groups.where("name = '#{params[:group_name]}' and id != #{params[:group_id]}").count > 0
+ data[:result] = 0
+ else
+ group.name = params[:group_name]
+ group.save
+ end
end
- @canShowCode = isCourseTeacher(User.current.id,@course) && params[:role] != '1'
- @is_remote = true
- @members = student_homework_score(0,0, 10,"desc")
- @course_groups = @course.course_groups
- @limit = 50
- @page = params[:page].nil? ? 1 : params['page'].to_i
- @members_count = @members.count
- @no_group_count = @members_count - @course.members.where("course_group_id != 0").count
- @mem_pages = Paginator.new @members_count, @limit, @page
- @members = paginateHelper @members, @limit
+ render :json => data
+ end
+
+ def choose_group_allow
+ @course.update_attributes(:choose_group_allow => !@course.choose_group_allow)
end
# 显示/隐藏课程"开源检索"的入口
@@ -317,33 +445,55 @@ class CoursesController < ApplicationController
render :json => req
end
- def teacher_assign_group
- @member = Member.where(:course_id => @course.id, :user_id => params[:user_id]).first
- @member.course_group_id = params[:course_group_id].to_i
- @member.save
- if params[:group_id] != "0"
- if params[:group_id] == "-1"
- @group = "-1"
- else
- @group = CourseGroup.find params[:group_id]
+ def delete_course_students
+ if params[:member_ids]
+ params[:member_ids].split(",").each do |member_id|
+ member = Member.find member_id
+ if member
+ if member.member_roles.count == 1
+ joined = StudentsForCourse.where('student_id = ? and course_id = ?', member.user_id,@course.id).destroy_all
+ member.destroy
+ else
+ member.member_roles.where("role_id = 10").destroy_all
+ joined = StudentsForCourse.where('student_id = ? and course_id = ?', member.user_id,@course.id).destroy_all
+ member.update_attributes(:course_group_id => 0)
+ if params[:group_id] == '0'
+ members = @course.members.select{|m| m.roles.to_s.include?("Student")}
+ else
+ members = @course.members.where("course_group_id = 0").select{|m| m.roles.to_s.include?("Student")}
+ end
+ member.member_roles.where("role_id = 7 or role_id = 9").first.update_attributes(:is_current => 1)
+ end
+ end
end
- # results = student_homework_score(@group.id,0,0,"desc")
- # @limit = 50
- # @page = params[:page].nil? ? 1 : params['page'].to_i
- # @members_count = results.count
- # @mem_pages = Paginator.new @members_count, @limit, @page
- # @results = paginateHelper results, @limit
end
- @course_groups = @course.course_groups
- @no_group_count = @course.student.count - @course.members.where("course_group_id != 0").count
- @canShowCode = isCourseTeacher(User.current.id,@course)
+ @group = @course.course_groups.where(:id => params[:group_id].to_i).first if params[:group_id]
+ @teacher_count = searchTeacherAndAssistant(@course).count
+ @student_count = @course.student.count
+ @no_group_count = @course.members.where("course_group_id = 0").select{|m| m.roles.to_s.include?("Student")}.count
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def teacher_assign_group
+ @group = @course.course_groups.where(:id => params[:course_group_id].to_i).first
+ if params[:member_ids] && @group
+ params[:member_ids].each do |member_id|
+ member = Member.find member_id
+ member.update_attributes(:course_group_id => params[:course_group_id].to_i) if member
+ end
+ end
+ @teacher_count = searchTeacherAndAssistant(@course).count
+ @student_count = @course.student.count
+ @no_group_count = @course.members.where("course_group_id = 0").select{|m| m.roles.to_s.include?("Student")}.count
respond_to do |format|
format.js
end
end
def join_group
- group = CourseGroup.find(params[:object_id])
+ group = CourseGroup.find(params[:group_id])
member = Member.where(:course_id => @course.id, :user_id => User.current.id).first
member.course_group_id = group.id
member.save
@@ -351,7 +501,7 @@ class CoursesController < ApplicationController
#@course_groups = @course.course_groups
#@no_group_count = @course.student.count - @course.members.where("course_group_id != 0").count
- redirect_to group_member_course_path(@course, :group_id => @group.id)
+ redirect_to has_group_student_list_course_path(@course, :group_id => @group.id)
#search_group_members group
end
@@ -377,6 +527,178 @@ class CoursesController < ApplicationController
end
end
+ def all_student_list
+ @order, @r_sort = params[:order] || "student_id", params[:sort] || "asc"
+ @sort = @r_sort == "desc" ? "asc" : "desc"
+
+ @search = params[:search]
+ q = params[:search] ? "#{params[:search].strip}" : ""
+ # if @order == "student_id"
+ # @members = @course.members.joins("join user_extensions on members.user_id = user_extensions.user_id").order("student_id #{@r_sort}").select{|m| m.roles.to_s.include?("Student")}
+ # else
+ # @members = @course.members.joins("join users on members.user_id = users.id").order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@r_sort}, login #{@r_sort}").select{|m| m.roles.to_s.include?("Student")}
+ # end
+ @members = Member.find_by_sql("SELECT members.*,(
+ SELECT SUM(student_works.work_score)
+ FROM student_works,homework_commons
+ WHERE student_works.homework_common_id = homework_commons.id
+ AND homework_commons.homework_type in (1, 4)
+ AND homework_commons.course_id = #{@course.id}
+ AND student_works.user_id = members.user_id
+ ) AS score FROM members
+ JOIN students_for_courses
+ ON students_for_courses.student_id = members.user_id AND students_for_courses.course_id = members.course_id
+ WHERE members.course_id = #{@course.id} ORDER BY score desc")
+ if q.nil? || q == ""
+ else
+ members = []
+ @members.each do |m|
+ username = m.user[:lastname].to_s.downcase + m.user[:firstname].to_s.downcase
+ if m && m.user && (m.user.user_extensions[:student_id].to_s.downcase.include?(q) || username.include?(q))
+ members << m
+ end
+ end
+ @members = members
+ end
+ #分页
+ @member_count = @members.count
+ @all_member_ids = @members.map(&:id).join(",")
+ @limit = 20
+ @is_remote = true
+ @page = (params['page'] || 1).to_i
+ @member_pages = Paginator.new @member_count, @limit, params['page'] || 1
+ @offset ||= @member_pages.offset
+ @members = paginateHelper @members,@limit
+
+ @teacher_count = TeacherAndAssistantCount @course
+ @student_count = studentCount(@course)
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
+ @import_attachments = Attachment.where(:container_id => @course.id, :container_type => "ImportStudent") # 统计上传的Excel数量
+ @left_nav_type = 8
+ respond_to do |format|
+ format.js
+ format.html{render :layout => 'base_courses'}
+ end
+ end
+
+ def no_group_student_list
+ @order, @r_sort = params[:order] || "student_id", params[:sort] || "asc"
+ @sort = @r_sort == "desc" ? "asc" : "desc"
+
+ @search = params[:search]
+ q = params[:search] ? "#{params[:search].strip}" : ""
+ @members = Member.find_by_sql("SELECT members.*,(
+ SELECT SUM(student_works.work_score)
+ FROM student_works,homework_commons
+ WHERE student_works.homework_common_id = homework_commons.id
+ AND homework_commons.homework_type in (1, 4)
+ AND homework_commons.course_id = #{@course.id}
+ AND student_works.user_id = members.user_id
+ ) AS score FROM members
+ JOIN students_for_courses
+ ON students_for_courses.student_id = members.user_id AND students_for_courses.course_id = members.course_id
+ WHERE members.course_id = #{@course.id} AND members.course_group_id = 0 ORDER BY score desc")
+ # if @order == "student_id"
+ # @members = @course.members.where(:course_group_id => 0).joins("join user_extensions on members.user_id = user_extensions.user_id").order("student_id #{@sort}").select{|m| m.roles.to_s.include?("Student")}
+ # else
+ # @members = @course.members.where(:course_group_id => 0).joins("join users on members.user_id = users.id").order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@sort}, login #{@b_sort}").select{|m| m.roles.to_s.include?("Student")}
+ # end
+ if q.nil? || q == ""
+ else
+ members = []
+ @members.each do |m|
+ username = m.user[:lastname].to_s.downcase + m.user[:firstname].to_s.downcase
+ if m && m.user && (m.user.user_extensions[:student_id].to_s.downcase.include?(q) || username.include?(q))
+ members << m
+ end
+ end
+ @members = members
+ end
+ #分页
+ @member_count = @members.count
+ @all_member_ids = @members.map(&:id).join(",")
+ @limit = 20
+ @is_remote = true
+ @page = (params['page'] || 1).to_i
+ @member_pages = Paginator.new @member_count, @limit, params['page'] || 1
+ @offset ||= @member_pages.offset
+ @members = paginateHelper @members,@limit
+
+ @teacher_count = TeacherAndAssistantCount @course
+ @student_count = studentCount(@course)
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
+ @left_nav_type = 9
+ respond_to do |format|
+ format.js
+ format.html{render :layout => 'base_courses'}
+ end
+ end
+
+ def has_group_student_list
+ #@order, @r_sort = params[:order] || "student_id", params[:sort] || "asc"
+ #@sort = @r_sort == "desc" ? "asc" : "desc"
+
+ @search = params[:search]
+ q = params[:search] ? "#{params[:search].strip}" : ""
+ @group = @course.course_groups.find params[:group_id]
+ @members = Member.find_by_sql("SELECT members.*,(
+ SELECT SUM(student_works.work_score)
+ FROM student_works,homework_commons
+ WHERE student_works.homework_common_id = homework_commons.id
+ AND homework_commons.homework_type in (1, 4)
+ AND homework_commons.course_id = #{@course.id}
+ AND student_works.user_id = members.user_id
+ ) AS score FROM members
+ JOIN students_for_courses
+ ON students_for_courses.student_id = members.user_id AND students_for_courses.course_id = members.course_id
+ WHERE members.course_id = #{@course.id} AND members.course_group_id = #{@group.id} ORDER BY score desc")
+ # if @order == "student_id"
+ # @members = @course.members.where(:course_group_id => @group.id).joins("join user_extensions on members.user_id = user_extensions.user_id").select{|m| m.roles.to_s.include?("Student")}.reorder("student_id #{@sort}")
+ # else
+ # @members = @course.members.where(:course_group_id => @group.id).joins("join users on members.user_id = users.id").select{|m| m.roles.to_s.include?("Student")}.reorder("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@sort}, login #{@b_sort}")
+ # end
+ if q.nil? || q == ""
+ else
+ members = []
+ @members.each do |m|
+ username = m.user[:lastname].to_s.downcase + m.user[:firstname].to_s.downcase
+ if m && m.user && (m.user.user_extensions[:student_id].to_s.downcase.include?(q) || username.include?(q))
+ members << m
+ end
+ end
+ @members = members
+ end
+
+ #分页
+ @member_count = @members.count
+ @all_member_ids = @members.map(&:id).join(",")
+ @limit = 20
+ @is_remote = true
+ @page = (params['page'] || 1).to_i
+ @member_pages = Paginator.new @member_count, @limit, params['page'] || 1
+ @offset ||= @member_pages.offset
+ @members = paginateHelper @members,@limit
+
+ @teacher_count = TeacherAndAssistantCount @course
+ @student_count = studentCount(@course)
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
+ @left_nav_type = 10
+
+ respond_to do |format|
+ format.js
+ format.html{render :layout => 'base_courses'}
+ end
+ end
+
+ def choose_course_group
+ @member_ids = params[:member_ids].split(",")
+ @type = params[:type]
+ @groups = @course.course_groups.order("name asc")
+ respond_to do |format|
+ format.js
+ end
+ end
+
def search_course_teacher_list
q = params[:search] ? "#{params[:search].strip}" : ""
@members = searchTeacherAndAssistantNoManager(@course)
@@ -431,17 +753,19 @@ class CoursesController < ApplicationController
end
def unjoin_group
- @subPage_title = l :label_student_list
- group = CourseGroup.find(params[:object_id])
- member = Member.where(:course_id => @course.id, :user_id => User.current.id).first
+ #@subPage_title = l :label_student_list
+ group = CourseGroup.find(params[:group_id])
+ member = Member.find params[:member]
+ @user = member.user
member.course_group_id = 0
member.save
@group = group
- @course_groups = @course.course_groups
- @no_group_count = @course.student.count - @course.members.where("course_group_id != 0").count
-
- search_group_members group
+ @course = @group.course
+ @teacher_count = searchTeacherAndAssistant(@course).count
+ @student_count = @course.student.count
+ @no_group_count = @course.members.where("course_group_id = 0").select{|m| m.roles.to_s.include?("Student")}.count
end
+
def searchgroupmembers
@subPage_title = l :label_student_list
@render_file = 'new_member_list'
@@ -461,7 +785,7 @@ class CoursesController < ApplicationController
page_from = params[:page].nil? ? 0 : (params[:page].to_i - 1)
@results = student_homework_score(0,page_from, 10,"desc")
end
- @no_group_count = @course.student.count - @course.members.where("course_group_id != 0").count
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
@course_groups = @course.course_groups
@limit = 50
@page = params[:page].nil? ? 1 : params['page'].to_i
@@ -493,48 +817,70 @@ class CoursesController < ApplicationController
end
def member
+ if User.current.member_of_course?(@course) || User.current.admin?
# 当前用户查看班级消息时,设置消息为已读
update_messsages_to_viewed("CourseMessage", @course)
## 有角色参数的才是课程,没有的就是项目
- if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course)))
- @render_file = 'new_member_list'
- @score_sort_by = "desc"
- @sort_type = params[:sort_type] ? params[:sort_type] : "score"
- @canShowCode = User.current.allowed_to?(:as_teacher,@course) && params[:role] != '1'
- @role = params[:role].nil? ? '2':params[:role]
- @is_remote = true
- @course_groups = @course.course_groups if @course.course_groups
- @show_serch = params[:role] == '2'
- @search_name = ""
- case @role
- when '1'
- @subPage_title = l :label_teacher_list
- @all_members = searchTeacherAndAssistant(@course)
- @members = @all_members
- when '2'
- if @course.open_student == 1 || User.current.member_of_course?(@course) || User.current.admin?
- @limit = 50
- @subPage_title = l :label_student_list
- @page = params[:page].nil? ? 1 : params['page'].to_i
- @all_members = student_homework_score(0, @page - 1, @limit, @score_sort_by, @sort_type)
- @members_count = @all_members.count
- @no_group_count = @members_count - @course.members.where("course_group_id != 0").count
- @mem_pages = Paginator.new @members_count, @limit, @page
- @members = paginateHelper @all_members, @limit
- @left_nav_type = 9
- else
- render_403
- return
- end
+ @order, @r_sort = params[:order] || "student_id", params[:sort] || "asc"
+ @sort = @r_sort == "desc" ? "asc" : "desc"
+
+ @search = params[:search]
+ q = params[:search] ? "#{params[:search].strip}" : ""
+ if params[:role] == 't'
+ @members = searchTeacherAndAssistant(@course)
+ elsif params[:role] == 'as'
+ if @order == "student_id"
+ @members = @course.members.joins("join user_extensions on members.user_id = user_extensions.user_id").order("student_id #{@sort}").select{|m| m.roles.to_s.include?("Student")}
+ else
+ @members = @course.members.joins("join users on members.user_id = users.id").order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@sort}, login #{@b_sort}").select{|m| m.roles.to_s.include?("Student")}
end
- respond_to do |format|
- if params[:page]
- format.html {render :layout => 'base_courses'}
- format.js
- else
- format.html {render :layout => 'base_courses'}
+ elsif params[:role] == 'ns'
+ if @order == "student_id"
+ @members = @course.members.where(:course_group_id => 0).joins("join user_extensions on members.user_id = user_extensions.user_id").order("student_id #{@sort}").select{|m| m.roles.to_s.include?("Student")}
+ else
+ @members = @course.members.where(:course_group_id => 0).joins("join users on members.user_id = users.id").order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@sort}, login #{@b_sort}").select{|m| m.roles.to_s.include?("Student")}
+ end
+ else
+ @group = @course.course_groups.find params[:role]
+ if @order == "student_id"
+ @members = @course.members.where(:course_group_id => @group.id).joins("join user_extensions on members.user_id = user_extensions.user_id").order("student_id #{@sort}").select{|m| m.roles.to_s.include?("Student")}
+ else
+ @members = @course.members.where(:course_group_id => @group.id).joins("join users on members.user_id = users.id").order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@sort}, login #{@b_sort}").select{|m| m.roles.to_s.include?("Student")}
+ end
+ end
+
+ if q.nil? || q == ""
+ else
+ members = []
+ @members.each do |m|
+ username = m.user[:lastname].to_s.downcase + m.user[:firstname].to_s.downcase
+ if m && m.user && (m.user.user_extensions[:student_id].to_s.downcase.include?(q) || username.include?(q))
+ members << m
end
end
+ @members = members
+ end
+ #分页
+ @member_count = @members.count
+ @limit = 20
+ @is_remote = true
+ @page = (params['page'] || 1).to_i
+ @member_pages = Paginator.new @member_count, @limit, params['page'] || 1
+ @offset ||= @member_pages.offset
+ @members = paginateHelper @members,@limit
+
+ @teacher_count = TeacherAndAssistantCount @course
+ @student_count = studentCount(@course)
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
+
+ respond_to do |format|
+ if @search
+ format.js
+ else
+ format.html {render :layout => 'base_edu'}
+ format.js
+ end
+ end
else
render_403
end
@@ -554,7 +900,7 @@ class CoursesController < ApplicationController
end
@homeworks = @course.homework_commons.where("publish_time <= '#{Time.now}'").order("created_at asc")
- filename="#{@course.teacher.lastname.to_s + @course.teacher.firstname.to_s }_#{@course.name}_#{@course.time.to_s + @course.term}#{l(:excel_member_list)}";
+ filename="#{@course.teacher.lastname.to_s + @course.teacher.firstname.to_s }_#{@course.name}_#{l(:excel_member_list)}";
respond_to do |format|
format.xls {
@@ -601,7 +947,7 @@ class CoursesController < ApplicationController
@limit = 50
@page = params[:page].nil? ? 1 : params['page'].to_i
@members_count = @results.count
- @no_group_count = @members_count - @course.members.where("course_group_id != 0").count
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
@mem_pages = Paginator.new @members_count, @limit, @page
@results = paginateHelper @results, @limit
end
@@ -647,7 +993,7 @@ class CoursesController < ApplicationController
CourseMessage.create(:user_id => member.user_id, :course_id => @course.id, :course_message_type => "RemoveFromCourse", :viewed => false, :course_message_id => User.current.id)
@course_groups = @course.course_groups
- @no_group_count = @course.student.count - @course.members.where("course_group_id != 0").count
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
@canShowCode = isCourseTeacher(User.current.id,@course)
respond_to do |format|
format.js
@@ -668,35 +1014,86 @@ class CoursesController < ApplicationController
end
def settings
- #添加成员消息状态
- join_course_messages = CourseMessage.where("user_id =? and course_message_type =? and course_id =? and status = ? and viewed =?", User.current.id, 'JoinCourse', @course.id, 1, 0)
- join_course_messages.update_all(:viewed => true)
-
if User.current.allowed_to?(:as_teacher,@course)
- @select_tab = params[:tab]
- @issue_custom_fields = IssueCustomField.sorted.all
- @issue_category ||= IssueCategory.new
- @member ||= @course.members.new
- @trackers = Tracker.sorted.all
-
- @roles = Role.givable.all[3..5]
- @members = @course.member_principals.includes(:roles, :principal).all.sort
-
- course_org_ids = OrgCourse.find_by_sql("select distinct organization_id from org_courses where course_id = #{@course.id}").map(&:organization_id)
- if course_org_ids.empty?
- @orgs_not_in_course = User.current.organizations
- else
- course_org_ids = "(" + course_org_ids.join(',') + ")"
- @orgs_not_in_course = User.current.organizations.where("organizations.id not in #{course_org_ids}")
+ course_module = @course.course_modules
+ if course_module.blank?
+ type = ["news", "boards", "homework", "exercises", "poll", "statistics", "attachment"]
+ for i in 0..6
+ CourseModule.create(:course_id => @course.id, :type => type[i], :position => i + 1, :hidden => 0 )
+ end
+ course_module = @course.course_modules
end
+ @curr_page = '设置'
respond_to do |format|
- format.html { render :layout => 'base_courses' }
+ format.html { render :layout => 'base_edu_course' }
format.api { render_validation_errors(@course) }
end
else
render_403
end
+ end
+ def members
+ #添加成员消息状态
+ join_course_messages = CourseMessage.where("user_id =? and course_message_type =? and course_id =? and status = ? and viewed =?", User.current.id, 'JoinCourse', @course.id, 1, 0)
+ join_course_messages.update_all(:viewed => true)
+
+ @member ||= @course.members.new
+ @role = params[:role] if params[:role]
+
+ @teachers = searchTeacherAndAssistant(@course)
+ @teacher_count = @teachers.count
+ @student_count = studentCount(@course)
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
+ @apply_users = CourseMessage.where(:course_id => @course.id,:course_message_type => 'JoinCourseRequest', :status => 0)
+
+ @curr_page = '成员管理'
+ respond_to do |format|
+ format.js
+ format.html { render :layout => 'base_edu_course' }
+ format.api { render_validation_errors(@course) }
+ end
+ end
+
+ def update_position
+
+ course_module = @course.course_modules
+
+ for i in 0..6
+ case params[:position][i]
+ when "boards"
+ course_module.where(:module_type => 'boards').first.update_attribute('position', i+1)
+ when "news"
+ course_module.where(:module_type => 'news').first.update_attribute('position', i+1)
+ when "homework"
+ course_module.where(:module_type => 'homework').first.update_attribute('position', i+1)
+ when "exercises"
+ course_module.where(:module_type => 'exercises').first.update_attribute('position', i+1)
+ when "poll"
+ course_module.where(:module_type => 'poll').first.update_attribute('position', i+1)
+ when "statistics"
+ course_module.where(:module_type => 'statistics').first.update_attribute('position', i+1)
+ when "attachment"
+ course_module.where(:module_type => 'attachment').first.update_attribute('position', i+1)
+ end
+ end
+
+ # params[:message] 有值 就更行字段: 0为不隐藏,1为隐藏
+ type = ["news", "boards", "attachment", "homework", "poll", "exercises", "statistics"]
+
+ hidden = type - params[:message]
+ course_module.where(:module_type => params[:message]).update_all(:hidden => 0)
+ course_module.where(:module_type => hidden).update_all(:hidden => 1)
+
+
+ @modules = @course.course_modules.order("position asc")
+ @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
end
def private_or_public
@@ -990,12 +1387,24 @@ class CoursesController < ApplicationController
@course.safe_attributes = params[:course]
@syllabus = Syllabus.where("id = #{params[:syllabus_id].to_i}").first if params[:syllabus_id]
# month = Time.now.month
- render :layout => 'new_base'
+ render :layout => 'base_edu'
else
redirect_to signin_url
end
end
+ def search_course_list
+ data = {courses: []}
+ search = params[:search] ? "%#{params[:search].strip}%" : "%%"
+ CourseList.where("name like '#{search}'").each do |course|
+ option = []
+ option << course.name.to_s
+ option << course.id
+ data[:courses] << option
+ end
+ render :json => data
+ end
+
def desc_sort_course_by_avtivity(activity_count, courses)
return courses if activity_count.size<2
(activity_count.size-2).downto(0) do |i|
@@ -1009,66 +1418,6 @@ class CoursesController < ApplicationController
return courses
end
- def index
- if !User.current.admin?
- render_404
- return
- end
- @course_type = params[:course_type]
- @school_id = params[:school_id]
- per_page_option = 10
- if @school_id == "0" || @school_id.nil?
- @courses_all = Course.active.visible.
- joins("LEFT JOIN #{CourseStatus.table_name} ON #{Course.table_name}.id = #{CourseStatus.table_name}.course_id")
- else
- @courses_all = Course.active.visible.
- joins("LEFT JOIN #{CourseStatus.table_name} ON #{Course.table_name}.id = #{CourseStatus.table_name}.course_id").
- where("#{Course.table_name}.school_id = ?", @school_id)
- end
- @course_count = @courses_all.count
- @course_pages = Paginator.new @course_count, per_page_option, params['page']
- @course_activity_count=Hash.new
- @courses_all.each do |course|
- @course_activity_count[course.id]=0
- end
- case params[:course_sort_type]
- when '0'
- @courses = @courses_all.order("created_at desc")
- @s_type = 0
- @courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page)
- @course_activity_count=get_course_activity @courses, @course_activity_count
- when '1'
- @courses = @courses_all.order("course_ac_para desc")
- @s_type = 1
- @courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page)
- @course_activity_count=get_course_activity @courses, @course_activity_count
- when '2'
- @courses = @courses_all.order("watchers_count desc")
- @s_type = 2
- @courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page)
- @course_activity_count=get_course_activity @courses, @course_activity_count
- when '3'
- @course_activity_count=get_course_activity @courses_all, @course_activity_count
- @courses=handle_course @courses_all, @course_activity_count
- @s_type = 3
- @courses = @courses[@course_pages.offset, @course_pages.per_page]
- else
- @s_type = 0
- @courses = @courses_all.order("created_at desc")
- @courses = @courses.offset(@course_pages.offset).limit(@course_pages.per_page)
- @course_activity_count=get_course_activity @courses, @course_activity_count
- end
-
- respond_to do |format|
- format.html {
- render :layout => 'base'
- }
- format.atom {
- courses = Course.visible.order('created_on DESC').limit(Setting.feeds_limit.to_i).all
- render_feed(courses, :title => "#{Setting.app_title}: #{l(:label_course_latest)}")
- }
- end
- end
def toggleCourse
@course_prefs = Course.find_by_extra(@course.extra)
@@ -1153,13 +1502,17 @@ 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
+ 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?
case params[:type]
- when "homework"
- @course_activities = course_activities.where("course_act_type = 'HomeworkCommon'").order('updated_at desc')
+ when "common_homework"
+ homework_ids = @course.homework_commons.where(:homework_type => 1)
+ @course_activities = course_activities.where(:course_act_type => 'HomeworkCommon', :course_act_id => homework_ids.map(&:id)).order('updated_at desc')
+ when "shixun_homework"
+ homework_ids = @course.homework_commons.where(:homework_type => 4)
+ @course_activities = course_activities.where(:course_act_type => 'HomeworkCommon', :course_act_id => homework_ids.map(&:id)).order('updated_at desc')
when "news"
@course_activities = course_activities.where("course_act_type = 'News'").order('updated_at desc')
when "message"
@@ -1181,6 +1534,7 @@ class CoursesController < ApplicationController
@type = params[:type]
@left_nav_type = 1
+ @show_page = true
respond_to do |format|
format.js
format.html{render :layout => 'base_courses'}
@@ -1238,6 +1592,7 @@ class CoursesController < ApplicationController
# 作业查重
def code_repeat
#代码查重新加的
+ @index = params[:index]
@order,@b_sort,@name,@group = params[:order] || "score",params[:sort] || "desc",params[:name] || "",params[:group]
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
@@ -1258,13 +1613,13 @@ class CoursesController < ApplicationController
puts tmpwork.id
end
- #respond_to do |format|
- #format.html {render :layout => 'base_courses'}
- #end
+ respond_to do |format|
+ format.html {render :layout => 'base_edu'}
+ end
end
def show_comparecode
-
+ @index = params[:index]
src_id = params[:src_id]
dst_id = params[:dst_id]
@@ -1295,7 +1650,7 @@ class CoursesController < ApplicationController
@dst_username = dst_user.try(:realname) != " " ? dst_user.lastname + dst_user.firstname : dst_user.try(:login)
respond_to do |format|
- format.js
+ format.html{render :layout => 'base_edu'}
end
end
@@ -1371,9 +1726,15 @@ class CoursesController < ApplicationController
#删除课程
#删除课程只是将课程的is_deleted状态改为false,is_deleted为false状态的课程只有管理员可以看到
def destroy
+ @course_id = @course.id
+ syllabus = @course.syllabus
@course.delete!
- @course = nil
- redirect_to user_url(User.current)
+ respond_to do |format|
+ format.js
+ format.html{redirect_to courses_path()}
+ end
+
+ # redirect_to :back
end
#归档班级
@@ -1472,6 +1833,54 @@ class CoursesController < ApplicationController
redirect_to course_path(@course)
end
+ def search_not_teachers
+ members = searchTeacherAndAssistant @course
+ member_ids = "(" + members.map(&:user_id).join(',') + ")"
+ condition = "%#{params[:search]}%".gsub(" ","")
+ @school = params[:school] || @course.teacher.school_name
+ if @school != ""
+ school_s = "%#{@school}%".gsub(" ","")
+ school_ids = School.where("name like '#{school_s}'").blank? ? "(-1)" : "(" + School.where("name like '#{school_s}'").map(&:id).join(",") + ")"
+ @users = User.joins(:user_extensions).where("users.id not in #{member_ids} and status = 1 and LOWER(concat(lastname, firstname)) LIKE '#{condition}' and user_extensions.school_id in #{school_ids}")
+ else
+ @users = User.where("id not in #{member_ids} and status = 1 and LOWER(concat(lastname, firstname)) LIKE '#{condition}'").includes(:user_extensions)
+ end
+
+ @user_ids = @users.map(&:id).join(",")
+ @limit = 8
+ @page = params[:page].nil? ? 1 : params['page'].to_i
+ @users_count = @users.count
+ @users_pages = Paginator.new @users_count, @limit, @page
+ @users = paginateHelper @users, @limit
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def search_not_students
+ members = @course.members.select{|m| m.roles.to_s.include?("Student")}
+ member_ids = members.empty? ? "(-1)" : "(" + members.map(&:user_id).join(',') + ")"
+ condition = "%#{params[:search]}%".gsub(" ","")
+ @school = params[:school] || @course.teacher.school_name
+ if @school != ""
+ school_s = "%#{@school}%".gsub(" ","")
+ school_ids = School.where("name like '#{school_s}'").blank? ? "(-1)" : "(" + School.where("name like '#{school_s}'").map(&:id).join(",") + ")"
+ @users = User.joins(:user_extensions).where("users.id not in #{member_ids} and status = 1 and user_extensions.school_id in #{school_ids} and (LOWER(concat(lastname, firstname)) LIKE '#{condition}' or user_extensions.student_id LIKE '#{condition}')")
+ else
+ @users = User.joins(:user_extensions).where("users.id not in #{member_ids} and status = 1 and (LOWER(concat(lastname, firstname)) LIKE '#{condition}' or user_extensions.student_id LIKE '#{condition}')")
+ end
+
+ @user_ids = @users.map(&:id).join(",")
+ @limit = 8
+ @page = params[:page].nil? ? 1 : params['page'].to_i
+ @users_count = @users.count
+ @users_pages = Paginator.new @users_count, @limit, @page
+ @users = paginateHelper @users, @limit
+ respond_to do |format|
+ format.js
+ end
+ end
+
private
def update_quotes attachment
if attachment.copy_from
@@ -1626,6 +2035,164 @@ class CoursesController < ApplicationController
@results = paginateHelper @results, @limit
end
+ def shixun_xls homeworks, course
+ xls_report = StringIO.new
+ book = Spreadsheet::Workbook.new
+ blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
+ black = Spreadsheet::Format.new :color => :black, :weight => :bold, :size => 10
+ current_row = 0
+ sheet = book.create_worksheet :name => "学员统计"
+ sheet.row(0).default_format = blue
+ sheet.row(0).concat(["学生id","学生姓名","作业编号","作业/实训名称","关卡"," 经验值","金币","评测历史","评测时间","评测结果"])
+ course.student.each_with_index do |course, i|
+ # 总统计
+ count_exp_score = 0
+ count_gold_score = 0
+ count_test = 0
+ count_time = 0
+ game_count = 0
+ # end
+ user = course.student
+ current_row += 1
+ sheet[current_row, 0] = user.login
+ sheet[current_row, 1] = user.show_real_name
+ homeworks.each_with_index do |homework, j|
+ # 关卡统计
+ count_game_exp_score = 0
+ count_game_gold_score = 0
+ count_game_test = 0
+ count_game_time = 0
+ # end
+ sheet[current_row, 2] = "# #{j + 1}"
+ sheet[current_row, 3] = homework.name
+ shixun = homework.homework_commons_shixuns.shixun if homework.homework_commons_shixuns
+ if shixun
+ shixun.challenges.each_with_index do |challenge, k|
+ sheet[current_row, 4] = "第#{k+1}关"
+ games = Game.where(:challenge_id => challenge.id, :user_id => user.id)
+ game_count = game_count + games.count
+ if games.count > 0
+ games.each do |game|
+ sheet[current_row, 5] = game.final_score ? "+#{game.final_score.to_s}" : "--"
+ sheet[current_row, 6] = game.final_score ? (game.answer_open? ? "#{-challenge.score.to_i}" : "+#{game.final_score.to_i}") : "--"
+ count_exp_score += (game.final_score ? game.final_score.to_i : 0)
+ count_gold_score += (game.final_score ? (game.answer_open? ? -challenge.score.to_i : game.final_score.to_i) : 0)
+ count_game_exp_score += (game.final_score ? game.final_score.to_i : 0)
+ count_game_gold_score += (game.final_score ? (game.answer_open? ? -challenge.score.to_i : game.final_score.to_i) : 0)
+ count = game.outputs.count
+ if count > 0
+ outputs = game.outputs.where(:test_set_position => 1).reorder("created_at asc")
+ outputs.each_with_index do |output, k|
+ count_test += 1
+ count_game_test += 1
+ sheet[current_row, 7] = "第#{k+1}次评测"
+ sheet[current_row, 8] = k == 0 ? game_spend_time((output.created_at - game.created_at).to_i) : game_spend_time((output.created_at - outputs[k-1].created_at).to_i)
+ count_time = count_time + (k == 0 ? (output.created_at - game.created_at).to_i : (output.created_at - outputs[k-1].created_at).to_i)
+ count_game_time += (k == 0 ? (output.created_at - game.created_at).to_i : (output.created_at - outputs[k-1].created_at).to_i)
+ sheet[current_row, 9] = game.outputs.where(:query_index => output.query_index).select{|ou| ou.result == false}.count > 0 ? "失败" : "成功"
+ current_row += 1
+ end
+ else
+ current_row += 1
+ end
+ end
+ else
+ current_row += 1
+ end
+ end
+ end
+ sheet[current_row,4] = "合计"
+ sheet[current_row,5] = count_game_exp_score >= 0 ? "+#{count_game_exp_score}" : "-#{count_game_exp_score}"
+ sheet[current_row,6] = count_game_gold_score >= 0 ? "+#{count_game_gold_score}" : "#{count_game_gold_score}"
+ sheet[current_row,7] = "共#{count_game_test}次评测"
+ sheet[current_row,8] = game_spend_time((count_game_time == 0 ? 0 : (count_game_time / count_test)).to_i)+"/次"
+ sheet.row(current_row).default_format = black
+ current_row += 1
+ end
+ sheet[current_row,2] = "合计"
+ sheet[current_row,4] = "共#{game_count}"
+ sheet[current_row,5] = count_exp_score >= 0 ? "+#{count_exp_score}" : "-#{count_exp_score}"
+ sheet[current_row,6] = count_gold_score >= 0 ? "+#{count_gold_score}" : "#{count_gold_score}"
+ sheet[current_row,7] = "共#{count_test}次评测"
+ sheet[current_row,8] = game_spend_time((count_time == 0 ? 0 : (count_time / count_test)).to_i)+"/次"
+ sheet.row(current_row).default_format = black
+ end
+
+ homeworks.each_with_index do |homework, i|
+ sheet = book.create_worksheet :name => "第#{i+1}次作业"
+ sheet.row(0).default_format = blue
+ sheet[0,0] = "课堂编号"
+ sheet[0,1] = "主讲老师"
+ sheet[0,2] = "课堂名称"
+ sheet[0,3] = "作业编号"
+ sheet[0,4] = "作业/实训名称"
+ sheet[0,5] = "关卡"
+ sheet[0,6] = "学生id"
+ sheet[0,7] = "学生姓名"
+ sheet[0,8] = "经验值"
+ sheet[0,9] = "金币"
+ sheet[0,10] = "评测历史"
+ sheet[0,11] = "评测时间"
+ sheet[0,12] = "评测结果"
+ sheet[1,0] = course.id
+ sheet[1,1] = course.teacher.show_real_name
+ sheet[1,2] = course.name
+ sheet[1,3] = "# #{i + 1}"
+ sheet[1,4] = homework.name
+ current_row = 1
+ shixun = homework.homework_commons_shixuns.shixun if homework.homework_commons_shixuns
+ if shixun
+ shixun.challenges.each_with_index do |challenge, j|
+ sheet[current_row,5] = "第#{j+1}关"
+ games = Game.where(:challenge_id => challenge.id, :user_id => homework.student_works.where("work_status != 0").map(&:user_id))
+ count_exp_score = 0
+ count_gold_score = 0
+ count_test = 0
+ count_time = 0
+ if games.count > 0
+ games.each do |game|
+ user = game.user
+ sheet[current_row,6] = user.login
+ sheet[current_row,7] = user.show_real_name
+ sheet[current_row,8] = game.final_score ? "+#{game.final_score.to_s}" : "--"
+ count_exp_score = count_exp_score + (game.final_score ? game.final_score.to_i : 0)
+ sheet[current_row,9] = game.final_score ? (game.answer_open? ? "#{-challenge.score.to_i}" : "+#{game.final_score.to_i}") : "--"
+ count_gold_score = count_gold_score + (game.final_score ? (game.answer_open? ? -challenge.score.to_i : game.final_score.to_i) : 0)
+
+ count = game.outputs.count
+ if count > 0
+ outputs = game.outputs.where(:test_set_position => 1).reorder("created_at asc")
+ outputs.each_with_index do |output, k|
+ count_test = count_test + 1
+ sheet[current_row,10] = "第#{k+1}次评测"
+ sheet[current_row,11] = k == 0 ? game_spend_time((output.created_at - game.created_at).to_i) : game_spend_time((output.created_at - outputs[k-1].created_at).to_i)
+ count_time = count_time + (k == 0 ? (output.created_at - game.created_at).to_i : (output.created_at - outputs[k-1].created_at).to_i)
+ sheet[current_row,12] = game.outputs.where(:query_index => output.query_index).select{|ou| ou.result == false}.count > 0 ? "失败" : "成功"
+ current_row = current_row + 1
+ end
+ else
+ current_row = current_row + 1
+ end
+ end
+ else
+ current_row = current_row + 1
+ end
+
+ sheet[current_row,6] = "合计"
+ sheet[current_row,7] = games.count.to_s + "人"
+ sheet[current_row,8] = count_exp_score >= 0 ? "+#{count_exp_score}" : "-#{count_exp_score}"
+ sheet[current_row,9] = count_gold_score >= 0 ? "+#{count_gold_score}" : "#{count_gold_score}"
+ sheet[current_row,10] = "共#{count_test}次评测"
+ sheet[current_row,11] = game_spend_time((count_time == 0 ? 0 : (count_time / count_test)).to_i)+"/次"
+ sheet.row(current_row).default_format = black
+ current_row = current_row + 1
+ end
+ end
+ end
+ book.write xls_report
+ xls_report.string
+ end
+
def member_to_xls homeworks, course, members,groups
xls_report = StringIO.new
book = Spreadsheet::Workbook.new
@@ -1634,32 +2201,30 @@ class CoursesController < ApplicationController
#sheet1.row(0).default_format = blue
#sheet1.row(0).concat([l(:excel_user_id),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_mail),l(:excel_class),l(:excel_f_score),l(:excel_commit_time)])
sheet1[0,0] = "课程编号"
- sheet1[0,1] = course.syllabus.id
+ sheet1[0,1] = course.course_list_id
sheet1[1,0] = "课程名称"
- sheet1[1,1] = course.syllabus.title
+ sheet1[1,1] = course.course_list_name
sheet1[2,0] = "班级编号"
sheet1[2,1] = course.id
- sheet1[3,0] = "班级学期"
- sheet1[3,1] = course.time.to_s+"年"+course.term
- sheet1[4,0] = "班级名称"
- sheet1[4,1] = course.name
- sheet1[5,0] = "教师团队"
- sheet1[5,1] = (searchTeacherAndAssistant course).map{|member| member.user.show_name}.join('、')
- sheet1[6,0] = "主讲教师"
- sheet1[6,1] = course.teacher.show_name
- sheet1[7,0] = "排名"
- sheet1[7,1] = "学生姓名"
- sheet1[7,2] = "昵称"
- sheet1[7,3] = "学号"
+ sheet1[3,0] = "班级名称"
+ sheet1[3,1] = course.name
+ sheet1[4,0] = "教师团队"
+ sheet1[4,1] = (searchTeacherAndAssistant course).map{|member| member.user.show_name}.join('、')
+ sheet1[5,0] = "主讲教师"
+ sheet1[5,1] = course.teacher.show_name
+ sheet1[6,0] = "排名"
+ sheet1[6,1] = "学生姓名"
+ sheet1[6,2] = "昵称"
+ sheet1[6,3] = "学号"
for i in 0 ... homeworks.count
- sheet1[7,i+4] = "第"+(i+1).to_s+"次"
+ sheet1[6,i+4] = "第"+(i+1).to_s+"次"
end
- sheet1[7,homeworks.count+4] = "作业得分"
- sheet1[7,homeworks.count+5] = "测评得分"
- sheet1[7,homeworks.count+6] = "社区得分"
- sheet1[7,homeworks.count+7] = "总得分"
- sheet1[7,homeworks.count+8] = "分班"
- count_row = 8
+ sheet1[6,homeworks.count+4] = "作业得分"
+ sheet1[6,homeworks.count+5] = "测评得分"
+ sheet1[6,homeworks.count+6] = "社区得分"
+ sheet1[6,homeworks.count+7] = "总得分"
+ sheet1[6,homeworks.count+8] = "分班"
+ count_row = 7
members.each_with_index do |member, i|
sheet1[count_row,0]= i+1
sheet1[count_row,1] = member.user.lastname.to_s + member.user.firstname.to_s
@@ -1689,32 +2254,30 @@ class CoursesController < ApplicationController
homeworks.each_with_index do |home, i|
sheet = book.create_worksheet :name => "第#{i+1}次作业"
sheet[0,0] = "课程编号"
- sheet[0,1] = course.syllabus.id
+ sheet[0,1] = course.course_list_id
sheet[1,0] = "课程名称"
- sheet[1,1] = course.syllabus.title
+ sheet[1,1] = course.course_list_name
sheet[2,0] = "班级编号"
sheet[2,1] = course.id
- sheet[3,0] = "班级学期"
- sheet[3,1] = course.time.to_s+"年"+course.term
- sheet[4,0] = "班级名称"
- sheet[4,1] = course.name
- sheet[5,0] = "教师团队"
- sheet[5,1] = (searchTeacherAndAssistant course).map{|member| member.user.show_name}.join('、')
- sheet[6,0] = "主讲教师"
- sheet[6,1] = course.teacher.show_name
- sheet[6,0] = "作业批次"
- sheet[6,1] = "第#{i+1}次作业"
- sheet[6,0] = "作业名称"
- sheet[6,1] = home.name
+ sheet[3,0] = "班级名称"
+ sheet[3,1] = course.name
+ sheet[4,0] = "教师团队"
+ sheet[4,1] = (searchTeacherAndAssistant course).map{|member| member.user.show_name}.join('、')
+ sheet[5,0] = "主讲教师"
+ sheet[5,1] = course.teacher.show_name
+ sheet[5,0] = "作业批次"
+ sheet[5,1] = "第#{i+1}次作业"
+ sheet[5,0] = "作业名称"
+ sheet[5,1] = home.name
if home.homework_type == 1 #普通作业
if home.anonymous_comment ==0
- sheet.row(7).concat([l(:excel_rank),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_homework_name),l(:excel_homework_des),
+ sheet.row(6).concat([l(:excel_rank),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_homework_name),l(:excel_homework_des),
l(:excel_t_score),l(:excel_ta_score), l(:excel_n_score),l(:excel_a_penalty),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
else
- sheet.row(7).concat([l(:excel_rank),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_homework_name),l(:excel_homework_des),
+ sheet.row(6).concat([l(:excel_rank),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_homework_name),l(:excel_homework_des),
l(:excel_t_score),l(:excel_ta_score),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
end
- count_row = 8
+ count_row = 7
items = home.student_works.order("work_score desc")
items.each_with_index do |stu, j|
sheet[count_row,0]= j + 1
@@ -1740,13 +2303,13 @@ class CoursesController < ApplicationController
end
elsif home.homework_type == 2 #编程作业
if home.anonymous_comment ==0
- sheet.row(7).concat([l(:excel_rank),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_homework_name),l(:excel_homework_des),
+ sheet.row(6).concat([l(:excel_rank),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_homework_name),l(:excel_homework_des),
l(:excel_t_score),l(:excel_ta_score), l(:excel_s_score),l(:excel_n_score),l(:excel_a_penalty),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
else
- sheet.row(7).concat([l(:excel_rank),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_homework_name),l(:excel_homework_des),
+ sheet.row(6).concat([l(:excel_rank),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_homework_name),l(:excel_homework_des),
l(:excel_t_score),l(:excel_ta_score), l(:excel_s_score),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
end
- count_row = 8
+ count_row = 7
items = home.student_works.order("work_score desc")
items.each_with_index do |stu, j|
sheet[count_row,0]= j + 1
@@ -1773,13 +2336,13 @@ class CoursesController < ApplicationController
end
elsif home.homework_type == 3 #分组作业
if home.anonymous_comment ==0
- sheet.row(7).concat([l(:excel_rank),l(:excel_group_member),l(:excel_homework_name),l(:excel_homework_project),l(:excel_homework_des),
+ sheet.row(6).concat([l(:excel_rank),l(:excel_group_member),l(:excel_homework_name),l(:excel_homework_project),l(:excel_homework_des),
l(:excel_t_score),l(:excel_ta_score),l(:excel_n_score),l(:excel_a_penalty),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
else
- sheet.row(7).concat([l(:excel_rank),l(:excel_group_member),l(:excel_homework_name),l(:excel_homework_project),l(:excel_homework_des),
+ sheet.row(6).concat([l(:excel_rank),l(:excel_group_member),l(:excel_homework_name),l(:excel_homework_project),l(:excel_homework_des),
l(:excel_t_score),l(:excel_ta_score),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
end
- count_row = 8
+ count_row = 7
items = home.student_works.order("work_score desc")
items.each_with_index do |stu, j|
sheet[count_row,0] = j + 1
diff --git a/app/controllers/debates_controller.rb b/app/controllers/debates_controller.rb
new file mode 100644
index 000000000..5e442e4bb
--- /dev/null
+++ b/app/controllers/debates_controller.rb
@@ -0,0 +1,2 @@
+class DebatesController < ApplicationController
+end
diff --git a/app/controllers/department_controller.rb b/app/controllers/department_controller.rb
new file mode 100644
index 000000000..4533a3ee6
--- /dev/null
+++ b/app/controllers/department_controller.rb
@@ -0,0 +1,120 @@
+class DepartmentController < ApplicationController
+
+ before_filter :find_department, :only => [:destroy]
+
+ #根据部门名字或者拼音来查询
+ def on_search
+ school = School.find params[:school_id]
+ if school
+ condition = "#{params[:name].strip}".gsub(" ","")
+ #获取拼音的第一次出现的位置
+
+ if(condition == '')
+ @departments = school.departments.order("CONVERT(name USING gbk) COLLATE gbk_chinese_ci asc").page((params[:page].to_i || 1) - 1).per(100)
+ @department_count = school.departments.count
+ else
+ @departments = school.departments.where("name like '%#{condition}%'").order("CONVERT(name USING gbk) COLLATE gbk_chinese_ci asc").page((params[:page].to_i || 1) - 1).per(100)
+ @department_count = school.departments.where("name like '%#{condition}%'").count
+ end
+
+ render :json =>{ :departments => @departments,:count=>@department_count}.to_json
+ end
+ end
+
+ #申请学院或部门(单位) name:名称 remarks:备注
+ def apply_add_department
+ school = School.find params[:school_id]
+
+ data = {result:0,name:params[:name],department_id:0}
+ #0 成功 1参数错误 2名称已存在 3.失败
+ data[:result] = 0
+
+ if school
+ #检验参数
+ if params[:name] == ""
+ data[:result] = 1
+ else
+ department = Department.where(:school_id => school.id, :name => params[:name]).first
+ if department
+ data[:result] = 2
+ else
+ department = Department.new
+ department.name = params[:name].strip
+ department.school = school
+
+ #status 0未处理 1通过 2拒绝
+ apply_department = ApplyAddDepartment.new
+
+ #用belongs_to 可以一起存数据库
+ apply_department.department = department
+ apply_department.school = department.school
+ apply_department.name = department.name
+ apply_department.status = 0
+ apply_department.remarks = params[:remarks]
+ apply_department.user_id = User.current.id
+ if apply_department.save
+ data[:department_id] = department.id
+ unless User.current.professional_certification
+ user_extention = User.current.extensions
+ user_extention.department_id = department.id
+ user_extention.save!
+ end
+
+ # 向管理员发送信息
+ 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 => apply_department.id, :applied_type => "ApplyAddDepartment", :name => department.name )
+ end
+
+ else
+ data[:result] = 3
+ end
+ end
+ end
+ else
+ data[:result] = 4
+ end
+
+ render :json =>data
+ end
+
+ def search_repeat_departmentname
+ status = 0 #没有重复的
+ name = params[:name]
+ school = School.where(:id => params[:school_id].to_i).first
+ if school
+ if name
+ department = school.departments.where(:name => name).first
+ if department
+ status = 1 #有重复的
+ else
+ status = 2 #无重复的
+ end
+ end
+ else
+ status = 0
+ end
+
+ render :json =>status
+ end
+
+ def destroy
+ if @department
+ # if UserExtensions.where(:department_id => @department.id).count == 0
+ ApplyAddDepartment.where(:department_id=>@department.id).update_all(:status => 2)
+ @apply_dep = ApplyAddDepartment.where(:department_id=>@department.id).first
+ @department.destroy
+ # end
+ respond_to do |format|
+ format.js
+ end
+ end
+ end
+
+ private
+ def find_department
+ @department = Department.find params[:id]
+ rescue ActiveRecord::RecordNotFound
+ render_404
+ end
+end
diff --git a/app/controllers/discusses_controller.rb b/app/controllers/discusses_controller.rb
new file mode 100644
index 000000000..e434eaef9
--- /dev/null
+++ b/app/controllers/discusses_controller.rb
@@ -0,0 +1,80 @@
+# encoding: utf-8
+class DiscussesController < ApplicationController
+ include ApplicationHelper
+ before_filter :find_dis_object, :except => [:destroy]
+ before_filter :find_discuss, :only => [:destroy]
+
+ def create
+ if @model
+ if params[:reply_id].blank?
+ notes = User.current.show_name.to_s + " 评论了你发布的实训:#{params[:content]} "
+ @model.discusses << Discuss.new(:content => params[:content], :user_id => User.current.id, :praise_count => 0, :challenge_id => params[:challenge_id])
+ JournalsForMessage.create(
+ :jour_id => @model.user_id,
+ :jour_type => "Principal",
+ :user_id => User.current.id,
+ :reply_id => 0,
+ :is_readed => 0,
+ :private => 1,
+ :notes => notes
+ )
+ else
+ notes = User.current.show_name.to_s + " 评论了你的回复:#{params[:content]} "
+ user_id = Discuss.find(params[:reply_id]).try(:user_id)
+ @model.discusses << Discuss.new(
+ :content => params[:content],
+ :user_id => User.current.id,
+ :parent_id => params[:reply_id],
+ :root_id => params[:reply_id],
+ :praise_count => 0,
+ :challenge_id => params[:challenge_id]
+ )
+ JournalsForMessage.create(
+ :jour_id => user_id,
+ :jour_type => "Principal",
+ :user_id => User.current.id,
+ :reply_id => 0,
+ :is_readed => 0,
+ :private => 1,
+ :notes => notes
+ )
+ end
+
+
+ if params[:dis_type] == "Shixun"
+ redirect_to shixun_discuss_shixun_path(@model, :challenge_id => params[:challenge_id])
+ end
+ end
+ end
+
+ def destroy
+ if @discuss
+ if @discuss.dis_type == "Shixun"
+ @shixun = @discuss.dis
+ end
+ @discuss.destroy
+ @game_challenge = Challenge.find(params[:challenge_id])
+ end
+ end
+
+ private
+
+ def find_discuss
+ @discuss = Discuss.find params[:id]
+ rescue ActiveRecord::RecordNotFound
+ render_404
+ end
+
+ def find_dis_object
+ unless params[:dis_id] && params[:dis_type]
+ render_404
+ else
+ case params[:dis_type]
+ when 'Shixun'
+ @model = Shixun.find params[:dis_id]
+ end
+ end
+ rescue ActiveRecord::RecordNotFound
+ render_404
+ end
+end
diff --git a/app/controllers/exercise_controller.rb b/app/controllers/exercise_controller.rb
index 4c6023265..317e6cde5 100644
--- a/app/controllers/exercise_controller.rb
+++ b/app/controllers/exercise_controller.rb
@@ -1,115 +1,109 @@
+#encoding: utf-8
class ExerciseController < ApplicationController
layout "base_courses"
before_filter :find_exercise_and_course, :only => [:create_exercise_question, :edit, :update, :show, :destroy,
:commit_exercise, :commit_answer,:publish_exercise,:republish_exercise,
:show_student_result,:student_exercise_list, :update_question_num,
- :send_to_course, :get_student_uncomplete_question, :edit_question_score]
+ :send_to_course, :get_student_uncomplete_question, :edit_question_score, :setting, :set_public,
+ :ex_setting]
before_filter :find_course, :only => [:index,:new,:create]
include ExerciseHelper
def index
- publish_exercises = Exercise.where("publish_time is not null and exercise_status = 1 and publish_time <=?",Time.now)
- publish_exercises.each do |exercise|
- exercise.update_column('exercise_status', 2)
- course = exercise.course
- course.members.each do |m|
- exercise.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => 2)
- end
- end
-
if @course.is_public == 0 && !(User.current.member_of_course?(@course)||User.current.admin?)
render_403
return
end
- remove_invalid_exercise(@course)
- @is_teacher = User.current.allowed_to?(:as_teacher,@course)
- if @is_teacher || User.current.admin?
- exercises = @course.exercises.order("created_at asc")
+ #remove_invalid_exercise(@course)
+ @is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
+ if @is_teacher
+ exercises = @course.exercises.order("created_at desc")
else
- exercises = @course.exercises.where("exercise_status <> 1").order("created_at asc")
+ exercises = @course.exercises.where("exercise_status <> 1").order("created_at desc")
end
- @exercises = paginateHelper exercises,20 #分页
- @left_nav_type = 8
+ if params[:type]
+ @type = params[:type]
+ exercises = exercises.where(:exercise_status => params[:type])
+ end
+ @search = params[:search] ? params[:search].to_s.strip : ""
+ if params[:search]
+ exercises = exercises.where("exercise_name like '%#{@search}%'")
+ end
+ @exercises = paginateHelper exercises,15 #分页
+ @left_nav_type = 4
respond_to do |format|
+ format.js
format.html
end
end
def show
- publish_exercises = Exercise.where("publish_time is not null and exercise_status = 1 and publish_time <=?",Time.now)
- publish_exercises.each do |exercise|
- exercise.update_column('exercise_status', 2)
- course = exercise.course
- course.members.each do |m|
- exercise.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => course.id, :viewed => false, :status => 2)
- end
- end
-
unless User.current.member_of_course?(@course) || User.current.admin?
render_403
return
end
- @exercise = Exercise.find params[:id]
@exercise.course_messages.each do |message|
if User.current.id == message.user_id && message.viewed == 0
message.update_attributes(:viewed => true) if message.viewed == 0
end
end
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
- exercise_end = @exercise.end_time.nil? ? false : @exercise.end_time > Time.now
- if @exercise.time == -1
- @can_edit_excercise = exercise_end
- else
- @can_edit_excercise = !has_commit_exercise?(@exercise.id,User.current.id)&& exercise_end
- end
+
unless @is_teacher
@exercise_user = ExerciseUser.where("user_id=? and exercise_id=?", User.current.id, @exercise.id).first
if @exercise_user.nil?
eu = ExerciseUser.create(:user_id => User.current.id, :exercise_id => @exercise.id, :start_at => Time.now, :status => false)
@exercise_user = ExerciseUser.where("user_id=? and exercise_id=?", User.current.id, @exercise.id).first
+ elsif @exercise_user.start_at.nil?
+ @exercise_user.update_attributes(:start_at => Time.now)
+ end
+
+ exercise_end = @exercise.end_time.nil? ? false : @exercise.end_time > Time.now
+ if @exercise.time == -1
+ @can_edit_excercise = exercise_end && @exercise_user.commit_status == 0
+ else
+ @can_edit_excercise = !has_commit_exercise?(@exercise.id,User.current.id) && exercise_end
end
#score = calculate_student_score(@exercise, User.current)
#@exercise_user.update_attributes(:objective_score => score, :score => (score + (@exercise_user.subjective_score > 0 ? @exercise_user.subjective_score : 0)))
+ else
+ @can_edit_excercise = false
end
# @percent = get_percent(@exercise,User.current)
- @exercise_questions = @exercise.exercise_questions
- @left_nav_type = 8
+ #@exercise_questions = @exercise.exercise_questions
respond_to do |format|
- format.html {render :layout => 'base_courses'}
+ format.html {render :layout => 'base_edu'}
end
#end
end
def new
- option = {
- :exercise_name => "",
- :course_id => @course.id,
- :exercise_status => 1,
- :user_id => User.current.id,
- :time => "",
- :end_time => "",
- :publish_time => "",
- :exercise_description => "",
- :show_result => 1
- }
- @exercise = Exercise.create option
- if @exercise
- redirect_to edit_exercise_url @exercise.id
+ # option = {
+ # :exercise_name => "",
+ # :course_id => @course.id,
+ # :exercise_status => 1,
+ # :user_id => User.current.id,
+ # :time => "",
+ # :end_time => "",
+ # :publish_time => "",
+ # :exercise_description => "",
+ # :show_result => 1
+ # }
+ @exercise = Exercise.new
+ respond_to do |format|
+ format.html{render :layout => 'base_edu'}
end
end
def create
if params[:exercise]
- exercise = Exercise.find(params[:exercise_id]) if params[:exercise_id]
- exercise ||= Exercise.new
+ exercise = Exercise.new
exercise.exercise_name = params[:exercise][:exercise_name]
exercise.exercise_description = params[:exercise][:exercise_description]
- exercise.end_time = Time.at(params[:exercise][:end_time].to_time.to_i + 16*60*60 -1)
- exercise.publish_time = params[:exercise][:publish_time]
exercise.user_id = User.current.id
- exercise.time = params[:exercise][:time]
exercise.course_id = params[:course_id]
+ exercise.time = -1
exercise.exercise_status = 1
if exercise.save
@exercise = exercise
@@ -121,21 +115,15 @@ class ExerciseController < ApplicationController
end
def edit
- @left_nav_type = 8
respond_to do |format|
- format.html{render :layout => 'base_courses'}
- end
+ format.html{render :layout => 'base_edu'}
+ end
end
def update
@exercise.exercise_name = params[:exercise][:exercise_name]
@exercise.exercise_description = params[:exercise][:exercise_description]
- @exercise.time = params[:exercise][:time].blank? ? -1 : params[:exercise][:time]
- @exercise.end_time = Time.at(params[:exercise][:end_time].to_time.to_i + 16*60*60 -1)
- @exercise.publish_time = params[:exercise][:publish_time]
- @exercise.show_result = params[:show_result] ? 1 : 0
- @exercise.question_random = params[:question_random] ? 0 : 1
- @exercise.choice_random = params[:choice_random] ? 0 : 1
+
if @exercise.save
respond_to do |format|
format.js
@@ -148,15 +136,34 @@ class ExerciseController < ApplicationController
def destroy
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
if @exercise && @exercise.destroy
- if @is_teacher
- exercises = Exercise.where("course_id =?", @course.id)
- else
- exercises = Exercise.where("course_id =? and exercise_status =?", @course.id, 2)
- end
- @exercises = paginateHelper exercises,20 #分页
- respond_to do |format|
- format.js
- end
+ redirect_to exercise_index_path(:course_id => @course.id)
+ end
+ end
+
+ def setting
+ @is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
+ @is_new = params[:is_new] ? true : false
+ respond_to do |format|
+ format.html{render :layout => 'base_edu'}
+ end
+ end
+
+ def ex_setting
+ @exercise.publish_time = params[:exercise_publish_time] if params[:exercise_publish_time]
+ @exercise.end_time = params[:exercise_end_time] if params[:exercise_end_time]
+ @exercise.time = -1
+ @exercise.question_random = params[:question_random] ? 1 : 0
+ @exercise.choice_random = params[:choice_random] ? 1 : 0
+ @exercise.score_open = params[:score_open] ? 1 : 0
+ @exercise.answer_open = params[:answer_open] ? 1 : 0
+ if @exercise.save
+ redirect_to student_exercise_list_exercise_path(@exercise)
+ end
+ end
+
+ def set_public
+ if User.current.admin? || User.current.allowed_to?(:as_teacher, @course)
+ @exercise.update_attributes(:is_public => true)
end
end
@@ -165,7 +172,7 @@ class ExerciseController < ApplicationController
@exercise = Exercise.find(params[:id])
exercise_questions = @exercise.exercise_questions
@exercise_questions = paginateHelper exercise_questions, 5
- @left_nav_type = 8
+ @left_nav_type = 4
respond_to do |format|
format.html{render :layout => 'base_courses'}
end
@@ -178,10 +185,7 @@ class ExerciseController < ApplicationController
option = {
:question_title => question_title,
:question_type => params[:question_type] || 1,
- :question_number => params[:question_type] == "1"? @exercise.exercise_questions.where("question_type = 1").count + 1 :
- (params[:question_type] == "2" ? (@exercise.exercise_questions.where("question_type = 2").count + 1) :
- (params[:question_type] == "3" ? (@exercise.exercise_questions.where("question_type = 3").count + 1) :
- @exercise.exercise_questions.where("question_type = 4").count + 1)),
+ :question_number => @exercise.exercise_questions.count + 1,
:question_score => params[:question_score]
}
@exercise_questions = @exercise.exercise_questions.new option
@@ -197,20 +201,23 @@ class ExerciseController < ApplicationController
end
end
# 如果是插入的话,那么从插入的这个id以后的question_num都将要+1
- if params[:quest_id]
+ if params[:quest_id] != "0"
@is_insert = true
- if @exercise_questions.question_type == 1
- ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 1).update_all(" question_number = question_number + 1")
- #@exercise.exercise_questions.where("question_number > #{params[:quest_num].to_i} and question_type == 1").update_all(" question_number = question_number + 1")
- elsif @exercise_questions.question_type == 2
- ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 2).update_all(" question_number = question_number + 1")
- elsif @exercise_questions.question_type == 3
- ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 3).update_all(" question_number = question_number + 1")
- else
- ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 4).update_all(" question_number = question_number + 1")
+ insert_que = ExerciseQuestion.find params[:quest_id]
+ if insert_que
+ @exercise.exercise_questions.where("question_number>?",insert_que.question_number).update_all("question_number = question_number + 1")
+ # if @exercise_questions.question_type == 1
+ # ExerciseQuestion.where("question_number>?",params[:quest_num].to_i).update_all(" question_number = question_number + 1")
+ # elsif @exercise_questions.question_type == 2
+ # ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 2).update_all(" question_number = question_number + 1")
+ # elsif @exercise_questions.question_type == 3
+ # ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 3).update_all(" question_number = question_number + 1")
+ # else
+ # ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 4).update_all(" question_number = question_number + 1")
+ # end
+ # @exercise_question_num = params[:quest_num].to_i
+ @exercise_questions.question_number = insert_que.question_number + 1
end
- # @exercise_question_num = params[:quest_num].to_i
- @exercise_questions.question_number = params[:quest_num].to_i + 1
end
if @exercise_questions.save
# params[:exercise_choice] 标准答案参数
@@ -327,16 +334,17 @@ class ExerciseController < ApplicationController
@exercise_question = ExerciseQuestion.find params[:exercise_question]
@exercise = @exercise_question.exercise
- if @exercise_question.question_type == 1
- ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 1).update_all(" question_number = question_number - 1")
- #@exercise.exercise_questions.where("question_number > #{params[:quest_num].to_i} and question_type == 1").update_all(" question_number = question_number + 1")
- elsif @exercise_question.question_type == 2
- ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 2).update_all(" question_number = question_number - 1")
- elsif @exercise_question.question_type == 3
- ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 3).update_all(" question_number = question_number - 1")
- else
- ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 4).update_all(" question_number = question_number - 1")
- end
+ ExerciseQuestion.where("question_number>?",params[:quest_num].to_i).update_all("question_number = question_number - 1")
+ # if @exercise_question.question_type == 1
+ # ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 1).update_all(" question_number = question_number - 1")
+ # #@exercise.exercise_questions.where("question_number > #{params[:quest_num].to_i} and question_type == 1").update_all(" question_number = question_number + 1")
+ # elsif @exercise_question.question_type == 2
+ # ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 2).update_all(" question_number = question_number - 1")
+ # elsif @exercise_question.question_type == 3
+ # ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 3).update_all(" question_number = question_number - 1")
+ # else
+ # ExerciseQuestion.where("question_number>? and question_type=?",params[:quest_num].to_i, 4).update_all(" question_number = question_number - 1")
+ # end
# @exercise_question_num = params[:quest_num].to_i
# @exercise_questions.question_number = params[:quest_num].to_i - 1
#
@@ -358,12 +366,12 @@ class ExerciseController < ApplicationController
exercise_questions = @exercise.exercise_questions
if @exercise_question
if params[:opr] == 'up' && @exercise_question.question_number > 1
- @before_que = exercise_questions.where("question_type = #{@exercise_question.question_type} and question_number = #{@exercise_question.question_number - 1}").first
+ @before_que = exercise_questions.where("question_number = #{@exercise_question.question_number - 1}").first
if @before_que && @exercise_question.update_attribute('question_number', @exercise_question.question_number - 1)
@before_que.update_attribute('question_number', @before_que.question_number + 1)
end
elsif params[:opr] == 'down' && @exercise_question.question_number < exercise_questions.count
- @after_que = exercise_questions.where("question_type = #{@exercise_question.question_type} and question_number = #{@exercise_question.question_number + 1}").first
+ @after_que = exercise_questions.where("question_number = #{@exercise_question.question_number + 1}").first
if @after_que && @exercise_question.update_attribute('question_number', @exercise_question.question_number + 1)
@after_que.update_attribute('question_number', @after_que.question_number - 1)
end
@@ -470,77 +478,69 @@ class ExerciseController < ApplicationController
end
def student_exercise_list
-=begin
- if @exercise.end_time <= Time.now
- @course.student.each do |student|
- if ExerciseUser.where("user_id = ? && exercise_id = ?",student.student_id,@exercise.id).empty?
- ExerciseUser.create(:user_id => student.student_id, :exercise_id => @exercise.id, :start_at => @exercise.end_time, :status => true,:score=>0)
- end
-
- s_score = calculate_student_score(@exercise, student.student)
- exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", student.student_id, @exercise.id).first
- exercise_user.update_attributes(:score => s_score)
- end
- end
-=end
- @name,@select_group = params[:name].to_s.strip || "",params[:group]
+ @order,@b_sort,@name,@group,@comment,@status = params[:order] || "end_at",params[:sort] || "desc",params[:name].to_s.strip || "",params[:ex_group], params[:ex_comment], params[:ex_status]
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
- if @is_teacher
- @all_exercises = @course.exercises.order("created_at desc")
- else
- @all_exercises = @course.exercises.where("exercise_status > 1").order("created_at desc")
- end
+
student_id = @course.student.blank? ? "(-1)" : "(" + @course.student.map{|student| student.student_id}.join(",") + ")"
- if @select_group
- if @select_group == "0"
- none_group_students = @course.members.select{ |member| member.course_group_id == 0 }
- if none_group_students.empty?
- student_in_group = '(0)'
- else
- student_in_group = '(' + none_group_students.map{ |member| member.user_id }.join(',') + ')'
- end
- elsif @select_group == "-1"
- all_group_students = @course.members.select{ |member| member.course_group_id }
- if all_group_students.empty?
- student_in_group = '(0)'
- else
- student_in_group = '(' + all_group_students.map{ |member| member.user_id }.join(',') + ')'
- end
+ if @group
+ group_students = @course.members.where(:course_group_id => @group).joins("join users on members.user_id = users.id").select{|m| m.roles.to_s.include?("Student")}
+
+ if group_students.empty?
+ student_in_group = '(-1)'
else
- course_group = CourseGroup.find_by_id(@select_group)
- group_students = course_group.users
- if group_students.empty?
- student_in_group = '(0)'
- else
- student_in_group = '(' + group_students.map{ |user| user.id }.join(',') + ')'
- end
+ student_in_group = '(' + group_students.map{ |member| member.user_id }.join(',') + ')'
end
- if @is_teacher || (!@exercise.exercise_users.where("user_id = #{User.current.id}").empty? && @exercise.end_time <= Time.now)
- @exercise_users_list = search_exercise_member @exercise.exercise_users.where("user_id in #{student_id} and user_id in #{student_in_group}"), @name
+
+ if @is_teacher || (!@exercise.exercise_users.where(:user_id => User.current.id, :commit_status => 1).empty? && @exercise.score_open && @exercise.end_time <= Time.now)
+ @exercise_users_list = @exercise.exercise_users.where("user_id in #{student_in_group}").order("#{@order} #{@b_sort}")
@show_all = true;
- elsif !@exercise.exercise_users.where("user_id = #{User.current.id}").empty? && @exercise.end_time > Time.now
- @exercise_users_list = search_exercise_member @exercise.exercise_users.where("user_id = ? and user_id in #{student_id} and user_id in #{student_in_group}",User.current.id), @name
+ elsif !@exercise.exercise_users.where(:user_id => User.current.id, :commit_status => 1).empty?
+ @exercise_users_list = @exercise.exercise_users.where("user_id = ? and user_id in #{student_in_group}",User.current.id)
else
@exercise_users_list = []
end
else
- if @is_teacher || (!@exercise.exercise_users.where("user_id = #{User.current.id}").empty? && @exercise.end_time <= Time.now)
- @exercise_users_list = search_exercise_member @exercise.exercise_users.where("user_id in #{student_id}"), @name
+ if @is_teacher || (!@exercise.exercise_users.where(:user_id => User.current.id, :commit_status => 1).empty? && @exercise.score_open && @exercise.end_time <= Time.now)
+ @exercise_users_list = @exercise.exercise_users.where("user_id in #{student_id}").order("#{@order} #{@b_sort}")
@show_all = true;
- elsif !@exercise.exercise_users.where("user_id = #{User.current.id}").empty? && @exercise.end_time > Time.now
- @exercise_users_list = search_exercise_member @exercise.exercise_users.where("user_id = ? and user_id in #{student_id}",User.current.id), @name
+ elsif User.current.member_of_course?(@course)
+ @exercise_users_list = @exercise.exercise_users.where("user_id = ? and user_id in #{student_id}",User.current.id)
else
@exercise_users_list = []
end
end
- @exercise_count = @exercise.exercise_users.where("commit_status = 1 and user_id in #{student_id}").count
- @left_nav_type = 8
+
+ unless @comment.blank?
+ if @comment.include?('0')
+ @exercise_users_list = @exercise_users_list.where(:subjective_score => -1)
+ else
+ @exercise_users_list = @exercise_users_list.where("subjective_score != -1")
+ end
+ end
+
+ unless @status.blank?
+ @exercise_users_list = @exercise_users_list.where(:commit_status => @status)
+ end
+
+ @exercise_users_list = search_exercise_member @exercise_users_list, @name
+
+ @tab = params[:tab].nil? ? 1 : params[:tab].to_i
+ @score = @b_sort == "desc" ? "asc" : "desc"
+ @exercise_count = @exercise_users_list.count
+ @has_commit_count = @exercise.exercise_users.where(:commit_status => 1).count
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
+ @limit = 50
+ @is_remote = true
+ @page = (params['page'] || 1).to_i
+ @exercise_pages = Paginator.new @exercise_count, @limit, @page
+ @offset ||= @exercise_pages.offset
+ @exercise_users_list = paginateHelper @exercise_users_list, @limit
respond_to do |format|
format.js
- format.html
+ format.html{render :layout => 'base_edu'}
format.xls {
- filename = "#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@course.time.to_s + @course.term}_#{@exercise.exercise_name}#{l(:excel_exercise_list)}.xls"
+ filename = "#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@exercise.exercise_name}#{l(:excel_exercise_list)}.xls"
send_data(exercise_to_xls(@exercise_users_list), :type => "text/excel;charset=utf-8; header=present",
:filename => filename_for_content_disposition(filename))
}
@@ -690,11 +690,11 @@ class ExerciseController < ApplicationController
else
# 更新提交状态
cur_exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", User.current, @exercise.id).first
- cur_exercise_user.update_attributes(:status => 1, :commit_status => 1)
- if @exercise.time && @exercise.time != -1
+ cur_exercise_user.update_attributes(:status => 1, :commit_status => 1, :end_at => Time.now)
+ #if @exercise.time && @exercise.time != -1
score = calculate_student_score(@exercise, User.current)
- cur_exercise_user.update_attributes(:score => score)
- end
+ cur_exercise_user.update_attributes(:objective_score => score, :score => score + (cur_exercise_user.subjective_score > 0 ? cur_exercise_user.subjective_score : 0))
+ #end
# 答题过程中需要统计完成量
#@uncomplete_question = get_uncomplete_question(@exercise, User.current)
# 获取改学生的考试得分
@@ -748,16 +748,20 @@ class ExerciseController < ApplicationController
#查看学生的答卷情况
def show_student_result
- @user = User.find params[:user_id]
- @can_edit_excercise = false
- @exercise_questions = @exercise.exercise_questions
- #score = calculate_student_score(@exercise, @user)
- #eu = get_exercise_user(@exercise.id, @user.id)
- #eu.update_attributes(:score => score)
- @exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", @user.id, @exercise.id).first
- @left_nav_type = 8
- respond_to do |format|
- format.html {render :layout => 'base_courses'}
+ @is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
+ if @is_teacher || (User.current.member_of_course?(@exercise.course) && @exercise.exercise_status > 2)
+ @user = User.find params[:user_id]
+ #@can_edit_excercise = false
+ @exercise_questions = @exercise.exercise_questions
+ #score = calculate_student_score(@exercise, @user)
+ #eu = get_exercise_user(@exercise.id, @user.id)
+ #eu.update_attributes(:score => score)
+ @exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", @user.id, @exercise.id).first
+ respond_to do |format|
+ format.html {render :layout => 'base_edu'}
+ end
+ else
+ render_403
end
end
@@ -820,11 +824,13 @@ class ExerciseController < ApplicationController
# 查作者是我,或者作者是当前课程的老师,且不在当前课程内的试卷 进行导入
@order,@b_sort = params[:order] || "created_at",params[:sort] || "desc"
@r_sort = @b_sort == "desc" ? "asc" : "desc"
- courses = User.current.courses.not_deleted.select { |course| User.current.allowed_to?(:as_teacher,course)}
- course_ids = courses.empty? ? "(-1)" : "(" + courses.map { |course| course.id}.join(',') + ")"
+ @search = params[:search] ? params[:search].to_s.strip.downcase : ""
+ #courses = User.current.courses.not_deleted.select { |course| User.current.allowed_to?(:as_teacher,course)}
+ #course_ids = courses.empty? ? "(-1)" : "(" + courses.map { |course| course.id}.join(',') + ")"
#none_courses = User.current.courses.where("is_delete = 1 or #{Course.table_name}.id = #{params[:course_id].to_i}")
#none_course_ids = none_courses.empty? ? "(-1)" : "(" + none_courses.map { |course| course.id}.join(',') + ")"
- @exercises = Exercise.where("(user_id = #{User.current.id} or course_id in #{course_ids}) and course_id != #{params[:course_id].to_i}").order("#{@order} #{@b_sort}")
+ #@exercises = Exercise.where("(user_id = #{User.current.id} or course_id in #{course_ids}) and course_id != #{params[:course_id].to_i} and exercise_name like '%#{@search}%'").order("#{@order} #{@b_sort}")
+ @exercises = Exercise.where("user_id = #{User.current.id} and exercise_name like '%#{@search}%'").order("#{@order} #{@b_sort}")
@course_id = params[:course_id]
@is_remote = true
@ex_count = @exercises.count
@@ -859,15 +865,15 @@ class ExerciseController < ApplicationController
def import_other_exercise
course_id = params[:course_id]
@course = Course.find(course_id)
- params[:exercise_id].each_with_index do |ex,i|
- exercise = Exercise.find(ex)
+ if params[:exercise_id]
+ exercise = Exercise.find(params[:exercise_id])
option = {
:exercise_name => exercise.exercise_name,
:exercise_status => 1,
:user_id => User.current.id,
:show_result => 1,
:course_id => @course.id,
- :time => exercise.time,
+ :time => -1,
:exercise_description => exercise.exercise_description
}
@exercise = Exercise.create option
@@ -899,9 +905,6 @@ class ExerciseController < ApplicationController
end
@exercise.save
end
- respond_to do |format|
- format.js
- end
end
private
@@ -937,7 +940,7 @@ class ExerciseController < ApplicationController
else
name = name.downcase
select_exercises = exercises.select{ |exercise|
- exercise.user[:login].to_s.downcase.include?(name) || exercise.user.user_extensions[:student_id].to_s.downcase.include?(name) || (exercise.user[:lastname].to_s.downcase + exercise.user[:firstname].to_s.downcase).include?(name)
+ exercise.user.user_extensions[:student_id].to_s.downcase.include?(name) || (exercise.user[:lastname].to_s.downcase + exercise.user[:firstname].to_s.downcase).include?(name)
}
end
select_exercises
diff --git a/app/controllers/files_controller.rb b/app/controllers/files_controller.rb
index 760dfa3da..186e7f175 100644
--- a/app/controllers/files_controller.rb
+++ b/app/controllers/files_controller.rb
@@ -74,21 +74,21 @@ class FilesController < ApplicationController
begin
q = "%#{params[:name].strip}%"
#(redirect_to stores_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?
- if params[:insite]
- if q == "%%"
- @result = []
- # @searched_attach = paginateHelper @result,10
- else
- @result = find_public_attache q,sort
- @result = visable_attachemnts_insite @result,@course
- # @searched_attach = paginateHelper @result,10
- end
- else
+ # if params[:insite]
+ # if q == "%%"
+ # @result = []
+ # # @searched_attach = paginateHelper @result,10
+ # else
+ # @result = find_public_attache q,sort
+ # @result = visable_attachemnts_insite @result,@course
+ # # @searched_attach = paginateHelper @result,10
+ # end
+ # else
@result = find_course_attache q,@course,sort
@result = visable_attachemnts @result
# @searched_attach = paginateHelper @result,10
- @tag_list = get_course_tag_list @course
- end
+ #@tag_list = get_course_tag_list @course
+ #end
@all_attachments = @result
get_attachment_for_tip(@all_attachments)
@limit = 10
@@ -124,6 +124,9 @@ class FilesController < ApplicationController
else
@file.is_publish = 1
end
+ if @file.is_public == 0 && params[:is_public]
+ @file.is_public = 1
+ end
@file.save
respond_to do |format|
format.js
@@ -223,9 +226,9 @@ class FilesController < ApplicationController
sort = "created_on DESC"
end
if keywords != "%%"
- resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND filename LIKE :like ", like: "%#{keywords}%").reorder(sort)
+ resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND (filename LIKE '#{keywords}' or description LIKE '#{keywords}')").reorder(sort)
else
- resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' "). reorder(sort)
+ resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' ").reorder(sort)
end
#resultSet = Attachment.find_by_sql("SELECT `attachments`.* FROM `attachments` LEFT OUTER JOIN `homework_attaches` ON `attachments`.container_type = 'HomeworkAttach' AND `attachments`.container_id = `homework_attaches`.id LEFT OUTER JOIN `homework_for_courses` ON `homework_attaches`.bid_id = `homework_for_courses`.bid_id LEFT OUTER JOIN `homework_for_courses` AS H_C ON `attachments`.container_type = 'Bid' AND `attachments`.container_id = H_C.bid_id WHERE (`homework_for_courses`.course_id = 117 OR H_C.course_id = 117 OR (`attachments`.container_type = 'Course' AND `attachments`.container_id = 117)) AND `attachments`.filename LIKE '%#{keywords}%'").reorder("created_on DESC")
end
@@ -377,6 +380,8 @@ class FilesController < ApplicationController
end
end
else
+ @sort = "created_on"
+ @order = "desc"
sort = "#{Attachment.table_name}.created_on desc"
end
@@ -385,7 +390,7 @@ class FilesController < ApplicationController
show_attachments @containers
get_attachment_for_tip(@all_attachments)
- @tag_list = attachment_tag_list @all_attachments
+ #@tag_list = attachment_tag_list @all_attachments
@left_nav_type = 5
render :layout => 'base_courses'
@@ -597,7 +602,12 @@ class FilesController < ApplicationController
attachment.publish_time = Time.now
end
attachment.description = params[:description]
+ attachment.is_public = params[:is_public] ? 1 : 0
attachment.save
+ resource_bank = ResourceBank.create(:course_id => @course.id, :attachment_id => attachment.id, :filename => attachment.filename, :disk_filename => attachment.disk_filename, :filesize => attachment.filesize, :digest => attachment.digest, :downloads => 0,
+ :user_id => attachment.author_id, :description => attachment.description, :disk_directory => attachment.disk_directory, :is_public => attachment.is_public, :copy_from => attachment.copy_from,
+ :quotes => 1, :applicable_syllabus => @course.course_list_name, :content_type => attachment.content_type)
+ attachment.update_column('resource_bank_id', resource_bank.id)
end
end
if params[:course_attachment_type] && params[:course_attachment_type].is_a?(Array)
@@ -935,7 +945,7 @@ class FilesController < ApplicationController
@tag_list = get_project_tag_list @project
@result_search_project = @result
else
- @tag_list = get_course_tag_list @course
+ #@tag_list = get_course_tag_list @course
end
respond_to do |format|
format.js
diff --git a/app/controllers/forums_controller.rb b/app/controllers/forums_controller.rb
index 24223c25d..8abb426a9 100644
--- a/app/controllers/forums_controller.rb
+++ b/app/controllers/forums_controller.rb
@@ -8,6 +8,7 @@ class ForumsController < ApplicationController
before_filter :authenticate_user_edit, :only => [:edit, :update]
before_filter :authenticate_user_destroy, :only => [:destroy]
before_filter :require_login, :only => [:new, :create,:destroy,:update,:edit]
+ before_filter :check_authentication
helper :sort
include SortHelper
@@ -118,8 +119,10 @@ class ForumsController < ApplicationController
end
def index
- order = ""
+ order = "sticky desc, created_at desc"
@order_str = ""
+ @user = User.current
+=begin
if(params[:reorder_complex])
order = "replies_count #{params[:reorder_complex]}, #{Memo.table_name}.created_at #{params[:reorder_complex]}"
@order_str = "reorder_complex="+params[:reorder_complex]
@@ -133,6 +136,7 @@ class ForumsController < ApplicationController
order = "#{Memo.table_name}.updated_at desc"
@order_str = "reorder_time=desc"
end
+=end
@memo = Memo.new(:forum => @forum)
@memos = Memo.where("parent_id is null")
@topic_count = @memos.count
@@ -143,14 +147,18 @@ class ForumsController < ApplicationController
reorder(order).
preload(:author, {:last_reply => :author}).
all
- @forums = Forum.find_by_sql("SELECT *,topic_count + memo_count tm FROM `forums` order by tm desc;")
+
+ #@forums = Forum.find_by_sql("SELECT *,topic_count + memo_count tm FROM `forums` order by tm desc;")
@my_forums_count = Memo.where("author_id =? and parent_id is null", User.current.id).count
@my_memos_count = Memo.where("author_id =? and parent_id is not null", User.current.id).count
@errors = params[:errors]
+ memos_id = Memo.where("author_id =?", User.current.id).map(&:id)
+ @memos_praise_count = PraiseTread.where(:praise_tread_object_id => memos_id, :praise_tread_object_type => "Memo").count
+
respond_to do |format|
format.js
format.html {
- render :layout => 'base_new_forum'
+ render :layout => 'base_edu'
}# show.html.erb
format.json { render json: @forum }
end
@@ -180,13 +188,10 @@ class ForumsController < ApplicationController
end
@memo = Memo.new(:forum => @forum)
@topic_count = @forum.topics.count
- @topic_pages = Paginator.new @topic_count, per_page_option, params['page']
- @memos = @forum.topics.includes(:last_reply).
- limit(@topic_pages.per_page).
- offset(@topic_pages.offset).
- reorder(order).
- preload(:author, {:last_reply => :author}).
- all
+ @limit = 20
+ @is_remote = true
+ @topic_pages = Paginator.new @topic_count, @limit, params['page'] || 1
+ @memos = paginateHelper @forum.topics.includes(:last_reply).reorder(order).preload(:author, {:last_reply => :author}), @limit
@my_topic_count = Memo.where("forum_id = #{@memo.forum_id} and parent_id is null").count
@my_replies_count = Memo.where("forum_id = #{@memo.forum_id} and parent_id is not null").count
@errors = params[:errors]
diff --git a/app/controllers/games_controller.rb b/app/controllers/games_controller.rb
index d919ac59a..1bc01fd78 100644
--- a/app/controllers/games_controller.rb
+++ b/app/controllers/games_controller.rb
@@ -3,13 +3,77 @@ class GamesController < ApplicationController
layout "base_myshixun"
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]
- before_filter :find_repository, :only => [:show, :entry, :file_edit, :file_update]
+ before_filter :find_game, :only => [:show, :game_build, :entry,:next_step, :prev_step,:outputs_show, :file_edit, :file_update, :get_waiting_time, :web_display,
+ :game_status, :change_status, :answer, :minus_score, :refresh_game_list, :reset_original_code, :reset_new_code, :evaluating_choice, :sync_codes]
+ before_filter :find_repository, :only => [:show, :entry, :file_edit, :file_update, :reset_original_code, :reset_new_code, :html_show]
before_filter :allowd_manager
before_filter :allowd_view, :only => [:show]
before_filter :find__shixun_language, :only => [:show, :entry]
include ApplicationHelper
+ require 'open3'
+ # 同步更新最新代码
+ # 同步完成后,需要更新myshixun的commit_id为实训的commit最新值
+ # --------------------------
+ # 新思路,有冲突则则重置,没有冲突直接pull
+ # --------------------------
+ def sync_codes
+ g = Gitlab.client
+ myshixun_user_login = User.where(:id => @myshixun.user_id).first.try(:login)
+ myshixun_rep_identifier = Repository.where(:myshixun_id => @myshixun.id, :type => "Repository::Gitlab").first.try(:identifier)
+ gitlab_address = Redmine::Configuration['gitlab_address']
+ myshixun_domain = Redmine::Configuration['myshixun_domain']
+ gitlab_myshixun_url = git_myshixun_url(@myshixun, @myshixun.try(:user_id))
+ shixun = @myshixun.shixun
+ gitlab_shixun_url = git_shixun_url(shixun, (shixun.try(:fork_from).blank? ? "educoder" : "eduforge"))
+ if RUBY_PLATFORM =~ /w32/
+ path = "c:/test/"
+ else
+ path = "/home/pdl/myshixun_shell"
+ end
+ script = "cd #{path}
+ git clone #{gitlab_address.to_s+'/'+myshixun_user_login+'/'+ myshixun_rep_identifier}.git
+ cd #{myshixun_rep_identifier}/
+ git remote set-url origin https://#{shixun.fork_from.blank? ? "educoder" : "eduforge"}:xinhu1ji2qu3@#{myshixun_domain}/#{myshixun_user_login}/#{myshixun_rep_identifier}.git
+ git remote add remote_origin #{gitlab_shixun_url}
+ #git pull
+ git pull remote_origin master
+ if [ $? -eq 0 ];then
+ echo -e 'git pull succssed'
+ else
+ git reset --hard #{@myshixun.commit_id}
+ git pull remote_origin master
+ if [ $? -eq 0 ];then
+ echo -e 'git reset and pull succssed'
+ else
+ echo -e 'git reset and pull failed'
+ fi
+ fi
+ git push -f origin master
+ if [ $? -eq 0 ];then
+ echo -e 'git push succssed'
+ else
+ echo -e 'git push failed'
+ fi
+ cd ../
+ rm -rf #{myshixun_rep_identifier}/"
+ aFile =File.new(File.join("#{path}","#{@myshixun.identifier}.sh"), "w+")
+ if aFile
+ aFile.syswrite(script)
+ else
+ logger.error "Unable to open file!"
+ end
+ system("sh #{path}/#{@myshixun.identifier}.sh")
+ # stdin, stdout, stderr = Open3.popen3("sh #{path}/#{@myshixun.identifier}.sh")
+ shixun_new_commit = g.commits(@myshixun.shixun.try(:gpid)).first.try(:id)
+ @myshixun.update_column(:commit_id, shixun_new_commit)
+ sleep(2) # g
+ respond_to do |format|
+ format.js{ redirect_to myshixun_game_path( @game, :myshixun_id => @myshixun)}
+ end
+ # render :json => {:status => 200}
+ end
+
def index
@games = @myshixun.games.includes(:challenge)
@games_count = @games.count
@@ -22,55 +86,117 @@ class GamesController < ApplicationController
# mushixun的版本库必须创建时就创建
# 首次进入版本库自动打开文件
# path:"" && path: @game.path
+ # @praise 判断是否点赞
+ # @tread 判断是否踩
+ # git_repository_url @myshixun, "Myshixun"
+ # @st 0 实践任务 1 选择题任务
def show
+ # g = Gitlab.client
+ # g_name = g.project(@myshixun.gpid).try(:name)
+ # g_rep = @myshixun.repository
+ # g_identifier = g_rep.try(:identifier)
+ # if g_name.include?("-") || g_identifier.include?("-")
+ # g_user_id = @myshixun.owner.try(:gid)
+ # g_name = g_name.split("-")
+ # g_project_name = g_name[0]
+ # num = g_name[1]
+ # g_id = g.current_user_project(g_user_id, g_project_name).first.try(:id)
+ # sql = "update `repositories` set identifier='#{g_project_name}' where id=#{g_rep.id}"
+ # ActiveRecord::Base.connection.execute(sql)
+ # @myshixun.update_attribute(:gpid, g_id)
+ # end
+ # 展示全部实训
+ # git_myshixun_url_ip @myshixun, user_id
+ @is_subject = params[:is_subject]
+ if @game.status == 1
+ # 放置页面ajax数据还没获取就关闭
+ @game.update_attribute(:status, 0)
+ end
+
+ # logger.info("#################%%%%%%#{@game.outputs.first.out_put}")
+ # @games = @myshixun.games.includes(:challenge)
@game_challenge = @game.challenge
- logger.info("test ................#{@game_challenge.id}")
- game_path = (@game_challenge.path.blank? ? @path : @game_challenge.path.strip)
- logger.info("test game_path ................#{game_path}")
+ @challenges = Challenge.where(:shixun_id => @myshixun.shixun_id)
+ @shixun = @myshixun.shixun
+ # 判断tpm是否修改了
+ @tpm_modified = tpm_is_modified(@myshixun, @shixun.try(:gpid))
+ # end
+ @praise_count = PraiseTread.where(:praise_tread_object_id => @game_challenge.id, :praise_tread_object_type => "Challenge").count
+ @tread_count = PraiseTread.where(:praise_tread_object_id => @game_challenge.id, :praise_tread_object_type => "ChallengeTread").count
+ # @games_count = @games.count
+ @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
- @git_url = git_repository_url(@myshixun, "Myshixun")
@type = params[:type]
- logger.info("##########************languae is #{@language}")
- logger.info("out is666************#{@path} ")
+ challenge_path = @game_challenge.path
+ @discusses_count = @shixun.discusses.where(:parent_id => nil).count
+ # 用户选项
+ #@user_answer = @game.outputs.first.actual_output.split("") unless @st == 0 || @game.outputs.blank?
# 默认打开文件
- if @path == "" && !game_path.nil? && !@repository.cat(game_path, @rev).blank? && @type != "root"
- @path = game_path
- @file_open = true
- logger.info("666666666666************languae ")
- logger.info("path is666************#{@path} ")
- @content = @repository.cat(@path, @rev)
- logger.info("666666666666************languae is #{@content}")
- else
- logger.info("77777************languae ")
+ 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文件名的合法性
+ if @path.blank? && !challenge_path.blank? && challenge_path.include?(".") && @type != "root"
+ @path = challenge_path.strip
+ file_content = @g.files(@myshixun.gpid, @path, @rev).content
+ if file_content.blank?
+ # gitlab缺陷:forked完成,短暂时间内取不了内容的,所以做一个小轮询,间隔0.1秒
+ # 超过2秒则失败,需通过页面刷新
+ for i in 0..20 do
+ sleep(0.1)
+ file_content = @g.files(@myshixun.gpid, @path, @rev).content
+ unless file_content.blank?
+ logger.info("start: file_content is####{file_content.first(6)}")
+ break
+ end
+ end
+ end
+ @content = tran_base64_decode64(file_content)
+ end
+ if @content.nil?
@entries = @repository.entries(@path, @rev)
- logger.info("7777************#{@entries} ")
end
- logger.info("88888************#{@entries} ")
- @latest_output = @game.latest_output.try(:out_put).to_s
- outputs = @game.outputs
- (@myshixun.games.count == @game_challenge.position && @game.status ==2) ? @had_done = 1 : @had_done = 0
- if outputs.count == 0
- @results = []
- else
- @results = outputs.map{|result| [result.code, result.id]}
+ # 页面前后端分离数据转换
+ test_sets = @game_challenge.test_sets
+ unless test_sets.blank?
+ @test_sets = test_set_static_data(test_sets)
end
- logger.info("##################languae is #{@language}")
- logger.info("##################latest_output is #{@latest_output}")
- logger.info("##################had_done is #{@had_done}")
- logger.info("##################status is #{@game.status}")
- logger.info("##################result is #{@results}")
+
+ logger.info("#################################{@public_test_sets}")
+ @test_sets_count = test_sets.count
+ @test_sets_hidden_count = test_sets.blank? ? 0 :test_sets.select{|test_set| test_set.is_public == false}.count
+ @test_sets_public_count = @test_sets_count - @test_sets_hidden_count
+ had_test = Output.where(:game_id => @game.id, :query_index => (@game.query_index - 1))
+ @had_test_count = had_test.count
+ @had_passed_testsests_error_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == false}.count
+ @had_passed_testsests_error_count = @had_test_count - @had_passed_testsests_error_count
+ @had_passed_testsests_hidden_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == true && had_test.is_public == false}.count
+ @had_passed_testsests_public_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == true && had_test.is_public == true}.count
+ @final_score = ((@game.answer_open? || @shixun.status <= 1) ? 0 : @game.final_score.to_i)
+ @gold = @myshixun.shixun.status <= 1 ? 0 : (@game.answer_open? ? -@game_challenge.score.to_i : @game.final_score.to_i)
+ @had_done = @game.had_done
+ @language = @game_challenge.shixun.language
+ error_position = had_test.blank? ? nil : had_test.select{|had_test| had_test.result == false}.last
+ logger.info("latest output id is #{error_position.id unless error_position.blank?}")
+ @latest_output = error_position.try(:out_put).gsub(/\n/, ' ').gsub(/\t/, ' ').to_json unless error_position.try(:out_put).blank?
+ logger.info(@latest_output)
+
respond_to do |format|
format.html
format.js
end
rescue Exception => e
+ logger.error("game error##############{e.message}")
flash[:error] = e.message
end
# 代码预览
def entry
- entry_and_raw(false)
- @content = @repository.cat(@path, @rev)
+ # entry_and_raw(false)
+ file_content = @g.files(@myshixun.gpid, @path, @rev).content
+ @content =tran_base64_decode64(file_content)
+ # @content = @repository.cat(@path, @rev)
end
def file_edit
@@ -83,13 +209,19 @@ class GamesController < ApplicationController
def file_update
@g = Gitlab.client
- content = params[:content].strip
- @g.edit_file(@myshixun.gpid, :content => params[:content], :file_path => @path, :branch_name => @rev, :commit_message => "shixun exec")
+ content = params[:content].try(:strip)
+ code_file = @g.edit_file(@myshixun.gpid, :content => params[:content], :file_path => @path, :branch_name => @rev, :commit_message => "shixun exec")
+ unless code_file.blank?
+ render :json => {:success => "success"}
+ end
+
+=begin
respond_to do |format|
- format.js{redirect_to entry_myshixun_game_path(@game, :myshixun_id => @myshixun, :path => @path)}
+ format.js
end
rescue Exception => e
puts e.message
+=end
end
# json调用,显示左边的隐藏具体详情@game 字段 msg
@@ -101,57 +233,200 @@ class GamesController < ApplicationController
end
end
+ # 获取评测的等待的时间
+ # res['waitNum'] 评测等待人数
+ # res['waitingTime'] 评测等待时间
+ # res['onRun'] 0 表示在等待中 1 表示可执行
+ def get_waiting_time
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ uri = "#{shixun_tomcat}/bridge/game/getWaitingTime"
+ params = {:tpiID => "#{@myshixun.id}"}
+ resubmit = @_params['resubmit']
+ res = uri_exec uri, params
+ if (res && res['code'] != 0)
+ @message = "实训云平台繁忙(繁忙等级:94)"
+ raise("实训云平台繁忙(繁忙等级:94)")
+ end
+ render :json => {:result => "success", :onRun => res['onRun'], :waitNum => res['waitNum'], :waitingTime => res['waitingTime'], :resubmit => resubmit }
+ #render :json => {:result => "success", :onRun => 0, :waitNum => 12, :waitingTime => 1234 }
+ rescue Exception => e
+ render :json => {:result => "failed"}
+ end
+
# status 0: 未提交测评或者提交测评失败后报错;1:中间状态还没返回值;2:返回值并成功
+ # resubmit 唯一随机码,为了区分每一次重新评测结果
+ CODES = %W(1 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 game_build
game_challenge = @game.challenge
- gitUrl = git_repository_url(@myshixun, "Myshixun")
- gitUrl = Base64.encode64(gitUrl)
- taskId = params[:id]
- jobName = "myshixun_#{@myshixun.id}"
- ActiveRecord::Base.transaction do
- @game.update_attributes!(:status => 1)
- testCode = {}
- test_sets = game_challenge.test_sets
- unless test_sets.blank?
- test_sets.each_with_index do |test_set, index|
- testCode.store("testCode_#{index}",test_set.try(:output))
+ shixun = @myshixun.shixun
+ gitUrl = git_myshixun_url_ip(@myshixun, @myshixun.try(:user_id))
+ gitUrl = Base64.urlsafe_encode64(gitUrl)
+ taskId = @game.id
+ code = CODES.sample(8).join
+ # status为2说明是重新评测
+ if @game.status == 2
+ resubmit = "#{code}_#{@myshixun.id}"
+ else
+ # 重新评测不影响已通关的实训状态
+ @game.update_attributes!(:status => 1) if resubmit.nil?
+ end
+
+ gameInfo = shixun.gameInfo
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ step = game_challenge.try(:position)
+ # 注意:这个地方的参数写的时候不能换行
+ params = {:tpiID => "#{@myshixun.id}", :buildID => "#{taskId}", :instanceGitURL => "#{gitUrl}", :instanceChallenge => "#{step}", :resubmit => resubmit, :operationEnvironment => "#{shixun.try(:language)}"}
+ # uri = URI("#{shixun_tomcat}/bridge/game/gameEvaluate")
+ uri = "#{shixun_tomcat}/bridge/game/gameEvaluate"
+ res = uri_exec uri, params
+ logger.info("#####################buildJobForInstance result is #{res}")
+ logger.info("#####################buildJobForInstance params is #{params}")
+ if (res && res['code'] != 0)
+ @message = "实训云平台繁忙(繁忙等级:86)"
+ raise("实训云平台繁忙(繁忙等级:86)")
+ end
+ render :json => {:result => "success", :resubmit => resubmit}
+ rescue Exception => e
+ if resubmit.nil?
+ @game.update_attributes!(:status => 0)
+ end
+ logger.error("###################" + e.message)
+ #REDO Jenkins服务异常弹框抛出
+ render :json => {:result => "failed"}
+ end
+
+ # @myshixun -status 1:完成实训
+ # 全部通关奖励1000分
+ # retry_status 评测的唯一标识,重新评测对以前已产生的结果不造成影响
+ # params[:resubmit] 不为空表示已通过该关后重新评测, 重新评测必须是通过该关后才能执行
+ # @had_done 1 通关所有关
+ def game_status
+ game_challenge = @game.challenge
+ had_done = @game.had_done
+ resubmit_identifier = @game.resubmit_identifier
+ shixun = @myshixun.shixun
+ score = 0
+ tag_count = 0
+ logger.info("##### resubmit_identifier is #{resubmit_identifier}")
+ if params[:resubmit].blank? # 非重新评测
+ if had_done == 1 # 通过最后一关,即所有关卡
+ @myshixun.update_attribute(:status, 1)
+ end
+ # 通过当前一关
+ if @game.status == 2
+ @game.update_attribute(:end_time, Time.now)
+ game_passed_code(@game.id, game_challenge.try(:path), @myshixun.try(:gpid), 1)
+ if !@game.answer_open && shixun.status > 1
+ reward_grade(@game.user, @game.id, 'Game', game_challenge.score)
+ reward_experience(@game.user, @game.id, 'Game', game_challenge.score)
+ score = game_challenge.score
+ tag_count = game_challenge.challenge_tags.count
+ elsif shixun.status > 1 && @game.answer_open
+ score = -game_challenge.score.to_i
+ tag_count = 0
+ else
+ score = "+0"
+ tag_count = 0
end
end
- testCode = testCode.to_json
- jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
- step = game_challenge.try(:position)
- params = {:jobName => "#{jobName}", :taskId => "#{taskId}", :step => "#{step}", :gitUrl => "#{gitUrl}", :testCode => "#{testCode}"}
- uri = URI("#{jenkins_shixuns}/jenkins-exec/api/buildJob")
- res = uri_exec uri, params
- if (res && res['code'] != 0)
- raise("Build job failed")
+ game_status = @game.status
+ else # 重新评测
+ if params[:resubmit] == resubmit_identifier # 本次重新评测结果已经返回并存入数据库
+ game_status = (@game.retry_status == 2 ? 2 : 0) # retry_status 2:成功 1: 失败
+ if game_status == 2 && had_done == 1 # 重新评测如果评测成功
+ had_done =1
+ game_passed_code(@game.id, game_challenge.try(:path), @myshixun.try(:gpid), 1)
+ else
+ had_done = 0
+ end
+ else
+ # game_status 在前端有行为判断,2表示通关;0表示失败;1表示评测中的中间状态
+ game_status = 1
+ had_done = 0
end
- render :json => {data:"success"}
end
- rescue
- raise ActiveRecord::Rollback
- redirect_to myshixun_game_path(@game, :myshixun_id => @myshixun)
+ test_sets = game_challenge.test_sets
+ unless test_sets.blank?
+ total_test_sets = test_set_static_data(test_sets)
+ end
+
+ logger.info("#################################{@public_test_sets}")
+ @test_sets_count = test_sets.count
+ @test_sets_hidden_count = test_sets.blank? ? 0 :test_sets.select{|test_set| test_set.is_public == false}.count
+ @test_sets_public_count = @test_sets_count - @test_sets_hidden_count
+ had_test = Output.where(:game_id => @game.id, :query_index => (@game.query_index - 1))
+ @had_test_count = had_test.count
+ @had_passed_testsests_error_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == false}.count
+ @had_passed_testsests_error_count = @had_test_count - @had_passed_testsests_error_count
+ @had_passed_testsests_hidden_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == true && had_test.is_public == false}.count
+ @had_passed_testsests_public_count = had_test.blank? ? 0 : had_test.select{|had_test| had_test.result == true && had_test.is_public == true}.count
+ @final_score = ((@game.answer_open? || shixun.status <= 1) ? 0 : @game.final_score.to_i)
+ @gold = @myshixun.shixun.status <= 1 ? 0 : (@game.answer_open? ? -game_challenge.score.to_i : @game.final_score.to_i)
+ error_position = had_test.blank? ? nil : had_test.select{|had_test| had_test.result == false}.last
+ @latest_output = error_position.try(:out_put).gsub(/\n/, ' ').gsub(/\t/, ' ') unless error_position.try(:out_put).blank?
+ logger.info("@compile_success###################{@compile_success}")
+ @language = game_challenge.shixun.language
+ render :json => {test_sets: total_test_sets,
+ test_sets_count: @test_sets_count,
+ test_sets_hidden_count: @test_sets_hidden_count,
+ test_sets_public_count: @test_sets_public_count,
+ had_test_count: @had_test_count,
+ had_passed_testsests_error_count: @had_passed_testsests_error_count,
+ had_passed_testsests_hidden_count: @had_passed_testsests_hidden_count,
+ had_passed_testsests_public_count: @had_passed_testsests_public_count,
+ final_score: @final_score,
+ gold: @gold,
+ latest_output: @latest_output,
+ status: game_status,
+ had_done: had_done,
+ language: @language,
+ score: score,
+ tag_count: tag_count,
+ position: game_challenge.position
+ }
end
- def game_status
- outputs = @game.outputs
- game_challenge = @game.challenge
- if outputs.count == 0
- outputs = ""
- else
- outputs = outputs.map{|result| [result.code, result.id]}
+ # 选择题评测(选择题不需要重新评测)
+ # score 获得金币数 tag_count 技能数 right用户是否全对 answer_right全部选择题的正确性
+ def evaluating_choice
+ @game_challenge = @game.challenge
+ @challenges = Challenge.where(:shixun_id => @myshixun.shixun_id)
+ @shixun = @myshixun.shixun
+ score = 0
+ tag_count = 0
+ @right = true
+ answer_right = []
+ @game_challenge.challenge_chooses.each_with_index do |choose, index|
+ correct = (params[:answer][index] == choose.standard_answer) ? true : false
+ #choose.current_choose_outputs.delete if choose.current_choose_outputs.present?
+ #ChooseOutputs.create(:challenge_choose_id => choose.id, :user_id => User.current.id, :answer => params[:answer][index], :correct => correct)
+ Output.create(:game_id => @game.id, :test_set_position => choose.position, :actual_output => params[:answer][index], :result => correct, :query_index => @game.query_index)
+ if @shixun.status > 1 && !@game.answer_open
+ if correct
+ score += choose.score
+ tag_count += choose.challenge_tags.count
+ end
+ elsif @shixun.status > 1 && @game.answer_open
+ score -= choose.score
+ end
+ unless correct
+ @right = false
+ end
+ answer_right << correct
end
- (@myshixun.games.count == game_challenge.position && @game.status ==2) ? had_done = 1 : had_done = 0
-
- # 下一关自动开启
- if had_done != 1 && @game.status == 2
- @game.next_game.update_attribute(:status, 0)
+ @had_done = @game.had_done
+ if @right
+ @game.update_attributes(:status => 2, :end_time => Time.now)
+ reward_grade(@game.user, @game.id, 'Game', score)
+ reward_experience(@game.user, @game.id, 'Game', score)
+ @game.update_attribute(:final_score, score)
+ end
+ respond_to do |format|
+ format.js{redirect_to myshixun_game_path(@game, :myshixun_id => @myshixun, :choose => @right)}
end
-
- latest_output = @game.latest_output.try(:out_put)
- render :json => {status: @game.status, output: latest_output, results: outputs, had_done: had_done}
end
+
def change_status
@game.update_attribute(:status, 0)
outputs = @game.outputs
@@ -163,18 +438,203 @@ class GamesController < ApplicationController
render :json => {status: @game.status, output: "服务器网络异常", results: outputs, had_done: 0}
end
+ # 获取等待的任务数
+ # 如果没有等待任务页面上将不显示
+ # msg: -1 不存在等待的任务
+ # 如果该方法异常则直接返回0,跳过等待
+ def waiting_info
+ begin
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ params = {:buildID => "#{@game.id}"}
+ uri = URI("#{shixun_tomcat}/jenkins-exec/api/getWaitingTime")
+ res = uri_exec uri, params
+ if (res && res['code'] != 0)
+ raise("获取等待任务数异常")
+ end
+ task_count = res['msg'].to_i
+ task_count > 0 ? task_count : 0
+ render :json => {task_count: task_count}
+ rescue
+ render :json => {task_count: 0}
+ end
+ end
+
# 自动推送下一个任务
def next_step
- render_403 if @game.status != 2
+ unless show_next_stage?(@game, @myshixun.shixun.try(:status))
+ render_403
+ end
next_game = @game.next_game
- next_game.update_attribute(:status, 0) if next_game.status == 3
+ next_game.update_attributes(:status => 0, :open_time => Time.now) if next_game.status == 3
+ respond_to do |format|
+ format.js{ redirect_to myshixun_game_path(next_game, :myshixun_id => @myshixun)}
+ end
+ end
+
+ def prev_step
+ prev_game = @game.prev_game
+ respond_to do |format|
+ format.js{ redirect_to myshixun_game_path(prev_game, :myshixun_id => @myshixun)}
+ end
+ end
+
+ # 获取答案,第一次查看需扣掉该关卡的积分
+ # 如果已看过,下次可以免费查看
+ # viewed 1: 直接查看 2:弹框提示将要扣除积分,确定后显示内容 3:弹框提示分数不够
+ def answer
+ challenge = @game.challenge
+ @challenge_score = challenge.score.to_i
+ @answer = ""
+ # 已经开启过
+ @score = User.current.grade.to_i - @challenge_score
+ if(params[:choose] == "true")
+ challenge.challenge_chooses.each_with_index do |choose, index|
+ @answer += "第"+ ((index + 1).to_s) +"题: "
+ @answer += (choose.answer.blank? ? choose.standard_answer : choose.answer)
+ @answer += " "
+ end
+ else
+ @answer = challenge.answer
+ end
+
+ if challenge.shixun.status < 2 || @game.answer_open || (challenge.st != 0 && @game.status == 2)
+ @viewed = 1
+ else
+ if @score >= 0
+ @viewed = 2
+ else
+ @viewed = 3
+ end
+ end
+ respond_to do |format|
+ format.js
+ format.html
+ end
+ end
+
+ # web渲染
+ def web_display
+ path = @game.challenge.path.strip
+ port = (50000 + @game.myshixun_id).to_s
+ # 测试
+ #path = "src/step1/Helloworld.php"
+ #port = (50000+4116).to_s
+ @url = "http://106.75.96.108:" + port + '/' + path
respond_to do |format|
- format.js{redirect_to myshixun_game_path(next_game, :myshixun_id => @myshixun.id)}
+ format.html{render :layout => false}
+ end
+ end
+
+ def minus_score
+ @game_challenge = @game.challenge
+ user = User.current
+ challenge_score = @game_challenge.score.to_i
+ reward_grade(user, @game.id, 'Answer', -challenge_score)
+ @answer = ""
+ if @game.challenge.st == 0
+ @answer = @game_challenge.answer
+ else
+ @game_challenge.challenge_chooses.each_with_index do |choose, index|
+ @answer += "第"+ ((index + 1).to_s) +"题: "
+ @answer += (choose.answer.blank? ? choose.standard_answer : choose.answer)
+ @answer += " "
+ end
+ end
+ @game.update_column(:answer_open, true)
+ end
+
+ def refresh_game_list
+ myshixun_id = params[:myshixun_id]
+ @myshixun = Myshixun.find_by_identifier(myshixun_id)
+ @challenges = Challenge.where(:shixun_id => @myshixun.shixun_id)
+
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def reset_original_code
+ begin
+ @shixun = @myshixun.shixun
+ @g = Gitlab.client
+ game_code = GameCode.where(:game_id => @game.id).first
+ content = game_code.try(:original_code)
+ if content.nil?
+ raise("初始代码为空,代码重置失败")
+ end
+ @path = params[:path]
+ @rev = @rev.nil? ? "master" : @rev
+ message = "file reset"
+ update_gitlab_file(content, @path, @rev, message)
+ file_content = @g.files(@myshixun.gpid, @path, @rev).content
+ @content = tran_base64_decode64(file_content)
+ if @content.nil?
+ raise("初始代码为空,代码重置失败")
+ # @entries = @repository.entries(@path, @rev)
+ end
+ respond_to do |format|
+ format.js
+ end
+ rescue Exception => e
+ @error_messages = e.message
+ end
+ end
+
+ def reset_new_code
+ begin
+ @shixun = @myshixun.shixun
+ @g = Gitlab.client
+ game_code = GameCode.where(:game_id => @game.id).first
+ content = game_code.try(:new_code)
+ if content.nil?
+ raise("示例代码为空,代码重置失败")
+ end
+ @path = params[:path]
+ @rev = @rev.nil? ? "master" : @rev
+ message = "file reset"
+ update_gitlab_file(content, @path, @rev, message)
+ file_content = @g.files(@myshixun.gpid, @path, @rev).content
+ @content = tran_base64_decode64(file_content)
+ if @content.nil?
+ raise("示例代码为空,代码重置失败")
+ # @entries = @repository.entries(@path, @rev)
+ end
+ respond_to do |format|
+ format.js
+ end
+ rescue Exception => e
+ @error_messages = e.message
end
end
private
+ def update_gitlab_file content, path, rev, message
+ code_file = @g.edit_file(@myshixun.gpid, :content => content, :file_path => path, :branch_name => rev, :commit_message => "#{message}")
+ if code_file.nil?
+ raise("网络异常,文件更新失败")
+ end
+ end
+
+ def test_set_static_data test_sets
+ test_result = []
+ unless test_sets.blank?
+ test_sets.each do |test_set|
+ output = Output.where(:game_id => @game.id, :test_set_position => test_set.position).first
+ actual_output = output.try(:actual_output)
+ result = output.try(:result)
+ compile_success = (actual_output.blank? || !actual_output.downcase.match(/error/).blank?) ? 0 : 1
+ public_result = {:is_public => (test_set.is_public ? 1 : 0), :result => result, :input => test_set.input,
+ :actual_output => actual_output, :output => test_set.output, :compile_success => compile_success}
+ logger.info("1111#################################{public_result.to_json}")
+ test_result << public_result.to_json
+ end
+ end
+ test_result = test_result.blank? ? test_result : test_result.join(",")
+ logger.info("222#################################{test_result}")
+ return test_result
+ end
+
def entry_and_raw(is_raw)
@entry = @repository.entry(@path, @rev)
(show_error_not_found; return) unless @entry
@@ -230,7 +690,10 @@ class GamesController < ApplicationController
# 判断成员是否允许查看
def allowd_view
- render_403 if @game.status == 3
+ if @myshixun.shixun.try(:status) == 2 && @game.status == 3 && User.current.id != @myshixun.shixun.try(:user_id)
+ render_403
+ end
+ # render_403 if (@game.status == 3 && User.current.id != @myshixun.shixun.try(:user_id))
end
def find__shixun_language
@@ -241,13 +704,22 @@ class GamesController < ApplicationController
# Find myshixun of id params[:id]
def find_myshixun
myshixun_id = params[:myshixun_id] || (params[:game] && params[:game][:myshixun_id])
- @myshixun = Myshixun.find(myshixun_id)
+ @myshixun = Myshixun.find_by_identifier(myshixun_id)
+ if @myshixun.nil?
+ render_404
+ return
+ end
rescue ActiveRecord::RecordNotFound
render_404
end
def find_game
- @game = Game.find(params[:id])
+ # myshixun_id = params[:myshixun_id]
+ @game = Game.find_by_identifier(params[:id])
+ if @game.nil?
+ render_404
+ return
+ end
@myshixun = @game.myshixun
rescue ActiveRecord::RecordNotFound
render_404
diff --git a/app/controllers/homework_bank_controller.rb b/app/controllers/homework_bank_controller.rb
new file mode 100644
index 000000000..77627e2e3
--- /dev/null
+++ b/app/controllers/homework_bank_controller.rb
@@ -0,0 +1,254 @@
+class HomeworkBankController < ApplicationController
+ before_filter :require_login, :only => [:index, :show, :new, :create, :edit, :update, :destroy, :destroy_all, :choose_user_course, :send_h_bank_to_course]
+ before_filter :find_homework_bank, :only => [:show, :edit, :update, :destroy, :set_public]
+
+ def index
+ @order,@b_sort = params[:order] || "updated_at",params[:sort] || "desc"
+ @user = User.current
+ @r_sort = @b_sort == "desc" ? "asc" : "desc"
+ @search = params[:search]
+ if(params[:type].blank? || params[:type] == "1") #我的题库
+ @homeworks = @user.homework_banks.where("homework_type in (1, 4) and name like ?", "%#{@search}%")
+ elsif params[:type] == "2" #公共题库
+ @homeworks = HomeworkBank.where(:is_public => true).where("homework_type in (1, 4) and name like ?", "%#{@search}%")
+ end
+ if params[:property]
+ @property = params[:property].to_i
+ @homeworks = @homeworks.where(:homework_type => params[:property].to_i)
+ end
+ @homeworks = @homeworks.reorder("#{@order} #{@b_sort}")
+ @type = params[:type] ? params[:type] : '1'
+ @limit = 15
+ @is_remote = true
+ @hw_count = @homeworks.count
+ @hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
+ @offset ||= @hw_pages.offset
+ @homeworks = paginateHelper @homeworks,15
+ respond_to do |format|
+ format.js
+ format.html {render :layout => 'base_edu'}
+ end
+ end
+
+ def show
+ @is_admin = User.current == @homework.user || User.current.admin?
+ respond_to do |format|
+ format.html {render :layout => 'base_edu'}
+ end
+ end
+
+ def new
+ @homework_type = params[:homework_type].to_i
+ @homework = HomeworkBank.new
+ respond_to do |format|
+ format.html{render :layout => 'base_edu'}
+ end
+ end
+
+ # 新建实训作业
+ def shixuns
+ search = params[:search]
+ @homework = HomeworkBank.new
+ @shixuns = Shixun.where(:status => 2).where("name like ?", "%#{search}%")
+ @shixuns_count = @shixuns.count
+ @limit = 10
+ @is_remote = true
+ @shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
+ @offset ||= @shixun_pages.offset
+ @shixuns = paginateHelper @shixuns, @limit
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def create
+ if params[:homework_bank] || params[:shixun_homework]
+ homework = HomeworkBank.new
+ if params[:shixun_homework]
+ shixun = Shixun.find(params[:shixun_homework])
+ homework.name = shixun.name
+ homework.description = shixun.description
+ else
+ homework.name = params[:homework_bank][:name]
+ homework.description = params[:homework_bank][:description]
+ homework.reference_answer = params[:homework_bank][:reference_answer]
+ homework.save_attachments(params[:attachments])
+ render_attachment_warning_if_needed(homework)
+ end
+ homework.is_public = 0
+ homework.quotes = 0
+ homework.homework_type = params[:shixun_homework] ? 4 : (params[:homework_type].to_i || 1)
+ homework.user_id = User.current.id
+ unless params[:course_list].blank?
+ if CourseList.where(:name => params[:course_list].strip).count > 0
+ homework.course_list_id = CourseList.where(:name => params[:course_list].strip).first.id
+ else
+ course_list = CourseList.create(:name => params[:course_list].strip, :user_id => User.current.id, :is_admin => 0)
+ homework.course_list_id = course_list.id
+ end
+ end
+ #homework.syllabus_id = params[:syllabus_id] if params[:syllabus_id] && params[:syllabus_id] != '0'
+
+ #编程作业相关属性
+ if homework.homework_type == 2
+ homework.language = params[:language_type].to_i
+
+ sample_inputs = params[:sample][:input]
+ if Array === sample_inputs
+ sample_inputs.each_with_index do |val, i|
+ homework.homework_bank_samples << HomeworkBankSample.new(
+ input: val,
+ output: params[:sample][:output][i]
+ )
+ end
+ end
+
+ inputs = params[:program][:input]
+ if Array === inputs
+ inputs.each_with_index do |val, i|
+ homework.homework_bank_tests << HomeworkBankTest.new(
+ input: val,
+ output: params[:program][:output][i]
+ )
+ end
+ end
+ end
+
+ #分组作业
+ if homework.homework_type == 3
+ homework.min_num = params[:min_num].to_i
+ homework.max_num = params[:max_num].to_i
+ end
+
+ if homework.save
+ if homework.homework_type == 4
+ HomeworkBankShixun.create(:homework_bank_id => homework.id, :shixun_id => shixun.id)
+ end
+ redirect_to homework_bank_path(homework)
+ end
+ end
+ end
+
+ def edit
+ @homework_type = @homework.homework_type
+ respond_to do |format|
+ format.html{render :layout => 'base_edu'}
+ end
+ end
+
+ def update
+ if params[:homework_bank]
+ @homework.name = params[:homework_bank][:name]
+ @homework.description = params[:homework_bank][:description]
+ @homework.reference_answer = params[:homework_bank][:reference_answer]
+ if params[:course_list].blank?
+ @homework.course_list_id = nil
+ else
+ if CourseList.where(:name => params[:course_list].strip).count > 0
+ @homework.course_list_id = CourseList.where(:name => params[:course_list].strip).first.id
+ else
+ course_list = CourseList.create(:name => params[:course_list].strip, :user_id => User.current.id, :is_admin => 0)
+ @homework.course_list_id = course_list.id
+ end
+ end
+ #@homework.syllabus_id = params[:syllabus_id] ? (params[:syllabus_id] == '0' ? nil : params[:syllabus_id].to_i) : nil
+ @homework.save_attachments(params[:attachments])
+ render_attachment_warning_if_needed(@homework)
+
+ #编程作业相关属性
+ if @homework.homework_type == 2
+ @homework.language = params[:language_type].to_i if params[:language_type]
+
+ @homework.homework_bank_samples.delete_all if params[:sample]
+ sample_inputs = params[:sample][:input] if params[:sample]
+ if Array === sample_inputs
+ sample_inputs.each_with_index do |val, i|
+ @homework.homework_bank_samples << HomeworkBankSample.new(
+ input: val,
+ output: params[:sample][:output][i]
+ )
+ end
+ end
+
+ @homework.homework_bank_tests.delete_all if params[:program]
+ inputs = params[:program][:input] if params[:program]
+ if Array === inputs
+ inputs.each_with_index do |val, i|
+ @homework.homework_bank_tests << HomeworkBankTest.new(
+ input: val,
+ output: params[:program][:output][i]
+ )
+ end
+ end
+ end
+
+ #分组作业
+ if @homework.homework_type == 3
+ @homework.min_num = params[:min_num].to_i if params[:min_num]
+ @homework.max_num = params[:max_num].to_i if params[:max_num]
+ end
+
+ if @homework.save
+ redirect_to homework_bank_path(@homework)
+ end
+ end
+ end
+
+ def destroy
+ @homework.homework_commons.update_all(:homework_bank_id => nil)
+ @homework.destroy
+ redirect_to homework_bank_index_path()
+ end
+
+ def destroy_all
+ if params[:check_homework_bank] && !params[:check_homework_bank].blank?
+ params[:check_homework_bank].each do |hb_id|
+ homework = HomeworkBank.find hb_id
+ if homework && homework.user == User.current
+ HomeworkCommon.where(:homework_bank_id => homework.id).update_all(:homework_bank_id => nil)
+ homework.destroy
+ end
+ end
+ end
+ redirect_to homework_bank_index_path
+ end
+
+ def choose_user_course
+ if !params[:search].nil?
+ search = "%#{params[:search].to_s.strip.downcase}%"
+ @courses = User.current.courses.where("is_delete = 0 and is_end = 0 and (#{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like :p)",:p=>search).select{ |course| User.current.has_teacher_role(course)}
+ else
+ @courses = User.current.courses.where("is_delete = 0 and is_end = 0").select{ |course| User.current.has_teacher_role(course)}
+ end
+ @homework_ids = params[:check_homework_bank] if params[:check_homework_bank]
+ @search = params[:search]
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def send_h_bank_to_course
+ course = Course.find params[:course_id]
+ if course
+ params[:homework_id].each do |homework_id|
+ homework = HomeworkBank.find homework_id
+ quote_homework_bank homework, course
+ end
+ end
+ end
+
+ def set_public
+ @homework.update_attributes(:is_public => true)
+ respond_to do |format|
+ format.html{ redirect_to homework_bank_path(@homework) }
+ format.js
+ end
+ end
+
+ private
+ def find_homework_bank
+ @homework = HomeworkBank.find params[:id]
+ rescue ActiveRecord::RecordNotFound
+ render_404
+ end
+end
diff --git a/app/controllers/homework_common_controller.rb b/app/controllers/homework_common_controller.rb
index 1812e7cff..0f267f212 100644
--- a/app/controllers/homework_common_controller.rb
+++ b/app/controllers/homework_common_controller.rb
@@ -5,37 +5,54 @@ class HomeworkCommonController < ApplicationController
layout "base_courses"
include StudentWorkHelper
+ include ApplicationHelper
before_filter :find_course, :only => [:index,:new,:create]
before_filter :find_homework, :only => [:edit,:update,:alert_anonymous_comment,:start_anonymous_comment,:stop_anonymous_comment,:destroy,:start_evaluation_set,
:set_evaluation_attr,:score_rule_set,:alert_forbidden_anonymous_comment,:alert_open_student_works,:open_student_works,
- :set_score_open,:alert_score_open_modal,:add_to_homework_bank,:publish_homework]
+ :set_score_open,:alert_score_open_modal,:add_to_homework_bank,:publish_homework,:setting,:set_public,:homework_setting,:update_explanation]
before_filter :teacher_of_course, :only => [:new, :create, :edit, :update, :destroy, :start_anonymous_comment, :stop_anonymous_comment, :alert_anonymous_comment,
:start_evaluation_set,:set_evaluation_attr,:score_rule_set,:alert_forbidden_anonymous_comment,:alert_open_student_works,
- :open_student_works,:add_to_homework_bank,:publish_homework]
- before_filter :member_of_course, :only => [:index]
+ :open_student_works,:add_to_homework_bank,:publish_homework,:update_explanation]
+ before_filter :member_of_course, :only => [:index,:setting]
def index
#unless params[:page]
# update_homework_time(@course.homework_commons)
#end
- search = "%#{params[:search].to_s.strip.downcase}%"
- @new_homework = HomeworkCommon.new
- @new_homework.homework_detail_manual = HomeworkDetailManual.new
- @new_homework.course = @course
+ @search = "#{params[:search].to_s.strip.downcase}" if params[:search]
+ @order = params[:order]
@page = params[:page] ? params[:page].to_i + 1 : 0
+ @homework_type = params[:homework_type].to_i
@is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@course))
- if @is_teacher
- #@homeworks = @course.homework_commons.order("created_at desc").limit(10).offset(@page * 10)
- @homework_commons = @course.homework_commons.where("name like '%#{search}%'").order("created_at desc")
+ if @search
+ @homework_commons = @course.homework_commons.where(:homework_type => @homework_type).where("name like '%#{@search}%'")
else
- #@homeworks = @course.homework_commons.where("publish_time <= '#{Date.today}'").order("created_at desc").limit(10).offset(@page * 10)
- @homework_commons = @course.homework_commons.where("name like '%#{search}%' and publish_time <= '#{Time.now}'").order("created_at desc")
+ @homework_commons = @course.homework_commons.where(:homework_type => @homework_type)
+ end
+ if @order.blank?
+ if @is_teacher
+ @homework_commons = @homework_commons.order("publish_time desc")
+ else
+ @homework_commons = @homework_commons.where("publish_time <= '#{Time.now}'").order("publish_time desc")
+ end
+ else
+ case @order
+ when '1'
+ @homework_commons = @homework_commons.includes(:homework_detail_manual).where("homework_detail_manuals.comment_status = #{@order} and end_time > '#{Time.now}'").order("homework_commons.publish_time desc")
+ when '3'
+ @homework_commons = @homework_commons.includes(:homework_detail_manual).where("homework_detail_manuals.comment_status = #{@order} and homework_detail_manuals.evaluation_end > '#{Time.now}'").order("homework_commons.publish_time desc")
+ when '4'
+ @homework_commons = @homework_commons.includes(:homework_detail_manual).where("(homework_detail_manuals.comment_status = #{@order} and homework_detail_manuals.appeal_time > '#{Time.now}')").order("homework_commons.publish_time desc")
+ when '5'
+ @homework_commons = @homework_commons.includes(:homework_detail_manual).where("(homework_detail_manuals.comment_status = #{@order} and archive_time > '#{Time.now}')").order("homework_commons.publish_time desc")
+ else
+ @homework_commons = @homework_commons.includes(:homework_detail_manual).where("homework_detail_manuals.comment_status = #{@order}").order("homework_commons.publish_time desc")
+ end
end
- #update_homework_time @homework_commons
@is_student = User.current.logged? && (User.current.admin? || (User.current.member_of_course?(@course) && !@is_teacher))
@is_new = params[:is_new]
- @homeworks = paginateHelper @homework_commons,10
+ @homeworks = paginateHelper @homework_commons,15
#设置at已读
ids = @homeworks.inject([]) do |ids, homework|
jids = homework.journals_for_messages.map(&:id)
@@ -58,33 +75,294 @@ class HomeworkCommonController < ApplicationController
#新建作业,在个人作业列表创建作业
def new
- render_404
+ @homework_type = params[:homework_type].to_i
+ @homework = HomeworkCommon.new
+ @ref_answer = HomeworkReferenceAnswer.new
+ respond_to do |format|
+ format.html{render :layout => 'base_edu'}
+ end
+ end
+
+ # 新建实训作业
+ def shixuns
+ search = params[:search]
+ @course = Course.find(params[:course])
+ @homework = HomeworkCommon.new
+ @shixuns = Shixun.where(:status => 2).where("name like ?", "%#{search}%")
+ @shixuns_count = @shixuns.count
+ @limit = 8
+ @is_remote = true
+ @shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
+ @offset ||= @shixun_pages.offset
+ @shixuns = paginateHelper @shixuns, @limit
+ respond_to do |format|
+ format.js
+ end
end
#新建作业,在个人作业列表创建作业
def create
- redirect_to user_homeworks_user_path(User.current.id)
+ if params[:homework_common] || params[:shixun_homework]
+ homework = HomeworkCommon.new
+ if params[:shixun_homework]
+ shixun = Shixun.find(params[:shixun_homework])
+ homework.name = shixun.name
+ homework.description = shixun.description
+ else
+ homework.name = params[:homework_common][:name]
+ homework.description = params[:homework_common][:description]
+ homework.reference_answer = params[:homework_common][:reference_answer]
+ homework.save_attachments(params[:attachments])
+ render_attachment_warning_if_needed(homework)
+ end
+ homework.anonymous_comment = 1
+ homework.homework_type = params[:shixun_homework] ? 4 : (params[:homework_type].to_i || 1)
+ homework.late_penalty = 0
+ homework.teacher_priority = 1
+ homework.user_id = User.current.id
+ homework.course_id = params[:course]
+
+
+ homework_detail_manual = HomeworkDetailManual.new
+ homework_detail_manual.te_proportion = 1.0
+ homework_detail_manual.ta_proportion = 0
+ homework_detail_manual.comment_status = 0
+
+ homework_detail_manual.evaluation_num = 0
+ homework_detail_manual.absence_penalty = 0
+ homework.homework_detail_manual = homework_detail_manual
+
+ #编程作业相关属性
+ if homework.homework_type == 2
+ homework_detail_programing = HomeworkDetailPrograming.new
+ homework.homework_detail_programing = homework_detail_programing
+ homework_detail_programing.ta_proportion = 0
+ homework_detail_programing.language = params[:language_type].to_i
+
+ sample_inputs = params[:sample][:input]
+ if Array === sample_inputs
+ sample_inputs.each_with_index do |val, i|
+ homework.homework_samples << HomeworkSample.new(
+ input: val,
+ output: params[:sample][:output][i]
+ )
+ end
+ end
+
+ inputs = params[:program][:input]
+ if Array === inputs
+ inputs.each_with_index do |val, i|
+ homework.homework_tests << HomeworkTest.new(
+ input: val,
+ output: params[:program][:output][i]
+ )
+ end
+ end
+ end
+
+ #分组作业
+ if homework.homework_type == 3
+ homework_detail_group = HomeworkDetailGroup.new
+ homework.homework_detail_group = homework_detail_group
+ homework_detail_group.min_num = params[:min_num].to_i
+ homework_detail_group.max_num = params[:max_num].to_i
+ homework_detail_group.base_on_project = 0
+ end
+
+ if homework.save
+ homework_detail_manual.save if homework_detail_manual
+ homework_detail_programing.save if homework_detail_programing
+ homework_detail_group.save if homework_detail_group
+
+ if homework.homework_type != 4 && homework_detail_manual.comment_status == 1
+ create_works_list homework
+ elsif homework.homework_type == 4
+ HomeworkCommonsShixuns.create(:homework_common_id => homework.id, :shixun_id => shixun.id)
+ end
+
+ if params[:quotes] && !params[:quotes].blank?
+ quotes_homework = HomeworkBank.find params[:quotes].to_i
+ quotes_homework.update_column(:quotes, quotes_homework.quotes+1)
+ homework.update_attributes(:homework_bank_id => quotes_homework.id)
+ end
+
+ # if params[:add_to_bank]
+ # homework_bank = add_to_homework_bank_f homework
+ # homework_bank.save
+ # homework.update_attributes(:homework_bank_id => homework_bank.id)
+ # end
+ redirect_to student_work_index_path(:homework => homework.id, :is_new => 1, :tab => 4)
+ end
+ end
+ end
+
+ def setting
+ @is_new = params[:is_new].to_i if params[:is_new]
+ @is_empty = @homework.publish_time.nil?
+ @is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@course))
+ respond_to do |format|
+ format.html{render :layout => 'base_edu'}
+ end
+ end
+
+ def homework_setting
+ @homework.publish_time = params[:homework_publish_time] if params[:homework_publish_time]
+ @homework.end_time = params[:homework_end_time] if params[:homework_end_time]
+ @homework.archive_time = params[:homework_archive_time] if params[:homework_archive_time]
+ if @homework.archive_time < Time.now && @homework_detail_manual.comment_status < 6
+ @homework_detail_manual.comment_status = 6
+ elsif @homework.archive_time > Time.now && @homework_detail_manual.comment_status == 6
+ @homework_detail_manual.comment_status = 5
+ end
+
+ if params[:homework_allow_late] == '1'
+ @homework.allow_late = true
+ @homework.late_penalty = params[:homework_late_penalty].to_i
+ else
+ @homework.allow_late = false
+ @homework.late_penalty = 0
+ end
+
+ anonymous_comment = @homework.anonymous_comment
+ absence_penalty = @homework_detail_manual.absence_penalty
+ appeal_penalty = @homework_detail_manual.appeal_penalty
+ if @homework_detail_manual.comment_status < 3
+ if params[:homework_anonymous_comment]
+ @homework.anonymous_comment = 0
+ @homework_detail_manual.evaluation_start = params[:homework_evaluation_start] if params[:homework_evaluation_start]
+ @homework_detail_manual.evaluation_end = params[:homework_evaluation_end] if params[:homework_evaluation_end]
+ @homework_detail_manual.evaluation_num = params[:homework_evaluation_num] if params[:homework_evaluation_num]
+ @homework_detail_manual.absence_penalty = params[:homework_absence_penalty] if params[:homework_absence_penalty]
+ else
+ @homework.anonymous_comment = 1
+ @homework_detail_manual.evaluation_start = nil
+ @homework_detail_manual.evaluation_end = nil
+ @homework_detail_manual.evaluation_num = 0
+ @homework_detail_manual.absence_penalty = 0
+ end
+ else
+ @homework_detail_manual.evaluation_end = params[:homework_evaluation_end] if params[:homework_evaluation_end]
+ @homework_detail_manual.evaluation_num = params[:homework_evaluation_num] if params[:homework_evaluation_num]
+ @homework_detail_manual.absence_penalty = params[:homework_absence_penalty] if params[:homework_absence_penalty]
+ end
+ if anonymous_comment != @homework.anonymous_comment
+ @homework_detail_manual.te_proportion = 1
+ @homework_detail_manual.ta_proportion = 0
+ @homework_detail_programing.ta_proportion = 0 if @homework_detail_programing
+ end
+ if @homework_detail_manual.comment_status < 4
+ if @homework.anonymous_comment == 0 && params[:homework_anonymous_appeal]
+ @homework.anonymous_appeal = 1
+ @homework_detail_manual.appeal_time = params[:homework_appeal_time] if params[:homework_appeal_time]
+ @homework_detail_manual.appeal_penalty = params[:homework_appeal_penalty] if params[:homework_appeal_penalty]
+ else
+ @homework.anonymous_appeal = 0
+ @homework_detail_manual.appeal_time = nil
+ @homework_detail_manual.appeal_penalty = 0
+ end
+ else
+ @homework_detail_manual.appeal_time = params[:homework_appeal_time] if params[:homework_appeal_time]
+ @homework_detail_manual.appeal_penalty = params[:homework_appeal_penalty] if params[:homework_appeal_penalty]
+ end
+ if absence_penalty != @homework_detail_manual.absence_penalty && @homework_detail_manual.comment_status >= 4
+ all_dis_eva = StudentWorksEvaluationDistribution.where(:student_work_id => @homework.student_works.map(&:id))
+ has_sw_count = all_dis_eva.select("distinct user_id").count
+ anon_count = all_dis_eva.count / has_sw_count
+ @homework.student_works.where("work_status != 0").each do |student_work|
+ absence_penalty_count = student_work.user.student_works_evaluation_distributions.where(:student_work_id => @homework.student_works.map(&:id)).count - student_work.user.student_works_scores.where(:student_work_id => @homework.student_works.map(&:id), :reviewer_role => 3).count
+ student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * @homework_detail_manual.absence_penalty : 0
+ student_work.save
+ end
+ end
+ if appeal_penalty != @homework_detail_manual.appeal_penalty && @homework_detail_manual.comment_status >= 4
+ @homework.student_works.each do |student_work|
+ appeal_penalty_count = student_work.user.student_works_scores.where(:student_work_id => @homework.student_works.map(&:id), :appeal_status => 3).count
+ student_work.appeal_penalty = appeal_penalty_count > 0 ? appeal_penalty_count * @homework_detail_manual.absence_penalty : 0
+ student_work.save
+ end
+ end
+
+ if params[:homework_ta_mode] && @homework_detail_manual.ta_mode.to_i != params[:homework_ta_mode].to_i
+ @homework_detail_manual.ta_mode = params[:ta_mode].to_i
+ @homework_detail_manual.save
+ if @homework_detail_manual.ta_mode == 1
+ @homework.student_works.where("work_status != 0").each do |student_work|
+ ts_score = StudentWorksScore.find_by_sql("SELECT AVG(score) AS score FROM (SELECT * FROM (SELECT * FROM student_works_scores WHERE student_work_id = #{student_work.id} AND reviewer_role = 2 AND score IS NOT NULL ORDER BY created_at DESC) AS t GROUP BY user_id) AS a")
+ student_work.teaching_asistant_score = ts_score.first.score.nil? ? nil : ts_score.first.score.try(:round, 2).to_f
+ student_work.save
+ end
+ else
+ @homework.student_works.where("work_status != 0").each do |student_work|
+ ts_score = StudentWorksScore.where("student_work_id = #{student_work.id} AND reviewer_role = 2 AND score IS NOT NULL").order("created_at DESC")
+ student_work.teaching_asistant_score = ts_score.first.nil? ? nil : ts_score.first.score
+ student_work.save
+ end
+ end
+ end
+
+ if params[:homework_final_mode] && params[:homework_final_mode].to_i != @homework_detail_manual.final_mode
+ @homework_detail_manual.final_mode = params[:homework_final_mode].to_i
+ if params[:homework_final_mode].to_i == 0
+ @homework_detail_manual.te_proportion = params[:te_proportion]
+ @homework_detail_manual.ta_proportion = params[:ta_proportion]
+ @homework_detail_programing.ta_proportion = params[:sy_proportion] if @homework_detail_programing
+ @homework_detail_programing.save if @homework_detail_programing
+ end
+ @homework_detail_manual.save if @homework_detail_manual
+ @homework.save
+ @homework = HomeworkCommon.find @homework.id
+ @homework.student_works.each do |student_work|
+ set_final_score @homework,student_work
+ student_work.save
+ end
+ elsif params[:homework_final_mode] && @homework_detail_manual.final_mode == 0
+ if (params[:te_proportion] && params[:te_proportion].to_s != @homework_detail_manual.te_proportion.to_s) || (params[:ta_proportion] && params[:ta_proportion].to_s != @homework_detail_manual.ta_proportion.to_s) || (@homework_detail_programing && @homework_detail_programing.ta_proportion.to_s != params[:sy_proportion].to_s)
+ @homework_detail_manual.te_proportion = params[:te_proportion]
+ @homework_detail_manual.ta_proportion = params[:ta_proportion]
+ @homework_detail_programing.ta_proportion = params[:sy_proportion] if @homework_detail_programing
+
+ @homework_detail_manual.save if @homework_detail_manual
+ @homework_detail_programing.save if @homework_detail_programing
+ @homework.save
+ @homework = HomeworkCommon.find @homework.id
+ @homework.student_works.each do |student_work|
+ set_final_score @homework,student_work
+ student_work.save
+ end
+ end
+ end
+
+ if @homework.homework_type == 4
+ if @homework_detail_manual.answer_open_evaluation != params[:answer_open_evaluation].to_i
+ @homework_detail_manual.answer_open_evaluation = params[:answer_open_evaluation].to_i
+ if @homework.end_time < Time.now
+ @homework.student_works.each do |student_work|
+ set_shixun_final_score @homework, student_work, @homework_detail_manual.answer_open_evaluation
+ end
+ end
+ end
+ @homework.score_open = params[:homework_score_open] ? 1 : 0
+ else
+ @homework.work_public = params[:homework_work_public] ? 1 : 0
+ @homework.score_open = params[:homework_score_open] ? 1 : 0
+ @homework.answer_public = params[:homework_answer_public] ? 1 : 0
+ end
+ @homework.save
+ @homework_detail_manual.save
+ redirect_to student_work_index_path(:homework => @homework.id)
end
def edit
@user = User.current
- @hw_status = params[:hw_status].to_i
- @is_manage = params[:is_manage]
- if @hw_status != 1
- @left_nav_type = 3
- respond_to do |format|
- format.html{render :layout => 'base_courses'}
- end
- else
- respond_to do |format|
- format.html{render :layout => 'base_course_community'}
- end
+ @homework_type = @homework.homework_type
+ respond_to do |format|
+ format.html{render :layout => 'base_edu'}
end
end
def update
if params[:homework_common]
- is_update = @homework.name != params[:homework_common][:name] || @homework.description != params[:homework_common][:description] || params[:homework_type].to_i != @homework.homework_type
+ is_update = @homework.name != params[:homework_common][:name] || @homework.description != params[:homework_common][:description] || @homework.reference_answer != params[:homework_common][:reference_answer]
if params[:homework_type].to_i == 2
is_update = is_update || params[:language_type] != @homework.homework_detail_programing.language
if !is_update && params[:sample] && params[:program]
@@ -98,92 +376,8 @@ class HomeworkCommonController < ApplicationController
@homework.name = params[:homework_common][:name]
@homework.description = params[:homework_common][:description]
- homework_detail_manual = @homework.homework_detail_manual || HomeworkDetailManual.new
- if params[:homework_common][:end_time] != ""
- if params[:homework_common][:publish_time] == ""
- @homework.publish_time = Time.now
- else
- @homework.publish_time = params[:homework_common][:publish_time]
- end
- param_end_time = Time.parse(params[:homework_common][:end_time]).to_s
- homework_end_time = @homework.end_time ? @homework.end_time.to_s : ''
- if homework_end_time != param_end_time
- if homework_end_time > param_end_time
- @homework.student_works.where("work_status = 1").each do |st|
- if param_end_time < st.commit_time
- st.late_penalty = @homework.late_penalty
- st.work_status = 2
- st.save
- #更新CourseHomeworkStatistics中学生的迟交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, st.user_id)
- course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
- end
- end
- else
- @homework.student_works.where("work_status = 2").each do |st|
- if param_end_time >= Time.parse(st.commit_time.to_s).strftime("%Y-%m-%d")
- st.late_penalty = 0
- st.work_status = 1
- st.save
- #更新CourseHomeworkStatistics中学生的迟交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, st.user_id)
- course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
- end
- end
- end
- end
- @homework.end_time = params[:homework_common][:end_time] || Time.now
-
- status = false
- if @homework.publish_time > Time.now && homework_detail_manual.comment_status == 1
- homework_detail_manual.comment_status = 0
- @homework.student_works.destroy_all
- #更新CourseHomeworkStatistics中每个学生的未交作品数
- @homework.course.student.each do |student|
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
- course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
- end
- elsif @homework.publish_time <= Time.now && homework_detail_manual.comment_status == 0
- homework_detail_manual.comment_status = 1
- create_works_list @homework if params[:homework_type].to_i != 3
- status = true
- #更新CourseHomeworkStatistics中每个学生的未交作品数
- @homework.course.student.each do |student|
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
- course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
- end
- end
-
- eval_start = homework_detail_manual.evaluation_start
- if eval_start.nil? || (Time.parse(eval_start.to_s) <= @homework.end_time && homework_detail_manual.comment_status <= 1)
- homework_detail_manual.evaluation_start = (@homework.end_time + 7*24*60*60).strftime("%Y-%m-%d")
- homework_detail_manual.evaluation_end = homework_detail_manual.evaluation_start + 7
- end
- end
-
- if params[:homework_type] && params[:homework_type].to_i != @homework.homework_type
- if @homework.homework_type == 2
- @homework.homework_detail_programing.destroy if @homework.homework_detail_programing
- @homework.homework_tests.destroy_all
- elsif @homework.homework_type == 3
- @homework.homework_detail_group.destroy if @homework.homework_detail_group
- create_works_list @homework if homework_detail_manual.comment_status > 0 && @homework.student_works.empty?
- end
- if params[:homework_type].to_i == 3
- @homework.student_works.destroy_all
- end
- @homework.homework_type = params[:homework_type].to_i
- end
- anonymous = params[:homework_common][:anonymous_comment] ? params[:homework_common][:anonymous_comment].to_i : 1
- if anonymous != @homework.anonymous_comment
- if anonymous == 1
- homework_detail_manual.ta_proportion = @homework.homework_type == 2 ? 0.4 : 1.0
- else
- homework_detail_manual.ta_proportion = @homework.homework_type == 2 ? 0.3 : 0.6
- end
- end
-
@homework.save_attachments(params[:attachments])
+ @homework.reference_answer = params[:homework_common][:reference_answer]
render_attachment_warning_if_needed(@homework)
#编程作业相关属性
@@ -191,13 +385,6 @@ class HomeworkCommonController < ApplicationController
@homework.homework_detail_programing ||= HomeworkDetailPrograming.new
@homework_detail_programing = @homework.homework_detail_programing
@homework_detail_programing.language = params[:language_type].to_i if params[:language_type]
- if anonymous != @homework.anonymous_comment
- if anonymous == 1
- @homework_detail_programing.ta_proportion = 0.6
- else
- @homework_detail_programing.ta_proportion = 0.5
- end
- end
@homework.homework_samples.delete_all if params[:sample]
sample_inputs = params[:sample][:input] if params[:sample]
@@ -231,15 +418,7 @@ class HomeworkCommonController < ApplicationController
@homework_detail_group.base_on_project = params[:base_on_project] ? 1 : 0
end
- if anonymous != @homework.anonymous_comment
- @homework.student_works.where("work_status != 0").each do |student_work|
- student_work.save
- end
- end
-
- @homework.anonymous_comment = params[:homework_common][:anonymous_comment] ? params[:homework_common][:anonymous_comment].to_i : 1
if @homework.save
- homework_detail_manual.save if homework_detail_manual
@homework_detail_programing.save if @homework_detail_programing
@homework_detail_group.save if @homework_detail_group
@@ -247,20 +426,7 @@ class HomeworkCommonController < ApplicationController
# create_works_list @homework
# end
- @hw_status = params[:hw_status].to_i
- if params[:is_manage] == "1"
- redirect_to user_manage_homeworks_user_path(User.current.id)
- elsif params[:is_manage] == "2"
- redirect_to user_receive_homeworks_user_path(User.current.id)
- elsif @hw_status == 1
- redirect_to user_course_community_path(User.current.id)
- elsif @hw_status == 2
- redirect_to course_path(@course.id)
- elsif @hw_status == 5
- redirect_to student_work_index_url(:homework => @homework.id)
- else
- redirect_to homework_common_index_path(:course => @course.id)
- end
+ redirect_to student_work_index_url(:homework => @homework.id)
end
end
end
@@ -275,43 +441,43 @@ class HomeworkCommonController < ApplicationController
is_eva_student_works = StudentWork.where(:homework_common_id => is_eva_homeworks.map{|hw| hw.id})
has_eva_homeworks = @course.homework_commons.includes(:homework_detail_manual).where("homework_commons.anonymous_comment = 0 and homework_detail_manuals.comment_status = 3")
has_eva_student_works = StudentWork.where(:homework_common_id => has_eva_homeworks.map{|hw| hw.id})
- @course.student.each do |student|
- user = student.student
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
- if user && course_statistics
- committed_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status != 0").count
- un_commit_work_num = (hw_count - committed_work_num) < 0 ? 0 : (hw_count - committed_work_num)
- late_commit_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status = 2").count
- absence_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => has_eva_student_works.map(&:id)).count -
- user.student_works_scores.where(:reviewer_role => 3, :student_work_id => has_eva_student_works.map(&:id)).group_by(&:student_work_id).count
- absence_evaluation_work_num = absence_evaluation_work_num < 0 ? 0 : absence_evaluation_work_num
- un_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => is_eva_student_works.map(&:id)).count -
- user.student_works_scores.where(:reviewer_role => 3, :student_work_id => is_eva_student_works.map(&:id)).group_by(&:student_work_id).count
- un_evaluation_work_num = un_evaluation_work_num < 0 ? 0 : un_evaluation_work_num
- appeal_num = user.student_works_scores.where(:student_work_id => student_works.map(&:id), :appeal_status => 3).count
- average_score = user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first.score : 0
- total_score = user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first.score : 0
- course_statistics.update_attributes(:committed_work_num => committed_work_num, :un_commit_work_num => un_commit_work_num,
- :late_commit_work_num => late_commit_work_num, :absence_evaluation_work_num => absence_evaluation_work_num, :un_evaluation_work_num => un_evaluation_work_num,
- :appeal_num => appeal_num, :average_score => average_score, :total_score => total_score)
- end
- end
+ # @course.student.each do |student|
+ # user = student.student
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
+ # if user && course_statistics
+ # committed_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status != 0").count
+ # un_commit_work_num = (hw_count - committed_work_num) < 0 ? 0 : (hw_count - committed_work_num)
+ # late_commit_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status = 2").count
+ # absence_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => has_eva_student_works.map(&:id)).count -
+ # user.student_works_scores.where(:reviewer_role => 3, :student_work_id => has_eva_student_works.map(&:id)).group_by(&:student_work_id).count
+ # absence_evaluation_work_num = absence_evaluation_work_num < 0 ? 0 : absence_evaluation_work_num
+ # un_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => is_eva_student_works.map(&:id)).count -
+ # user.student_works_scores.where(:reviewer_role => 3, :student_work_id => is_eva_student_works.map(&:id)).group_by(&:student_work_id).count
+ # un_evaluation_work_num = un_evaluation_work_num < 0 ? 0 : un_evaluation_work_num
+ # appeal_num = user.student_works_scores.where(:student_work_id => student_works.map(&:id), :appeal_status => 3).count
+ # average_score = user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first.score : 0
+ # total_score = user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first.score : 0
+ # course_statistics.update_attributes(:committed_work_num => committed_work_num, :un_commit_work_num => un_commit_work_num,
+ # :late_commit_work_num => late_commit_work_num, :absence_evaluation_work_num => absence_evaluation_work_num, :un_evaluation_work_num => un_evaluation_work_num,
+ # :appeal_num => appeal_num, :average_score => average_score, :total_score => total_score)
+ # end
+ # end
respond_to do |format|
format.html {
- @hw_status = params[:hw_status].to_i
- if @hw_status == 1
- redirect_to user_path(User.current.id)
- elsif @hw_status == 2
- redirect_to course_path(@course.id)
- else
- redirect_to homework_common_index_path(:course => @course.id)
- end
+ redirect_to homework_common_index_path(:course => @course.id, :homework_type => @homework.homework_type)
}
end
end
end
+ #更新作业说明
+ def update_explanation
+ @is_teacher = User.current.admin? || User.current.allowed_to?(:as_teacher, @course)
+ @homework.update_attribute('explanation', params[:homework_common][:explanation])
+ redirect_to student_work_index_path(:homework => @homework.id, :tab => 2)
+ end
+
#加入到题库
def add_to_homework_bank
if params[:type] && (params[:type].to_i == 1 || params[:type].to_i == 3)
@@ -325,24 +491,25 @@ class HomeworkCommonController < ApplicationController
end
homework_bank = add_to_homework_bank_f @homework
homework_bank.save
+ if @homework.homework_type == 4
+ HomeworkBankShixun.create(:homework_bank_id => homework_bank.id, :shixun_id => @homework.homework_commons_shixuns.shixun_id)
+ end
@homework.update_attributes(:homework_bank_id => homework_bank.id)
elsif params[:type].to_i == 2
homework_bank = HomeworkBank.where(:id => @homework.homework_bank_id).first
if homework_bank
- homework_bank.update_attributes(:name => @homework.name, :description => @homework.description, :homework_type => @homework.homework_type)
+ homework_bank.update_attributes(:name => @homework.name, :description => @homework.description, :homework_type => @homework.homework_type, :reference_answer => @homework.reference_answer)
if @homework.homework_type == 2 && @homework.homework_detail_programing
homework_bank.update_attributes(:language => @homework.homework_detail_programing.language)
homework_bank.homework_bank_tests.destroy_all
@homework.homework_tests.each_with_index do |homework_test|
homework_bank.homework_bank_tests << HomeworkBankTest.new(
- test_type: 1,
input: homework_test.input,
output: homework_test.output
)
end
@homework.homework_samples.each_with_index do |homework_test|
- homework_bank.homework_bank_tests << HomeworkBankTest.new(
- test_type: 0,
+ homework_bank.homework_bank_samples << HomeworkBankSample.new(
input: homework_test.input,
output: homework_test.output
)
@@ -355,9 +522,14 @@ class HomeworkCommonController < ApplicationController
if @homework.is_update
@homework.update_attributes(:is_update => 0)
end
- @user_activity_id = params[:user_activity_id].to_i
- @hw_status = params[:hw_status].to_i
- @is_teacher = User.current.admin? || User.current.allowed_to?(:as_teacher, @course)
+ end
+
+ def set_public
+ @homework.update_attributes(:is_public => true)
+ respond_to do |format|
+ format.html{ redirect_to student_work_index_path(:homework => @homework.id) }
+ format.js
+ end
end
def publish_homework
@@ -374,10 +546,10 @@ class HomeworkCommonController < ApplicationController
create_works_list @homework
end
#更新CourseHomeworkStatistics中每个学生的未交作品数
- @course.student.each do |student|
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
- course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
- end
+ # @course.student.each do |student|
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student.student_id)
+ # course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
+ # end
@course.members.each do |m|
@homework.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => @course.id, :viewed => false, :status => nil)
@@ -434,8 +606,8 @@ class HomeworkCommonController < ApplicationController
end
#更新CourseHomeworkStatistics中该学生的待匿评数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, pro_work.user_id)
- course_statistics.update_attribute('un_evaluation_work_num', course_statistics.un_evaluation_work_num + n) if course_statistics
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, pro_work.user_id)
+ # course_statistics.update_attribute('un_evaluation_work_num', course_statistics.un_evaluation_work_num + n) if course_statistics
end
else
student_works.each_with_index do |work, index|
@@ -449,8 +621,8 @@ class HomeworkCommonController < ApplicationController
end
#更新CourseHomeworkStatistics中该学生的待匿评数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, user.id)
- course_statistics.update_attribute('un_evaluation_work_num', course_statistics.un_evaluation_work_num + n) if course_statistics
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, user.id)
+ # course_statistics.update_attribute('un_evaluation_work_num', course_statistics.un_evaluation_work_num + n) if course_statistics
end
end
@homework_detail_manual.update_column('comment_status', 2)
@@ -485,9 +657,9 @@ class HomeworkCommonController < ApplicationController
student_work.save
#更新CourseHomeworkStatistics中该学生的待匿评数和缺评数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student_work.user_id)
- course_statistics.update_attribute('un_evaluation_work_num', (course_statistics.un_evaluation_work_num - absence_penalty_count) < 0 ? 0 : (course_statistics.un_evaluation_work_num - absence_penalty_count)) if course_statistics
- course_statistics.update_attribute('absence_evaluation_work_num', course_statistics.absence_evaluation_work_num + absence_penalty_count) if course_statistics
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, student_work.user_id)
+ # course_statistics.update_attribute('un_evaluation_work_num', (course_statistics.un_evaluation_work_num - absence_penalty_count) < 0 ? 0 : (course_statistics.un_evaluation_work_num - absence_penalty_count)) if course_statistics
+ # course_statistics.update_attribute('absence_evaluation_work_num', course_statistics.absence_evaluation_work_num + absence_penalty_count) if course_statistics
end
# 未参与匿评的缺评计算
diff --git a/app/controllers/iframes_controller.rb b/app/controllers/iframes_controller.rb
new file mode 100644
index 000000000..2d1091219
--- /dev/null
+++ b/app/controllers/iframes_controller.rb
@@ -0,0 +1,17 @@
+class IframesController < ApplicationController
+ layout false
+ skip_before_filter :verify_authenticity_token, :only => [:html_content]
+
+ def show
+ render :layout => false
+ end
+
+ # 渲染实训代码
+ def html_content
+ @contents = params[:contents] || ""
+ respond_to do |format|
+ format.js
+ format.html
+ end
+ end
+end
diff --git a/app/controllers/kubernete_controller.rb b/app/controllers/kubernete_controller.rb
new file mode 100644
index 000000000..84575841d
--- /dev/null
+++ b/app/controllers/kubernete_controller.rb
@@ -0,0 +1,72 @@
+class KuberneteController < ApplicationController
+ require 'open3'
+ layout "base_edu"
+
+ RC_PATH = "files/k8s/webssh/controller.yaml"
+ SVC_PATH = "files/k8s/webssh/service.yaml"
+ SERVER_URL = "https://106.75.96.108:6443"
+ TOKEN = "c7dd73a7c86992fb"
+ # YAML.load(File.open(rc_PATH))
+ # REDO:销毁的时候文件一并要销毁
+ def exec_pod
+ # 生成ymal文件
+ nod_name = params[:name]
+ path_type = params[:type]
+ rc = YAML.load(File.open(RC_PATH))
+ svc = YAML.load(File.open(SVC_PATH))
+ File.new(File.join("files/k8s/#{path_type}", "controller-#{nod_name}.yaml"),"w+")
+ File.new(File.join("files/k8s/#{path_type}", "service-#{nod_name}.yaml"),"w+")
+ rc = change_yaml_info(rc, nod_name, "rc")
+ svc = change_yaml_info(svc, nod_name, "svc")
+ current_rc_path = "files/k8s/#{path_type}/controller-#{nod_name}.yaml"
+ current_svc_path = "files/k8s/#{path_type}/service-#{nod_name}.yaml"
+ open(current_rc_path, 'w') { |f| YAML.dump(rc, f) }
+ open(current_svc_path, 'w') { |f| YAML.dump(svc, f) }
+ # 启动容器
+ # 删除容器命令
+ # 如果连接到其它服务器可以使用ssh -t
+ kubenete_rc = "kubectl --server='" + SERVER_URL + "' --token='" + TOKEN + "' --insecure-skip-tls-verify=true " + "create -f " + current_rc_path
+ kubenete_svc = "kubectl --server='" + SERVER_URL + "' --token='" + TOKEN + "' --insecure-skip-tls-verify=true " + "create -f " + current_svc_path
+ logger.info("webss kubenete_rc is" + kubenete_rc)
+ logger.info("webss kubenete_svc is" + kubenete_svc)
+ # stdin, stdout, stderr, wait_thr = Open3.popen3([env,] cmd... [, opts])
+ # 可以多少秒以后执行
+ stdin, stdout, stderr = Open3.popen3(kubenete_rc)
+ logger.info("Open3 result is ###"+ stdout.gets)
+ stdin2, stdout2, stderr2 = Open3.popen3(kubenete_svc)
+ logger.info("Open3 result is ###"+ stdout2.gets)
+ render :json => {:status => "good"}
+ end
+
+ def exec_container
+ pod_name = "webssh-master#{parmas[:myshixun_id]}"
+ git_url =
+ # kubectl exec webssh-master1-gn1ww -c webssh python -v
+ # webssh 容器中执行命令,克隆代码,注意代码存放位置
+ git_clone = "kubectl --server='#{SERVER_URL}' --token='#{TOKEN}' --insecure-skip-tls-verify=true exec webssh-master1-gn1ww -c webssh clone #{git_url}"
+ stdin, stdout, stderr = Open3.popen3(git_clone)
+ format.js
+ end
+
+ def new
+ end
+
+ def create
+
+ end
+
+ private
+ # yaml数据处理
+ # 处理数据类型如下
+ def change_yaml_info rc, nod_name, type
+ rc['metadata']['name'] = rc['metadata']['name'] + nod_name
+ rc['metadata']['labels']['name'] = rc['metadata']['labels']['name'] + nod_name
+ rc['spec']['selector']['name'] = rc['spec']['selector']['name'] + nod_name
+ if type == "rc"
+ rc['spec']['template']['metadata']['labels']['name'] = rc['spec']['template']['metadata']['labels']['name'] + nod_name
+ elsif type == "svc"
+ rc['spec']['ports'][0]['nodePort'] = rc['spec']['ports'][0]['nodePort'].to_i + nod_name.to_i
+ end
+ return rc
+ end
+end
diff --git a/app/controllers/managements_controller.rb b/app/controllers/managements_controller.rb
new file mode 100644
index 000000000..198917000
--- /dev/null
+++ b/app/controllers/managements_controller.rb
@@ -0,0 +1,1738 @@
+# encoding: utf-8
+class ManagementsController < ApplicationController
+ before_filter :require_admin
+ layout 'base_management'
+ include ManagementsHelper
+ include SortHelper
+ include UsersHelper
+ include ApplicationHelper
+
+ #用户修改
+ def account
+ @user = User.find(params[:user_id])
+ ue = @user.user_extensions
+ # @trail_authentication = ApplyAction.where(:user_id => @user.id, :container_type => "TrialAuthorization").order("created_at desc").first
+ # @authentication = @user.authentication
+ # if @user.nickname.nil? || @user.lastname.nil? || ue.try(:identity).nil? || ue.try(:location).nil? || ue.try(:location).nil?
+ # @require_auth = true
+ # else
+ # if User.current.certification != 1 && (@trail_authentication.blank? || (@trail_authentication.status == 2 && (@trail_authentication.updated_at.to_i + 5*60) < Time.now.to_i))
+ # @require_trail_auth = true
+ # end
+ # end
+ # @s_message = AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddSchools').first
+ # @d_message = AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddDepartment').first
+
+ # AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddSchools').update_all(:viewed => true)
+ # AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddDepartment').update_all(:viewed => true)
+
+ lg = @user.login
+ @pref = @user.pref
+ diskfile = disk_filename('User', @user.id)
+ diskfile1 = diskfile + 'temp'
+ begin
+ if request.post?
+ @user.nickname = params[:nickname]
+ @user.lastname = params[:lastname]
+ @user.firstname = ""
+ @user.show_realname = params[:show_realname] ? 0 : 1
+ @user.pref.attributes = params[:pref]
+ @user.mail = params[:mail]
+ @user.phone = params[:phone]
+ @user.password = params[:new_password]
+ @user.pref[:no_self_notified] = (params[:no_self_notified] == '1')
+ @se = @user.extensions
+ @se.school_id = params[:occupation]
+ @se.department_id = params[:department_id]
+ @se.gender = params[:sex]
+ @se.location = params[:province] if params[:province]
+ @se.location_city = params[:city] if params[:city]
+ @se.identity = params[:identity].to_i if params[:identity]
+ if @se.identity == 0
+ @se.technical_title = params[:te_technical_title] if params[:te_technical_title]
+ @se.student_id = nil
+ elsif @se.identity == 1
+ @se.student_id = params[:no] if params[:no]
+ @se.technical_title = nil
+ elsif @se.identity == 2
+ @se.technical_title = params[:pro_technical_title] if params[:pro_technical_title]
+ @se.student_id = nil
+ end
+ @se.brief_introduction = params[:brief_introduction]
+
+ if @user.save && @se.save
+ reward_grade(@user, @user.id, 'Account', 500)
+ # 头像保存
+ FileUtils.mv diskfile1, diskfile, force: true if File.exist? diskfile1
+ @user.pref.save
+ @user.notified_project_ids = (@user.mail_notification == 'selected' ? params[:notified_project_ids] : [])
+ set_language_if_valid @user.language
+ flash[:notice] = l(:notice_account_updated)
+ return
+ else
+ @user.login = lg
+ end
+
+ end
+ # 不管前面是否有异常,如果文件已存在就删除
+ ensure
+ File.delete(diskfile1) if File.exist?(diskfile1)
+ end
+ @setting_type = 1
+ end
+
+ # 镜像管理
+ def mirror_repository
+ @menu_type = 3
+ @sub_type = 4
+ @mirror_types = MirrorType.where("0=0")
+ mirror_rep = Redmine::Configuration['mirror_rep']
+ uri = "#{mirror_rep}/images/json"
+ uri = URI.parse(URI.encode(uri.strip))
+ begin
+ res = Net::HTTP.get(uri)
+ res = JSON.parse(res)
+ res.each do |mirror|
+ mirrorID = mirror['Id'][7, 12]
+ if MirrorRepository.where(:mirrorID => mirrorID).count == 0
+ MirrorRepository.create(:mirrorID => mirrorID, :status => 0, :created_at => Time.at(mirror['Created']), :updated_at => Time.at(mirror['Created']))
+ end
+ end
+ rescue
+ end
+ @mirrors = MirrorRepository.where("0=0").reorder("updated_at desc")
+ end
+
+ def add_mirror_type
+ data = {result: 0}
+ if params[:name]
+ if MirrorType.where(:name => params[:name]).count == 0
+ new_type = MirrorType.new(:user_id => User.current.id, :name => params[:name])
+ if new_type.save
+ data[:result] = 1
+ end
+ else
+ data[:result] = 2
+ end
+ end
+ render :json => data
+ end
+
+ def modify_mirror
+ @mirror = MirrorRepository.find params[:mirror_id]
+ @mirror_types = MirrorType.where("0=0")
+ end
+
+ def search_mirror_type
+ data = {mirror_types: []}
+ search = params[:search]
+ MirrorType.where("name like '%#{search}%'").each do |mirror_type|
+ option = []
+ option << mirror_type.name.to_s
+ option << mirror_type.id
+ data[:mirror_types] << option
+ end
+ render :json => data
+ end
+
+ def update_mirror
+ data = {result: 0, ID:""}
+ begin
+ mirror = MirrorRepository.find params[:mirror_id]
+ if mirror
+ last_index = params[:main_type].strip().rindex(";");
+ params[:main_type] = last_index.nil? ? "" : params[:main_type].strip()[0 ... last_index]
+ if params[:main_type] != ""
+ # 判断镜像主类别和小类别是否重复
+ if MirrorRepository.where("id != #{mirror.id} and main_type = '#{params[:main_type]}' and tag = '#{params[:tag].strip()}'").count > 0
+ data[:result] = 1
+ data[:ID] = MirrorRepository.where("id != #{mirror.id} and main_type = #{params[:main_type]} and tag = #{params[:tag].strip()}").first.mirrorID
+ else
+ main_types = params[:main_type].split(";")
+ main_name = main_types.join('-')
+ data_tag = params[:tag].strip().gsub(/;/, '-')
+ # 更改tag
+ mirror_rep = Redmine::Configuration['mirror_rep']
+ uri = "#{mirror_rep}/images/"+mirror.mirrorID.to_s+"/tag"
+ params = {repo: "#{main_name}", tag: "#{data_tag}"}
+ uri = URI.parse(URI.encode(uri.strip))
+ res = Net::HTTP.post_form(uri, params).body
+ if res == ""
+ # 删除原tag
+ del_mirror_name = mirror.main_name.to_s + ":" + mirror.tag.gsub(/;/, '-').to_s
+ del_uri = "#{mirror_rep}/images/" + del_mirror_name
+ del_res = delete_mirror_http del_uri
+ if del_res.code == '200'
+ # 同步更新数据库的记录
+ transaction do
+ mirror.mirror_repository_types.destroy_all
+ main_types.each do |type|
+ mirror_tp = MirrorType.where(:name => type).first
+ if mirror_tp
+ MirrorRepositoryType.create(:mirror_type_id => mirror_tp.id, :mirror_repository_id => mirror.id)
+ end
+ end
+ MirrorUpdateRecord.create(:user_id => User.current.id, :mirror_repository_id => mirror.id, :newDescription => params[:description], :oldDescription => mirror.description,
+ :newName => main_name, :oldName => mirror.name, :newStatus => params[:status], :oldStatus => mirror.status, :newTag => params[:tag], :oldTag => mirror.tag, :newType => params[:main_type], :oldType => mirror.main_type)
+ mirror.update_attributes(:name => main_name, :main_type => params[:main_type], :tag => params[:tag], :description => params[:description], :status => params[:status])
+ end
+ else
+ # 删除失败则删除新加的tag
+ del_mirror_name = main_name.to_s + ":" + data_tag
+ del_uri = "#{mirror_rep}/images/" + del_mirror_name
+ del_res = delete_mirror_http del_uri
+ data[:result] = 4
+ end
+ else
+ logger.error(res['message'])
+ data[:result] = 4
+ end
+ end
+ else
+ data[:result] = 2
+ end
+ else
+ data[:result] = 3
+ end
+ rescue Exception => e
+ puts e
+ end
+ render :json => data
+ end
+
+ def delete_mirror
+ mirror = MirrorRepository.find params[:mirror_id]
+ mirror_rep = Redmine::Configuration['mirror_rep']
+ uri = "#{mirror_rep}/images/" + mirror.mirrorID.to_s
+ uri = URI.parse(URI.encode(uri.strip))
+ data = {name:mirror.mirrorID.to_s}
+ http = Net::HTTP.new uri.host, uri.port
+ begin
+ req = Net::HTTP::Delete.new(uri.request_uri)
+ req.form_data = data
+ res= http.start { |http| http.request req }
+ if res.code == '200'
+ @status = 1
+ mirror.destroy
+ else
+ @status = 0
+ end
+ rescue =>err
+ end
+ end
+
+ # 用户修改界面
+ def update_user
+ @menu_type = 7
+ @sub_type = 1
+ # @next_type = 1
+ if params[:flag]
+ applied_message = AppliedMessage.where(:id => params[:applied_message_id]).first
+ applied_message.update_attribute(:viewed, true)
+ end
+ @user = User.find(params[:user])
+ # 创建实训
+ @create_num = (@user == User.current ? Shixun.where(:user_id => @user).count : Shixun.where(:user_id => @user).visible.count)
+ # 创建课堂
+ @create_courses_count = @user.courses.not_deleted_not_end.select{ |course| @user.has_teacher_role(course)}.count
+ # 我的所有课程数
+ @all_courses_count = @user.courses.not_deleted_not_end.count
+ # 参与课堂
+ @join_courses_count = @all_courses_count - @create_courses_count
+ # 我合作的实训数
+ coop_id = Shixun.find_by_sql("select shixun_id from shixun_members where user_id=#{@user.id} and role = 2").map(&:shixun_id) # 合作者的实训id
+ @cooperative_num = Shixun.where(:id => coop_id).count
+ # 我挑战的实训数
+ ch_id = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
+ @challenge_num = Shixun.where(:id => ch_id).count
+ #参与实训
+ @join_shixuns = @cooperative_num + @challenge_num
+ # 我的关注
+ watch_query = User.watched_by(@user.id)
+ @user_watchlist_count = watch_query.count()
+ # 我的粉丝
+ fan_query = @user.watcher_users
+ @user_fanlist_count = fan_query.count()
+ end
+
+ #用户信息修改
+ def update_user_message
+
+ end
+
+ # 实训留言
+ def shixun_feedback
+ @menu_type = 9
+ @sub_type = 1
+ @discusses = Discuss.where(:dis_type => "Shixun").reorder("created_at desc")
+ @discusses_count = @discusses.count
+ @limit = 20
+ @is_remote = true
+ @page = (params['page'] || 1).to_i
+ @discusses_pages = Paginator.new @discusses_count, @limit, @page
+ @offset ||= @discusses_pages.offset
+ @discusses = paginateHelper @discusses, @limit
+ respond_to do |format|
+ format.js
+ format.html
+ end
+ end
+
+ # 实训反馈
+ def shixun_feedback_message
+ @menu_type = 8
+ @sub_type = 2
+ @discusses = Discuss.where(:dis_type => "Shixun").reorder("created_at desc")
+ @discusses_count = @discusses.count
+ @limit = 20
+ @is_remote = true
+ @page = (params['page'] || 1).to_i
+ @discusses_pages = Paginator.new @discusses_count, @limit, @page
+ @offset ||= @discusses_pages.offset
+ @discusses = paginateHelper @discusses, @limit
+ respond_to do |format|
+ format.js
+ format.html
+ end
+ end
+
+ # 作业回复
+ def leave_message
+ @menu_type = 8
+ @sub_type = 1
+ @jour = JournalsForMessage.where(:jour_type => 'HomeworkCommon').order("created_on desc")
+ @jour_count = @jour.count
+ limit = 20
+ @is_remote = true
+ @jour_pages = Paginator.new @jour_count, limit, params['page'] || 1
+ @offset ||= @jour_pages.offset
+ @jour = paginateHelper @jour, limit
+ respond_to do |format|
+ format.html
+ format.js
+ end
+ end
+
+ # 课堂讨论区
+ def messages_list
+ @menu_type = 8
+ @sub_type = 3
+ @memo = Memo.where("0=0").order("created_at desc")
+ @memo_count = @memo.count
+ limit = 20
+ @is_remote = true
+ @memo_pages = Paginator.new @memo_count, limit, params['page'] || 1
+ @offset ||= @memo_pages.offset
+ @memo = paginateHelper @memo, limit
+ respond_to do |format|
+ format.html
+ format.js
+ end
+ end
+
+ # 专业列表
+ def profession
+ @major=Major.where("0=0")
+ # @menu_type = 12
+ @sub_type = 1
+ @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
+ major_level_option = params[:major_level] if params[:major_level]
+ discipline_category_option = params[:discipline_category_id] if params[:discipline_category_id]
+ first_level_discipline_option = params[:first_level_discipline_id] if params[:first_level_discipline_id]
+ if major_level_option && major_level_option != '0'
+ @major = @major.where(:major_level => major_level_option)
+ end
+ if discipline_category_option && discipline_category_option != '0'
+ @major=@major.where(:discipline_category_id => discipline_category_option)
+ end
+ if first_level_discipline_option && first_level_discipline_option != '0'
+ @major=@major.where(:first_level_discipline_id => first_level_discipline_option)
+ end
+
+ if params[:support_shixuns]
+ @major = @major.where(:support_shixuns => params[:support_shixuns].to_i,:major_level=> 2)
+ end
+
+ @major = @major.order("created_at #{@sx_order}")
+ @major_count = @major.count
+ limit = 20
+ @is_remote = true
+ @major_pages = Paginator.new @major_count, limit, params['page'] || 1
+ @offset ||= @major_pages.offset
+ @major = paginateHelper @major, limit
+ respond_to do |format|
+ format.js
+ format.html
+ end
+ end
+
+ # 新增专业页面
+ def new_major
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ # 新增专业
+ def insert_major
+ major_list = Major.create(:name=>params[:major],:first_level_discipline_id=>params[:first_level_discipline_id],:major_level=>params[:major_level],:discipline_category_id=>params[:discipline_category_id],:major_code=>params[:major_code])
+ redirect_to profession_managements_path
+ end
+
+ # 支撑实训
+ def support_shixun
+ if params[:syllabus_id]
+ major = Major.find params[:syllabus_id]
+ major.update_attributes(:support_shixuns => !major.support_shixuns)
+ end
+ end
+
+ # 实训适用课程
+ def applicable_course
+ # @menu_type = 12
+ @sub_type = 2
+ @major = Major.where(:major_level => 2,:support_shixuns => 1)
+ @courselist = CourseList.where("0=0")
+ search=params[:search]
+ unless search.blank?
+ @courselist = @courselist.where("name like '%#{search}%'")
+ end
+ @courselist = @courselist.reorder("created_at desc")
+ @courselist_count = @courselist.count
+
+ @limit = 15
+ @is_remote = true
+ @page = params['page'] ? params['page'].to_i : 1
+ @courselist_pages = Paginator.new @courselist_count, @limit, @page
+ @offset ||=@courselist_pages.offset
+ @courselist = paginateHelper @courselist, @limit
+ respond_to do |format|
+ format.js
+ format.html
+ end
+end
+
+ # 增加课程
+ def add_course
+ courselist= CourseList.create(:name => params[:course])
+ redirect_to applicable_course_managements_path
+ end
+
+ # 增加课程所属专业
+ def add_major
+ data = {result: 0}
+ id = MajorCourse.where(:course_list_id => params[:course_list_id]).first
+ if (id.nil?) || (params[:major_id].to_i != '0' && params[:major_id].to_i != id.major_id)
+ MajorCourse.create(:course_list_id => params[:course_list_id],:major_id=>params[:major_id])
+ data[:result] = 1
+ end
+ render :json => data
+ end
+
+ # 单位部门列表
+ def departments
+ @menu_type = 6
+ @sub_type = 2
+ @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
+ @department = Department.where(:is_auth => 1)
+ search=params[:search]
+ if search.blank?
+ @department = @department
+ else
+ apply = School.where("name like '%#{search}%'").map(&:id)
+ @department = @department.where(:school_id => apply)
+ end
+ @department = @department.reorder("created_at #{@sx_order}")
+ @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 create_departments
+ dep = Department.order("created_at desc").first
+ @latest_school = School.find(dep.try(:school_id)).try(:name)
+ @school_id = dep.try(:school_id)
+
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def add_department
+ department = Department.where(:school_id => params[:school], :name => params[:department]).first
+ if department.nil?
+ department = Department.create(:school_id => params[:school],:name => params[:department])
+ ApplyAddDepartment.create(:school_id => params[:school],
+ :status => 1,
+ :name => params[:department],
+ :department_id => department.id,
+ :user_id => User.current.id);
+ end
+ redirect_to departments_managements_path
+ end
+
+ # 修改单位部门列表
+ def update_department
+ dep = Department.find params[:department_id]
+ apply_schools = ApplyAddDepartment.where(:status => 1, :school_id => dep.school_id)
+ apply_school_ids = apply_schools.empty? ? "(-1)" : "(" + apply_schools.map{|sc| sc.department_id}.join(',') + ")"
+ @edit_id = params[:department_id]
+ @search = params[:search]
+ if !params[:search].nil?
+ search = "%#{params[:search].to_s.strip.downcase}%"
+ @departments = Department.where("id in #{apply_school_ids} and #{Department.table_name}.name like :p", :p => search)
+ #@schools = School.all
+ else
+ @departments = Department.where("id in #{apply_school_ids}")
+ end
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def edit_departments_school
+ begin
+ dep = Department.find(params[:department_id])
+ alter_dep = Department.find(params[:alter_dep_id])
+ apply_dep = ApplyAddDepartment.where(:department_id => params[:alter_dep_id])
+ if dep && alter_dep && dep != alter_dep
+ # users = UserExtensions.where("department_id = #{dep.id}")
+ # users.update_all(:department_id => params[:alter_dep_id])
+ # dep.destroy
+ # apply_dep.update_all(:status => 2)
+ # ApplyAddDepartment.where(:department_id =>params[:departments]).update_all(:department_id=>department_id)
+ # users = UserExtensions.where("department_id = #{alt_dep.department_id}")
+ # users.update_all(:department_id => department.id)
+ apply_dep.destroy_all;
+ users = UserExtensions.where(:department_id => params[:alter_dep_id])
+ users.update_all(:department_id => dep.id)
+ alter_dep.destroy
+ end
+ rescue Exception => e
+ puts e
+ end
+ redirect_to departments_managements_path
+ end
+
+ # 单位列表
+ def departments_part
+ @menu_type = 6
+ @sub_type = 1
+ @schools = School.where("0=0")
+ @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
+ search=params[:search]
+ if search.blank?
+ @schools = @schools
+ else
+ @schools = @schools.where("name like '%#{search}%'")
+ end
+ @schools = @schools.reorder("created_at #{@sx_order}")
+ @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 add_departments_part
+
+ end
+
+ # 修改单位名称
+ def upload_logo
+ @menu_type = 6
+ @sub_type = 1
+ @next_type = 1
+ @school = School.find(params[:school])
+ end
+
+ # 修改单位名称为其他
+ def school_upload_logo
+ school = School.where(:id => params[:applied_id]).first
+ ApplyAddSchools.where(:school_id => params[:applied_id]).destroy_all
+ before_apply_departments = Department.where(:school_id => params[:applied_id])
+ after_apply_deparments = Department.where(:school_id => params[:school_id])
+ before_apply_departments.each do |department|
+ after_dep = Department.where(:school_id => params[:school_id], :name => department.name).first
+ if after_dep
+ UserExtensions.where(:school_id => params[:applied_id], :department_id => department.id).update_all(:department_id => after_dep.id)
+ else
+ new_department = Department.create(:name => department.name,:school_id =>params[:school_id], :is_auth => 1)
+ UserExtensions.where(:school_id => params[:applied_id]).update_all(:department_id => new_department.id)
+ end
+ ApplyAddDepartment.where(:department_id => department.id).destroy_all
+ department.destroy
+ end
+ UserExtensions.where(:school_id => params[:applied_id]).update_all(:school_id => params[:school_id])
+ school.destroy
+ redirect_to departments_part_managements_path
+ end
+
+ # 修改单位信息
+ def school_message_update
+ school = School.where(:name =>params[:schoolname]).first
+ school_id = school.id
+ School.where(:id => school_id).update_all(:province => params[:province],:city =>params[:city],:address => params[:address],:shool_code => params[:school_code])
+ redirect_to departments_part_managements_path
+ end
+
+ # 删除单位
+ def delete_school
+ school = School.where(:id => params[:school]).first
+ UserExtensions.where(:school_id => params[:school]).update_all(:school_id => nil, :department_id => nil)
+ ApplyAddSchools.where(:school_id => params[:school]).destroy_all
+ ApplyAddDepartment.where(:school_id => params[:school]).destroy_all
+ school.destroy
+ redirect_to departments_part_managements_path
+ end
+
+ def save_school
+ uploaded_io = params[:logo]
+ sl = School.create(:name => params[:schoolname],:province => params[:province],:city => params[:city],:address => params[:address])
+ unless uploaded_io.nil?
+ File.open(Rails.root.join('public', 'images', 'school', sl.id.to_s+'.png'), 'wb') do |file|
+ file.write(uploaded_io.read)
+ end
+ sl.logo_link = '/images/school/'+sl.id.to_s+'.png'
+ sl.save
+ end
+
+ @user = User.current
+ @se = @user.extensions
+
+ # if @user.save && @se.save
+ # diskfile1 = disk_filename('school', sl.id , 'id')
+ # diskfileID = diskfile1 + 'temp'
+ # begin
+ # FileUtils.mv diskfileID, diskfile1, force: true if File.exist? diskfileID
+ # ensure
+ # File.delete(diskfileID) if File.exist?(diskfileID)
+ # end
+ # end
+ redirect_to departments_part_managements_path
+ end
+
+ # 部门审核
+ def depart
+ @menu_type = 10
+ @sub_type = 3
+ search = params[:search]
+ @apply_status = ApplyAddDepartment.where(:status=>0)
+ @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
+ if search.blank?
+ @apply_status = @apply_status.where("0=0")
+ else
+ @apply_status= @apply_status.where("name like '%#{search}%'")
+ end
+ @apply_status = @apply_status.order("created_at #{@sx_order}")
+ @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 approve_applied_departments
+ applied_department = ApplyAddDepartment.find(params[:id])
+ applied_message = AppliedMessage.where(:applied_id => applied_department.id, :applied_type => "ApplyAddDepartment")
+ applied_message.update_all(:status => 1)
+ if applied_department.department
+ applied_department.department.update_attributes(:is_auth => 1)
+ end
+ applied_department.update_attribute(:status, 1) unless applied_department.nil?
+ AppliedMessage.create(:user_id => applied_department.user_id, :status => 1, :viewed => 0, :applied_id => applied_department.id, :applied_type => "ApplyAddDepartment", :name => applied_department.name )
+ UserExtensions.where(:user_id => applied_department.user_id).update_all(:department_id => applied_department.department_id)
+ respond_to do |format|
+ format.html{ redirect_to depart_managements_path }
+ end
+ end
+
+ # 删除
+ def delete_applied_departments
+ applied_department = ApplyAddDepartment.find params[:id]
+ applied_message = AppliedMessage.where(:applied_id => applied_department.id, :applied_type => "ApplyAddDepartment")
+ applied_message.update_all(:status => 3)
+ applied_department.update_attribute(:status, 3)
+ # 未审批删除
+ if params[:tip] == "unapplied"
+ AppliedMessage.create(:user_id => applied_department.user_id, :status => 3, :viewed => 0, :applied_id => applied_department.id, :applied_type => "ApplyAddDepartment", :name => applied_department.name )
+ # 删除学校的用户
+ users = UserExtensions.where("department_id = #{applied_department.department_id}")
+ users.update_all(:department_id => nil)
+ applied_department.department.destroy
+ redirect_to depart_managements_path
+ # 已审批删除
+ elsif params[:tip] == "applied"
+ applied_department.destroy
+ redirect_to depart_managements_path
+ end
+ end
+
+ # 部门修改
+ def all_department
+ @edit_id = params[:department_id]
+ @search = params[:search]
+ dep = ApplyAddDepartment.where(:id => @edit_id).first
+ apply_department = ApplyAddDepartment.where(:status => 1, :school_id => dep.school_id)
+ apply_department_ids = apply_department.empty? ? "(-1)" : "(" + apply_department.map{|sc| sc.department_id}.join(',') + ")"
+ if !params[:search].nil?
+ search = "%#{params[:search].to_s.strip.downcase}%"
+ @department = Department.where("id in #{apply_department_ids} and #{Department.table_name}.name like :p", :p => search)
+ #@schools = School.all
+ else
+ #@course = @user.courses.where("is_delete = 0 and #{Course.table_name}.id != #{homework.course_id}").select { |course| @user.allowed_to?(:as_teacher,course)}
+ @department = Department.where("id in #{apply_department_ids}")
+ end
+ respond_to do |format|
+ format.js
+ end
+ # redirect_to unit_managements_path
+ end
+
+ # 修改
+ def edit_applied_department
+ aas =ApplyAddDepartment.find(params[:applied_id])
+ # aas.update_attribute(:name, params[:name])
+ #applied_add_school = ApplyAddSchools.where(:name => aas.name)
+ department =Department.find params[:department_id]
+ begin
+ #更新消息表的status
+ if aas.department_id != department.id.to_i
+ applied_message_id = aas.department_id
+ applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddDepartment")
+ applied_message.update_all(:status => 4)
+ aas.update_attribute(:status, 2)
+ AppliedMessage.create(:user_id => aas.user_id, :status => 2, :viewed => 0, :applied_id => aas.id, :applied_type => "ApplyAddDepartment", :name =>department.name )
+ users = UserExtensions.where("department_id = #{aas.department_id}")
+ users.update_all(:department_id => department.id)
+ aas.department.destroy
+ ApplyAddDepartment.where(:department_id => aas.department_id).update_all(:department_id => department.id)
+ Department.where(:department_id => aas.department_id).destroy_all
+ aas.destroy_all
+ end
+ rescue Exception => e
+ puts e
+ end
+ redirect_to depart_managements_path
+ end
+
+ # 单位审批
+ def unit
+ @menu_type = 10
+ @sub_type = 4
+ search = params[:search]
+ @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
+ @apply_status = ApplyAddSchools.where(:status=>0)
+ if search.blank?
+ @apply_status = @apply_status.where("0=0")
+ else
+ @apply_status= @apply_status.where("name like '%#{search}%'")
+ end
+ @apply_status = @apply_status.order("created_at #{@sx_order}")
+ @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 approve_applied_schools
+ applied_school = ApplyAddSchools.where(:id =>params[:id]).first
+ applied_message_id = applied_school.school_id
+ applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
+ applied_message.update_all(:status => 1)
+ unless applied_school.nil?
+ applied_school.update_column('status', 1)
+ end
+ school = applied_school.school
+ school.update_attribute("province", applied_school.province)
+ AppliedMessage.create(:user_id => applied_school.user_id, :status => 1, :viewed => 0, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
+ redirect_to unit_managements_path
+ end
+
+ # 删除
+ def delete_applied_schools
+ applied_school = ApplyAddSchools.find(params[:id])
+ applied_message_id = applied_school.school_id
+ applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
+ applied_message.update_all(:status => 3)
+ applied_school.update_attribute(:status, 3)
+ # 单位对应的部门审核也应做删除处理
+ applied_departments = ApplyAddDepartment.where(:school_id => applied_school.school_id)
+ applied_departments.update_all(:status => 3)
+ AppliedMessage.where(:applied_id => applied_departments.map(&:id), :applied_type => "ApplyAddDepartment").update_all(:status => 3)
+ # 未审批删除
+ if params[:tip] == "unapplied"
+ AppliedMessage.create(:user_id => applied_school.user_id, :status => 3, :viewed => 0, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
+ if applied_departments.first
+ AppliedMessage.create(:user_id => applied_departments.first.user_id, :status => 3, :viewed => 0, :applied_id => applied_departments.first.id, :applied_type => "ApplyAddDepartment", :name => applied_departments.first.name )
+ end
+# 删除学校的用户
+ users = UserExtensions.where("school_id = #{applied_school.school_id}")
+ users.update_all(:school_id => nil, :department_id => nil)
+ applied_school.school.destroy
+ applied_school.school.departments.destroy_all
+ redirect_to unit_managements_path
+ # 已审批删除
+ elsif params[:tip] == "applied"
+ applied_school.destroy
+ redirect_to unit_managements_path
+ end
+ end
+
+ # 单位审批修改
+ def all_schools
+ apply_schools = ApplyAddSchools.where("status = 0")
+ apply_school_ids = apply_schools.empty? ? "(#{params[:school_id].to_i})" : "(" + apply_schools.map{|sc| sc.school_id}.join(',') + ")"
+ if !params[:search].nil?
+ search = "%#{params[:search].to_s.strip.downcase}%"
+ @schools = School.where("id not in #{apply_school_ids} and id != #{params[:school_id].to_i} and #{School.table_name}.name like :p", :p => search)
+ else
+ @schools = School.where("id not in #{apply_school_ids} and id != #{params[:school_id].to_i}")
+ end
+ @edit_id = params[:school_id]
+ @search = params[:search]
+ @upload = params[:upload]
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ # 修改
+ def edit_applied_schools
+ aas = ApplyAddSchools.find(params[:applied_id])
+ school = School.find params[:school_id]
+ begin
+ #更新消息表的status
+ if aas.school_id != school.id.to_i
+ applied_message_id = aas.school_id
+ applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
+ applied_message.update_all(:status => 4)
+ aas.update_attribute(:status, 2)
+ AppliedMessage.create(:user_id => aas.user_id, :status => 2, :viewed => 0, :applied_id => aas.id, :applied_type => "ApplyAddSchools", :name => school.name )
+ users = UserExtensions.where("school_id = #{aas.school_id}")
+ users.update_all(:school_id => school.id)
+ ApplyAddDepartment.where(:school_id => aas.school_id).update_all(:school_id => school.id)
+ # 判断重复
+ before_apply_departments = Department.where(:school_id => params[:applied_id])
+ after_apply_deparments = Department.where(:school_id => params[:school_id])
+ before_apply_departments.each do |department|
+ after_dep = Department.where(:school_id => params[:school_id], :name => department.name).first
+ if after_dep
+ UserExtensions.where(:school_id => params[:applied_id], :department_id => department.id).update_all(:department_id => after_dep.id)
+ else
+ UserExtensions.where(:school_id => params[:applied_id]).update_all(:department_id => new_department.id)
+ if after_dep.status == 2 ||after_dep.status == 3
+ new_department = Department.create(:name => department.name,:school_id =>params[:school_id], :is_auth => 1)
+ else
+ new_department = Department.create(:name => department.name,:school_id =>params[:school_id], :is_auth => 0)
+ end
+ end
+ ApplyAddDepartment.where(:department_id => department.id).destroy_all
+ department.destroy
+ end
+ UserExtensions.where(:school_id => params[:applied_id]).update_all(:school_id => params[:school_id])
+
+ # Department.where(:school_id => aas.school_id).update_all(:school_id => school.id)
+ aas.school.destroy
+ aas.update_attribute(:school_id, school.id)
+ end
+ rescue Exception => e
+ puts e
+ end
+ redirect_to unit_managements_path
+ end
+
+ # 课堂列表
+ def classroom
+ @menu_type = 2
+ @sub_type = 1
+ @courselist = CourseList.where("0=0")
+ @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
+ keyword = params[:keyword]
+ search = params[:search]
+
+ if params[:support_shixuns_search_title]
+ @courselist = @courselist.where(:support_shixuns_search => params[:support_shixuns_search_title].to_i)
+ end
+ if search.blank?
+ @courselist = @courselist
+ else
+ if "u_name" == keyword
+ user_id = User.where("concat(lastname, firstname) like '%#{search}%'")
+ @courselist = @courselist.includes(:user).where("concat(users.lastname, users.firstname) like '%#{search}%'")
+ else
+ @courselist = @courselist.where("name like '%#{search}%'")
+ end
+ end
+ @courselist = @courselist.order("created_at #{@sx_order}")
+ @courselist_count = @courselist.count
+ limit = 20
+ @is_remote = true
+ @courselist_pages = Paginator.new @courselist_count, limit, params['page'] || 1
+ @offset ||= @courselist_pages.offset
+ @courselist = paginateHelper @courselist, limit
+
+ # @courselist = @courselist.order("courselist.created_at #{@sx_order}")
+ respond_to do |format|
+ format.js
+ format.html
+ end
+ end
+
+ # 支撑实训检索
+ def support_shixuns_search
+ if params[:shixun_id]
+ courselist = CourseList.find params[:shixun_id]
+ courselist.update_attributes(:support_shixuns_search => !courselist.support_shixuns_search)
+ end
+ end
+
+ # 课堂列表
+ def classroom_classment
+ @menu_type = 2
+ @sub_type = 2
+ @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
+ @courses = Course.where(:is_delete => 0)
+ @timing=Course.where(:is_end=>false).count
+ @end=Course.where(:is_end=>true).count
+ @course_lists = CourseList.where(:id => Course.where(:is_delete => 0 ).map(&:course_list_id) )
+ 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]
+ @courselist = params[:course_list]
+ @school_id = params[:school_id]
+
+ if params[:school_id] && params[:school_id] != ''
+ @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]}")
+ end
+
+ if params[:homepage_show]
+ @courses = @courses.where(:homepage_show => params[:homepage_show].to_i)
+ end
+
+ if params[:course_list] && params[:course_list] != ''
+ @courses = @courses.where(:course_list_id => @courselist)
+ end
+
+ if params[:status] && params[:status]!=''
+ @courses =@courses.where(:is_end => @status.to_i)
+ end
+ if "u_name" == @keyword
+ if @search.blank?
+ @courses = @courses
+ 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}%'")
+ end
+ else
+ school = School.where("name like '%#{@search}%'").map(&:id)
+ @courses = @courses.where(:school_id => school)
+ # @courses= @courses.where("name like '%#{@search}%'")
+ end
+ @courses = @courses.select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS updatetime").reorder("updatetime #{@sx_order}")
+ @export_courses = @courses
+ @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
+ format.xls{
+ @export_courses = @export_courses.all
+ filename = "#{l(:label_course_list_xls)}.xls"
+ send_data(course_list_xls(@export_courses), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
+ }
+ end
+ end
+
+ # 班级首页显示
+ def course_homepage_show
+ if params[:course_id]
+ course = Course.find params[:course_id]
+ course.update_attributes(:homepage_show => !course.homepage_show)
+ end
+ end
+
+ # 课程实训
+ def class_shixuns
+ @menu_type = 4
+ @sub_type = 1
+ @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
+ @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
+ 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
+ @c_shixuns = @c_shixuns.order("created_at #{@sx_order}")
+
+ @c_shixuns_count = @c_shixuns.count
+ limit = 20
+ @c_shixuns_pages = Paginator.new @c_shixuns_count, limit, params['page'] || 1
+ @offset ||= @c_shixuns_pages.offset
+ @c_shixuns = paginateHelper @c_shixuns, limit
+ respond_to do |format|
+ format.js
+ format.html
+ end
+ end
+
+ def update_subject_hidden
+ @subject = Subject.find(params[:subject_id])
+ @subject.update_column(:hidden, !@subject.hidden)
+ end
+
+ # 已发布课程实训
+ def class_publish_shixuns
+ @menu_type = 4
+ @sub_type = 2
+ @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
+ 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?
+ elsif "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
+ 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
+ @c_shixuns = @c_shixuns.order("created_at #{@sx_order}")
+ @c_shixuns_count = @c_shixuns.count
+ limit = 20
+ @c_shixuns_pages = Paginator.new @c_shixuns_count, limit, params['page'] || 1
+ @offset ||= @c_shixuns_pages.offset
+ @c_shixuns = paginateHelper @c_shixuns, limit
+ respond_to do |format|
+ format.js
+ format.html
+ end
+ end
+
+ # 导出excel
+ def export_excel
+ @course = params[:course]
+ respond_to do |format|
+ format.xls {
+ @course = @course.reorder("#{Tracker.table_name}.position, #{Course.table_name}.id").all
+ filename = "#{l(:label_course_list_xls)}.xls"
+ send_data(course_list_xls(@course), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
+ }
+ 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? ? "last_login_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}")
+ else
+ @users = User.where("#{condition} like '%#{params[:research_contents]}%'").order("#{@order_key} #{@us_order}")
+ end
+ else
+ if params[:research_condition] == "phone" && params[:research_contents].blank?
+ @users = User.where(:status => status).order("#{@order_key} #{@us_order}")
+ else
+ @users = User.where("status = #{status} and #{condition} like '%#{params[:research_contents]}%'").order("#{@order_key} #{@us_order}")
+ end
+ end
+
+ if params[:school] && params[:school] != ''
+ school_name = params[:school]
+ school = School.where("name like '%#{school_name}%'")
+ school_id = school.map(&:id)
+ user_id = UserExtensions.where(:school_id => school_id).map(&:user_id)
+ @users = @users.where(:id => user_id).order("#{@order_key} #{@us_order}")
+ 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
+ if params[:keyword] == "sx_name"
+ @shixuns = Shixun.where("name like '%#{search}%'").where(:status => sx_status).order("created_at #{@sx_order}")
+ else
+ school_id = School.where("name like '%#{search}%'").map(&:id)
+ user_id = UserExtensions.where(:school_id => school_id).map(&:user_id)
+ @shixuns = Shixun.where(:user_id => user_id).where(:status => sx_status).order("created_at #{@sx_order}")
+ end
+ 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 update_shixun_hidden
+ @shixun = Shixun.find(params[:shixun_id])
+ @shixun.update_column(:hidden, !@shixun.hidden)
+ 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
+ if params[:homepage_show]
+ @shixuns = @shixuns.where(:homepage_show => params[:homepage_show].to_i)
+ 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 shixun_homepage_show
+ if params[:shixun_id]
+ shixun = Shixun.find params[:shixun_id]
+ shixun.update_attributes(:homepage_show => !shixun.homepage_show)
+ end
+ end
+
+ # 允许复制
+ def shixun_can_copy
+ if params[:shixun_id]
+ shixun = Shixun.find params[:shixun_id]
+ shixun.update_attributes(:can_copy => !shixun.can_copy)
+ 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
+ @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
+ @users = User.where(:status => 1).order("last_login_on #{@sx_order}").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 auto_users_trial
+ @menu_type = 7
+ @sub_type = 3
+ @apply_action = School.where(:auto_users_trial => 1).order('updated_at desc')
+ @auto_school_ids = @apply_action.empty? ? "(-1)" : "(" + @apply_action.map(&:id).join(",") + ")"
+ @apply_action_count = @apply_action.count
+ limit = 20
+ @is_remote = true
+ @apply_action_pages = Paginator.new @apply_action_count, limit, params['page'] || 1
+ @offset ||= @apply_action_pages.offset
+ @apply_action = paginateHelper @apply_action, limit
+ respond_to do |format|
+ format.html
+ format.js
+ end
+ end
+
+ # 添加
+ def create_auto_users_trial
+ School.where(:id => params[:school]).update_all(:auto_users_trial => 1)
+ redirect_to auto_users_trial_managements_path
+ end
+
+ # 删除
+ def update_auto_users_trial
+ School.where(:id => params[:school]).update_all(:auto_users_trial => 0)
+ redirect_to auto_users_trial_managements_path
+ 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"
+ aUser = User.where(:id => params[:member_ids])
+ aUser.update_all(:certification => 1)
+ apply_user = ApplyAction.where(:user_id => params[:member_ids])
+ apply_user.update_all(:status => 1) unless apply_user.blank?
+ elsif params[:member_ids] && params[:trial_whether] == "trial_cancel"
+ User.where(:id => params[:member_ids]).update_all(:certification => 0)
+ apply_user = ApplyAction.where(:user_id => params[:member_ids])
+ apply_user.update_all(:status => 2) unless apply_user.blank?
+ end
+
+ if params[:member_ids] && params[:occupation] == "occupation_agree"
+ User.where(:id => params[:member_ids]).update_all(:professional_certification => true)
+ apply_user = ApplyUserAuthentication.where(:user_id => params[:member_ids], :auth_type => 2)
+ unless apply_user.blank?
+ apply_user.update_all(:status => 1)
+ end
+ elsif params[:member_ids] && params[:realname] == "realname_agree"
+ User.where(:id => params[:member_ids]).update_all(:authentication => true)
+ apply_user = ApplyUserAuthentication.where(:user_id => params[:member_ids], :auth_type => 1)
+ unless apply_user.blank?
+ apply_user.update_all(:status => 1)
+ end
+ elsif params[:member_ids] && params[:occupation] == "occupation_cancel"
+ User.where(:id => params[:member_ids]).update_all(:professional_certification => false)
+ apply_user = ApplyUserAuthentication.where(:user_id => params[:member_ids], :auth_type => 2)
+ unless apply_user.blank?
+ apply_user.update_all(:status => 2)
+ end
+ elsif params[:member_ids] && params[:realname] == "realname_cancel"
+ User.where(:id => params[:member_ids]).update_all(:authentication => false)
+ apply_user = ApplyUserAuthentication.where(:user_id => params[:member_ids], :auth_type => 1)
+ unless apply_user.blank?
+ apply_user.update_all(:status => 2)
+ end
+ 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 and certification = 0").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]
+ elsif params[:trial] == "0"
+ apply = ApplyAction.where(:status => 0)
+ apply_user_id = apply.blank? ? [-1] : apply.map{|a| a.user_id}.split(",")[0]
+ else
+ apply_user_id = User.where(:status => 1, :certification => params[:trial]).all
+ apply_user_id = apply_user_id.blank? ? [-1] : apply_user_id.map{|a| a.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("last_login_on desc")
+ elsif params[:research_condition] == "email"
+ @users = User.where(:id => user_id).where("mail like '%#{params[:research_contents]}%'").order("last_login_on desc")
+ elsif params[:research_condition] == "phone"
+ @users = User.where(:id => user_id).where("phone like '%#{params[:research_contents]}%'").order("last_login_on desc")
+ elsif params[:research_condition] == "nickname"
+ if params[:research_contents].blank?
+ @users = User.where(:id => user_id).order("last_login_on desc")
+ else
+ @users = User.where(:id => user_id).where("nickname like '%#{params[:research_contents]}%'").order("last_login_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.where(:id => apply_action.user_id).first.update_attributes(:certification => (params[:type] == "1" ? 2 : 1))
+ 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, :auth_type => 1).find_by_sql("SELECT s.*, TIMESTAMPDIFF(SECOND, s.updated_at, now()) diff FROM `apply_user_authentications` s order by diff asc")
+ @unapproved_user = ApplyUserAuthentication.where(:status => @type, :user_id => user_id, :auth_type => 1).order("updated_at desc")
+
+ @unapproved_user_count = @unapproved_user.count
+ @limit = 15
+ @is_remote = true
+ @unapproved_user_pages = Paginator.new @unapproved_user_count, @limit, params['page'] || 1
+ @offset ||= @unapproved_user_pages.offset
+ @unapproved_user = paginateHelper @unapproved_user, @limit
+ respond_to do |format|
+ format.html
+ format.js
+ end
+ end
+
+ def professional_authentication
+ @menu_type = 10
+ @sub_type = 7
+ @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, :auth_type => 2).find_by_sql("SELECT s.*, TIMESTAMPDIFF(SECOND, s.updated_at, now()) diff FROM `apply_user_authentications` s order by diff asc")
+ @unapproved_user = ApplyUserAuthentication.where(:status => @type, :user_id => user_id, :auth_type => 2).order("updated_at desc")
+
+ @unapproved_user_count = @unapproved_user.count
+ @limit = 15
+ @is_remote = true
+ @unapproved_user_pages = Paginator.new @unapproved_user_count, @limit, params['page'] || 1
+ @offset ||= @unapproved_user_pages.offset
+ @unapproved_user = paginateHelper @unapproved_user, @limit
+ respond_to do |format|
+ format.html
+ format.js
+ end
+ end
+
+ # 拒绝身份认证
+ # copy from admin
+ def reject_authentication
+ apply_user = ApplyUserAuthentication.where(:id => params[:apply_id], :auth_type => 1).first
+ 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.where(:id => params[:apply_id], :auth_type => 1).first
+ user = User.find(apply_user.user_id)
+ apply_user.update_attribute(:status, 1)
+ user.update_attribute(:authentication, true)
+
+ @unapproved_user = ApplyUserAuthentication.where(:status => 0, :auth_type => 1).order("updated_at desc")
+ @unapproved_user_count = @unapproved_user.count
+ @limit = 15
+ @is_remote = true
+ @unapproved_user_pages = Paginator.new @unapproved_user_count, @limit, params['page'] || 1
+ @offset ||= @unapproved_user_pages.offset
+ @unapproved_user = paginateHelper @unapproved_user, @limit
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ # 拒绝职业认证
+ def reject_authentication_pro
+ apply_user = ApplyUserAuthentication.where(:id => params[:apply_id], :auth_type => 2).first
+ reason = apply_user.update_attributes(:status => 2, :remarks => params[:reject_reason])
+ render :json => {success: reason}
+
+ end
+
+ # 同意职业认证
+ def agree_authentication_pro
+ apply_user = ApplyUserAuthentication.where(:id => params[:apply_id], :auth_type => 2).first
+ user = User.find(apply_user.user_id)
+ apply_user.update_attribute(:status, 1)
+ user.update_attribute(:professional_certification, true)
+ @unapproved_user = ApplyUserAuthentication.where(:status => 0, :auth_type => 2).order("updated_at desc")
+ @unapproved_user_count = @unapproved_user.count
+ @limit = 15
+ @is_remote = true
+ @unapproved_user_pages = Paginator.new @unapproved_user_count, @limit, params['page'] || 1
+ @offset ||= @unapproved_user_pages.offset
+ @unapproved_user = paginateHelper @unapproved_user, @limit
+ 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]
+ # sql = select * from apply_actions where dealer_id is null
+ @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)
+ add_shixun_modify_status shixun, 1
+ # 实训发布后则不允许修改代码
+ # g = Gitlab.client
+ # shixun.shixun_members.each do |member|
+ # gid = User.find(member.user_id).try(:gid)
+ # g.edit_team_member(shixun.gpid, gid, 10) # 3代表角色master
+ # end
+ # # 加入超级管理员
+ # admin_gid = User.where(:admin => 1).first.try(:gid)
+ # g.add_team_member(shixun.gpid, admin_gid, 40) # 30代表角色master
+ 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
+
+ # 课程删除
+ before_filter :find_courselist, :only => [:destroy]
+
+ # 课程列表的删除
+ def destroy
+ if @courselist
+ CourseList.where(:id => @courselist.id).destroy_all
+ respond_to do |format|
+ format.js
+ end
+ end
+ end
+ private
+ # Find courselist of id params[:id]
+ def find_courselist
+ @courselist = CourseList.find_by_id(params[:id])
+ render_404 if @courselist.nil?
+ rescue ActiveRecord::RecordNotFound
+ render_404
+ end
+
+ def course_list_xls courses
+ xls_report = StringIO.new
+ book = Spreadsheet::Workbook.new
+ sheet1 = book.create_worksheet :name => "course"
+ blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
+ sheet1.row(0).default_format = blue
+ sheet1.row(0).concat(["ID","课堂名称","成员","资源","普通作业"," 实训作业","试卷","私有","状态","创建者单位","创建者","动态时间"])
+ count_row = 1
+ courses.each do |course|
+ school = course.teacher.try(:user_extensions).try(:school).try(:name).blank? ? "--" : course.teacher.school_name
+ teacher_name = course.teacher ? course.teacher.show_real_name : ""
+ sheet1[count_row,0] = course.id
+ sheet1[count_row,1] = course.name
+ sheet1[count_row,2] = course.members.count
+ sheet1[count_row,3] = course.attachments.count
+ sheet1[count_row,4] = course.homework_commons.where(:homework_type => 1).count
+ sheet1[count_row,5] = course.homework_commons.where(:homework_type => 4).count
+ sheet1[count_row,6] = course.exercises.count
+ sheet1[count_row,7] = course.is_public.to_i == 1 ? '否' : '是'
+ sheet1[count_row,8] = course.is_end ? "已结束" : "正在进行"
+ sheet1[count_row,9] = school
+ sheet1[count_row,10] = teacher_name
+ sheet1[count_row,11] = format_time(course.updatetime)
+ count_row += 1
+ end
+ book.write xls_report
+ xls_report.string
+ end
+end
diff --git a/app/controllers/members_controller.rb b/app/controllers/members_controller.rb
index 11f3db099..4a0026311 100644
--- a/app/controllers/members_controller.rb
+++ b/app/controllers/members_controller.rb
@@ -19,6 +19,7 @@
class MembersController < ApplicationController
helper :users
model_object Member
+ include CoursesHelper
before_filter :find_model_object, :except => [:index, :create, :autocomplete, :allow_to_join_project, :refused_allow_to_join_project]
#before_filter :find_model_object_contest, :except => [:index, :create, :autocomplete]
before_filter :find_project_from_association, :except => [:index, :create, :autocomplete, :allow_to_join_project, :refused_allow_to_join_project]
@@ -240,18 +241,27 @@ class MembersController < ApplicationController
@create_member_error_messages = "角色不能留空" unless params[:membership][:role_ids]
@create_member_error_messages = "用户不能留空" unless params[:membership][:user_ids]
- if params[:membership][:user_ids]
+ #if params[:membership][:user_ids]
+ if params[:choose_student_ids] && params[:membership]
attrs = params[:membership].dup
- user_ids = attrs.delete(:user_ids)
+ user_ids = params[:choose_student_ids].split(",")
user_ids.each do |user_id|
- member = Member.new(:role_ids => params[:membership][:role_ids], :user_id => user_id)
-
+ if @course.members.where(:user_id => user_id).empty?
+ member = Member.new(:role_ids => params[:membership][:role_ids], :user_id => user_id)
+ else
+ member = @course.members.where(:user_id => user_id).first
+ member_role = MemberRole.new(:role_id => params[:membership][:role_ids][0], :is_current => 0)
+ member.member_roles << member_role
+ end
role_ids = params[:membership][:role_ids]
#role = Role.find(params[:membership][:role_ids])
# 这里的判断只能通过角色名,可以弄成常量
if role_ids && role_ids.include?("10")
StudentsForCourse.create(:student_id => user_id, :course_id =>@course.id)
end
+ if params[:course_group_id] && params[:course_group_id] != '0'
+ member.course_group_id = params[:course_group_id].to_i
+ end
#给新成员和老师发送加入课程的消息,发送者id放在CourseMessage的course_message_id字段中
#course_message_type设置为JoinCourse
@@ -276,9 +286,11 @@ class MembersController < ApplicationController
end
@course.members << members
@course.course_infos << course_info
-
- @roles = Role.givable.all[3..5]
- members = @course.member_principals.includes(:roles, :principal).all.sort
+ #@teacher_count = searchTeacherAndAssistant(@course).count
+ #@student_count = @course.student.count
+ #@no_group_count = @course.members.where("course_group_id = 0").select{|m| m.roles.to_s.include?("Student")}.count
+ #@roles = Role.givable.all[3..5]
+ #members = @course.member_principals.includes(:roles, :principal).all.sort
else
@create_member_error_messages = l(:label_user_role_null)
end
@@ -441,24 +453,42 @@ class MembersController < ApplicationController
end
elsif @course
if request.delete? && @member.deletable?
- @member.destroy
- user_admin = CourseInfos.where("user_id = ? and course_id = ?", @member.user_id, @course.id)
- if user_admin.size > 0
- user_admin.each do |user|
- user.destroy
+ if @member.member_roles.count == 1
+ joined = StudentsForCourse.where('student_id = ? and course_id = ?', @member.user_id,@course.id).destroy_all
+ @member.destroy
+ else
+ if params[:type] == '1'
+ @member.member_roles.where("role_id = 7 or role_id = 9").destroy_all
+ @member.member_roles.where("role_id = 10").first.update_attributes(:is_current => 1)
+ else
+ @member.member_roles.where("role_id = 10").destroy_all
+ joined = StudentsForCourse.where('student_id = ? and course_id = ?', @member.user_id,@course.id).destroy_all
+ @member.update_attributes(:course_group_id => 0)
+ if params[:group_id] == '0'
+ @members = @course.members.select{|m| m.roles.to_s.include?("Student")}
+ else
+ @members = @course.members.where("course_group_id = 0").select{|m| m.roles.to_s.include?("Student")}
+ end
+ @member.member_roles.where("role_id = 7 or role_id = 9").first.update_attributes(:is_current => 1)
end
end
- joined = StudentsForCourse.where('student_id = ? and course_id = ?', @member.user_id,@course.id)
- joined.each do |join|
- join.destroy
- end
+ @teacher_count = searchTeacherAndAssistant(@course).count
+ @student_count = @course.student.count
+ @no_group_count = @course.members.where("course_group_id = 0").select{|m| m.roles.to_s.include?("Student")}.count
+ # user_admin = CourseInfos.where("user_id = ? and course_id = ?", @member.user_id, @course.id)
+ # if user_admin.size > 0
+ # user_admin.each do |user|
+ # user.destroy
+ # end
+ # end
+
@roles = Role.givable.all[3..5]
- @members = @course.member_principals.includes(:roles, :principal).all.sort
+ #@members = @course.member_principals.includes(:roles, :principal).all.sort
#移出课程发送消息
CourseMessage.create(:user_id => @member.user_id, :course_id => @course.id, :course_message_type => "RemoveFromCourse", :viewed => false, :course_message_id => User.current.id)
end
respond_to do |format|
- format.html { redirect_to_settings_in_courses }
+ format.html { redirect_to members_course_path(@course) }
format.js
format.api {
if @member.destroyed?
diff --git a/app/controllers/memos_controller.rb b/app/controllers/memos_controller.rb
index 2bdc39707..b96c1774f 100644
--- a/app/controllers/memos_controller.rb
+++ b/app/controllers/memos_controller.rb
@@ -1,6 +1,6 @@
class MemosController < ApplicationController
default_search_scope :memos
- before_filter :find_forum, :only => [:new, :create, :preview, :update]
+ before_filter :find_forum, :only => [:new, :create, :preview, :update, :reply]
before_filter :find_attachments, :only => [:preview]
before_filter :find_memo, :except => [:new, :create, :preview]
before_filter :authenticate_user_edit, :only => [:edit, :update]
@@ -29,13 +29,14 @@ class MemosController < ApplicationController
def new
# 如何是问吧主页来的,导航不显示具体贴吧名
+ @user = User.current
@memo = Memo.new
- @my_forums_count = Memo.where("author_id =? and parent_id is null", User.current.id).count
- @my_memos_count = Memo.where("author_id =? and parent_id is not null", User.current.id).count
+ @my_forums_count = Memo.where("author_id =? and parent_id is null",@user.id).count
+ @my_memos_count = Memo.where("author_id =? and parent_id is not null", @user.id).count
@forums = Forum.reorder("topic_count desc,updated_at desc")
respond_to do |format|
format.js
- format.html {render layout: 'base_new_forum'}
+ format.html {render layout: 'base_edu'}
format.json { render json: @memo }
end
end
@@ -88,6 +89,7 @@ class MemosController < ApplicationController
REPLIES_PER_PAGE = 20 unless const_defined?(:REPLIES_PER_PAGE)
def show
+ @user = User.current
# 更新贴吧帖子留言对应的memo_messages的viewed字段
unless @memo.children.blank?
@memo.children.each do |child|
@@ -99,12 +101,13 @@ class MemosController < ApplicationController
end
end
query_memo_messages = @memo.memo_messages
- query_memo_messages.each do |query_memo_message|
- if User.current.id == query_memo_message.user_id
- query_memo_message.update_attributes(:viewed => true)
+ unless query_memo_messages
+ query_memo_messages.each do |query_memo_message|
+ if User.current.id == query_memo_message.user_id
+ query_memo_message.update_attributes(:viewed => true)
+ end
end
end
-
pre_count = REPLIES_PER_PAGE
@memo = @memo.root # 取出楼主,防止输入帖子id让回复作为主贴显示
@memo.update_column(:viewed_count, (@memo.viewed_count.to_i + 1))
@@ -140,19 +143,20 @@ class MemosController < ApplicationController
respond_to do |format|
format.js
- format.html {render :layout => 'base_new_forum'}
+ format.html {render :layout => 'base_edu'}
format.json { render json: @memo }
format.xml { render xml: @memo }
end
end
def edit
- @my_topic_count = 0
- @my_replies_count = Memo.where(:parent_id => @memo.id).count
- @forums = Forum.reorder("topic_count desc,updated_at desc")
- @replying = false
+ #@my_topic_count = 0
+ #@my_replies_count = Memo.where(:parent_id => @memo.id).count
+ #@forums = Forum.reorder("topic_count desc,updated_at desc")
+ #@replying = false
+ @user = User.current
respond_to do |format|
- format.html {render :layout => 'base_new_forum'}
+ format.html {render :layout => 'base_edu'}
end
end
@@ -161,10 +165,9 @@ class MemosController < ApplicationController
@flag = false
respond_to do |format|
- if( #@memo.update_column(:subject, params[:memo][:subject]) &&
- @memo.update_column(:content, params[:memo][:content]) &&
- @memo.update_column(:sticky, params[:memo][:sticky]) &&
- @memo.update_column(:lock, params[:memo][:lock]) &&
+ if( @memo.update_column(:content, params[:memo][:content]) &&
+ @memo.update_column(:sticky, params[:memo][:sticky].to_i) &&
+ @memo.update_column(:lock, params[:memo][:lock].to_i) &&
@memo.update_column(:subject,params[:memo][:subject]) &&
@memo.update_column(:updated_at,Time.now))
@memo.save_attachments(params[:attachments] || (params[:memo] && params[:memo][:uploads]))
@@ -172,7 +175,7 @@ class MemosController < ApplicationController
@flag = @memo.save
# @memo.root.update_attribute(:updated_at, @memo.updated_at)
format.js
- format.html {redirect_to back_memo_url, notice: "#{l :label_memo_update_succ}"}
+ format.html {redirect_to back_memo_url}
else
format.js
format.html { render action: "edit" }
@@ -181,12 +184,64 @@ class MemosController < ApplicationController
end
end
+ def reply
+ if params[:memo].present? && params[:memo][:parent_id].present?
+ parent = Memo.find params[:memo][:parent_id]
+ @memo = params[:activity_id].blank? ? parent : Memo.find(params[:activity_id].to_i)
+ @reply = Memo.new
+ @reply.author = User.current
+ @reply.forum_id = parent.forum_id
+ @reply.content = params[:content]
+ @reply.subject = "RE: #{@memo.subject}"
+ #@reply.reply_id = params[:id]
+ @reply.root_id = parent.root_id.nil? ? parent.id : parent.root_id
+ # @reply.reply_id = params[:id]
+ parent.children << @reply
+ else
+ @reply = Memo.new()
+ @reply.content = params[:content]
+ @reply.subject = @memo.subject
+ @reply.author = User.current
+ @reply.forum_id = @forum.id
+ #@reply.content = @quote + @reply.content
+ #@reply.subject = "RE: #{@topic.subject}" unless params[:reply][:subject]
+ @reply.root_id = @memo.id
+ @reply.safe_attributes = params[:reply]
+ @memo.children << @reply
+ # @reply.reply_id = params[:id]
+ end
+
+ redirect_to message_replies_forum_memo_path(@memo.forum, @memo, :user_activity_id => params[:user_activity_id])
+ end
+
+ def message_replies
+ @replies = Memo.where(:root_id => @memo.id).order("created_at 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? ? @memo.id : params[:user_activity_id].to_i
+ respond_to do |format|
+ format.js
+ end
+
+ end
+
def destroy
@memo.destroy
-
respond_to do |format|
- # format.html { redirect_to @back_url }
- format.html { redirect_to back_memo_or_forum_url }
+ #format.html { redirect_to @back_url }
+ format.html { redirect_to forums_path }
+ format.js{
+ @memo = Memo.find(params[:user_activity_id].to_i)
+ @replies = Memo.where(:root_id => @memo.id).order("created_at desc")
+ @reply_count = @replies.count
+ @replies = get_no_children_comments_all @replies
+ #redirect_to message_replies_forum_memo_path(@memo.forum, @memo, :user_activity_id => params[:user_activity_id])
+ }
format.json { head :no_content }
end
end
@@ -195,7 +250,13 @@ class MemosController < ApplicationController
def change_sticky
@memo.sticky ? @memo.update_attribute(:sticky, false) : @memo.update_attribute(:sticky, true)
respond_to do |format|
- format.html { redirect_to forum_memo_path(@memo.forum, @memo) }
+ format.html {
+ if params[:index]
+ redirect_to forums_path
+ else
+ redirect_to forum_memo_path(@memo.forum, @memo)
+ end
+ }
end
end
diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb
index c9f826c57..79639da1f 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,56 @@ 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
+ if !params[:user_activity_id].blank? && params[:user_activity_id].to_i != @topic.id
+ @topic.update_attributes(:visits => @topic.visits + 1)
+ end
+ 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 +303,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 +342,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
@@ -366,7 +373,7 @@ class MessagesController < ApplicationController
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
- redirect_to course_activity_path(@course)
+ redirect_to course_path(@course)
elsif params[:is_course] && params[:is_course].to_i == 1 && params[:is_board] && params[:is_board].to_i == 1
redirect_to course_boards_path(@course)
elsif @message.parent
@@ -399,6 +406,21 @@ 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)
+ respond_to do |format|
+ format.js
+ format.html{
+ if params[:is_board]
+ redirect_to course_boards_path(@course)
+ else
+ redirect_to board_message_path(@topic.board_id, @topic)
+ end
+ }
+ end
+ end
+
def quote
# @subject = @message.subject
# @subject = "RE: #{@subject}" unless @subject.starts_with?('RE:')
@@ -437,8 +459,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/my_controller.rb b/app/controllers/my_controller.rb
index ce5a575c0..882f255aa 100644
--- a/app/controllers/my_controller.rb
+++ b/app/controllers/my_controller.rb
@@ -16,10 +16,10 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class MyController < ApplicationController
+ include ApplicationHelper
layout "users_base"
- # edit
+ skip_before_filter :check_authentication, :only => [:account]
before_filter :auth_login1, :only => [:account]
- #
before_filter :require_login, except: [:change_mail_notification]
helper :issues
@@ -145,14 +145,43 @@ class MyController < ApplicationController
applied_message = AppliedMessage.where(:id => params[:applied_message_id]).first
applied_message.update_attribute(:viewed, true)
end
-
- # 基本资料不完善 @force为false, 完善 @force为true
- @force = false
- if params[:tip]
- @force = true
+ @user = params[:user_id].nil? ? User.current : User.find(params[:user_id])
+ # @user = User.current
+ # 认证
+ ue = @user.user_extensions
+ @trail_authentication = ApplyAction.where(:user_id => User.current.id, :container_type => "TrialAuthorization").order("created_at desc").first
+ @authentication = @user.authentication
+ if @user.nickname.nil? || @user.lastname.nil? || ue.try(:identity).nil? || ue.try(:location).nil? || ue.try(:location).nil?
+ @require_auth = true
+ else
+ if User.current.certification != 1 && (@trail_authentication.blank? || (@trail_authentication.status == 2 && (@trail_authentication.updated_at.to_i + 5*60) < Time.now.to_i))
+ @require_trail_auth = true
+ end
end
+ # @require_auth = true
+ #
+ # # 基本资料不完善 @force为false, 完善 @force为true
+ # @force = false
+ # # @authentication = @user.authentication
+ # @trail_authentication = AuthenticationsUsers.where(:user_id => User.current.id).first
+ # if params[:tip]
+ # @force = true
+ # else
+ # user = UserExtensions.where(:user_id => User.current.id).first
+ # if user.identity.nil? || user.school_id.nil? || User.current.lastname.nil?
+ # @force = false
+ # else
+ # @force = @trail_authentication.blank? ? false : true
+ # end
+ # end
+ # # 用户认证
+ # @auth = @user.authentication ? false : true
- @user = User.current
+ @s_message = AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddSchools').first
+ @d_message = AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddDepartment').first
+
+ AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddSchools').update_all(:viewed => true)
+ AppliedMessage.where(:status => 3, :user_id => User.current.id, :viewed => 0, :applied_type => 'ApplyAddDepartment').update_all(:viewed => true)
lg = @user.login
@pref = @user.pref
@@ -160,21 +189,23 @@ class MyController < ApplicationController
diskfile1 = diskfile + 'temp'
begin
if request.post?
- changed_login = (@user.login != params[:login])
- changed_mail = (@user.mail != params[:user][:mail])
- @user.safe_attributes = params[:user]
+ #changed_login = (@user.login != params[:login])
+ #changed_mail = (@user.mail != params[:user][:mail])
+ #@user.safe_attributes = params[:user]
+ @user.nickname = params[:nickname]
@user.lastname = params[:lastname]
@user.firstname = ""
+ @user.show_realname = params[:show_realname] ? 0 : 1
@user.pref.attributes = params[:pref]
@user.pref[:no_self_notified] = (params[:no_self_notified] == '1')
- @user.login = params[:login].strip
- unless @user.user_extensions.nil?
- # 如果用户是从业者,将单位名称保存至学校id字段
- if @user.user_extensions.identity == 3
- # @user.firstname = params[:enterprise_name]
- @user.user_extensions.school_id = params[:occupation]
- end
- end
+ #@user.login = params[:login].strip
+ # unless @user.user_extensions.nil?
+ # # 如果用户是从业者,将单位名称保存至学校id字段
+ # if @user.user_extensions.identity == 3
+ # # @user.firstname = params[:enterprise_name]
+ # @user.user_extensions.school_id = params[:occupation]
+ # end
+ # end
@se = @user.extensions
# if params[:occupation].to_i.to_s == params[:occupation]
@@ -183,30 +214,53 @@ class MyController < ApplicationController
# @se.occupation = params[:occupation]
# end
@se.school_id = params[:occupation]
+ @se.department_id = params[:department_id]
@se.gender = params[:sex]
@se.location = params[:province] if params[:province]
@se.location_city = params[:city] if params[:city]
@se.identity = params[:identity].to_i if params[:identity]
- @se.technical_title = params[:technical_title] if params[:technical_title]
- @se.student_id = params[:no] if params[:no]
+ if @se.identity == 0
+ @se.technical_title = params[:te_technical_title] if params[:te_technical_title]
+ @se.student_id = nil
+ elsif @se.identity == 1
+ @se.student_id = params[:no] if params[:no]
+ @se.technical_title = nil
+ elsif @se.identity == 2
+ @se.technical_title = params[:pro_technical_title] if params[:pro_technical_title]
+ @se.student_id = nil
+ end
# @se.brief_introduction = params[:brief_introduction]
- @se.description = params[:description]
+ @se.brief_introduction = params[:brief_introduction]
if @user.save && @se.save
- # 修改邮箱的时候同步修改到gitlab
- if changed_mail || changed_login
- g = Gitlab.client
- s = Trustie::Gitlab::Sync.new
- begin
- gid = @user.gid
- if gid.nil?
- gid = s.sync_user(@user).id
+
+ reward_grade(@user, @user.id, 'Account', 500)
+
+ if @se.identity == 1
+ school_ids = School.where(:auto_users_trial => 1).map(&:id)
+ if !@se.student_id.nil? && @se.student_id != "" && !@se.school.nil? && school_ids.include?(@se.school_id)
+ apply_action = ApplyAction.where(:user_id => @user.id, :container_type => "TrialAuthorization", :status => 0).first
+
+ unless apply_action.blank?
+ @user.update_attributes(:certification => 1)
+ apply_action.update_attributes(:status => 1)
end
- g.edit_user(gid, :email => params[:user][:mail], :username => @user.login)
- rescue Exception => e
- puts e
end
end
+ # 修改邮箱的时候同步修改到gitlab
+ # if changed_mail || changed_login
+ # g = Gitlab.client
+ # s = Trustie::Gitlab::Sync.new
+ # begin
+ # gid = @user.gid
+ # if gid.nil?
+ # gid = s.sync_user(@user).id
+ # end
+ # g.edit_user(gid, :email => params[:user][:mail], :username => @user.login)
+ # rescue Exception => e
+ # puts e
+ # end
+ # end
# 头像保存
FileUtils.mv diskfile1, diskfile, force: true if File.exist? diskfile1
@@ -214,7 +268,7 @@ class MyController < ApplicationController
@user.notified_project_ids = (@user.mail_notification == 'selected' ? params[:notified_project_ids] : [])
set_language_if_valid @user.language
flash[:notice] = l(:notice_account_updated)
- redirect_to user_url(@user)
+ redirect_to my_account_url()
return
else
@user.login = lg
@@ -225,7 +279,8 @@ class MyController < ApplicationController
File.delete(diskfile1) if File.exist?(diskfile1)
end
- render :layout => 'new_base_user'
+ @setting_type = 1
+ render :layout => 'base_edu_account'
end
# Destroys user's account
@@ -250,6 +305,7 @@ class MyController < ApplicationController
def password
begin
@act='password'
+ # @user = params[:user_id].nil? ? User.current : User.find(params[:user_id])
@user = User.current
unless @user.change_password_allowed?
flash.now[:error] = l(:notice_can_t_change_password)
@@ -278,7 +334,8 @@ class MyController < ApplicationController
end
flash.now[:error] = l(:notice_account_old_wrong_password)
end
- render :template => 'my/account',:layout=>'new_base_user'
+ @setting_type = 5
+ render :template => 'account/change_psd',:layout=>'base_edu_account'
end
# Create a new feeds key
@@ -367,7 +424,7 @@ class MyController < ApplicationController
}
layout[group] = group_items
@user.pref[:my_page_layout] = layout
- @user.pref.save
+ @user.pref.saveaccount
end
end
render :nothing => true
diff --git a/app/controllers/myshixuns_controller.rb b/app/controllers/myshixuns_controller.rb
index b8df444b3..fad907f1c 100644
--- a/app/controllers/myshixuns_controller.rb
+++ b/app/controllers/myshixuns_controller.rb
@@ -1,33 +1,167 @@
+# encoding: utf-8
class MyshixunsController < ApplicationController
layout 'base_myshixun'
- skip_before_filter :verify_authenticity_token, :only => [:training_task_status]
- before_filter :require_login, :except => [:training_task_status]
- before_filter :find_myshixun, :only => [:show]
+ skip_before_filter :verify_authenticity_token, :only => [:training_task_status, :close_webssh]
+ before_filter :require_login, :except => [:training_task_status, :close_webssh]
+ before_filter :check_authentication, :except => [:training_task_status, :close_webssh]
+ before_filter :find_myshixun, :only => [:show, :myshixun_reset, :open_webssh]
+
+
+ include ApplicationHelper
+
+ # 将代码重置到开启状态
+ # 方法:使用文件更新,非Git重置
+ def code_reset
+
+ end
+
+ def code_reset_success
+
+ end
+
+ # 连接webssh
+ def open_webssh
+ username = Redmine::Configuration['webssh_username']
+ password = Redmine::Configuration['webssh_password']
+ begin
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ uri = "#{shixun_tomcat}/bridge/webssh/getConnectInfo"
+ user_id = User.current.id
+ params = {tpiID:@myshixun.id, operationEnvironment:@myshixun.shixun.try(:language)}
+ res = uri_exec uri, params
+ if res && res['code'].to_i != 0
+ raise("实训云平台繁忙(繁忙等级:92)")
+ end
+ render :json => {:host => res['address'], :port => res['port'], :username => username, :password => password, :game_id => @myshixun.id}
+ rescue Exception => e
+ logger.error(e)
+ render :json => {:error => e.try(:message)}
+ # @message = e.try(:message)
+ end
+ end
+
+ # 断开webssh连接
+ def close_webssh
+ username = Redmine::Configuration['webssh_username']
+ password = Redmine::Configuration['webssh_password']
+ begin
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ uri = "#{shixun_tomcat}/bridge/webssh/deleteSSH"
+ user_id = User.current.id
+ logger.info("#############################")
+ logger.info("game_id:" + @_params[:id])
+ params = {tpiID:@_params[:id]} # @_params[:id] 是webssh传过来的gameId
+ res = uri_exec uri, params
+ if res && res['code'].to_i != 0
+ raise("实训云平台繁忙(繁忙等级:93)")
+ end
+ render :jsonp => {:host => res['address'], :port => res['port'], :username => username, :password => password}
+ rescue Exception => e
+ logger.error(e)
+ @message = e.try(:message)
+ end
+ end
+
+ # 实训重置只更新脚本
+ def myshixun_reset
+ ActiveRecord::Base.transaction do
+ begin
+ g = Gitlab.client
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ shixun = @myshixun.shixun
+ @challenges = shixun.challenges
+ # 删除选择题用户记录
+ unless @challenges.blank?
+ @challenges.each do |challenge|
+ if challenge.st != 0
+ challenge.challenge_chooses.each do |choose|
+ user_output = choose.choose_outputs
+ unless user_output.blank?
+ user_output.delete
+ end
+ end
+ end
+ end
+ end
+ #end
+ myshixun_job = Base64.urlsafe_encode64("myshixun_#{@myshixun.id}")
+ StudentWork.where(:myshixun_id => @myshixun.id).update_all(:myshixun_id => nil, :work_status => 0)
+ @myshixun.destroy
+ myshixun_member = @myshixun
+ repository = @myshixun.repository
+ repository.destroy
+ g_project = g.project(@myshixun.gpid)
+ unless g_project.id.nil?
+ git_rep = g.delete_project(@myshixun.gpid)
+ logger.info("### delete repository result is #{git_rep}")
+ if git_rep != true
+ raise("实训云平台繁忙(繁忙等级:87)")
+ end
+ end
+ redirect_to shixun_exec_shixun_path(shixun, :type => 1, :is_subject => params[:is_subject])
+ rescue Exception => e
+ flash[:error] = "实训云平台繁忙(繁忙等级:89)"
+ g.delete_project(@myshixun.gpid) if !g_project.try(:id).nil?
+ redirect_to myshixun_path(@myshixun)
+ logger.error("myshixun reset failed #{e}")
+ raise ActiveRecord::Rollback
+ end
+ end
+ end
# taskId 即返回的game id
- # params [:stauts] 0 表示成功,其它则失败
+ # 返回结果:params [:stauts] 0 表示成功,其它则失败
# msg 错误信息
# output 为测试用户编译输出结果
# myshixun:status 1为完成实训
+ # @jenkins: caseId对应test_set的position,passed: 1表示成功,0表示失败
+ # resubmit 1:表示已通关后重新评测;0:表示非重新评测
+ # retry_status 0:初始值;1:重新评测失败;2:重新评测成功
def training_task_status
- status = params[:status].to_i
- task_id = params[:taskId]
- outPut = Base64.decode64(params[:outPut]) unless params[:outPut].blank?
- message = Base64.decode64(params[:msg]) unless params[:msg].blank?
- game = Game.find(task_id)
+ #params[:jsonTestDetails] = '{"buildID":"1","compileSuccess":"1","msg":[{"caseId":"1","expectedOutput":"56ysMOS9jeWQjOWtpueahOaAu+WIhuS4ujoyNDcK56ysMeS9jeWQjOWtpueahOaAu+WIhuS4ujoz MjIK","input":"Mg0KMjMsNTYsNzgsOTANCjIxLDU2LDc4LDc2LDkx","output":"56ysMOS9jeWQjOWtpueahOaAu+WIhuS4ujoyNDcK56ysMeS9jeWQjOWtpueahOaAu+WIhuS4ujoz MjIK","passed":"1"},{"caseId":"2","expectedOutput":"56ysMOS9jeWQjOWtpueahOaAu+WIhuS4ujoyMjgK56ysMeS9jeWQjOWtpueahOaAu+WIhuS4ujoy MzUK56ysMuS9jeWQjOWtpueahOaAu+WIhuS4ujoyMDYK","input":"Mw0KOTgsNzYsNTQNCjkwLDU0LDg3LDQNCjc4LDI2LDEyLDkw","output":"56ysMOS9jeWQjOWtpueahOaAu+WIhuS4ujoyMjgK56ysMeS9jeWQjOWtpueahOaAu+WIhuS4ujoy MzUK56ysMuS9jeWQjOWtpueahOaAu+WIhuS4ujoyMDYK","passed":"1"}],"outPut":"Y29tcGlsZSBzdWNjZXNzZnVsbHk","resubmit":"57D9COBR_5806","status":"0"}'
+ jsonTestDetails = JSON.parse(params[:jsonTestDetails])
+ status = jsonTestDetails['status']
+ game_id = jsonTestDetails['buildID']
+ resubmit = jsonTestDetails['resubmit']
+ outPut = tran_base64_decode64(jsonTestDetails['outPut'])
+ jenkins_testsets = jsonTestDetails['msg']
+ compile_success = jsonTestDetails['compileSuccess']
+ # message = Base64.decode64(params[:msg]) unless params[:msg].blank?
+ logger.info(outPut)
+ game = Game.find(game_id)
challenge = game.challenge
- if status == 0
- myshixun = game.myshixun
- games_count = myshixun.games.count
- if challenge.position == games_count
- myshixun.update_attribute(:status, 1)
+ unless jenkins_testsets.blank?
+ jenkins_testsets.each do |j_test_set|
+ logger.info("j_test_set: ############## #{j_test_set['output']}")
+ actual_output = tran_base64_decode64(j_test_set['output'])
+ logger.info "actual_output:################################################# #{actual_output}"
+ game_outputs = Output.create(:code => status, :game_id => game_id, :out_put => outPut, :test_set_position => j_test_set['caseId'],
+ :actual_output => actual_output, :result => j_test_set['passed'].to_i, :query_index => game.query_index, :compile_success => compile_success.to_i)
+ # output = Output.where(:game_id => game.id, :test_set_position => j_test_set['caseId'].to_i).first
+ # logger.info("#############{outPut}")
+ # if output.nil?
+ # game_outputs = Output.create(:code => status, :game_id => game_id, :out_put => outPut, :test_set_position => j_test_set['caseId'],
+ # :actual_output => actual_output, :result => j_test_set['passed'].to_i)
+ # else
+ # output.update_attributes(:code => status, :out_put => outPut, :actual_output => actual_output, :result => j_test_set['passed'].to_i)
+ # end
+ end
+ end
+ if status == "0"
+ if !resubmit.blank?
+ game.update_attributes(:retry_status => 2, :resubmit_identifier => resubmit)
+ else
+ game.update_attributes(:status => 2, :end_time => Time.now)
+ unless game.answer_open? # 如果没有查看答案,则获得该关卡得分
+ game.update_attribute(:final_score, challenge.score)
+ end
+ end
+ else # status == "-1" 表示返回结果错误
+ if !resubmit.blank?
+ game.update_attributes(:retry_status => 1, :resubmit_identifier => resubmit)
+ else
+ game.update_attribute(:status, 0)
end
- game_outputs = Output.create(:code => status, :msg => message, :game_id => task_id, :out_put => outPut)
- game.update_attribute(:status, 2)
- game.update_attribute(:final_score, challenge.score)
- else
- game_outputs = Output.create(:code => status, :msg => message, :game_id => task_id, :out_put => outPut)
- game.update_attribute(:status, 0)
end
render :json => {:data => "success"}
end
@@ -41,7 +175,7 @@ class MyshixunsController < ApplicationController
private
# Find myshixun of id params[:id]
def find_myshixun
- @myshixun = Myshixun.find(params[:id])
+ @myshixun = Myshixun.find_by_identifier(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
diff --git a/app/controllers/praise_tread_controller.rb b/app/controllers/praise_tread_controller.rb
index 136915bbd..ad8655bdb 100644
--- a/app/controllers/praise_tread_controller.rb
+++ b/app/controllers/praise_tread_controller.rb
@@ -17,13 +17,24 @@ class PraiseTreadController < ApplicationController
end
# @is_in_list = nil
@obj = find_object_by_type_and_id(@obj_type,@obj_id)
- pts = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",@obj_id,@obj_type.to_s,User.current.id)
- unless pts.empty?
+ pts = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?", @obj_id, @obj_type.to_s, User.current.id).first
+ unless pts.blank?
+ if(params[:game_praise] == "true")
+ pts.delete
+ if params[:obj_type] == "Challenge"
+ praise_tread_count = PraiseTread.where(:praise_tread_object_id => @obj_id, :praise_tread_object_type => "Challenge").count
+ else
+ praise_tread_count = PraiseTread.where(:praise_tread_object_id =>@obj_id, :praise_tread_object_type => "ChallengeTread").count
+ end
+ render :json => {praise: false, praise_tread_count: praise_tread_count}
+ return
+ end
respond_to do |format|
format.js
end
return
end
+
@horizontal = params[:horizontal].downcase == "false" ? false:true if params[:horizontal]
# if @obj.respond_to?("author_id")
# author_id = @obj.author_id
@@ -33,6 +44,15 @@ class PraiseTreadController < ApplicationController
# unless author_id == User.current.id
praise_tread_plus(@obj_type,@obj_id,1)
# end
+ if params[:game_praise] == "true"
+ if params[:obj_type] == "Challenge"
+ praise_tread_count = PraiseTread.where(:praise_tread_object_id => @obj_id, :praise_tread_object_type => "Challenge").count
+ else
+ praise_tread_count = PraiseTread.where(:praise_tread_object_id => @obj_id, :praise_tread_object_type => "ChallengeTread").count
+ end
+ render :json => {praise: true, praise_tread_count: praise_tread_count}
+ return
+ end
respond_to do |format|
format.js
end
@@ -137,6 +157,10 @@ class PraiseTreadController < ApplicationController
@obj = Syllabus.find_by_id(id)
when 'Work'
@obj = Work.find_by_id(id)
+ when 'Challenge' || 'ChallengeTread'
+ @obj = Challenge.find_by_id(id)
+ when 'Discuss'
+ @obj = Discuss.find_by_id(id)
else
@obj = nil
end
diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb
index ff3f1c7d1..ea64d0397 100644
--- a/app/controllers/projects_controller.rb
+++ b/app/controllers/projects_controller.rb
@@ -929,10 +929,10 @@ class ProjectsController < ApplicationController
end
end
- def uri_exec uri, params
- res = Net::HTTP.post_form(uri, params).body
- res = JSON.parse(res)
- end
+ # def uri_exec uri, params
+ # # res = Net::HTTP.post_form(uri, params).body
+ # # res = JSON.parse(res)
+ # end
# 开启实训项目,学生会fork一个项目并自动发送任务
def training_project_extend
diff --git a/app/controllers/repositories_controller.rb b/app/controllers/repositories_controller.rb
index 81bd8d432..bcc2d3e63 100644
--- a/app/controllers/repositories_controller.rb
+++ b/app/controllers/repositories_controller.rb
@@ -36,17 +36,17 @@ class RepositoriesController < ApplicationController
before_filter :find_repository, :only => [:edit, :update, :destroy, :committers]
before_filter :find_project_repository, :except => [:commits, :shixun_show, :new, :create, :newcreate, :edit, :update, :destroy, :committers,
- :newrepo, :to_gitlab, :forked, :export_rep_static, :training_project_extend, :shixun_entry]
+ :newrepo, :to_gitlab, :forked, :export_rep_static, :training_project_extend, :shixun_entry, :shixun_commit_diff]
# 实训项目新增
- before_filter :find_project_and_repository, :only => [:commits, :shixun_show, :shixun_entry]
+ before_filter :find_project_and_repository, :only => [:commits, :shixun_show, :shixun_entry, :shixun_commit_diff]
# 连接gitlab
# before_filter :connect_gitlab, :only => [:quality_analysis, :commit_diff]
before_filter :find_changeset, :only => [:revision, :add_related_issue, :remove_related_issue]
# before_filter :authorize , :except => [:newrepo,:newcreate,:fork, :to_gitlab, :forked, :project_archive, :quality_analysis, :commit_diff]
- before_filter :authorize_visible , :except => [:shixun_show, :newrepo,:newcreate,:fork, :to_gitlab, :forked, :project_archive, :quality_analysis, :commit_diff]
+ before_filter :authorize_visible , :except => [:shixun_show, :newrepo,:newcreate,:fork, :to_gitlab, :forked, :project_archive, :quality_analysis, :commit_diff, :shixun_commit_diff]
# 版本库新增权限
# before_filter :show_rep, :only => [:show, :stats, :revisions, :revision, :diff, :commit_diff ]
accept_rss_auth :revisions
@@ -524,14 +524,14 @@ update
def shixun_show
# 顶部导航
@project_menu_type = 5
- @entries = @repository.entries(@path, @rev)
+ @entries = @repository.entries(@path, @rev) # Repository::Gitlab
if request.xhr?
@entries ? render(:partial => 'dir_list_content') : render(:nothing => true)
else
@changesets_latest_coimmit = @g.rep_last_changes(@shixun.gpid, :rev => @rev, :path => @path)
# @g.rep_last_changes(@project.gpid, :rev => @rev, :path => @path)
# 总的提交数
- @changesets_all_count = @g.user_static(@shixun.gpid, :rev => @rev).count
+ @changesets_all_count = @g.user_static(@shixun.gpid, :rev => @rev).count.to_i
# 获取默认分支
@g_default_branch = @g_project.default_branch.nil? ? "master" : @g_project.default_branch
@@ -543,10 +543,14 @@ update
# token值解密
# gitlab_token = aes_dicrypt("priEn3UwXfJs3Pmy", token)
@zip_path = Gitlab.endpoint.to_s + "/projects/" + @shixun.gpid.to_s + "/repository/archive?&private_token=" + token
-
- @creator = @shixun.owner.to_s
+ if @shixun.fork_from.present?
+ login = User.find_by_mail("eduforge@163.com").try(:login)
+ else
+ login = User.find_by_mail("educoder@163.com").try(:login)
+ end
gitlab_address = Redmine::Configuration['gitlab_address']
- @repos_url = gitlab_address.to_s+"/" + @creator + "/" + @repository.identifier+"."+"git"
+ @repos_url = git_shixun_url(@shixun, login)
+ # @repos_url = gitlab_address.to_s+"/" + @creator + "/" + @repository.identifier+"."+"git"
# 提交总数同步更新
@shixun.update_attribute(:changeset_num, @changesets_all_count)
@@ -619,11 +623,15 @@ update
@project_menu_type = 5
@entry = @repository.entry(@path, @rev)
(show_error_not_found; return) unless @entry
- limit = 10
+ limit = 15
# 每次页面的换回值从1开始,但是gitlab的页面查询是从0开始,所以先改变page的类型减一在改回来
@commits = @g.commits(@shixun.gpid, page:(params[:page].to_i - 1).to_s, ref_name:@rev)
@commits_count = params[:commit_count].nil? ? @g.user_static(@shixun.gpid, :rev => @rev).count : params[:commit_count].to_i
- @commits_pages = Paginator.new @commits_count, limit, params[:page]
+ # @commits_pages = Paginator.new @commits_count, limit, params[:page]
+
+ @commits_pages = Paginator.new @commits_count, limit, params['page'] || 1
+ @offset ||= @commits_pages.offset
+ @commits = paginateHelperForGitlab @commits, limit
render :layout => 'base_shixun'
end
@@ -687,7 +695,7 @@ update
# 顶部导航
@project_menu_type = 5
- entry_and_raw(false)
+ # entry_and_raw(false)
@content = @repository.cat(@path, @rev)
# @changesets_latest_coimmit = @g.commit(@project.gpid, @entry.try(:lastrev))
@changesets_latest_coimmit = @g.rep_last_changes(@shixun.gpid, :rev => @rev, :path => @path)
@@ -797,6 +805,17 @@ update
render :layout => 'base_projects'
end
+ def shixun_commit_diff
+ @commit_diff = @g.commit_diff(@shixun.gpid, params[:changeset_id])
+ diff = ActiveSupport::JSON.decode(@commit_diff.to_json).first
+ diff = OpenStruct.new(diff)
+ @diff_file = Trustie::Gitlab::Diff::File.new(diff)
+
+
+ # @commit_details = @g.commit(@project.gpid, params[:changeset])
+ render :layout => 'base_shixun'
+ end
+
# 实训项目
# 每次提交对应的文件差异
def commit
@@ -900,7 +919,7 @@ update
end
def find_project_and_repository
- @shixun = Shixun.find(params[:id])
+ @shixun = Shixun.find_by_identifier(params[:id])
@repository = @shixun.repository
render_404 if @shixun.gpid.nil?
@path = params[:path].is_a?(Array) ? params[:path].join('/') : params[:path].to_s
@@ -918,6 +937,7 @@ update
end
rescue ActiveRecord::RecordNotFound
render_404
+ return
rescue InvalidRevisionParam
show_error_not_found
end
diff --git a/app/controllers/school_controller.rb b/app/controllers/school_controller.rb
index b6e34a185..208cadae3 100644
--- a/app/controllers/school_controller.rb
+++ b/app/controllers/school_controller.rb
@@ -1,285 +1,317 @@
-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 << "#{p.province} "
- 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 << "#{s.name} "
- 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
+ before_filter :find_school, :only => [:destroy]
+ 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]
+ render :layout => "base_management"
+ end
+
+ #获取制定学校开设的课程数
+ def course_count school_id
+ School.find(school_id).courses.count
+ end
+
+
+ def index
+ render :layout => "base_management"
+ end
+
+ def get_province
+ @provinces = School.find_by_sql("select distinct province from schools")
+
+ options = ""
+
+ @provinces.each do |p|
+ options << "#{p.province} "
+ 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 << "#{s.name} "
+ 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 params[:no_school_ids]
+ if(condition == '')
+ @school = School.where("id not in #{params[:no_school_ids]}").reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100)
+ @school_count = School.count
+ else
+ @school = School.where("id not in #{params[:no_school_ids]} and name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100)
+ @school_count = School.where("id not in #{params[:no_school_ids]} and name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").count
+ end
+ else
+ 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
+ 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]
+ school.city = params[:city]
+ school.address = params[:address]
+
+ #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
+
+ def destroy
+ if @school
+ if UserExtensions.where(:school_id => @school.id).count == 0
+ School.where(:id=>@school.id).destroy_all
+ @school.destroy
+ end
+ respond_to do |format|
+ format.js
+ end
+ end
+ end
+
+ private
+ def find_school
+ @school = School.find params[:id]
+ rescue ActiveRecord::RecordNotFound
+ render_404
+ end
+end
diff --git a/app/controllers/shixuns_controller.rb b/app/controllers/shixuns_controller.rb
index bd92c6b9e..7eecc484c 100644
--- a/app/controllers/shixuns_controller.rb
+++ b/app/controllers/shixuns_controller.rb
@@ -2,119 +2,844 @@
# REDO: 创建版本库权限控制
class ShixunsController < ApplicationController
layout 'base_shixun'
- before_filter :require_login
- before_filter :find_shixun, :except => [ :index, :new, :create]
+ before_filter :require_login, :except => [:ghook]
+ before_filter :check_authentication, :except => [:ghook]
+ before_filter :find_shixun, :except => [ :index, :new, :create, :index, :search, :shixun_courses, :new_disscuss, :shixun_migrate]
+ skip_before_filter :verify_authenticity_token, :only => [:ghook]
before_filter :shixun_view_allow, :only => [:show]
- before_filter :require_manager, :only => [ :settings, :add_script]
+ before_filter :require_manager, :only => [ :settings, :add_script, :publish, :collaborators_delete, :shixun_members_added, :add_collaborators]
+ before_filter :validation_email, :only => [:new]
include ApplicationHelper
+ 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)
+ DCODES = %W(2 3 4 5 6 7 8 9 a b c f e f g h i j k l m n o p q r s t u v w x y z)
- def shixun_monitor
- monitor_filter
- if @had_exec
- @tpm = Myshixun.where(:user_id => User.current, :shixun_id => @shixun).first
+ # 获取版本库文件目录
+ def search_file_list
+ path = params[:path]
+ @path = to_path_param(path)
+ g = Gitlab.client
+ @dir = g.trees(@shixun.gpid, :path => @path).map{|tree|[tree.type, (@path.blank? ? tree.name : "#{@path}"+"/"+tree.name )]}
+ logger.info("dir is ##{@dir}")
+ respond_to do |format|
+ format.js
end
+ # render :json => {:dir => @dir}
+ end
+
+ def achieve_ways
+ @repository = @shixun.repository
+ @entries = @repository.entries(@path, @rev)
+ # @entries = Gitlab.client.trees(@shixun.gpid).map{|tree| tree.name}
+ end
+
+ def statistics_students
+ pub_shixun = ApplyAction.where(:container_type => "ApplyShixun", :status => 1, :container_id => @shixun.id).last
+ if pub_shixun.present?
+ updated_at = pub_shixun.updated_at
+ @statistics = @shixun.myshixuns.select{|myshixun| myshixun.updated_at > updated_at}
+ @statistics = @statistics.map(&:id)
+ @statistics = Myshixun.where(:id => @statistics).order("created_at desc")
+ #@statistics = @shixun.myshixuns.where("created_at > #{updated_at}").order("created_at desc")
+ @statistics_count = @statistics.count
+ @limit = 15
+ @is_remote = true
+ @statistic_pages = Paginator.new @statistics_count, @limit, params['page'] || 1
+ @offset ||= @statistic_pages.offset
+ @statistics = paginateHelper @statistics, @limit
+ end
+
+ end
+
+ # push代码的时候会触发gitlab hook
+ def ghook
+ # shixun_modify_status_without_publish(@shixun, 1)
+ render :json => {status: "success"}
+ end
+
+ # 注意:shixun_id 格式 /shixun_migrate?shixun_id=100
+ # 注意:language 格式 /shixun_migrate?language="Java,Python"
+ def shixun_migrate
+ unless User.current.admin?
+ render_403
+ return
+ end
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ if params[:language]
+ language = params[:language].split("/")
+ logger.info(language)
+ shixuns = Shixun.where(:language => language)
+ elsif params[:shixun_id]
+ shixuns = Shixun.where(:id => params[:shixun_id])
+ else
+ shixuns = Shixun.all
+ end
+ if shixuns.present?
+ shixuns.each do |shixun|
+ begin
+ logger.info("shixun id is #{shixun.id}")
+ tpiList =[]
+ gameInfo = shixun.gameInfo
+ myshixuns = shixun.myshixuns
+ if myshixuns.present?
+ myshixuns.each do |myshixun|
+ logger.info("tpiID is #{myshixun.id}")
+ tpiID = myshixun.id
+ instanceGitURL = git_myshixun_url_ip(myshixun, myshixun.try(:user_id))
+ logger.info("instanceGitURL is #{instanceGitURL}")
+ tpiList << {:tpiID => tpiID, :instanceGitURL => instanceGitURL}
+ logger.info("###############{tpiList.to_json unless tpiList.blank?}")
+
+ logger.info("************#{tpiList}")
+ end
+ end
+ tpiList = Base64.urlsafe_encode64(tpiList.to_json) unless tpiList.blank?
+ params = {:gameInfo => "#{gameInfo}", :tpiList => "#{tpiList}" }
+ logger.info("params is #{params}")
+ uri = "#{shixun_tomcat}/bridge/dataTransfer/transfer"
+ logger.info("uri is #{uri}")
+ res = uri_exec uri, params
+ logger.info("=====res is #{res['code']}")
+ render :json => {:result => "success"}
+ rescue Exception => e
+ logger.info("error ====> #{e.message}")
+ end
+ end
+ end
+ end
+
+ def shixun_test
+ jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
+ uri = URI("#{jenkins_shixuns}/jenkins-exec/webssh/getConnectInfo")
+ user_id = User.current.id
+ params = {userID:user_id}
+ res = uri_exec uri, params
+ render :json => {data:"succesed"}
+ end
+
+ def delete_shixun_test
+ jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
+ uri = URI("#{jenkins_shixuns}/jenkins-exec/webssh/deleteSSH")
+ user_id = User.current.id
+ params = {userID:user_id}
+ res = uri_exec uri, params
+ render :json => {data:"succesed"}
+ end
+
+ def game_webssh
+
+ end
+
+ def entry_edit
+ g = Gitlab.client
+ @path = params[:path]
+ @rev = params[:rev]
+ file_content = g.files(@shixun.gpid, @path, @rev).content
+ @content = tran_base64_decode64(file_content)
respond_to do |format|
format.js
end
end
- # copy_shixun:复制一个新的实训模块包括版本库
- # copy_myshixun自动创建系列game,game中只包含状态等信息,公共信息从Challeges中读取
- #
- def shixun_exec
- if has_exec_cur_shixun(@shixun) || User.current.id == @shixun.user_id
- render_403
+ def entry_update
+ g = Gitlab.client
+ @path = params[:path]
+ @rev = params[:rev]
+ @content = params[:content]
+ code_file = g.edit_file(@shixun.gpid, :content => params[:content], :file_path => @path, :branch_name => @rev, :commit_message => "shixun entry")
+ # if @shixun.try(:status).to_i < 2
+ # shixun_modify_status_without_publish(@shixun, 1)
+ # end
+ respond_to do |format|
+ format.js
end
- repository = @shixun.repository
+ end
+
+ def shixun_monitor
+ # monitor_filter
+ # if @had_exec
+ # @tpm = Myshixun.where(:user_id => User.current, :shixun_id => @shixun).first
+ # end
+ #
+ # respond_to do |format|
+ # format.js
+ # end
+ end
+
+ def statistics
+ @challenges = @shixun.challenges
+ @top_students = @shixun.myshixuns.where(:status => 1)
+ myshixuns = @shixun.myshixuns.includes(:games)
+ @latest_myshixuns = myshixuns.order("created_at desc").limit(4)
+ end
+
+
+
+ def autocompletion
+
+ end
+
+ def index
+ @order = "myshixun_count"
+ @sort = "asc"
+ search = params[:search]
+ @mail = User.current.mail.blank?
+ @shixun_all_count = Shixun.where(:hidden => 0).count
+ @shixuns = Shixun.where("name like ? and hidden = 0", "%#{search}%")
+ # @shixuns.each do |shixun|
+ # shixun[:myshixunCount] = shixun.myshixuns.count
+ # end
+ # @shixuns = @shixuns.sort{|x, y| y[:myshixunCount] <=> x[:myshixunCount]}
+ @shixuns = @shixuns.select("shixuns.*, (select count(myshixuns.id) from myshixuns where myshixuns.shixun_id = shixuns.id group by shixuns.id) AS myshixunCount").reorder("status = 2 desc, myshixunCount desc")
+
+ @shixun_my_score = Experience.find_by_sql("SELECT sum(score) as score FROM `experiences` where user_id=#{User.current.id}").first.try(:score).to_i
+ @current_user_had_passed = Myshixun.find_by_sql("select count(*) as had_passed from myshixuns where status =1 and user_id=#{User.current.id}
+ and shixun_id in (SELECT id FROM `shixuns` where status > 1)").first.try(:had_passed).to_i
+ #@majors = Major.where(:id => [635, 636, 637, 638, 639, 622, 619])
+ @courses = CourseList.where(:support_shixuns_search => 1)
+ @shixuns_count = @shixuns.count
+ @limit = 16
+ @is_remote = true
+ @shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
+ @offset ||= @shixun_pages.offset
+ @shixuns = paginateHelper @shixuns, @limit
+ render :layout => "base_edu"
+ end
+
+ def propaedeutics
+ respond_to do |format|
+ format.html
+ end
+ end
+
+ def update_propaedeutics
+ @shixun = Shixun.where(:identifier => params[:id]).first
+ @shixun.update_attribute("propaedeutics", params[:shixun][:propaedeutics])
+ redirect_to propaedeutics_shixun_path(@shixun)
+ end
+
+ def collaborators
+ @collaborators = @shixun.collaborators
+ end
+
+ def collaborators_delete
+ user_id = params[:c_id]
+ gid = User.find(user_id).try(:gid)
+ shixun_member = ShixunMember.where(:user_id => user_id, :shixun_id => @shixun.id, :role => 2).first
+ shixun_member.delete
+ g = Gitlab.client
+ unless gid.nil?
+ g.remove_team_member(@shixun.gpid, gid)
+ end
+ @collaborators = @shixun.collaborators
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ # 已存在的成员不添加
+ def add_collaborators
+ if !params[:search].nil?
+ # members = searchTeacherAndAssistant @course
+ member_ids = "(" + @shixun.shixun_members.map(&:user_id).join(',') + ")"
+ condition = "%#{params[:search].strip}%".gsub(" ","")
+ @users = User.where("id not in #{member_ids} and status = 1 and LOWER(concat(lastname, firstname, login, mail)) LIKE '#{condition}'").includes(:user_extensions)
+ end
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ # 事务处理,保证Trustie与Gitlab数据同步
+ def shixun_members_added
ActiveRecord::Base.transaction do
begin
- @g = Gitlab.client
- if User.current.gid.nil?
- s = Trustie::Gitlab::Sync.new
- s.sync_user(User.current)
- end
- gshixun = @g.fork(@shixun.gpid, User.current.gid)
- if !gshixun.id.nil?
- myshixun = copy_myshixun(@shixun, gshixun)
- challenges = @shixun.challenges
- # 之所以增加user_id是为了方便统计查询性能
- challenges.each_with_index do |challenge, index|
- status = (index == 0 ? 0 : 3)
- Game.create!(:challenge_id => challenge.id, :myshixun_id => myshixun.id, :status => status, :user_id => myshixun.user_id)
+ unless params[:membership][:user_ids].blank?
+ memberships = params[:membership][:user_ids]
+ memberships.each do |member|
+ user = User.find(member)
+ s = Trustie::Gitlab::Sync.new
+ if user.gid.present?
+ gid = user.gid
+ else
+ guser = s.sync_user(user)
+ gid = guser.id
+ end
+ ShixunMember.create!(:user_id => member, :shixun_id => @shixun.id, :role => 2)
+ u = s.g.add_team_member(@shixun.gpid, gid, 40) # 3代表角色master
+ if u.blank?
+ raise("同步Gitlab数据失败")
+ end
+ end
+ @collaborators = @shixun.collaborators
+ respond_to do |format|
+ format.js
end
- else
- raise("网络异常,请稍后重试")
- end
- respond_to do |format|
- format.html{myshixun_game_url(myshixun.current_task, :myshixun_id => myshixun)}
end
rescue Exception => e
- flash[:error] = l(:notice_shixun_failed_exec)+ " : " + e.message
- @g.delete_project(gshixun.id) if !gshixun.id.nil?
+ logger.error(e)
raise ActiveRecord::Rollback
end
end
end
+ def search
+ # 确定 sort 1升序 2 降序
+ @order = params[:order] || "myshixun_count"
+ bsort = params[:sort] || "desc"
+ @sort = bsort == "asc" ? "desc" : "asc"
+ if @order == "updated_at"
+ order_str = "#{Shixun.table_name}.updated_at #{@sort}"
+ else
+ order_str = "myshixun_count #{bsort}, #{Shixun.table_name}.updated_at #{bsort}"
+ end
+ @language = params[:language]
+ @status = params[:status].to_i
+ @shixun_status = params[:shixun_status] # 2是已发布 3是未发布
+ @search = params[:search]
+ #@major = params[:major]
+ @course = params[:course]
+ @trainee = params[:trainee]
+ #ids = Shixun.find_by_sql("select group_concat(id) as allId from shixuns where id in (SELECT distinct(shixun_id) FROM `challenges`)")
+ # @shixuns = Shixun.where("hidden = 0").reorder("updated_at desc")
+ @shixuns = Shixun.where("hidden = 0")
+ @shixuns = @shixuns.where(:language => @language) unless @language.blank?
+ @shixuns = @shixuns.where("name like ?", "%#{@search}%") unless @search.blank?
+ # if !@major.blank?
+ # @shixuns = @shixuns.where(:major_id => @major.to_i)
+ # @courses = CourseList.where(:id => MajorCourse.where(:major_id => @major).map(&:course_list_id))
+ # else
+ # @courses = CourseList.where(:id => MajorCourse.where(:major_id => [635, 636, 637, 638, 639, 622, 619]).map(&:course_list_id))
+ # end
+ @courses = CourseList.where(:support_shixuns_search => 1)
+ #if !@course.blank? && (@major.blank? || MajorCourse.where(:major_id => @major, :course_list_id => @course).count == 1)
+ if !@course.blank?
+ @shixuns = @shixuns.where(:id => ShixunMajorCourse.where(:course_list_id => @course).map(&:shixun_id))
+ end
+ # if !@major.blank? && MajorCourse.where(:major_id => @major, :course_list_id => @course).count == 0
+ # @course = nil
+ # end
+ @shixuns = @shixuns.where(:trainee => @trainee) unless @trainee.blank?
+ case @status
+ when 1, 0
+ @shixuns = @shixuns
+ when 2
+ @shixuns = @shixuns.where(:user_id => User.current)
+ when 3
+ shixun_ids = Myshixun.where(:user_id => User.current).blank? ? "(-1)" : "(" + Myshixun.where(:user_id => User.current).map(&:shixun_id).join(',') +")"
+ @shixuns = @shixuns.where("id not in #{shixun_ids}")
+ when 4
+ shixun_ids = Myshixun.where(:user_id => User.current, :status => 0).map(&:shixun_id)
+ @shixuns = @shixuns.where(:id => shixun_ids)
+ when 5
+ shixun_ids = Myshixun.where(:user_id => User.current, :status => 1).map(&:shixun_id)
+ @shixuns = @shixuns.where(:id => shixun_ids)
+ end
+ case @shixun_status
+ when "1"
+ @shixuns = @shixuns.where(:status => [0, 1])
+ when "2"
+ @shixuns = @shixuns.where(:status => 2)
+ when "3"
+ @shixuns = @shixuns.where(:status => 3)
+ when nil, "0"
+ @shixuns = @shixuns
+ end
+ if @order == "updated_at"
+ @shixuns =@shixuns.reorder(order_str)
+ else
+ # 最热排序
+ # @shixuns.each do |shixun|
+ # shixun[:myshixunCount] = shixun.myshixuns.count
+ # end
+ @shixuns = @shixuns.select("shixuns.*, (select count(myshixuns.id) from myshixuns where myshixuns.shixun_id = shixuns.id group by shixuns.id) AS myshixunCount").reorder("status = 2 desc, myshixunCount #{bsort}")
+ #@shixuns = @shixuns.reorder("status = 2 #{bsort}, myshixunCount #{bsort}")
+ # if bsort == "desc"
+ # @shixuns = @shixuns.sort{|x, y| y[:myshixunCount] <=> x[:myshixunCount]}
+ # else
+ # @shixuns = @shixuns.sort{|x, y| x[:myshixunCount] <=> y[:myshixunCount]}
+ # end
+ end
+ # @shixuns = Shixun.where(:authentication => 1).reorder(order)
+ @shixuns_count = @shixuns.count
+ @limit = 16
+ @is_remote = true
+ @shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
+ @offset ||= @shixun_pages.offset
+ @shixuns = paginateHelper @shixuns, @limit
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ # jenkins回调脚本
+ # gameID 及实训ID
+ def publish
+ @status = 0
+ @position = ""
+ begin
+ @shixun.challenges.each do |challenge|
+ if challenge.challenge_tags.count == 0
+ @status = 2
+ @position = (@position == "" ? @position : (@position + ",")) + challenge.position.to_s + "关"
+ end
+ end
+ if @status == 0
+ @shixun.update_attributes!(:status => 1)
+ apply = ApplyAction.where(:container_type => "ApplyShixun", :container_id => @shixun.id).order("created_at desc").first
+ if apply && apply.status == 0
+ @status = 0
+ else
+ ApplyAction.create(:container_type => "ApplyShixun", :container_id => @shixun.id, :user_id => User.current.id, :status => 0)
+ notes = User.current.show_name.to_s + " 申请发布实训:#{@shixun.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
+ rescue Exception => e
+ @jenkin_error = true
+ logger.error("pushlish game #{e}")
+ respond_to do |format|
+ format.js
+ end
+ end
+ end
+
+ def apply_publish
+ apply = ApplyAction.where(:container_type => "ApplyShixun", :container_id => @shixun.id).last
+ if apply && apply.status == 0
+ @status = 0
+ else
+ ApplyAction.create(:container_type => "ApplyShixun", :container_id => @shixun.id, :user_id => User.current.id, :status => 0)
+ notes = User.current.show_name.to_s + " 申请发布实训:#{@shixun.name} "
+ JournalsForMessage.create(:jour_id => 1, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0)
+ @shixun.update_column('status', 1)
+ @status = 1
+ end
+ end
+
+ def cancel_publish
+ apply = ApplyAction.where(:container_type => "ApplyShixun", :container_id => @shixun.id).order("created_at desc").first
+ if apply && apply.status == 0
+ apply.update_attributes(:status => 3)
+ @shixun.update_column('status', 0)
+ end
+ redirect_to shixun_path(@shixun)
+ end
+
+ def close
+ @shixun.update_column('status', 3)
+ redirect_to shixun_path(@shixun)
+ end
+
+ # copy_shixun:复制一个新的实训模块包括版本库
+ # copy_myshixun自动创建系列game,game中只包含状态等信息,公共信息从Challeges中读取
+ # 开启过实训的则直接跳入my实训页面
+ def shixun_exec
+ unless allow_shixun_exec(@shixun) && (User.current.manager_of_shixun?(@shixun) || @shixun.status > 0)
+ render_403
+ return
+ end
+ myshixun = Myshixun.where(:user_id => User.current.id, :shixun_id => @shixun.id).first
+ unless myshixun.blank?
+ logger.info("current task id is #{myshixun.current_task}")
+ redirect_to myshixun_game_path(myshixun.current_task, :myshixun_id => myshixun, :is_subject => params[:is_subject])
+ return
+ end
+ ActiveRecord::Base.transaction do
+ begin
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ code = down_generate_identifier("myshixun")
+ myshixun = Myshixun.create!(:shixun_id => @shixun.id, :user_id => User.current.id, :identifier => code)
+ # fork版本库,如果用户没有同步,则先同步用户
+ g = Gitlab.client
+ if User.current.gid.nil?
+ s = Trustie::Gitlab::Sync.new
+ s.sync_user(User.current)
+ end
+ gshixun = g.fork(@shixun.gpid, User.current.gid)
+ if gshixun.try(:id).present?
+ myshixun.update_column(:gpid, gshixun.id) if myshixun.try(:gpid).blank?
+ # educoder 加入到myshixun中
+ myshixun_admin_gid = User.where(:login => "educoder").first.try(:gid)
+ g.add_team_member(gshixun.id, myshixun_admin_gid, 40) # 30代表角色master
+ commit_id = g.commits(@shixun.gpid).first.try(:id)
+ myshixun.update_column(:commit_id, commit_id)
+ rep = Repository.create!(:myshixun_id => myshixun.id, :identifier => gshixun.name,:project_id => -1, :shixun_id => -2)
+ rep.update_column(:type, "Repository::Gitlab")
+ rep_url = Base64.urlsafe_encode64(git_shixun_url_ip @shixun, (@shixun.try(:fork_from).blank? ? "educoder" : "eduforge")) # 注意:educoder为默认给实训创建版本库的用户,如果换成别的用户,名字要相应的修改
+ logger.info("start openGameInstance")
+ uri = "#{shixun_tomcat}/bridge/game/openGameInstance"
+ logger.info("end openGameInstance")
+ params = {tpiID: "#{myshixun.id}", tpmID: "#{@shixun.id}", instanceGitURL:rep_url, operationEnvironment:"#{@shixun.try(:language)}"}
+ logger.info("openGameInstance params is #{params}")
+ res = uri_exec uri, params
+ if (res && res['code'].to_i != 0)
+ raise("实训云平台繁忙(繁忙等级:83)")
+ end
+ # 其它操作
+ challenges = @shixun.challenges
+ # 之所以增加user_id是为了方便统计查询性能
+ challenges.each_with_index do |challenge, index|
+ status = (index == 0 ? 0 : 3)
+ code = down_generate_identifier("game")
+ game =Game.create!(:challenge_id => challenge.id, :myshixun_id => myshixun.id, :status => status, :user_id => myshixun.user_id, :open_time => Time.now, :identifier => code)
+ # 记录刚开始时默认代开文件原始代码
+ # 刚开始fork的一段时间是获取不了content内容的
+ game_passed_code(game.try(:id), challenge.try(:path), myshixun.try(:gpid), 0)
+ end
+ if params[:type] == "1" # 重置过来的请求
+ shixun_mod = ShixunModify.where(:shixun_id => myshixun.try(:shixun_id), :myshixun_id => myshixun.try(:id)).first
+ if shixun_mod.nil?
+ ShixunModify.create(:shixun_id => myshixun.shixun_id, :myshixun_id => myshixun.id, :status => 0)
+ else
+ shixun_mod.update_attributes(:status => 0)
+ end
+ end
+ else
+ raise("实训云平台繁忙(繁忙等级:81)")
+ end
+ logger.info("myshixun id si #{myshixun.id} and current_task id is#{myshixun.current_task.id}")
+ redirect_to myshixun_game_path(myshixun.current_task, :myshixun_id => myshixun, :is_subject => params[:is_subject])
+ rescue Exception => e
+ flash[:error] = e.message
+ logger.info("failed to exec shixun: current task id is #{e}")
+ g.delete_project(gshixun.id) if !gshixun.id.nil?
+ redirect_to shixun_challenges_path(@shixun)
+ raise ActiveRecord::Rollback
+ end
+ end
+ end
+
+ def shixun_courses
+ data = {result:0,options:[]}
+ if params[:major_id] != 0
+ major = Major.find params[:major_id]
+ if major
+ data[:result] = 1
+ major_courses = major.major_courses
+ CourseList.where(:id => major_courses.map(&:course_list_id)).each do |course|
+ option = []
+ option << course.name.to_s
+ option << course.id
+ data[:options] << option
+ end
+ else
+ data[:result] = 0
+ end
+ else
+ data[:result] = 0
+ end
+ render :json =>data
+ end
+
def new
@shixun = Shixun.new
-
+ @support = Major.where(:support_shixuns=> 1)
respond_to do |format|
- format.html{render :layout => 'new_base'}
+ format.html{render :layout => 'base_edu'}
format.json
end
end
def create
+ identifier = generate_identifier
@shixun = Shixun.new(params[:shixun])
@shixun.user_id = User.current.id
@shixun.language = params[:language]
+ #@shixun.major_id = params[:major_id]
+ @shixun.trainee = params[:trainee]
+ @shixun.webssh = params[:webssh].to_i
+ @shixun.can_copy = params[:can_copy].to_i
+ @shixun.identifier = identifier
+ # if params[:course_id]
+ # params[:course_id].each do |course_id|
+ # @shixun.shixun_major_courses << ShixunMajorCourse.new(:major_id => params[:major_id], :course_list_id => course_id)
+ # end
+ # end
+ if CourseList.where(:name => params[:course_list].strip).count > 0
+ @shixun.shixun_major_courses << ShixunMajorCourse.new(:major_id => -1, :course_list_id => CourseList.where(:name => params[:course_list].strip).first.id)
+ else
+ course_list = CourseList.create(:name => params[:course_list].strip, :user_id => User.current.id, :is_admin => 0)
+ @shixun.shixun_major_courses << ShixunMajorCourse.new(:major_id => -1, :course_list_id => course_list.id)
+ end
(params[:shixun][:is_public] == "1" ? @shixun.is_public = true : @shixun.is_public = false)
- respond_to do |format|
- if @shixun.save
+ ActiveRecord::Base.transaction do
+ begin
+ @shixun.save!
m = ShixunMember.new(:user_id => User.current.id, :role => 1)
@shixun.shixun_members << m
- format.html { redirect_to @shixun, notice: l(:notice_successful_create) }
- format.js
- else
- format.html { render action: "new" }
- format.js
+ # 自动构建版本库
+ repository = Repository.new
+ repository.shixun = @shixun
+ repository.type = 'Repository::Gitlab'
+ repository.identifier = @shixun.identifier.downcase
+ repository.project_id = -1
+ repository.save!
+ s = Trustie::Gitlab::Sync.new
+ gproject = s.create_shixun(@shixun, repository)
+ raise "版本库创建失败" if @shixun.gpid.blank? # 若和gitlab没同步成功,则抛出异常
+ # g = Gitlab.client
+ # hook_url = Setting.protocol + "://" + Setting.host_name + "/shixuns/#{@shixun.identifier}" + "/ghook"
+ # g.add_project_hook(@shixun.gpid, hook_url)
+ redirect_to shixun_path @shixun, notice: l(:notice_successful_create)
+ rescue Exception => e
+ respond_to do |format|
+ flash[:notice] = "#{e.message}"
+ redirect_to new_shixun_path
+ raise ActiveRecord::Rollback
+ end
end
end
end
+ def copy
+ unless (@shixun.can_copy && User.current.user_extensions.try(:identity) == 0 && User.current.professional_certification)
+ render_403
+ return
+ end
+ ActiveRecord::Base.transaction do
+ begin
+ new_shixun = Shixun.new
+ new_shixun.attributes = @shixun.attributes.dup.except("id","user_id","visits","gpid","status", "identifier", "homepage_show")
+ new_shixun.user_id = User.current.id
+ new_shixun.identifier = generate_identifier
+ new_shixun.status = 0
+ new_shixun.fork_from = @shixun.id
+ new_shixun.save!
+ shixun_major_courses = ShixunMajorCourse.where(:shixun_id => @shixun.id)
+ if shixun_major_courses.present?
+ shixun_major_courses.each do |smc|
+ ShixunMajorCourse.create!(:shixun_id => new_shixun.id, :major_id => smc.major_id, :course_list_id => smc.course_list_id)
+ end
+ end
+ # 同步复制版本库,先fork再修改版本库名
+ # eduforge用户作为版本库的创建者
+ repository = Repository.new
+ repository.shixun = new_shixun
+ repository.type = 'Repository::Gitlab'
+ repository.identifier = new_shixun.identifier.downcase
+ repository.project_id = -1
+ repository.save!
+ g = Gitlab.client
+ user_gid = User.find_by_mail("eduforge@163.com").try(:gid)
+ gshixun = g.fork(@shixun.gpid, user_gid)
+ raise "版本库创建失败" if gshixun.try(:id).blank?
+ #gshixun = g.edit_project(gshixun.id, new_shixun.identifier, new_shixun.identifier)
+ raise "实训复制失败" if (gshixun.try(:name) != new_shixun.identifier || gshixun.try(:path) != new_shixun.identifier)
+ new_shixun.update_column(:gpid, gshixun.id)
+ # 同步复制者至gitlab,必须要求用户绑定了邮箱
+ ShixunMember.create!(:user_id => User.current.id, :shixun_id => new_shixun.try(:id), :role => 1)
+ s = Trustie::Gitlab::Sync.new
+ gid = User.current.try(:gid)
+ u = g.add_team_member(gshixun.id, gid, 40) # 3代表角色master
+
+ # # 同步复制合作者,合作者加入到gitlab
+ # unless User.current.manager_of_shixun?(@shixun)
+ # ShixunMember.create!(:user_id => User.current.id, :shixun_id => new_shixun.try(:id), :role => 1)
+ # end
+ # @shixun.shixun_members.each do |shixun_member|
+ # if ShixunMember.where(:shixun_id => new_shixun.try(:id), :user_id => shixun_member.user_id).blank?
+ # ShixunMember.create!(:user_id => shixun_member.try(:user_id), :shixun_id => new_shixun.try(:id),
+ # :role => (shixun_member.try(:user_id) == User.current.id ? 1 : 2))
+ # end
+ # s = Trustie::Gitlab::Sync.new
+ # gid = User.find(shixun_member.user_id).try(:gid)
+ # u = s.g.add_team_member(gshixun.id, gid, 40) # 3代表角色master
+ # if u.blank?
+ # raise("同步Gitlab数据失败")
+ # end
+ # end
+ # 同步复制关卡
+ if @shixun.challenges.present?
+ @shixun.challenges.each do |challenge|
+ new_challenge = Challenge.new
+ new_challenge.attributes = challenge.attributes.dup.except("id","shixun_id","user_id")
+ new_challenge.user_id = User.current.id
+ new_challenge.shixun_id = new_shixun.id
+ new_challenge.save!
+ if challenge.st == 0 # 评测题
+ # 同步测试集
+ if challenge.test_sets.present?
+ challenge.test_sets.each do |test_set|
+ new_test_set = TestSet.new
+ new_test_set.attributes = test_set.attributes.dup.except("id","challenge_id")
+ new_test_set.challenge_id = new_challenge.id
+ new_test_set.save!
+ end
+ end
+ # 同步关卡标签
+ challenge_tags = ChallengeTag.where("challenge_id =? and challenge_choose_id is null", challenge.id)
+ if challenge_tags.present?
+ challenge_tags.each do |challenge_tag|
+ ChallengeTag.create!(:challenge_id => new_challenge.id, :name => challenge_tag.try(:name))
+ end
+ end
+ elsif challenge.st == 1 # 选择题
+ if challenge.challenge_chooses.present?
+ challenge.challenge_chooses.each do |challenge_choose|
+ new_challenge_choose = ChallengeChoose.new
+ new_challenge_choose.attributes = challenge_choose.attributes.dup.except("id","challenge_id")
+ new_challenge_choose.challenge_id = new_challenge.id
+ new_challenge_choose.save!
+ # 每一题的选项
+ if challenge_choose.challenge_questions.present?
+ challenge_choose.challenge_questions.each do |challenge_question|
+ new_challenge_question = ChallengeQuestion.new
+ new_challenge_question.attributes = challenge_question.attributes.dup.except("id","challenge_choose_id")
+ new_challenge_question.challenge_choose_id = new_challenge_choose.id
+ new_challenge_question.save!
+ end
+ end
+ # 每一题的知识标签
+ st_challenge_tags = ChallengeTag.where(:challenge_id => challenge.id, :challenge_choose_id => challenge_choose.id)
+ if st_challenge_tags.present?
+ st_challenge_tags.each do |st_challenge_tag|
+ ChallengeTag.create!(:challenge_id => new_challenge.id, :name => st_challenge_tag.try(:name), :challenge_choose_id => new_challenge_choose.id)
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+ # 中间层创建测试集
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ gameInfo = new_shixun.gameInfo
+ uri ="#{shixun_tomcat}/bridge/game/publishGame"
+ params = {gameInfo:gameInfo}
+ res = uri_exec uri, params
+ if res && res['code'].to_i != 0
+ raise("实训云平台繁忙(繁忙等级:90)")
+ end
+ flash[:notice] = "实训复制成功"
+ redirect_to shixun_challenges_path(new_shixun)
+ rescue Exception => e
+ logger.info("copy shixun failed ##{e.message}")
+ flash[:notice] = "#{e.message}"
+ g.delete_project(gshixun.id) if gshixun.try(:id).present? # 异常后,如果已经创建了版本库需要删除该版本库
+ redirect_to shixun_challenges_path(@shixun)
+ raise ActiveRecord::Rollback
+ end
+ end
+ end
+
+ def fork_list
+ @shixuns = Shixun.where(:fork_from => @shixun.id)
+ @shixuns_count = @shixuns.count
+ @limit = 16
+ @is_remote = true
+ @shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
+ @offset ||= @shixun_pages.offset
+ @shixuns = paginateHelper @shixuns, @limit
+ end
+
def show
respond_to do |format|
format.html{redirect_to shixun_challenges_path(@shixun)}
end
end
- def edit
+ def generate_identifier
+ code = DCODES.sample(8).join
+ return generate_identifier if Shixun.where(identifier: code).present?
+ code
+ end
+ def down_generate_identifier type
+ if type == "game"
+ code = DCODES.sample(12).join
+ return down_generate_identifier(type) if Game.where(identifier: code).present?
+ elsif type == "myshixun"
+ code = DCODES.sample(10).join
+ return down_generate_identifier(type) if Myshixun.where(identifier: code).present?
+ end
+ code
+ end
+
+ def edit
end
def update
+ language = @shixun.language
@shixun.attributes = params[:shixun]
@shixun.language = params[:language]
+ @shixun.trainee = params[:trainee]
+ @shixun.webssh = params[:webssh].to_i
+ @shixun.can_copy = params[:can_copy].to_i
+ # if params[:course_id]
+ # @shixun.shixun_major_courses.destroy_all
+ # params[:course_id].each do |course_id|
+ # @shixun.shixun_major_courses << ShixunMajorCourse.new(:major_id => params[:major_id], :course_list_id => course_id)
+ # end
+ # end
+ # @shixun.major_id = params[:major_id]
+ @shixun.shixun_major_courses.destroy_all
+ course_lists = params[:course_list].strip.split(",")
+ course_lists.each do |course|
+ if CourseList.where(:name => course).count > 0
+ @shixun.shixun_major_courses << ShixunMajorCourse.new(:major_id => -1, :course_list_id => CourseList.where(:name => course.strip).first.id)
+ else
+ course_list = CourseList.create(:name => course.strip, :user_id => User.current.id, :is_admin => 0)
+ @shixun.shixun_major_courses << ShixunMajorCourse.new(:major_id => -1, :course_list_id => course_list.id)
+ end
+ end
params[:shixun][:is_public] == "on" ? @shixun.is_public = 1 : @shixun.is_public = 0
- @shixun.save
+ ActiveRecord::Base.transaction do
+ begin
+ @shixun.save!
+ if language != params[:language] && @shixun.status != 2 # 已发布不触发重置
+ add_shixun_modify_status(@shixun, 1)
+ end
+ rescue
+ @error = "实训保存失败"
+ raise ActiveRecord::Rollback
+ end
+ respond_to do |format|
+ format.js
+ end
+ end
+ end
+
+ def shixun_discuss
+ @discusses = @shixun.discusses.reorder("created_at desc")
+ @discusses_count = @discusses.count
+ #@limit = 15
+ #@is_remote = true
+ #@discusses_pages = Paginator.new @discusses_count, @limit, params['page'] || 1
+ # @offset ||= @discusses_pages.offset
+ #@discusses = paginateHelper @discusses, @limit
+ #@game_challenge = params[:challenge_id].blank? ? Challenge.find(@discusses.challenge_id) : Challenge.find(params[:challenge_id])
+ challenge_id = params[:challenge_id].nil? ? @shixun.challenges.first.try(:id) : params[:challenge_id].to_i
+ @game_challenge = Challenge.find(challenge_id)
respond_to do |format|
- format.html{redirect_to settings_shixun_url(@shixun)}
+ format.js
+ format.html
end
end
def destroy
-
+ unless User.current.admin?
+ render_403
+ return
+ end
+ Subject.where(:id => @shixun.stage_shixuns.map(&:subject_id)).destroy_all
+ g = Gitlab.client
+ g.delete_project(@shixun.gpid) if @shixun.try(:gpid).present?
+ @shixun.destroy
+ respond_to do |format|
+ format.html{ redirect_to shixuns_managements_path }
+ format.js
+ end
end
def settings
@repository = Repository.where(:shixun_id => @shixun, :type => "Repository::Gitlab").first
unless @repository.nil?
gitlab_address = Redmine::Configuration['gitlab_address']
- creator = @shixun.owner.try(:login)
- @repos_url = gitlab_address+"/" + creator + "/" + @repository.identifier+"."+"git"
+ login = User.find_by_mail("educoder@163.com").try(:login)
+ @repos_url = git_shixun_url(@shixun, login)
end
end
@@ -154,7 +879,8 @@ class ShixunsController < ApplicationController
# Find shixun of id params[:id]
def find_shixun
- @shixun = Shixun.find(params[:id])
+ @shixun = Shixun.find_by_identifier(params[:id])
+ render_404 if @shixun.nil?
rescue ActiveRecord::RecordNotFound
render_404
end
@@ -173,28 +899,90 @@ class ShixunsController < ApplicationController
end
end
+ # 实训行为操作
+ def operation
+ @is_subject = params[:is_subject]
+ @myshixun = Myshixun.where(:id => params[:myshixun_id]).first
+ @is_modify = ShixunModify.where(:myshixun_id => params[:myshixun_id], :shixun_id => @shixun.try(:id), :status => 1).first
+ @mail = User.current.mail.blank?
+ end
+
+ # 实训的发送至课堂:搜索课堂
+ def search_user_courses
+ @user = User.current
+ if !params[:search].nil?
+ search = "%#{params[:search].to_s.strip.downcase}%"
+ @courses = @user.courses.not_deleted_not_end.where("#{Course.table_name}.name like :p",:p=>search).select{|course| @user.has_teacher_role(course)}
+ else
+ @courses = @user.courses.not_deleted_not_end.select{|course| @user.has_teacher_role(course)}
+ end
+ @pages = Paginator.new @courses.count, 8, params['page'] || 1
+ @offset ||= @pages.offset
+ @courses = paginateHelper @courses, 8
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ # 将实训发送到课程
+ def send_to_course
+ homework = HomeworkCommon.new
+ homework.name = @shixun.name
+ homework.description = @shixun.description
+ homework.anonymous_comment = 1
+ homework.homework_type = 4
+ homework.late_penalty = 0
+ homework.teacher_priority = 1
+ homework.user_id = User.current.id
+ homework.course_id = params[:course]
+
+ homework_detail_manual = HomeworkDetailManual.new
+ homework_detail_manual.te_proportion = 1.0
+ homework_detail_manual.ta_proportion = 0
+ homework_detail_manual.comment_status = 0
+
+ homework_detail_manual.evaluation_num = 0
+ homework_detail_manual.absence_penalty = 0
+ homework.homework_detail_manual = homework_detail_manual
+ if homework.save!
+ homework_detail_manual.save if homework_detail_manual
+ HomeworkCommonsShixuns.create(:homework_common_id => homework.id, :shixun_id => @shixun.id)
+ redirect_to setting_homework_common_path(homework, :is_new => 1)
+ end
+ end
private
# REDO: 新增类型copy的时候
# 复制项目
# gshixun --> gitlab project
+ # CODES = %W(2 3 4 5 6 7 8 9 a b c f e f g h i j k l m n o p q r s t u v w x y z)
def copy_myshixun shixun, gshixun
myshixun = Myshixun.new
- myshixun.attributes = shixun.attributes.dup.except("id","user_id","visits","gpid","status")
+ # myshixun.attributes = shixun.attributes.dup.except("id","user_id","visits","gpid","status", "identifier","propaedeutics")
myshixun.shixun_id = shixun.id
myshixun.user_id = User.current.id
myshixun.gpid = gshixun.id
- jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
if myshixun.save!
- MyshixunMember.create!(:myshixun_id => myshixun.id, :user_id => User.current.id, :role => 1)
- uri = URI("#{jenkins_shixuns}/jenkins-exec/api/createJob")
- pipeLine = "#{Base64.encode64(shixun.script)}"
- params = {jobName: "myshixun_#{myshixun.id}", pipeLine: pipeLine}
- res = uri_exec uri, params
+ # 为了避免fork多次的问题
+ if gshixun.try(:name).include?("-")
+ logger.info("***** gshixun name is #{gshixun.try(:name)}")
+ @g.delete_project(gshixun.id)
+ gshixun = @g.project(myshixun.gpid)
+ myshixun.update_column(:gpid, gshixun.id)
+ end
+ code = down_generate_identifier("myshixun")
+ myshixun.update_attribute(:identifier, code)
rep = Repository.new(:myshixun_id => myshixun.id, :identifier => gshixun.name,:project_id => -1, :shixun_id => -2)
rep.type = "Repository::Gitlab"
rep.save!
- if (res && res['code'] != 0)
- raise("Job 创建失败")
+ login = User.find_by_mail("educoder@163.com").try(:login)
+ rep_url = Base64.urlsafe_encode64(git_shixun_url_ip shixun, login)
+ uri = "#{shixun_tomcat}/bridge/game/openGameInstance"
+ params = {tpiID: "#{myshixun.id}", tpmID: "#{shixun.id}", instanceGitURL:rep_url, operationEnvironment:"#{shixun.try(:language)}"}
+ logger.info("openGameInstance params is #{params}")
+ res = uri_exec uri, params
+ if (res && res['code'].to_i != 0)
+ raise("实训云平台繁忙(繁忙等级:83)")
end
return myshixun
end
@@ -210,16 +998,15 @@ class ShixunsController < ApplicationController
# 权限控制
def shixun_view_allow
- if @shixun.is_public?
- true
- else
- User.current.member_of?(@shixun) ? true : false
- end
+ render_403 if (@shixun.status == 0 && !(User.current.manager_of_shixun?(@shixun) || User.current.admin?))
end
# 实训管理员或者超级管理员
def require_manager
- render_403 unless User.current.manager_of_shixun?(@shixun)
+ render_403 unless (User.current.manager_of_shixun?(@shixun) || User.current.admin?)
end
+ def validation_email
+ render_403 if User.current.mail.blank?
+ end
end
diff --git a/app/controllers/stages_controller.rb b/app/controllers/stages_controller.rb
new file mode 100644
index 000000000..e5812e398
--- /dev/null
+++ b/app/controllers/stages_controller.rb
@@ -0,0 +1,85 @@
+class StagesController < ApplicationController
+ before_filter :check_authentication
+ before_filter :find_subject, :only => [ :create]
+ before_filter :find_stage, :only => [:edit, :update, :destroy]
+ include ApplicationHelper
+
+ def create
+ 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 && params[:shixun_id]
+ begin
+ params[:shixun_id].each do |shixun_id|
+ shixun = Shixun.find shixun_id
+ stage.stage_shixuns << StageShixun.new(:subject_id => @subject.id, :shixun_id => shixun_id, :position => stage.stage_shixuns.count + 1) if shixun
+ end
+ rescue Exception => e
+
+ end
+ end
+ end
+ redirect_to subject_path(@subject)
+ end
+ end
+
+ def edit
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def update
+ if params[:stage_name]
+ @stage.name = params[:stage_name]
+ @stage.description = params[:stage_des]
+ ActiveRecord::Base.transaction do
+ if @stage.save
+ begin
+ @stage.stage_shixuns.destroy_all
+ params[:shixun_id].each do |shixun_id|
+ shixun = Shixun.find shixun_id
+ @stage.stage_shixuns << StageShixun.new(:subject_id => @subject.id, :shixun_id => shixun_id, :position => @stage.stage_shixuns.count + 1) if shixun
+ end
+ rescue Exception => e
+
+ end
+ end
+ end
+ redirect_to subject_path(@subject)
+ end
+ end
+
+ def destroy
+ if User.current.manager_of_subject?(@subject)
+ @subject.stages.where("position > #{@stage.position}").update_all("position = position - 1")
+ @stage.destroy
+ @status = 1
+ else
+ @status = 0
+ end
+ end
+
+ private
+ def find_subject
+ @subject = Subject.find_by_id(params[:subject])
+ if @subject.nil?
+ render_404
+ return
+ end
+ rescue ActiveRecord::RecordNotFound
+ render_404
+ end
+
+ def find_stage
+ @stage = Stage.find(params[:id])
+ @subject = @stage.subject
+ rescue ActiveRecord::RecordNotFound
+ render_404
+ end
+end
diff --git a/app/controllers/student_work_controller.rb b/app/controllers/student_work_controller.rb
index 9ba631913..e89e7f363 100644
--- a/app/controllers/student_work_controller.rb
+++ b/app/controllers/student_work_controller.rb
@@ -7,8 +7,8 @@ class StudentWorkController < ApplicationController
require "base64"
before_filter :find_homework, :only => [:new, :index, :create, :student_work_absence_penalty, :absence_penalty_list, :evaluation_list, :program_test,:program_test_ex,
:set_score_rule,:forbidden_anonymous_comment,:delete_work,:new_student_work_project,:student_work_project,:cancel_relate_project,
- :search_course_students,:work_canrepeat,:add_group_member,:change_project]
- before_filter :find_work, :only => [:edit, :update, :show, :destroy, :add_score, :praise_student_work, :retry_work, :revise_attachment, :hide_score_detail]
+ :search_course_students,:work_canrepeat,:add_group_member,:change_project,:relate_myshixun]
+ before_filter :find_work, :only => [:edit, :update, :show, :destroy, :add_score, :praise_student_work, :retry_work, :revise_attachment, :hide_score_detail, :destroy_score]
before_filter :member_of_course, :only => [:new, :create, :show, :add_score, :praise_student_work]
before_filter :author_of_work, :only => [:edit, :update, :destroy]
before_filter :teacher_of_course, :only => [:student_work_absence_penalty, :absence_penalty_list, :evaluation_list, :set_score_rule, :forbidden_anonymous_comment]
@@ -157,14 +157,9 @@ class StudentWorkController < ApplicationController
unless student_work.save
resultObj[:status] = 200
else
- student_work.name = params[:title]
+ student_work.name = @homework.name.to_s + "的作品提交"
student_work.description = params[:src]
- if !is_test && @homework.end_time < Time.now.to_s
- student_work.late_penalty = @homework.late_penalty
- else
- student_work.late_penalty = 0
- end
#每次从数据库取出上次的结果加上本次的结果再存入数据库
if result["status"].to_i != -2
@@ -341,6 +336,7 @@ class StudentWorkController < ApplicationController
def index
# 作业消息状态更新?
+ @tab = params[:tab].nil? ? 1 : params[:tab].to_i
homeworkcommon_messages = CourseMessage.where(:user_id => User.current.id, :viewed => 0, :course_message_id => @homework.id, :course_message_type => "HomeWorkCommon")
homeworkcommon_messages.update_all(:viewed => true)
studentwork_messages = CourseMessage.where(:user_id => User.current.id, :viewed => 0, :course_id => @homework.course, :course_message_type => "StudentWork")
@@ -364,96 +360,52 @@ class StudentWorkController < ApplicationController
end
end
##################################################################################################################
- @order,@b_sort,@name,@group = params[:order] || "score",params[:sort] || "desc",params[:name].to_s.strip || "",params[:group]
+ if params[:order].nil? && params[:sort].nil? && params[:name].nil? && params[:group].nil? && params[:comment].nil? && params[:status].nil?
+ if @homework.homework_type == 4 && @homework.homework_detail_manual.comment_status > 0 && @homework.homework_detail_manual.comment_status != 6 && (@homework.end_time > Time.now || (@homework.end_time <= Time.now && @homework.allow_late))
+ update_shixun_work_status @homework
+ end
+ end
+ @order,@b_sort,@name,@group,@comment,@status = params[:order] || "updated_at",params[:sort] || "desc",params[:name].to_s.strip || "",params[:group], params[:comment], params[:status]
@homework_commons = @course.homework_commons.where("publish_time <= ?",Time.now).order("created_at desc")
@all_homework_commons = @course.homework_commons.order("created_at desc")
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
- @is_evaluation = @homework.homework_detail_manual && @homework.homework_detail_manual.comment_status == 2 && !@is_teacher #是不是匿评
+ @is_evaluation = @homework.homework_detail_manual && (@homework.homework_detail_manual.comment_status == 3 || @homework.homework_detail_manual.comment_status == 4) && !@is_teacher #是不是匿评
@show_all = false
+ @is_new = params[:is_new].to_i if params[:is_new]
# 0表示没有分组的学生,-1表示所有分组的学生
if @group
- if @group == "0"
- none_group_students = @course.members.select{ |member| member.course_group_id == 0 }
- if none_group_students.empty?
- student_in_group = '(0)'
- else
- student_in_group = '(' + none_group_students.map{ |member| member.user_id }.join(',') + ')'
- end
- elsif @group == "-1"
- all_group_students = @course.members.select{ |member| member.course_group_id }
- if all_group_students.empty?
- student_in_group = '(0)'
- else
- student_in_group = '(' + all_group_students.map{ |member| member.user_id }.join(',') + ')'
- end
+ group_students = @course.members.where(:course_group_id => @group).joins("join users on members.user_id = users.id").select{|m| m.roles.to_s.include?("Student")}
+
+ if group_students.empty?
+ student_in_group = '(-1)'
else
- course_group = CourseGroup.find_by_id(@group)
- group_students = course_group.users
- if group_students.empty?
- student_in_group = '(0)'
- else
- student_in_group = '(' + group_students.map{ |user| user.id }.join(',') + ')'
- end
+ student_in_group = '(' + group_students.map{ |member| member.user_id }.join(',') + ')'
end
#开放作品 || 老师 || 超级管理员 || 禁用匿评&&作业截止&&已提交作品 显示所有列表
- if (@homework.is_open == 1 && @course.is_public == 1) || (@homework.is_open == 1 && @course.is_public == 0 && User.current.member_of_course?(@course)) || @is_teacher || User.current.admin? || (User.current.member_of_course?(@course) && @homework.anonymous_comment == 1 && @homework.end_time < Time.now && !@homework.student_works.has_committed.where(:user_id => User.current.id).empty?)
- if @order == 'lastname'
- @stundet_works = search_homework_member @homework.student_works.no_copy.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@b_sort}, login #{@b_sort}"),@name
- elsif @order == 'student_id'
- @stundet_works = search_homework_member @homework.student_works.no_copy.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").joins("join user_extensions on student_works.user_id = user_extensions.user_id").order("#{@order} #{@b_sort}"),@name
- else
- @stundet_works = search_homework_member @homework.student_works.no_copy.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name
- end
+ if (@homework.work_public && User.current.member_of_course?(@course) && @homework.homework_detail_manual.comment_status == 6) || @is_teacher || User.current.admin?
+ @stundet_works = @homework.student_works.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}")
@show_all = true
elsif User.current.member_of_course?(@course)
- if @homework.homework_detail_manual.comment_status == 1 #学生 && 未开启匿评 只看到自己的
+ if @homework.homework_detail_manual.comment_status == 1 || @homework.homework_detail_manual.comment_status == 2 || @homework.homework_detail_manual.comment_status == 5 || @homework.homework_detail_manual.comment_status == 6 #学生 && 未开启匿评 只看到自己的
if @homework.homework_type == 3
- pro = @homework.student_work_projects.where(:user_id => User.current.id).first
- if pro.nil?
- @stundet_works = []
- else
- @stundet_works = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:id => pro.student_work_id)
- end
+ my_work = @homework.student_works.where(:user_id => User.current.id)
+ @stundet_works = !my_work.balnk? ? (my_work.first.group_id != 0 ? @homework.student_works.select("student_works.*,student_works.work_score as score").where(:group_id => my_work.first.group_id) : my_work) : []
else
- @stundet_works = @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
- end
- elsif @homework.homework_detail_manual.comment_status == 2 #学生 && 开启匿评 看到匿评列表
- if @homework.homework_type == 3
- pro = @homework.student_work_projects.where(:user_id => User.current.id).first
- if pro.nil?
- my_work = []
- else
- my_work = @homework.student_works.where(:id => pro.student_work_id)
- end
- else
- my_work = @homework.student_works.has_committed.where(:user_id => User.current.id)
+ @stundet_works = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
end
+ elsif @homework.homework_detail_manual.comment_status == 3 || @homework.homework_detail_manual.comment_status == 4 #学生 && 开启匿评 看到匿评列表
+ my_work = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
@stundet_works = my_work + User.current.student_works_evaluation_distributions.map(&:student_work).select { |work| work.homework_common_id == @homework.id}
- elsif @homework.homework_detail_manual.comment_status == 3 #学生 && 关闭匿评 未提交作品之前列表为空,提交了作品看到所有的
- if @homework.homework_type == 3
- pro = @homework.student_work_projects.where(:user_id => User.current.id).first
- if pro.nil?
- my_work = []
- else
- my_work = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:id => pro.student_work_id)
- end
- else
- my_work = @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
- end
- if my_work.empty?
- @stundet_works = []
- else
- if @order == 'lastname'
- @stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@b_sort}, login #{@b_sort}"),@name
- elsif @order == 'student_id'
- @stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").joins("join user_extensions on student_works.user_id = user_extensions.user_id").order("#{@order} #{@b_sort}"),@name
- else
- @stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name
- end
- @show_all = true
- end
+ # elsif @homework.homework_detail_manual.comment_status == 5 || @homework.homework_detail_manual.comment_status == 6 #学生 && 关闭匿评 未提交作品之前列表为空,提交了作品看到所有的
+ # my_work = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id).first
+ # if !my_work || my_work.status == 0
+ # @stundet_works = []
+ # else
+ # @stundet_works = @homework.student_works.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}")
+ # @show_all = true
+ # end
else
@stundet_works = []
end
@@ -462,64 +414,29 @@ class StudentWorkController < ApplicationController
return
end
- @student_work_count = (search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name).count
else
- if (@homework.is_open == 1 &&@course.is_public == 1) || (@homework.is_open == 1 && @course.is_public == 0 && User.current.member_of_course?(@course)) || @is_teacher || User.current.admin? || (User.current.member_of_course?(@course) && @homework.anonymous_comment == 1 && @homework.end_time < Time.now && !@homework.student_works.has_committed.where(:user_id => User.current.id).empty?)
- if @order == 'lastname'
- @stundet_works = search_homework_member @homework.student_works.no_copy.select("student_works.*,student_works.work_score as score").joins(:user).order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@b_sort}, login #{@b_sort}"),@name
- elsif @order == 'student_id'
- @stundet_works = search_homework_member @homework.student_works.no_copy.select("student_works.*,student_works.work_score as score").joins("join user_extensions on student_works.user_id = user_extensions.user_id").order("#{@order} #{@b_sort}"),@name
- else
- @stundet_works = search_homework_member @homework.student_works.no_copy.select("student_works.*,student_works.work_score as score").includes(:user => {:user_extensions => []}, :project => {}, :student_works_scores => {}).order("#{@order} #{@b_sort}"),@name
- end
+ if (@homework.work_public && User.current.member_of_course?(@course) && @homework.homework_detail_manual.comment_status == 6) || @is_teacher || User.current.admin?
+ @stundet_works = @homework.student_works.select("student_works.*,student_works.work_score as score").includes(:user => {:user_extensions => []}, :project => {}, :student_works_scores => {}).order("#{@order} #{@b_sort}")
@show_all = true
elsif User.current.member_of_course?(@course)
- if @homework.homework_detail_manual.comment_status == 1 #学生 && 未开启匿评 只看到自己的
+ if @homework.homework_detail_manual.comment_status == 1 || @homework.homework_detail_manual.comment_status == 2 || @homework.homework_detail_manual.comment_status == 5 || @homework.homework_detail_manual.comment_status == 6 #学生 && 未开启匿评 只看到自己的
if @homework.homework_type == 3
- pro = @homework.student_work_projects.where(:user_id => User.current.id).first
- if pro.nil?
- @stundet_works = []
- else
- @stundet_works = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:id => pro.student_work_id)
- end
+ my_work = @homework.student_works.where(:user_id => User.current.id)
+ @stundet_works = !my_work.blank? ? (my_work.first.group_id != 0 ? @homework.student_works.select("student_works.*,student_works.work_score as score").where(:group_id => my_work.first.group_id) : my_work) : []
else
- @stundet_works = @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
- end
- elsif @homework.homework_detail_manual.comment_status == 2 #学生 && 开启匿评 看到匿评列表
- if @homework.homework_type == 3
- pro = @homework.student_work_projects.where(:user_id => User.current.id).first
- if pro.nil?
- my_work = []
- else
- my_work = @homework.student_works.where(:id => pro.student_work_id)
- end
- else
- my_work = @homework.student_works.has_committed.where(:user_id => User.current.id)
+ @stundet_works = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
end
+ elsif @homework.homework_detail_manual.comment_status == 3 || @homework.homework_detail_manual.comment_status == 4 #学生 && 开启匿评 看到匿评列表
+ my_work = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
@stundet_works = my_work + User.current.student_works_evaluation_distributions.map(&:student_work).select { |work| work.homework_common_id == @homework.id}
- elsif @homework.homework_detail_manual.comment_status == 3 #学生 && 关闭匿评 未提交作品之前列表为空,提交了作品看到所有的
- if @homework.homework_type == 3
- pro = @homework.student_work_projects.where(:user_id => User.current.id).first
- if pro.nil?
- my_work = []
- else
- my_work = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:id => pro.student_work_id)
- end
- else
- my_work = @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
- end
- if my_work.empty?
- @stundet_works = []
- else
- if @order == 'lastname'
- @stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins(:user).order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@b_sort}, login #{@b_sort}"),@name
- elsif @order == 'student_id'
- @stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins("join user_extensions on student_works.user_id = user_extensions.user_id").order("#{@order} #{@b_sort}"),@name
- else
- @stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").order("#{@order} #{@b_sort}"),@name
- end
- @show_all = true
- end
+ # elsif @homework.homework_detail_manual.comment_status == 5 #学生 && 关闭匿评 未提交作品之前列表为空,提交了作品看到所有的
+ # my_work = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id).first
+ # if !my_work || my_work.work_status == 0
+ # @stundet_works = []
+ # else
+ # @stundet_works = @homework.student_works.select("student_works.*,student_works.work_score as score").order("#{@order} #{@b_sort}")
+ # @show_all = true
+ # end
else
@stundet_works = []
end
@@ -527,21 +444,46 @@ class StudentWorkController < ApplicationController
render_403
return
end
- @student_work_count = (search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").order("#{@order} #{@b_sort}"),@name).count
end
+
+ unless @comment.blank?
+ has_comment_works = User.current.student_works_scores.where(:student_work_id => @homework.student_works.map(&:id), :reviewer_role => [1, 2])
+ student_work_ids = has_comment_works.blank? ? '(-1)' : '(' + has_comment_works.map(&:student_work_id).join(',') + ')'
+ if @comment.include?('0')
+ @stundet_works = @stundet_works.where("student_works.id not in #{student_work_ids}")
+ else
+ @stundet_works = @stundet_works.where("work_status != 0 and student_works.id in #{student_work_ids}")
+ end
+ end
+
+ unless @status.blank?
+ @stundet_works = @stundet_works.where(:work_status => @status)
+ end
+
+ @stundet_works = search_homework_member @stundet_works, @name
+
@score = @b_sort == "desc" ? "asc" : "desc"
@is_focus = params[:is_focus] ? params[:is_focus].to_i : 0
# 消息传过来的ID
@message_student_work_id = params[:student_work_id]
+ @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
@left_nav_type = 3
@tab = params[:tab].to_i
+ @all_student_works = @stundet_works
+ @student_work_count = @stundet_works.count
+ @limit = 50
+ @is_remote = true
+ @page = (params['page'] || 1).to_i
+ @student_work_pages = Paginator.new @student_work_count, @limit, @page
+ @offset ||= @student_work_pages.offset
+ @stundet_works = paginateHelper @stundet_works, @limit
respond_to do |format|
format.js
- format.html
+ format.html { render :layout => 'base_edu'}
format.xls {
- filename = "#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@course.time.to_s + @course.term}_#{@homework.name}#{l(:excel_homework_list)}.xls"
- send_data(homework_to_xls(@stundet_works), :type => "text/excel;charset=utf-8; header=present",
+ filename = "#{@course.teacher.lastname.to_s + @course.teacher.firstname}_#{@course.name}_#{@homework.name}#{l(:excel_homework_list)}.xls"
+ send_data(homework_to_xls(@all_student_works), :type => "text/excel;charset=utf-8; header=present",
:filename => filename_for_content_disposition(filename))
}
end
@@ -552,17 +494,21 @@ class StudentWorkController < ApplicationController
noEvaluation = @homework.course_messages.where("user_id =? and viewed =?", User.current.id, 0)
noEvaluation.update_all(:viewed => true)
- if @homework.homework_type==2
- redirect_to new_user_commit_homework_users_path(homework_id: @homework.id)
+ # if @homework.homework_type==2
+ # redirect_to new_user_commit_homework_users_path(homework_id: @homework.id)
+ # return
+ # end
+ @is_test = params[:is_test] == 'true'
+ @user = User.current
+ @student_work = @homework.student_works.where("user_id = ?",User.current.id).first
+ if @student_work.nil?
+ @student_work = StudentWork.new
+ elsif @student_work.work_status != 0
+ render_403
return
end
- @user = User.current
- #@student_work = @homework.student_works.where("user_id = ?",User.current.id).first
- #if @student_work.nil?
- @student_work = StudentWork.new
- #end
respond_to do |format|
- format.html{ render :layout => "base_courses"}
+ format.html{ render :layout => "base_edu"}
end
end
@@ -574,21 +520,21 @@ class StudentWorkController < ApplicationController
@has_commit = true;
#flash[:notice] = l(:notice_successful_create)
#redirect_to edit_student_work_url(params[:student_work])
- respond_to do |format|
- format.js
- end
- return
- end
- if params[:student_work]
- @submit_result = true
+ # respond_to do |format|
+ # format.js
+ # end
+ # return
+ elsif params[:student_work]
student_work = StudentWork.find(params[:student_work_id]) if params[:student_work_id]
student_work = StudentWork.where("user_id =? and homework_common_id =? and work_status = 0", User.current.id, @homework.id).first
student_work ||= StudentWork.new
- student_work.name = params[:student_work][:name] == "#{@homework.name}的作品提交(可修改)" ? "#{@homework.name}的作品提交" : params[:student_work][:name]
+ student_work.name = @homework.name.to_s + "的作品提交"
student_work.description = params[:student_work][:description]
student_work.homework_common_id = @homework.id
student_work.user_id = User.current.id
student_work.commit_time = Time.now
+ #student_work.late_reason = params[:late_reason] if params[:late_reason]
+ student_work.group_id = @homework.homework_type == 3 ? @homework.student_works.all_commit.select("distinct group_id").count + 1 : 0
student_work.save_attachments(params[:attachments])
render_attachment_warning_if_needed(student_work)
if @homework.homework_type == 3 && @homework.homework_detail_group.base_on_project == 1
@@ -600,7 +546,7 @@ class StudentWorkController < ApplicationController
student_work.late_penalty = @homework.late_penalty
student_work.work_status = 2
# 缺评扣分
- if @homework.homework_detail_manual.no_anon_penalty == 0 && @homework.homework_detail_manual.comment_status == 3 && @homework.anonymous_comment == 0
+ if @homework.homework_detail_manual.no_anon_penalty == 0 && @homework.homework_detail_manual.comment_status == 5 && @homework.anonymous_comment == 0
work_ids = "(" + @homework.student_works.has_committed.map(&:id).join(",") + ")"
all_dis_eva = StudentWorksEvaluationDistribution.where("student_work_id IN #{work_ids}")
has_sw_count = all_dis_eva.select("distinct user_id").count
@@ -609,41 +555,42 @@ class StudentWorkController < ApplicationController
end
#更新CourseHomeworkStatistics中学生的迟交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, User.current.id)
- course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, User.current.id)
+ # course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
else
student_work.late_penalty = 0
student_work.work_status = 1
end
if student_work.save
#更新CourseHomeworkStatistics中学生的未交作品数、已交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, User.current.id)
- course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, User.current.id)
+ # course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
if @homework.homework_type == 3
if @homework.homework_detail_group.base_on_project == 1
@student_work_project.student_work_id = student_work.id
@student_work_project.save
elsif @homework.homework_detail_group.base_on_project == 0
- stu_project = StudentWorkProject.new(:homework_common_id => @homework.id, :student_work_id => student_work.id, :project_id => student_work.project_id, :user_id => student_work.user_id, :is_leader => 1, :course_id => @homework.course_id)
+ stu_project = StudentWorkProject.new(:homework_common_id => @homework.id, :student_work_id => student_work.id, :project_id => 0, :user_id => student_work.user_id, :is_leader => 1, :course_id => @homework.course_id)
stu_project.save
end
- members = params[:group_member_ids].split(',')
+ members = params[:user_id]
for i in 1 .. members.count-1
- stu_work = StudentWork.new(:name => student_work.name, :description => student_work.description,:user_id =>members[i].to_i, :homework_common_id => @homework.id,:project_id => student_work.project_id, :late_penalty => student_work.late_penalty,:work_status => 3, :commit_time => student_work.commit_time)
+ stu_work = @homework.student_works.where(:user_id=> members[i].to_i).empty? ? StudentWork.new : @homework.student_works.where(:user_id=> members[i].to_i).first
+ stu_work.update_attributes(:name => student_work.name, :description => student_work.description, :homework_common_id => @homework.id,:project_id => student_work.project_id, :late_penalty => student_work.late_penalty,:work_status => student_work.work_status, :commit_time => Time.now, :group_id => student_work.group_id)
if stu_work.save
- stu_project = StudentWorkProject.new(:homework_common_id => @homework.id, :student_work_id => student_work.id, :project_id => stu_work.project_id == 0 ? -1 : stu_work.project_id, :user_id => members[i].to_i, :is_leader => 0, :course_id => @homework.course_id)
+ stu_project = StudentWorkProject.new(:homework_common_id => @homework.id, :student_work_id => student_work.id, :project_id => stu_work.project_id == 0 ? 0 : stu_work.project_id, :user_id => members[i].to_i, :is_leader => 0, :course_id => @homework.course_id)
stu_project.save
end
#更新CourseHomeworkStatistics中学生的未交作品数、已交作品数、迟交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, members[i].to_i)
- course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
- if student_work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
- end
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, members[i].to_i)
+ # course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
+ # if student_work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
+ # end
end
end
@homework.update_column(:updated_at, Time.now)
@@ -655,33 +602,27 @@ class StudentWorkController < ApplicationController
course_message.save
@student_work = StudentWork.where(homework_common_id: @homework.id, user_id: User.current.id).first
- respond_to do |format|
- format.js
- end
- return
end
end
- @submit_result = false
- respond_to do |format|
- format.js
- end
+ redirect_to student_work_index_path(:homework => @homework.id)
end
def edit
@user = User.current
- if (!User.current.admin? && @homework.homework_type == 2) || @homework.end_time < Time.now #编程作业不能修改作业|| 截止日期已到不能修改作业
+ if @homework.end_time < Time.now #截止日期已到不能修改作业
render_403
else
+ if @homework.homework_type == 3
+ @commit_users = User.where(:id => @homework.student_works.where("group_id = #{@work.group_id} and user_id != #{@work.user_id}").map(&:user_id))
+ end
respond_to do |format|
- format.html{ render :layout => "base_courses"}
+ format.html{ render :layout => "base_edu"}
end
end
end
def update
if params[:student_work]
- @submit_result = true
- @work.name = params[:student_work][:name]
@work.description = params[:student_work][:description]
@work.save_attachments(params[:attachments])
render_attachment_warning_if_needed(@work)
@@ -690,59 +631,52 @@ class StudentWorkController < ApplicationController
send_message_to_teacher(@work)
if @homework.homework_type == 3
@student_work_project = @homework.student_work_projects.where("user_id=?",User.current.id).first
- student_work_projects = @homework.student_work_projects.where("student_work_id=? and is_leader =?",@work.id,0)
- user_ids = student_work_projects.empty? ? "(-1)" : "(" + student_work_projects.map{|stu|stu.user_id}.join(",") + ")"
- student_works = @homework.student_works.where("user_id in #{user_ids}")
- student_works.each do |sw|
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, sw.user_id)
- if @work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
- end
- course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
- end
- student_works.delete_all
+ student_work_projects = @homework.student_work_projects.where("student_work_id=? and user_id !=?",@student_work_project.student_work_id,User.current.id)
+ #user_ids = student_work_projects.empty? ? "(-1)" : "(" + student_work_projects.map{|stu|stu.user_id}.join(",") + ")"
+ student_works = @homework.student_works.where("group_id = #{@work.group_id} and user_id != #{@work.user_id}")
+ # student_works.each do |sw|
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, sw.user_id)
+ # if @work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
+ # end
+ # course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
+ # end
+ student_works.update_all(:work_status => 0, :description => nil, :project_id => 0, :late_penalty => 0,:work_status => 0, :commit_time => nil, :group_id => 0)
student_work_projects.delete_all
- members = params[:group_member_ids].split(',')
+ @student_work_project.update_attributes(:is_leader => 1)
+ members = params[:user_id]
for i in 1 .. members.count-1
- stu_work = StudentWork.new(:name => @work.name, :description => @work.description,:user_id=> members[i].to_i, :homework_common_id => @homework.id, :project_id => @work.project_id, :late_penalty => @work.late_penalty,:work_status => 3, :commit_time => @work.commit_time)
+ stu_work = @homework.student_works.where(:user_id=> members[i].to_i).empty? ? StudentWork.new : @homework.student_works.where(:user_id=> members[i].to_i).first
+ stu_work.update_attributes(:name => @work.name, :description => @work.description, :homework_common_id => @homework.id,:project_id => @work.project_id, :late_penalty => @work.late_penalty,:work_status => @work.work_status, :commit_time => Time.now, :group_id => @work.group_id)
if stu_work.save
stu_project = StudentWorkProject.new(:homework_common_id => @homework.id, :student_work_id => @work.id, :project_id => stu_work.project_id == 0 ? -1 : stu_work.project_id, :user_id => members[i].to_i, :is_leader => 0, :course_id => @homework.course_id)
stu_project.save
end
#更新CourseHomeworkStatistics中学生的未交作品数、已交作品数、迟交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, members[i].to_i)
- course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
- if @work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
- end
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, members[i].to_i)
+ # course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
+ # if @work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
+ # end
end
end
course_message = CourseMessage.new(:user_id =>User.current.id,:content=>"edit",:course_message_id=>@work.id,:course_id => @course.id,:course_message_type=>"StudentWork", :status => 9) #作品提交记录
course_message.save
@student_work = @work
- respond_to do |format|
- format.js
- end
- return
end
end
-=begin
respond_to do |format|
- format.html{redirect_to edit_student_work_url(@work)}
- end
-=end
- @submit_result = false
- respond_to do |format|
- format.js
+ format.html{redirect_to student_work_index_path(:homework => @homework.id)}
end
end
def show
#匿评申诉消息状态更新
+ @index = params[:index]
if @work && !@work.student_works_scores.where("reviewer_role = 3 and appeal_status != 0").blank?
score_ids = "(" + @work.student_works_scores.where("reviewer_role = 3 and appeal_status != 0").map{|score| score.id}.join(",") + ")"
score_appeal_ids = StudentWorksScoresAppeal.where("student_works_score_id in #{score_ids}").blank? ? "(-1)" : "(" + StudentWorksScoresAppeal.where("student_works_score_id in #{score_ids}").map{|score_appeal| score_appeal.id}.join(",") + ")"
@@ -752,15 +686,24 @@ class StudentWorkController < ApplicationController
appeal_message.update_all(:viewed => true)
end
+ @is_focus = params[:is_focus] if params[:is_focus]
@score = student_work_score @work,User.current
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
- if @homework.homework_detail_manual.comment_status == 2 && !@is_teacher && @work.user != User.current
- @student_work_scores = @work.student_works_scores.where("user_id = #{User.current.id} and reviewer_role = 3").order("updated_at desc")
+ if (@homework.homework_detail_manual.comment_status == 3 || @homework.homework_detail_manual.comment_status == 4) && !@is_teacher && @work.user != User.current
+ @student_work_scores = StudentWorksScore.where(:id => @work.student_works_scores.where("user_id = #{User.current.id} and reviewer_role = 3").select("max(id)"))
else
@student_work_scores = student_work_score_record(@work)
end
+ if @homework.homework_type == 3 && @work.work_status != 0
+ student_works = @homework.student_works.where("group_id = #{@work.group_id} and user_id != #{@work.user_id}")
+ @team_work = User.where(:id => student_works.map(&:user_id))
+ elsif @homework.homework_type == 4
+ @shixun = @homework.homework_commons_shixuns.shixun
+ @myshixun = Myshixun.find @work.myshixun_id
+ end
respond_to do |format|
format.js
+ format.html{render :layout => 'base_edu'}
end
end
@@ -770,16 +713,17 @@ class StudentWorkController < ApplicationController
user_ids = pros.empty? ? "(-1)" : "(" + pros.map{|stu|stu.user_id}.join(",") + ")"
student_works = @homework.student_works.where("user_id in #{user_ids}")
+
#更新CourseHomeworkStatistics中每个学生的未交作品数、已交作品数、迟交作品数
- student_works.each do |sw|
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, sw.user_id)
- if @work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
- end
- course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
- end
- student_works.delete_all
+ # student_works.each do |sw|
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, sw.user_id)
+ # if @work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
+ # end
+ # course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
+ # end
+ student_works.update_all(:work_status => 0, :description => nil, :project_id => 0, :late_penalty => 0,:work_status => 0, :commit_time => nil)
pros.delete_all
project = @work.student_work_projects.where("is_leader = 1").first
@@ -788,15 +732,17 @@ class StudentWorkController < ApplicationController
else
project.destroy
end
- @work.destroy
+
+ @homework.student_works.all_commit.where("group_id > #{@work.group_id}").update_all("group_id = group_id - 1")
+ @work.update_all(:work_status => 0, :description => nil, :project_id => 0, :late_penalty => 0,:work_status => 0, :commit_time => nil)
else
#更新CourseHomeworkStatistics中学生的已交作品数、迟交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, @work.user_id)
- if @work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
- end
- course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, @work.user_id)
+ # if @work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
+ # end
+ # course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
@work.attachments.destroy_all
@work.student_works_scores.destroy_all
@@ -821,14 +767,14 @@ class StudentWorkController < ApplicationController
student_works = @homework.student_works.where("user_id in #{user_ids}")
#更新CourseHomeworkStatistics中每个学生的已交作品数、迟交作品数
- student_works.each do |sw|
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, sw.user_id)
- if @work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
- end
- course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
- end
+ # student_works.each do |sw|
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, sw.user_id)
+ # if @work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
+ # end
+ # course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
+ # end
student_works.delete_all
pros.delete_all
@@ -841,12 +787,12 @@ class StudentWorkController < ApplicationController
@work.destroy
else
#更新CourseHomeworkStatistics中学生的已交作品数、迟交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, @work.user_id)
- if @work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
- end
- course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, @work.user_id)
+ # if @work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
+ # end
+ # course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
@work.update_attributes(:work_status => 0, :name => "#{@homework.name}的作品提交", :description => nil, :late_penalty => 0, :commit_time => nil, :project_id => 0)
@work.attachments.destroy_all
@@ -863,14 +809,14 @@ class StudentWorkController < ApplicationController
student_works = @homework.student_works.where("user_id in #{user_ids}")
#更新CourseHomeworkStatistics中每个学生的已交作品数、迟交作品数
- student_works.each do |sw|
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, sw.user_id)
- if @work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
- end
- course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
- end
+ # student_works.each do |sw|
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, sw.user_id)
+ # if @work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
+ # end
+ # course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
+ # end
student_works.delete_all
pros.delete_all
@@ -883,12 +829,12 @@ class StudentWorkController < ApplicationController
@work.destroy
else
#更新CourseHomeworkStatistics中学生的已交作品数、迟交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, @work.user_id)
- if @work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
- end
- course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, @work.user_id)
+ # if @work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
+ # end
+ # course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
@work.update_attributes(:work_status => 0, :name => "#{@homework.name}的作品提交", :description => nil, :late_penalty => 0, :commit_time => nil, :project_id => 0)
@work.attachments.destroy_all
@@ -900,12 +846,57 @@ class StudentWorkController < ApplicationController
end
end
+ def relate_myshixun
+ myshixun = Myshixun.where(:shixun_id => @homework.homework_commons_shixuns.shixun_id, :user_id => User.current.id).first
+ if myshixun
+ work = @homework.student_works.where(:user_id => User.current.id).first
+ work = work || StudentWork.new(:homework_common_id => @homework.id, :user_id => User.current.id, :work_status => 0)
+ if work.work_status == 0
+ work.myshixun_id = myshixun.id
+ work.commit_time = Time.now
+ if @homework.end_time < Time.now
+ work.late_penalty = @homework.late_penalty
+ work.work_status = 2
+
+ #更新CourseHomeworkStatistics中学生的迟交作品数
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, User.current.id)
+ # course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
+ else
+ work.late_penalty = 0
+ work.work_status = 1
+ end
+ if work.save
+ #更新CourseHomeworkStatistics中学生的未交作品数、已交作品数
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, User.current.id)
+ # course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
+
+ @homework.update_column(:updated_at, Time.now)
+ update_course_activity(@homework.class,@homework.id)
+ update_user_activity(@homework.class,@homework.id)
+ update_org_activity(@homework.class,@homework.id)
+
+ course_message = CourseMessage.new(:user_id =>User.current.id,:content=>"new",:course_message_id=>work.id,:course_id => @course.id,:course_message_type=>"StudentWork", :status => 9) #作品提交记录
+ course_message.save
+ @status = 1
+ end
+ else
+ @status = 2
+ end
+ else
+ @status = 0
+ end
+ end
+
#添加评分,已评分则为修改评分
def add_score
@is_last = params[:is_last] == "true"
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
#老师、教辅可以随时评分,学生只能在匿评作业的匿评阶段进行评分
- render_403 and return unless @is_teacher || @homework.homework_detail_manual.comment_status == 2
+ unless @is_teacher || @homework.homework_detail_manual.comment_status == 3
+ render_403
+ return
+ end
@score = student_work_score @work,User.current
#@score.comment = params[:new_form][:user_message] if params[:new_form] && params[:new_form][:user_message] && params[:new_form][:user_message] != ""
#@score.score = params[:score] if params[:score]
@@ -928,10 +919,15 @@ class StudentWorkController < ApplicationController
@new_score.student_work_id = @work.id
if @is_teacher && !@new_score.score.nil? && @work.work_status == 0
@work.update_attributes(:work_status => 1, :commit_time => Time.now)
+ if @homework.homework_type == 3
+ @work.update_attributes(:group_id => @homework.student_works.all_commit.select("distinct group_id").count + 1)
+ stu_project = StudentWorkProject.new(:homework_common_id => @homework.id, :student_work_id => @work.id, :project_id => 0, :user_id => @work.user_id, :is_leader => 1, :course_id => @homework.course_id)
+ stu_project.save
+ end
#更新CourseHomeworkStatistics中学生的已交作品数、未交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, @work.user_id)
- course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, @work.user_id)
+ # course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
end
if User.current.admin?
@new_score.reviewer_role = 1
@@ -963,7 +959,7 @@ class StudentWorkController < ApplicationController
case @new_score.reviewer_role
when 1 #教师评分:最后一个教师评分为最终评分
@work.teacher_score = @new_score.score
- if @is_group_leader && params[:same_score]
+ if params[:same_score]
add_score_to_member @work, @homework, @new_score
end
when 2 #教辅评分 教辅评分显示平均分
@@ -974,7 +970,7 @@ class StudentWorkController < ApplicationController
else
@work.teaching_asistant_score = @new_score.score
end
- if @is_group_leader && params[:same_score]
+ if params[:same_score]
add_score_to_member @work, @homework, @new_score
end
when 3 #学生评分 学生评分显示平均分
@@ -986,10 +982,10 @@ class StudentWorkController < ApplicationController
end
#更新CourseHomeworkStatistics中该学生的待匿评数, 只计算第一次评分
- if User.current.student_works_scores.where(:student_work_id => @work.id, :reviewer_role => 3).count == 1
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, User.current.id)
- course_statistics.update_attribute('un_evaluation_work_num', (course_statistics.un_evaluation_work_num - 1) < 0 ? 0 : (course_statistics.un_evaluation_work_num - 1)) if course_statistics
- end
+ # if User.current.student_works_scores.where(:student_work_id => @work.id, :reviewer_role => 3).count == 1
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, User.current.id)
+ # course_statistics.update_attribute('un_evaluation_work_num', (course_statistics.un_evaluation_work_num - 1) < 0 ? 0 : (course_statistics.un_evaluation_work_num - 1)) if course_statistics
+ # end
end
@homework.update_column('updated_at', Time.now)
update_course_activity(@homework.class,@homework.id)
@@ -997,8 +993,15 @@ class StudentWorkController < ApplicationController
update_org_activity(@homework.class,@homework.id)
if @work.save
@work = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:id => @work.id).first
- @count = @homework.student_works.has_committed.count
- @student_work_scores = student_work_score_record @work
+ @score = @new_score
+ if @homework.homework_detail_manual.comment_status == 3 && !@is_teacher && @work.user != User.current
+ @st_cover = @work.student_works_scores.where("user_id = #{User.current.id} and reviewer_role = 3").count > 1 ? 1 : 0
+ @student_work_scores = StudentWorksScore.where(:id => @work.student_works_scores.where("user_id = #{User.current.id} and reviewer_role = 3").select("max(id)"))
+ #@student_work_scores = @work.student_works_scores.where("user_id = #{User.current.id} and reviewer_role = 3").order("updated_at desc")
+ else
+ @student_work_scores = student_work_score_record(@work)
+ end
+ @count = @student_work_scores.count
respond_to do |format|
format.js
end
@@ -1022,6 +1025,14 @@ class StudentWorkController < ApplicationController
end
end
+ # 删除教师/教辅的评分记录
+ def destroy_score
+ @score = @work.student_works_scores.where(:id => params[:score_id]).first
+ if @score
+ @score.destroy
+ end
+ end
+
#删除评分的回复
def destroy_score_reply
@jour = JournalsForMessage.find params[:jour_id]
@@ -1275,6 +1286,27 @@ class StudentWorkController < ApplicationController
@is_last = params[:is_last]
end
+ # 删除评论记录,最新的一条不删除
+ def delete_score_comment
+ begin
+ student_work_score = StudentWorksScore.where(:id => params[:score_id]).first
+ @work = student_work_score.student_work
+ @count = @work.student_works_scores.count
+ student_work_id = student_work_score.student_work_id
+ can_delete = User.current.allowed_to?(:as_teacher,@course) || User.current.admin? || User.current.id == student_work_score.user_id
+ unless can_delete
+ render_403
+ return
+ end
+ student_work_score.destroy
+ respond_to do |format|
+ format.html{redirect_to student_work_path(student_work_id)}
+ end
+ rescue Exception => e
+ logger.error("###{e}")
+ end
+ end
+
def deal_appeal_score
@student_work_score = StudentWorksScore.where("id = #{params[:score_id].to_i}").first
@is_last = params[:is_last] == "true" ? true : false
@@ -1291,10 +1323,10 @@ class StudentWorkController < ApplicationController
sw.update_attribute("appeal_penalty", homework.homework_detail_manual.appeal_penalty + sw.appeal_penalty)
#申诉成功,匿评学生的被申诉记录加一
- course_homework_statistics = CourseHomeworkStatistics.where(:user_id => @student_work_score.user_id, :course_id => course.id).first
- if course_homework_statistics
- course_homework_statistics.update_attribute('appeal_num', course_homework_statistics.appeal_num + 1)
- end
+ # course_homework_statistics = CourseHomeworkStatistics.where(:user_id => @student_work_score.user_id, :course_id => course.id).first
+ # if course_homework_statistics
+ # course_homework_statistics.update_attribute('appeal_num', course_homework_statistics.appeal_num + 1)
+ # end
# 申诉成功 重新计算申诉者的匿评分
work = @student_work_score.student_work
@@ -1369,10 +1401,7 @@ class StudentWorkController < ApplicationController
CourseMessage.create(:user_id => student_work.homework_common.user_id, :course_id => student_work.homework_common.course_id, :viewed => false,:course_message_id=>attachment.container_id,:course_message_type=>'StudentWork',:status=>2)
end
@work.update_attributes(:re_commit => 1)
- respond_to do |format|
- format.js
- end
- @homework = @work.homework_common
+ redirect_to student_work_path(@work)
end
def new_student_work_project
@@ -1445,16 +1474,19 @@ class StudentWorkController < ApplicationController
unless params[:name].nil?
name = params[:name]
end
- if @homework.homework_detail_group.base_on_project == 0
- all_student_ids = "(" + @homework.course.student.map{|student| student.student_id}.join(",") + ")"
- else
- pro = Project.find @homework.student_work_projects.where("user_id=?",User.current.id).first.project_id
- all_student_ids = "(" + pro.members.map{|member| member.user_id}.join(",") + ")"
- end
- all_students = User.where("id in #{all_student_ids}")
- student_work_id = @homework.student_work_projects.where("user_id=? and student_work_id is not null",User.current.id).first.nil? ? -1 : @homework.student_work_projects.where("user_id=?",User.current.id).first.student_work_id
- @commit_student_ids = @homework.student_works.where("id != #{student_work_id}").map{|student| student.user_id}
- @users = searchstudent_by_name all_students,name
+
+ student_works = @homework.student_works.where("work_status != 0")
+ com_student_ids = student_works.blank? ? '(-1)' : '(' + student_works.map(&:user_id).join(",") + ')'
+ @users = User.includes(:user_extensions).where(:id => @course.student.where("student_id not in #{com_student_ids} and student_id != #{User.current.id}").map(&:student_id))
+ @users = searchstudent_by_name @users,name
+
+ @limit = 10
+ @page = (params['page'] || 1).to_i
+ @user_count = @users.count
+ @user_pages = Paginator.new @user_count, @limit, params['page'] || 1
+ @offset ||= @user_pages.offset
+ @users = paginateHelper @users,@limit
+
respond_to do |format|
format.js
end
@@ -1505,12 +1537,12 @@ class StudentWorkController < ApplicationController
end
#更新CourseHomeworkStatistics中学生的未交作品数、已交作品数、迟交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, params[:member_id][i].to_i)
- course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
- if student_work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
- end
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, params[:member_id][i].to_i)
+ # course_statistics.update_attribute('committed_work_num', course_statistics.committed_work_num + 1) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', (course_statistics.un_commit_work_num - 1) < 0 ? 0 : (course_statistics.un_commit_work_num - 1)) if course_statistics
+ # if student_work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', course_statistics.late_commit_work_num + 1) if course_statistics
+ # end
end
end
@@ -1522,12 +1554,12 @@ class StudentWorkController < ApplicationController
sp.destroy
if work
#更新CourseHomeworkStatistics中学生的未交作品数、已交作品数、迟交作品数
- course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, work.user_id)
- if student_work.work_status == 2
- course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
- end
- course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
- course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
+ # course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(@homework.course_id, work.user_id)
+ # if student_work.work_status == 2
+ # course_statistics.update_attribute('late_commit_work_num', (course_statistics.late_commit_work_num - 1) < 0 ? 0 : (course_statistics.late_commit_work_num - 1)) if course_statistics
+ # end
+ # course_statistics.update_attribute('committed_work_num', (course_statistics.committed_work_num - 1) < 0 ? 0 : (course_statistics.committed_work_num - 1)) if course_statistics
+ # course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
work.destroy
end
@@ -1590,8 +1622,7 @@ class StudentWorkController < ApplicationController
select_homework = homeworks
else
name = name.downcase
- select_homework = homeworks.select{ |homework|
- homework.user[:login].to_s.downcase.include?(name) || homework.user.user_extensions[:student_id].to_s.downcase.include?(name) || (homework.user[:lastname].to_s.downcase + homework.user[:firstname].to_s.downcase).include?(name)
+ select_homework = homeworks.select{ |homework| homework.user.user_extensions[:student_id].to_s.downcase.include?(name) || (homework.user[:lastname].to_s.downcase + homework.user[:firstname].to_s.downcase).include?(name)
}
end
select_homework
@@ -1670,34 +1701,54 @@ class StudentWorkController < ApplicationController
count_row += 1
end
elsif @homework.homework_type == 3 #分组作业
+ if @homework.anonymous_comment ==0
+ sheet1.row(0).concat([l(:excel_group_member),l(:excel_homework_name),l(:excel_homework_project),l(:excel_homework_des),
+ l(:excel_t_score),l(:excel_ta_score),l(:excel_n_score),l(:excel_a_penalty),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
+ else
+ sheet1.row(0).concat([l(:excel_group_member),l(:excel_homework_name),l(:excel_homework_project),l(:excel_homework_des),
+ l(:excel_t_score),l(:excel_ta_score),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
+ end
+ count_row = 1
+ items.each do |homework|
+ sheet1[count_row,0] = get_group_member_names homework
+ sheet1[count_row,1] = homework.name
+ sheet1[count_row,2] = (homework.project_id == 0 || homework.project_id.nil?) ? l(:excel_no_project) : homework.project.name
+ sheet1[count_row,3] = strip_html homework.description
+ sheet1[count_row,4] = homework.teacher_score.nil? ? l(:label_without_score) : homework.teacher_score.round(2)
+ sheet1[count_row,5] = homework.teaching_asistant_score.nil? ? l(:label_without_score) : homework.teaching_asistant_score.round(2)
if @homework.anonymous_comment ==0
- sheet1.row(0).concat([l(:excel_group_member),l(:excel_homework_name),l(:excel_homework_project),l(:excel_homework_des),
- l(:excel_t_score),l(:excel_ta_score),l(:excel_n_score),l(:excel_a_penalty),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
+ sheet1[count_row,6] = homework.student_score.nil? ? l(:label_without_score) : homework.student_score.round(2)
+ sheet1[count_row,7] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.absence_penalty
+ sheet1[count_row,8] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.late_penalty
+ sheet1[count_row,9] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : homework.score.round(2) : l(:label_without_score)
+ sheet1[count_row,10] = format_time(homework.created_at)
else
- sheet1.row(0).concat([l(:excel_group_member),l(:excel_homework_name),l(:excel_homework_project),l(:excel_homework_des),
- l(:excel_t_score),l(:excel_ta_score),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
- end
- count_row = 1
- items.each do |homework|
- sheet1[count_row,0] = get_group_member_names homework
- sheet1[count_row,1] = homework.name
- sheet1[count_row,2] = (homework.project_id == 0 || homework.project_id.nil?) ? l(:excel_no_project) : homework.project.name
- sheet1[count_row,3] = strip_html homework.description
- sheet1[count_row,4] = homework.teacher_score.nil? ? l(:label_without_score) : homework.teacher_score.round(2)
- sheet1[count_row,5] = homework.teaching_asistant_score.nil? ? l(:label_without_score) : homework.teaching_asistant_score.round(2)
- if @homework.anonymous_comment ==0
- sheet1[count_row,6] = homework.student_score.nil? ? l(:label_without_score) : homework.student_score.round(2)
- sheet1[count_row,7] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.absence_penalty
- sheet1[count_row,8] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.late_penalty
- sheet1[count_row,9] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : homework.score.round(2) : l(:label_without_score)
- sheet1[count_row,10] = format_time(homework.created_at)
- else
- sheet1[count_row,6] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.late_penalty
- sheet1[count_row,7] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : homework.score.round(2) : l(:label_without_score)
- sheet1[count_row,8] = format_time(homework.created_at)
- end
- count_row += 1
+ sheet1[count_row,6] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.late_penalty
+ sheet1[count_row,7] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : homework.score.round(2) : l(:label_without_score)
+ sheet1[count_row,8] = format_time(homework.created_at)
end
+ count_row += 1
+ end
+ elsif @homework.homework_type == 4 #普通作业
+ sheet1.row(0).concat([l(:excel_user_id),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_mail),l(:excel_homework_name),l(:excel_homework_complete_status),
+ l(:excel_t_score),l(:excel_ta_score),l(:excel_l_penalty),l(:excel_f_score),l(:excel_commit_time)])
+ count_row = 1
+ shixun = @homework.homework_commons_shixuns.shixun
+ items.each do |homework|
+ sheet1[count_row,0]=homework.user.id
+ sheet1[count_row,1] = homework.user.show_name
+ sheet1[count_row,2] = homework.user.login
+ sheet1[count_row,3] = homework.user.user_extensions.student_id
+ sheet1[count_row,4] = homework.user.mail
+ sheet1[count_row,5] = homework.name
+ sheet1[count_row,6] = homework.work_status == 0 ? '--' : had_passed_changllenge_num(shixun, homework.user).to_s+"/"+shixun.challenges.count.to_s
+ sheet1[count_row,7] = homework.teacher_score.nil? ? l(:label_without_score) : homework.teacher_score.round(2)
+ sheet1[count_row,8] = homework.teaching_asistant_score.nil? ? l(:label_without_score) : homework.teaching_asistant_score.round(2)
+ sheet1[count_row,9] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.late_penalty
+ sheet1[count_row,10] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : homework.score.round(2) : l(:label_without_score)
+ sheet1[count_row,11] = format_time(homework.created_at)
+ count_row += 1
+ end
end
book.write xls_report
xls_report.string
@@ -1758,7 +1809,7 @@ class StudentWorkController < ApplicationController
student_work = StudentWork.where(homework_common_id: @homework.id, user_id: User.current.id, is_test: is_test).first
if student_work.nil?
@homework.student_works.build(
- name: params[:title],
+ name: @homework.name.to_s + "的作品提交",
description: params[:src],
user_id: User.current.id,
is_test: is_test
@@ -1816,129 +1867,4 @@ class StudentWorkController < ApplicationController
end
JSON.parse(res.body)
end
-
- #成绩计算
- def set_final_score homework,student_work
- if homework && homework.homework_detail_manual
- if homework.homework_type != 2 #非编程作业
- if homework.teacher_priority == 1 #教师优先
- if student_work.teacher_score
- student_work.final_score = student_work.teacher_score
- student_work.work_score = student_work.teacher_score - student_work.absence_penalty - student_work.late_penalty
- else
- if student_work.teaching_asistant_score.nil?
- student_work.final_score = student_work.student_score
- elsif student_work.student_score.nil?
- student_work.final_score = student_work.teaching_asistant_score
- else
- ta_proportion = homework.homework_detail_manual.ta_proportion
- final_ta_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{ta_proportion}")
- final_s_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
- final_score = final_ta_score + final_s_score
- student_work.final_score = format("%.2f",final_score.to_f)
- end
- if student_work.final_score
- score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty - student_work.appeal_penalty
- student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
- else
- student_work.work_score = nil
- end
- end
- else #不考虑教师评分
- if student_work.teaching_asistant_score.nil?
- student_work.final_score = student_work.student_score
- elsif student_work.student_score.nil?
- student_work.final_score = student_work.teaching_asistant_score
- else
- ta_proportion = homework.homework_detail_manual.ta_proportion
- final_ta_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{ta_proportion}")
- final_s_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
- final_score = final_ta_score + final_s_score
- student_work.final_score = format("%.2f",final_score.to_f)
- end
- if student_work.final_score
- score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty - student_work.appeal_penalty
- student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
- else
- student_work.work_score = nil
- end
- end
- elsif homework.homework_type == 2 && homework.homework_detail_programing #编程作业-----设定:系统评分必定不为空
- if homework.teacher_priority == 1 #教师优先
- if student_work.teacher_score
- student_work.final_score = student_work.teacher_score
- student_work.work_score = student_work.teacher_score - student_work.absence_penalty - student_work.late_penalty - student_work.appeal_penalty
- else
- if student_work.teaching_asistant_score.nil? #教辅未评分
- if student_work.student_score.nil?
- student_work.final_score = student_work.system_score
- else
- ta_proportion = homework.homework_detail_programing.ta_proportion + homework.homework_detail_manual.ta_proportion / 2
- final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}")
- final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
- final_score = final_sy_score + final_st_score
- student_work.final_score = format("%.2f",final_score.to_f)
- end
- elsif student_work.student_score.nil? #学生未评分
- if student_work.teaching_asistant_score.nil?
- student_work.final_score = student_work.system_score
- else
- ta_proportion = homework.homework_detail_programing.ta_proportion + (1.0 - homework.homework_detail_manual.ta_proportion - homework.homework_detail_programing.ta_proportion) / 2
- final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}")
- final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
- final_score = final_sy_score + final_ts_score
- student_work.final_score = format("%.2f",final_score.to_f)
- end
- else
- final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}")
- final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}")
- final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") - BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}"))
- final_score = final_sy_score + final_ts_score + final_st_score
- student_work.final_score = format("%.2f",final_score.to_f)
- end
- if student_work.final_score
- score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty - student_work.appeal_penalty
- student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
- else
- student_work.work_score = nil
- end
- end
- else #不考虑教师评分
- if student_work.teaching_asistant_score.nil? #教辅未评分
- if student_work.student_score.nil?
- student_work.final_score = student_work.system_score
- else
- ta_proportion = homework.homework_detail_programing.ta_proportion + homework.homework_detail_manual.ta_proportion / 2
- final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}")
- final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
- final_score = final_sy_score + final_st_score
- student_work.final_score = format("%.2f",final_score.to_f)
- end
- elsif student_work.student_score.nil? #学生未评分
- if student_work.teaching_asistant_score.nil?
- student_work.final_score = student_work.system_score
- else
- ta_proportion = homework.homework_detail_programing.ta_proportion + (1.0 - homework.homework_detail_manual.ta_proportion - homework.homework_detail_programing.ta_proportion) / 2
- final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}")
- final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
- final_score = final_sy_score + final_ts_score
- student_work.final_score = format("%.2f",final_score.to_f)
- end
- else
- final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}")
- final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}")
- final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") - BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}"))
- final_score = final_sy_score + final_ts_score + final_st_score
- student_work.final_score = format("%.2f",final_score.to_f)
- end
- if student_work.final_score
- score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty - student_work.appeal_penalty
- student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
- else
- student_work.work_score = nil
- end
- end
- end
- end
- end
end
diff --git a/app/controllers/subjects_controller.rb b/app/controllers/subjects_controller.rb
new file mode 100644
index 000000000..9d05cc44b
--- /dev/null
+++ b/app/controllers/subjects_controller.rb
@@ -0,0 +1,157 @@
+# encoding: utf-8
+class SubjectsController < ApplicationController
+ layout 'base_subject'
+ before_filter :require_login
+ before_filter :check_authentication
+ before_filter :find_subject, :except => [:index, :new, :create, :create_subject, :new_subject, :append_to_stage]
+
+ include ApplicationHelper
+ include SubjectsHelper
+
+ def index
+ @order = params[:order] || "myshixun_count"
+ bsort = params[:sort] || "desc"
+ @sort = bsort == "desc" ? "asc" : "desc"
+ search = params[:search]
+ #ids = Subject.find_by_sql("select group_concat(id) as allId from subjects where id in (SELECT distinct(subject_id) FROM `stages`)")
+ if @order == "myshixun_count"
+ #@shixuns = @shixuns.select("shixuns.*, (select count(myshixuns.id) from myshixuns where myshixuns.shixun_id = shixuns.id group by shixuns.id) AS myshixunCount").reorder("status = 2 desc, myshixunCount desc")
+ @subjects = Subject.where("hidden = 0").select("subjects.*, (select count(myshixuns.id) from myshixuns, stage_shixuns where myshixuns.shixun_id = stage_shixuns.shixun_id and stage_shixuns.subject_id = subjects.id group by subjects.id) AS myshixunCount").reorder("status = 2 desc, myshixunCount #{bsort}")
+ else
+ @subjects = Subject.where("hidden = 0").reorder("#{@order} #{bsort}")
+ end
+ @subject_created_count = Subject.where(:user_id => User.current.id).count
+ @subjects_all_count = @subjects.count
+ #@subjects = Subject.where("name like ?", "%#{search}%").reorder("#{@order} #{@sort}")
+ @subjects_count = @subjects.count
+ @limit = 16
+ @is_remote = true
+ @subject_pages = Paginator.new @subjects_count, @limit, params['page'] || 1
+ @offset ||= @subject_pages.offset
+ @subjects = paginateHelper @subjects, @limit
+ render :layout => "base_edu"
+ end
+
+ def show
+ @stages = @subject.stages
+ @is_manager = User.current.manager_of_subject?(@subject)
+ end
+
+ def new
+ @subject = Subject.new
+ render :layout => "base_edu"
+ end
+
+ def create
+ if params[:subject]
+ subject = Subject.create(:name => params[:subject][:name], :learning_notes => params[:subject][:learning_notes], :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], :learning_notes => params[:subject][:learning_notes], :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
+ @course_lists = CourseList.where(:id => ShixunMajorCourse.where(:shixun_id => Shixun.where(:user_id => User.current.id).map(&:id)).map(&:course_list_id))
+ else
+ @status = 0
+ end
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def create_subject
+ if params[:course_list_id]
+ course = CourseList.find params[:course_list_id]
+ if course
+ subject = Subject.create(:name => course.name, :user_id => User.current.id, :visits => 0, :status => 0, :course_list_id => course.id)
+ end
+ end
+ redirect_to subject_path(subject)
+ end
+
+ def choose_subject_shixun
+ #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
+ @offset ||= @shixuns_pages.offset
+ @shixuns = paginateHelper @shixuns, @limit
+ end
+
+ def append_to_stage
+ @shixuns = Shixun.where(:id => params[:choose_ids].split(",")).reorder("id desc")
+ end
+
+ def publish
+ apply = ApplyAction.where(:container_type => "ApplySubject", :container_id => @subject.id).order("created_at desc").first
+ if apply && apply.status == 0
+ @status = 0
+ else
+ #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
+
+ def cancel_publish
+ 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)
+ end
+ @subject.update_attributes(:status => 0)
+ redirect_to subject_path(@subject)
+ end
+
+ def cancel_has_publish
+ @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
+ @subject = Subject.find_by_id(params[:id])
+ render_404 if @subject.nil?
+ rescue ActiveRecord::RecordNotFound
+ render_404
+ end
+end
diff --git a/app/controllers/syllabus_member_controller.rb b/app/controllers/syllabus_member_controller.rb
index b6da3290e..14d40cb2f 100644
--- a/app/controllers/syllabus_member_controller.rb
+++ b/app/controllers/syllabus_member_controller.rb
@@ -1,7 +1,9 @@
class SyllabusMemberController < ApplicationController
+ before_filter :find_syllabus, :only => [:syl_member_autocomplete, :create, :change_manager, :change_manager_alert]
+ before_filter :find_syllabus_member, :only => [:destroy, :update_rank]
+
def syl_member_autocomplete
- @syllabus = Syllabus.find(params[:syllabus])
@flag = params[:flag] || false
respond_to do |format|
format.js
@@ -9,11 +11,10 @@ class SyllabusMemberController < ApplicationController
end
def create
- @syllabus = Syllabus.find(params[:syllabus])
- if params[:membership].nil?
+ if params[:member_id].nil?
@fail_hint = l(:label_blank_user_lists_for_org)
else
- member_ids = params[:membership][:user_ids]
+ member_ids = params[:member_id]
last_rank = @syllabus.syllabus_members.order("rank asc").last.rank
user_ids = @syllabus.syllabus_members.map{|sy| sy.user_id}
member_ids.each_with_index do |user_id, i|
@@ -22,37 +23,53 @@ class SyllabusMemberController < ApplicationController
@syllabus.syllabus_members << member
end
end
- @members = @syllabus.syllabus_members.order("rank asc")
+ @members = @syllabus.syllabus_members.includes(:user => {:user_extensions => []}).order("rank asc")
+ @is_syllabus_member = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
end
respond_to do |format|
format.js
end
end
+ def change_manager_alert
+ @members = @syllabus.syllabus_members.where("id != #{@syllabus.user_id}")
+ end
+
+ def change_manager
+ if params[:chooseteacher]
+ man_member = SyllabusMember.where(:syllabus_id => @syllabus.id, :user_id => @syllabus.user_id).first
+ cha_member = @syllabus.syllabus_members.where(:id => params[:chooseteacher].to_i).first
+ if man_member && cha_member
+ man_member.update_attributes(:rank => cha_member.rank)
+ cha_member.update_attributes(:rank => 1)
+ @syllabus.update_attributes(:user_id => cha_member.user_id)
+ end
+ end
+ @members = @syllabus.syllabus_members.includes(:user => {:user_extensions => []}).order("rank asc")
+ @is_syllabus_member = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
+ end
+
def destroy
- member = SyllabusMember.find(params[:id])
- @syllabus = member.syllabus
- after_syl_members = @syllabus.syllabus_members.where("rank > #{member.rank}")
+ after_syl_members = @syllabus.syllabus_members.where("rank > #{@member.rank}")
after_syl_members.update_all("rank = rank - 1")
- member.destroy
- @members = @syllabus.syllabus_members.order("rank asc")
+ @member.destroy
+ @members = @syllabus.syllabus_members.includes(:user => {:user_extensions => []}).order("rank asc")
+ @is_syllabus_member = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
respond_to do |format|
format.js
end
end
def update_rank
- member = SyllabusMember.find(params[:id])
- @syllabus = member.syllabus
members = @syllabus.syllabus_members
- if params[:opr] == 'up' && member.rank > 1
- before_mem = members.where("rank = #{member.rank - 1}").first
- if before_mem && member.update_attribute('rank', member.rank - 1)
+ if params[:opr] == 'up' && @member.rank > 1
+ before_mem = members.where("rank = #{@member.rank - 1}").first
+ if before_mem && @member.update_attribute('rank', @member.rank - 1)
before_mem.update_attribute('rank', before_mem.rank + 1)
end
- elsif params[:opr] == 'down' && member.rank < members.count
- after_mem = members.where("rank = #{member.rank + 1}").first
- if after_mem && member.update_attribute('rank', member.rank + 1)
+ elsif params[:opr] == 'down' && @member.rank < members.count
+ after_mem = members.where("rank = #{@member.rank + 1}").first
+ if after_mem && @member.update_attribute('rank', @member.rank + 1)
after_mem.update_attribute('rank', after_mem.rank - 1)
end
end
@@ -61,4 +78,14 @@ class SyllabusMemberController < ApplicationController
format.js
end
end
+
+ private
+ def find_syllabus
+ @syllabus = Syllabus.find params[:syllabus]
+ end
+
+ def find_syllabus_member
+ @member = SyllabusMember.find(params[:id])
+ @syllabus = @member.syllabus
+ end
end
diff --git a/app/controllers/syllabuses_controller.rb b/app/controllers/syllabuses_controller.rb
index 2be73ff27..188028a12 100644
--- a/app/controllers/syllabuses_controller.rb
+++ b/app/controllers/syllabuses_controller.rb
@@ -1,42 +1,93 @@
-# encoding: utf-8
+#encoding: utf-8
class SyllabusesController < ApplicationController
include ApplicationHelper
helper :attachments
include AttachmentsHelper
include CoursesHelper
+ include SyllabusesHelper
+ include UsersHelper
+ before_filter :is_logged, :only => [:index, :show, :edit, :new, :update, :destroy, :delete_syllabus, :syllabus_resources, :syllabus_homeworks]
+ before_filter :check_authentication
+ before_filter :find_syllabus, :only => [:show, :edit, :update, :destroy, :syllabus_courselist, :edit_syllabus_eng_name, :edit_syllabus_title, :update_base_info, :delete_syllabus,
+ :delete_des, :members, :update_des, :edit_ref, :update_ref, :add_sy_member_alert, :search_not_sy_member, :syllabus_resources, :syllabus_homeworks,
+ :send_homeworks_to_course, :choose_user_course, :send_resources_to_course, :send_r_and_h_to_course]
- before_filter :is_logged, :only => [:index, :show, :edit, :new, :update, :destroy, :delete_syllabus]
- before_filter :find_syllabus, :only => [:show, :edit, :update, :destroy, :syllabus_courselist, :edit_syllabus_eng_name, :edit_syllabus_title, :update_base_info, :delete_syllabus, :delete_des, :members]
def index
+ @status = params[:type].nil? ? 1 : params[:type].to_i # 1表示正在进行,2表示已结束
+ @tab = params[:tab].nil? ? 1 : params[:tab].to_i
+ @my_syllabuses = "我的课堂"
user = User.current
- @syllabuses = user.syllabuses
+ if @status == 1
+ case @tab
+ when 2
+ @courses = user.courses.not_deleted_not_end.order("updated_at desc").select{ |course| user.has_teacher_role(course)}
+ when 3
+ @courses = user.courses.not_deleted_not_end.order("updated_at desc").select{ |course| !user.has_teacher_role(course)}
+ when 1
+ @courses = user.courses.not_deleted_not_end.order("updated_at desc")
+ end
+ else
+ case @tab
+ when 2
+ @courses = user.courses.not_deleted_but_is_end.order("updated_at desc").select{ |course| user.has_teacher_role(course)}
+ when 3
+ @courses = user.courses.not_deleted_but_is_end.order("updated_at desc").select{ |course| !user.has_teacher_role(course)}
+ when 1
+ @courses = user.courses.not_deleted_but_is_end.order("updated_at desc")
+ end
+ end
+
+ @limit = 15
+ @is_remote = true
+ @courses_count = @courses.count
+ @courses_pages = Paginator.new @courses_count, @limit, params['page'] || 1
+ @offset ||= @courses_pages.offset
+ @courses = paginateHelper @courses, @limit
+
+ respond_to do |format|
+ format.html{ render :layout => 'base_edu'}
+ format.js
+ end
end
def show
+ @is_syllabus_teacher = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id) || !@syllabus.courses.not_deleted_not_end.select { |course| User.current.has_teacher_role(course)}.blank?
+ @is_syllabus_member = !@syllabus.courses.not_deleted_not_end.select { |course| User.current.member_of_course?(course)}.blank?
+ @is_syllabus_admin = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
+ @is_authen_teacher = User.current.authentication && User.current.user_extensions.try(:identity) != 1
+ @reference_materials = @syllabus.reference_materials
+ @members = @syllabus.syllabus_members.includes(:user => {:user_extensions => []}).order("rank asc")
+ @courses = @syllabus.courses.where("is_delete = 0 and is_end = 0").select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS ca_update").order("ca_update desc")
+ @end_courses = @syllabus.courses.where("is_delete = 0 and is_end = 1").select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS ca_update").order("ca_update desc")
respond_to do |format|
format.js
- format.html{render :layout => 'base_syllabus'}
+ format.html{render :layout => 'base_edu_syllabus'}
format.api
end
end
def new
@syllabus = Syllabus.new
- render :layout => 'new_base'
+ render :layout => 'base_edu'
end
def create
if User.current.user_extensions.identity
@syllabus = Syllabus.new
- @syllabus.title = params[:title]
+ @syllabus.title = params[:title].to_s.strip
@syllabus.eng_name = params[:eng_name]
@syllabus.user_id = User.current.id
+ @syllabus.major_level = params[:major_level].to_i
+ @syllabus.discipline_category_id = params[:discipline_category_id].to_i
+ @syllabus.first_level_discipline_id = params[:first_level_discipline_id].to_i
+ @syllabus.major_id = params[:major_id].to_i
+ @syllabus.syllabus_type = params[:syllabus_type].to_i
@syllabus.description = Message.where("id = 19412").first.nil? ? '' : Message.where("id = 19412").first.content
if @syllabus && @syllabus.save
member = SyllabusMember.create(:user_id => @syllabus.user_id, :rank => 1)
@syllabus.syllabus_members << member
respond_to do |format|
- flash[:notice] = l(:notice_successful_create)
+ #flash[:notice] = l(:notice_successful_create)
format.html {redirect_to syllabus_path(@syllabus)}
format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'syllabuses', :action => 'show', :id => @syllabus.id) }
end
@@ -50,9 +101,219 @@ class SyllabusesController < ApplicationController
end
end
+ def regex_syllabus_name
+ data = {result:1}
+ if params[:syllabus_id]
+ if User.current.syllabuses.where("id != #{params[:syllabus_id]} and title = '#{params[:name]}'").count > 0
+ data[:result] = 0
+ end
+ else
+ if Syllabus.where(:user_id => User.current.id, :title => params[:name]).count > 0
+ data[:result] = 0
+ end
+ end
+ render :json => data
+ end
+
def edit
respond_to do |format|
- format.html{render :layout => 'base_syllabus'}
+ format.html{render :layout => 'base_edu'}
+ end
+ end
+
+ def update
+ title = @syllabus.title
+ @syllabus.title = params[:title].to_s.strip
+ @syllabus.eng_name = params[:eng_name]
+ @syllabus.major_level = params[:major_level].to_i
+ @syllabus.discipline_category_id = params[:discipline_category_id].to_i
+ @syllabus.first_level_discipline_id = params[:first_level_discipline_id].to_i
+ @syllabus.major_id = params[:major_id].to_i
+ @syllabus.syllabus_type = params[:syllabus_type].to_i
+ if @syllabus.save
+ if title != params[:title].to_s.strip
+ @syllabus.courses.each do |course|
+ course.name.gsub!(/^#{title}/, params[:title].to_s.strip)
+ course.save
+ end
+ end
+ end
+ redirect_to syllabus_path(@syllabus)
+ end
+
+ def edit_ref
+ @reference_materials = @syllabus.reference_materials
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def update_ref
+ @syllabus.reference_materials.destroy_all
+ refer_inputs = params[:syllabus][:book] if params[:syllabus]
+ if Array === refer_inputs
+ refer_inputs.each_with_index do |val, i|
+ @syllabus.reference_materials << ReferenceMaterial.new(
+ book: val,
+ editor: params[:syllabus][:editor][i],
+ press: params[:syllabus][:press][i]
+ )
+ end
+ end
+ sy_update_record = SyllabusUpdateRecord.new(:property => 2, :user_id => User.current.id)
+ @syllabus.syllabus_update_records << sy_update_record
+ @reference_materials = @syllabus.reference_materials
+ @is_syllabus_admin = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def update_des
+ @syllabus.description = params[:syllabus][:description]
+ @syllabus.des_status = 1
+ #@syllabus.save_attachments(params[:attachments])
+ if @syllabus.save
+ sy_update_record = SyllabusUpdateRecord.new(:property => 1, :user_id => User.current.id)
+ @syllabus.syllabus_update_records << sy_update_record
+ if params[:asset_id]
+ ids = params[:asset_id].split(',')
+ update_kindeditor_assets_owner ids,@syllabus.id,OwnerTypeHelper::SYLLABUS
+ end
+ end
+ redirect_to syllabus_path(@syllabus)
+ end
+
+ def add_sy_member_alert
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def search_not_sy_member
+ if params[:q] && params[:q].lstrip.rstrip != ""
+ @users = Principal.active.sorted.not_member_of_syllabus(@syllabus).like(params[:q])
+ else
+ @users = []
+ end
+ end
+
+ def syllabus_resources
+ @is_syllabus_teacher = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id) || !@syllabus.courses.not_deleted_not_end.select { |course| User.current.has_teacher_role(course)}.blank?
+ @is_syllabus_member = !@syllabus.courses.not_deleted_not_end.select { |course| User.current.member_of_course?(course)}.blank?
+ @is_syllabus_admin = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
+ @is_authen_teacher = User.current.authentication && User.current.user_extensions.try(:identity) != 1
+ @order, @r_sort = params[:order] || "created_at", params[:sort] || "asc"
+ @sort = @r_sort == "desc" ? "asc" : "desc"
+ @resources = sy_resources @syllabus
+ if @order == "created_at"
+ @resources = @resources.order("#{@order} #{@sort}")
+ else
+ @resources = @resources.select("resource_banks.*, (quotes+downloads) as heat").order("#{@order} #{@sort}, created_at desc")
+ end
+ @resource_count = @resources.count
+ @public_resource_count = @resources.where(:is_public => 1).count
+ @private_resource_count = @resources.where(:is_public => 0).count
+
+ if !(@is_syllabus_admin || @is_syllabus_member)
+ @resources = @resources.where(:is_public => 1)
+ end
+
+ #分页
+ @page_resource_count = @resources.count
+ @limit = 10
+ @is_remote = true
+ @resource_pages = Paginator.new @page_resource_count, @limit, params['page'] || 1
+ @offset ||= @resource_pages.offset
+ @resources = paginateHelper @resources,@limit
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def syllabus_homeworks
+ @is_syllabus_teacher = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id) || !@syllabus.courses.not_deleted_not_end.select { |course| User.current.has_teacher_role(course)}.blank?
+ @is_syllabus_member = !@syllabus.courses.not_deleted_not_end.select { |course| User.current.member_of_course?(course)}.blank?
+ @is_syllabus_admin = User.current.admin? || @syllabus.syllabus_members.map{|sm| sm.user_id}.include?(User.current.id)
+ @is_authen_teacher = User.current.authentication && User.current.user_extensions.try(:identity) != 1
+ @order, @r_sort = params[:order] || "created_at", params[:sort] || "asc"
+ @sort = @r_sort == "desc" ? "asc" : "desc"
+ @homeworks = @syllabus.homework_banks.order("#{@order} #{@sort}")
+ @homework_count = @homeworks.count
+ @public_homework_count = @homeworks.where(:is_public => 1).count
+ @private_homework_count = @homeworks.where(:is_public => 0).count
+
+ if !(@is_syllabus_admin || @is_syllabus_member)
+ @homeworks = @homeworks.where(:is_public => 1)
+ end
+
+ @page_homework_count = @homeworks.count
+ @limit = 10
+ @is_remote = true
+ @homework_pages = Paginator.new @page_homework_count, @limit, params['page'] || 1
+ @offset ||= @homework_pages.offset
+ @homeworks = paginateHelper @homeworks, @limit
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def choose_user_course
+ if !params[:search].nil?
+ search = "%#{params[:search].to_s.strip.downcase}%"
+ @courses = User.current.courses.where("is_delete = 0 and is_end = 0 and (#{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like :p)",:p=>search).select { |course| User.current.has_teacher_role(course)}
+ else
+ @courses = User.current.courses.where("is_delete = 0 and is_end = 0").select { |course| User.current.has_teacher_role(course)}
+ end
+ @resource_ids = params[:check_resource] if params[:check_resource]
+ @homework_ids = params[:check_homework] if params[:check_homework]
+ @search = params[:search]
+ #这里仅仅是传递需要发送的资源id
+ @type = params[:type]
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def send_resources_to_course
+ course = Course.find params[:course_id]
+ if course
+ params[:resource_id].each do |resource_id|
+ resource = ResourceBank.find resource_id
+ quote_resource_bank resource, course
+ end
+ end
+ end
+
+ def send_homeworks_to_course
+ course = Course.find params[:course_id]
+ if course
+ params[:homework_id].each do |homework_id|
+ homework = HomeworkBank.find homework_id
+ quote_homework_bank homework, course
+ end
+ end
+ end
+
+ def send_r_and_h_to_course
+ course = Course.find params[:course_id]
+ if course
+ resources = sy_resources @syllabus
+ homeworks = @syllabus.homework_banks.order("#{@order} #{@sort}")
+
+ ActiveRecord::Base.transaction do
+ begin
+ resources.each do |resource|
+ quote_resource_bank resource, course
+ end
+
+ homeworks.each do |homework|
+ quote_homework_bank homework, course
+ end
+ rescue Exception => e
+ puts e
+ end
+ end
end
end
@@ -62,21 +323,6 @@ class SyllabusesController < ApplicationController
end
end
- def update
- @syllabus.description = params[:syllabus][:description]
- @syllabus.des_status = 1
- @syllabus.save_attachments(params[:attachments])
- if @syllabus.save
- if params[:asset_id]
- ids = params[:asset_id].split(',')
- update_kindeditor_assets_owner ids,@syllabus.id,OwnerTypeHelper::SYLLABUS
- end
- redirect_to syllabus_path(@syllabus)
- else
- redirect_to syllabus_path(@syllabus)
- end
- end
-
#删除课程大纲的描述
def delete_des
if @syllabus
@@ -92,7 +338,7 @@ class SyllabusesController < ApplicationController
def destroy
if @syllabus && @syllabus.courses.not_deleted.empty?
@syllabus.destroy
- redirect_to user_courselist_user_path(User.current)
+ redirect_to syllabuses_path()
end
end
@@ -183,6 +429,57 @@ class SyllabusesController < ApplicationController
end
end
+ def get_discipline_categories
+ data = {result:0,options:[]}
+ if params[:major_level]
+ if DisciplineCategory.where(:major_level => params[:major_level].to_i).count > 0
+ data[:result] = 1
+ DisciplineCategory.where(:major_level => params[:major_level].to_i).each do |dis|
+ option = []
+ option << dis.name.to_s
+ option << dis.id
+ data[:options] << option
+ end
+ end
+ end
+
+ render :json =>data
+ end
+
+ def get_first_level_disciplines
+ data = {result:0,options:[]}
+ if params[:discipline_category_id]
+ if FirstLevelDiscipline.where(:discipline_category_id => params[:discipline_category_id].to_i).count > 0
+ data[:result] = 1
+ FirstLevelDiscipline.where(:discipline_category_id => params[:discipline_category_id].to_i).each do |dis|
+ option = []
+ option << dis.name.to_s
+ option << dis.id
+ data[:options] << option
+ end
+ end
+ end
+
+ render :json =>data
+ end
+
+ def get_major
+ data = {result:0,options:[]}
+ if params[:first_level_discipline_id]
+ if Major.where(:first_level_discipline_id => params[:first_level_discipline_id].to_i).count > 0
+ data[:result] = 1
+ Major.where(:first_level_discipline_id => params[:first_level_discipline_id].to_i).each do |dis|
+ option = []
+ option << dis.name.to_s
+ option << dis.id
+ data[:options] << option
+ end
+ end
+ end
+
+ render :json =>data
+ end
+
private
def find_syllabus
@syllabus = Syllabus.find params[:id]
diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb
index 79f4d83ee..d684943db 100644
--- a/app/controllers/users_controller.rb
+++ b/app/controllers/users_controller.rb
@@ -35,6 +35,8 @@ class UsersController < ApplicationController
#
before_filter :can_show_course, :only => [:user_courses,:user_homeworks]
+ before_filter :check_authentication
+
before_filter :find_user, :only => [:user_fanslist, :user_watchlist, :show, :edit, :update, :destroy, :edit_membership, :user_courses, :unsolved_issues_list, :unfinished_homework_list, :user_manage_homeworks,
:unfinished_poll_list, :user_homeworks,:student_homeworks, :destroy_membership, :user_activities, :user_projects, :user_newfeedback, :user_comments, :update_message_viewed,
:anonymous_evaluation_list,:unfinished_test_list, :watch_contests, :info, :watch_projects, :show_score, :topic_score_index, :project_score_index, :user_receive_homeworks,
@@ -43,7 +45,7 @@ class UsersController < ApplicationController
:user_courses4show,:user_projects4show,:user_contests4show,:user_course_activities,:user_project_activities,:user_feedback4show,:user_visitorlist,:user_messages,:edit_brief_introduction,
:user_import_homeworks,:user_search_homeworks,:user_import_resource, :user_system_messages,:choose_user_course,:user_courselist,:user_projectlist,:sort_syllabus_list,
:sort_project_list,:my_homeworks,:manage_or_receive_homeworks,:search_m_r_homeworks, :cancel_or_collect,:expand_courses,:homepage, :user_issues, :course_community, :project_community, :contest_community,
- :user_shixuns]
+ :shixuns, :user_show_course_list, :shixuns_or_courses_filter, :user_wathlist_and_fanslist, :growth_record, :user_grade, :user_experience]
before_filter :auth_user_extension, only: :show
before_filter :show_system_message, :only => [:show]
#before_filter :rest_user_score, only: :show
@@ -319,6 +321,16 @@ class UsersController < ApplicationController
when 'Syllabus'
@reply = JournalsForMessage.find params[:reply_id]
@type = 'Syllabus'
+ when 'Memo'
+ @reply = Memo.find params[:reply_id]
+ @user_activity_id = params[:user_activity_id]
+ @activity_id = params[:activity_id]
+ @type = 'Memo'
+ when 'Challenge'
+ @reply = Discuss.find params[:reply_id]
+ @user_activity_id = params[:user_activity_id]
+ @activity_id = params[:activity_id]
+ @type = 'Challenge'
end
respond_to do |format|
format.js
@@ -354,6 +366,7 @@ class UsersController < ApplicationController
case @type
when 'HomeworkCommon'
@root = HomeworkCommon.find reply.jour_id
+ @homework = @root
options = {:notes => params[:reply_message], :reply_id => reply.user_id,:user_id => User.current.id,:m_parent_id => params[:reply_id].to_i,:m_reply_id => params[:reply_id].to_i, :root_id => reply.root_id}
comment = HomeworkCommon.add_homework_jour(User.current, params[:reply_message], reply.jour_id, reply.root_id, options)
@root.update_column('updated_at', Time.now)
@@ -387,6 +400,9 @@ class UsersController < ApplicationController
comment.root_id = reply.root_id
reply.children << comment
@is_project = params[:is_project] if params[:is_project]
+
+ redirect_to message_replies_board_message_path(@root, :board_id => @root.board_id, :user_activity_id => params[:user_activity_id])
+ return
when 'BlogComment'
@root = reply.root
comment = BlogComment.new
@@ -444,6 +460,20 @@ class UsersController < ApplicationController
comment.subject = "#{@root.subject}"
comment.root_id = reply.root_id
reply.children << comment
+ when 'Challenge'
+ @game_challenge = Challenge.where(:id => reply.challenge_id).first
+ @root = reply.root
+ comment = Discuss.new
+ comment.user_id = User.current.id
+ comment.content = params[:reply_message]
+ comment.root_id = reply.root_id
+ comment.challenge_id = reply.challenge_id
+ comment.dis_type = "Shixun"
+ comment.dis_id = @game_challenge.shixun.try(:id)
+ comment.praise_count = 0
+ reply.children << comment
+ @discusses = @game_challenge.shixun.discusses.reorder("created_at desc")
+ @discusses_count = @discusses.count
end
update_course_activity(@root.class.to_s,@root.id)
update_user_activity(@root.class.to_s,@root.id)
@@ -500,9 +530,9 @@ class UsersController < ApplicationController
# 初始化/更新 点击按钮时间, 24小时内显示系统消息
update_onclick_time
# 全部设为已读
- # if params[:viewed] == "all"
+ # if params[:viewed] == "all"
# update_message_viewed(@user)
- # end
+ # end
# @new_message_count = forge_querys.count + forum_querys.count + course_querys.count + user_querys.count
courses = @user.courses.where("is_delete = 1")
course_ids = courses.empty? ? "(-1)" : "(" + courses.map{|course| course.id}.join(",") + ")"
@@ -584,24 +614,24 @@ class UsersController < ApplicationController
# 消息设置为已读
def update_message_viewed
if User.current.id == @user.id
- course_querys = CourseMessage.where("user_id =? and viewed =?", @user.id, 0)
- forge_querys = ForgeMessage.where("user_id =? and viewed =?", @user.id, 0)
- user_querys = UserFeedbackMessage.where("user_id =? and viewed =?", @user.id, 0)
- forum_querys = MemoMessage.where("user_id =? and viewed =?", @user.id, 0)
- org_querys = OrgMessage.where("user_id=? and viewed=0", @user.id)
- at_querys = AtMessage.where("user_id=? and viewed=0", @user.id)
- contest_querys = ContestMessage.where(:user_id => @user.id, :viewed => 0)
- blog_querys = BlogMessage.where(:user_id => @user.id, :viewed => 0)
- applied_querys = AppliedMessage.where("user_id=? and viewed =?", @user.id, 0)
- course_querys.update_all(:viewed => true) unless course_querys.nil?
- forge_querys.update_all(:viewed => true) unless forge_querys.nil?
- user_querys.update_all(:viewed => true) unless user_querys.nil?
- forum_querys.update_all(:viewed => true) unless forum_querys.nil?
- org_querys.update_all(:viewed => true) unless org_querys.nil?
- at_querys.update_all(:viewed => true) unless at_querys.nil?
- contest_querys.update_all(:viewed => true) unless contest_querys.nil?
- blog_querys.update_all(:viewed => true) unless blog_querys.nil?
- applied_querys.update_all(:viewed => true) unless applied_querys.nil?
+ course_querys = CourseMessage.where("user_id =? and viewed =?", @user.id, 0)
+ forge_querys = ForgeMessage.where("user_id =? and viewed =?", @user.id, 0)
+ user_querys = UserFeedbackMessage.where("user_id =? and viewed =?", @user.id, 0)
+ forum_querys = MemoMessage.where("user_id =? and viewed =?", @user.id, 0)
+ org_querys = OrgMessage.where("user_id=? and viewed=0", @user.id)
+ at_querys = AtMessage.where("user_id=? and viewed=0", @user.id)
+ contest_querys = ContestMessage.where(:user_id => @user.id, :viewed => 0)
+ blog_querys = BlogMessage.where(:user_id => @user.id, :viewed => 0)
+ applied_querys = AppliedMessage.where("user_id=? and viewed =?", @user.id, 0)
+ course_querys.update_all(:viewed => true) unless course_querys.nil?
+ forge_querys.update_all(:viewed => true) unless forge_querys.nil?
+ user_querys.update_all(:viewed => true) unless user_querys.nil?
+ forum_querys.update_all(:viewed => true) unless forum_querys.nil?
+ org_querys.update_all(:viewed => true) unless org_querys.nil?
+ at_querys.update_all(:viewed => true) unless at_querys.nil?
+ contest_querys.update_all(:viewed => true) unless contest_querys.nil?
+ blog_querys.update_all(:viewed => true) unless blog_querys.nil?
+ applied_querys.update_all(:viewed => true) unless applied_querys.nil?
end
redirect_to user_path(@user)
end
@@ -652,11 +682,99 @@ class UsersController < ApplicationController
end
end
- # 我发布的实训
- def user_shixuns
- @shixuns = Shixun.where(:user_id => User.current)
+ # params: index 1 课程 / 2 实训
+ # search 搜索关键字
+ def search_shixuns_or_courses
+ @index = params[:index].to_i
+ @search = params[:search]
+ @limit = 16
+ if 1 == @index
+ @course_result = Course.where("is_end = 0 and is_delete = 0 and name like '%#{@search}%'").order("created_at desc")
+ @course_result_count = @course_result.count
+ @course_result_pages = Paginator.new @course_result_count, @limit, params['page'] || 1
+ @offset ||= @course_result_pages.offset
+ @course_result = paginateHelper @course_result, @limit
+ else
+ # @shixuns_result = Shixun.where(:status => [2,3]).where("name like ?", "%#{@search}%").reorder("created_at desc")
+ @shixuns_result = Shixun.where("name like ?", "%#{@search}%").reorder("created_at desc")
+ @shixuns_result_count = @shixuns_result.count
+ @shixun_pages = Paginator.new @shixuns_result_count, @limit, params['page'] || 1
+ @offset ||= @shixun_pages.offset
+ @shixuns_result = paginateHelper @shixuns_result, @limit
+ end
respond_to do |format|
- format.html{render :layout=>'base_users_new'}
+ format.html{render :layout=>'base_edu'}
+ end
+ end
+
+ # 我发布的实训
+ def shixuns
+ @my_shixun = true
+ filter = params[:filter]
+ if filter == "shixun_cooperative"
+ # 合作者的实训id
+ id = Shixun.find_by_sql("select shixun_id from shixun_members where user_id=#{@user.id} and role = 2").map(&:shixun_id)
+ if @user == User.current
+ @shixuns = Shixun.where(:id => id).order("updated_at desc")
+ else
+ @shixuns = Shixun.where(:id => id).visible.order("updated_at desc")
+ end
+ elsif filter == "shixun_create"
+ if @user == User.current
+ @shixuns = Shixun.where(:user_id => @user).order("updated_at desc")
+ else
+ @shixuns = Shixun.where(:user_id => @user).visible.order("updated_at desc")
+ end
+ elsif filter == "shixun_challenge"
+ # 已挑战过
+ id = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
+ if @user == User.current
+ @shixuns = Shixun.where(:id => id).order("updated_at desc")
+ else
+ @shixuns = Shixun.where(:id => id).visible.order("updated_at desc")
+ end
+ elsif
+ # 合作者及创建者
+ ids = Shixun.find_by_sql("select shixun_id from shixun_members where user_id=#{@user.id}")
+ # 已挑战过
+ ids2 = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
+ ids = ids.map{|shixun| shixun.shixun_id} unless ids.blank?
+ ids2 = ids2.map{|shixun| shixun.id} unless ids2.blank?
+ id = ids + ids2
+ id = id.uniq
+ if @user == User.current
+ @shixuns = Shixun.where(:id => id).order("updated_at desc")
+ else
+ @shixuns = Shixun.where(:id => id).visible.order("updated_at desc")
+ end
+ end
+ @shixuns_count = @shixuns.count
+ @limit = 10
+ @shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
+ @offset ||= @shixun_pages.offset
+ @shixuns = paginateHelper @shixuns, @limit
+ respond_to do |format|
+ format.html{render :layout=> 'base_edu'}
+ format.js
+ end
+ end
+
+ def my_join_shixuns
+ # 我参入的
+ ids = Shixun.find_by_sql("select id from shixun_members where role=2 and user_id=#{@user.id}")
+ ids2 = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
+ ids = ids.map{|shixun| shixun.id} unless ids.blank?
+ ids2 = ids2.map{|shixun| shixun.id} unless ids2.blank?
+ id = ids + ids2
+ id = id.uniq
+ @shixuns = Shixun.where(:id => id)
+ @shixuns_count = @shixuns.count
+ @limit = 10
+ @shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
+ @offset ||= @shixun_pages.offset
+ @shixuns = paginateHelper @shixuns, @limit
+ respond_to do |format|
+ format.html{render :layout=> 'base_edu'}
end
end
@@ -699,14 +817,22 @@ class UsersController < ApplicationController
if integer_ids.include?(9)
cs = CoursesService.new
c = Course.find(@msg.course_id)
- cs.send_wechat_join_class_notice apply_user,c,9,0
+ #cs.send_wechat_join_class_notice apply_user,c,9,0
else
cs = CoursesService.new
c = Course.find(@msg.course_id)
- cs.send_wechat_join_class_notice apply_user,c,7,0
+ #cs.send_wechat_join_class_notice apply_user,c,7,0
end
end
+ apply_user = User.find @msg.course_message_id
+ notes = User.current.show_real_name.to_s + " 批准#{apply_user.show_real_name}以#{integer_ids.include?(7) ? '教辅' : '教师'}的身份加入班级:#{c.name} "
+ c.course_teachers.each do |mem|
+ user = mem.user
+ if user != User.current
+ user.journals_for_messages << JournalsForMessage.new(:user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0)
+ end
+ end
when 'N'
CourseMessage.create(:user_id => @msg.course_message_id, :course_id => @msg.course_id, :viewed => false,:course_message_id=>User.current.id,:content=>@msg.content,:course_message_type=>'CourseRequestDealResult',:status=>2)
@msg.update_attributes(:status=>2,:viewed=>1)
@@ -720,11 +846,8 @@ class UsersController < ApplicationController
c = Course.find(@msg.course_id)
cs.send_wechat_join_class_notice apply_user,c,7,1
end
-
- end
- respond_to do |format|
- format.js
end
+ redirect_to members_course_path(@msg.course_id)
end
# 处理资源引用请求
@@ -1007,72 +1130,7 @@ class UsersController < ApplicationController
course_ids = params[:course_ids]
course_ids.each do |course_id|
course = Course.find course_id.to_i
- new_homework = HomeworkCommon.new
- new_homework.name = homework.name
- new_homework.user_id = User.current.id
- new_homework.description = homework.description
- new_homework.homework_type = homework.homework_type
- new_homework.late_penalty = 0
- new_homework.course_id = course.id
- new_homework.teacher_priority = 1
- new_homework.anonymous_comment = 1
- new_homework.quotes = 0
- new_homework.is_open = 0
- new_homework.homework_bank_id = homework.id
- homework.attachments.each do |attachment|
- att = attachment.copy
- att.container_id = nil
- att.container_type = nil
- att.copy_from = attachment.id
- att.save
- new_homework.attachments << att
- end
- #homework_detail_manual = homework.homework_detail_manual
- #homework_detail_programing = homework.homework_detail_programing
- #homework_detail_group = homework.homework_detail_group
- #if homework_detail_manual
- new_homework.homework_detail_manual = HomeworkDetailManual.new
- new_homework_detail_manual = new_homework.homework_detail_manual
- new_homework_detail_manual.ta_proportion = new_homework.homework_type == 2 ? 0.4 : 1.0
- new_homework_detail_manual.comment_status = 0
- new_homework_detail_manual.evaluation_num = 3
- new_homework_detail_manual.absence_penalty = 0
- #end
- #if homework_detail_programing
- if new_homework.homework_type == 2
- new_homework.homework_detail_programing = HomeworkDetailPrograming.new
- new_homework.homework_detail_programing.ta_proportion = 0.6
- new_homework.homework_detail_programing.language = homework.language
- homework.homework_bank_tests.each_with_index do |homework_test|
- if homework_test.test_type
- new_homework.homework_tests << HomeworkTest.new(
- input: homework_test.input,
- output: homework_test.output
- )
- else
- new_homework.homework_samples << HomeworkSample.new(
- input: homework_test.input,
- output: homework_test.output
- )
- end
- end
- end
- #end
-
- #if homework_detail_group
- if new_homework.homework_type == 3
- new_homework.homework_detail_group = HomeworkDetailGroup.new
- new_homework.homework_detail_group.min_num = homework.min_num
- new_homework.homework_detail_group.max_num = homework.max_num
- new_homework.homework_detail_group.base_on_project = homework.base_on_project
- end
- #end
- if new_homework.save
- new_homework_detail_manual.save if new_homework_detail_manual
- new_homework.homework_detail_programing.save if new_homework.homework_detail_programing
- new_homework.homework_detail_group.save if new_homework.homework_detail_group
- end
- homework.update_column(:quotes, homework.quotes+1)
+ quote_homework_bank homework, course
end
@homework = homework
respond_to do |format|
@@ -1083,64 +1141,37 @@ class UsersController < ApplicationController
#导入作业
def user_import_homeworks
@user = User.current
- @select_course = params[:select_course] ? 1 : 0
- #@user_homeworks = HomeworkCommon.where(:user_id => @user.id).order("created_at desc")
- #courses = @user.courses.where("is_delete = 1")
- #course_ids = courses.empty? ? "(-1)" : "(" + courses.map{|course| course.id}.join(",") + ")"
- @homeworks = @user.homework_banks.order("#{@order} #{@b_sort}")
- @type = params[:type]
- @limit = 15
+ @select_course = params[:select_course]
+ @homework_type = params[:homework_type].to_i
+ search = params[:search].to_s.strip.downcase
+ if(params[:type].blank? || params[:type] == "1") #我的题库
+ @homeworks = @user.homework_banks.where(:homework_type => @homework_type)
+ elsif params[:type] == "2" #公共题库
+ @homeworks = HomeworkBank.where(:is_public => true, :homework_type => @homework_type)
+ end
+ @type = params[:type] || "1"
+ @homeworks = @homeworks.where("name like '%#{search}%'").reorder("created_at desc")
+ @limit = 10
@is_remote = true
@hw_count = @homeworks.count
@hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
@offset ||= @hw_pages.offset
- @homeworks = paginateHelper @homeworks,15
+ @homeworks = paginateHelper @homeworks,@limit
respond_to do |format|
format.js
end
end
def user_homework_type
- @order,@b_sort = params[:order] || "created_at",params[:sort] || "desc"
- @r_sort = @b_sort == "desc" ? "asc" : "desc"
@user = User.current
if(params[:type].blank? || params[:type] == "1") #我的题库
- #courses = @user.courses.where("is_delete = 1")
- #course_ids = courses.empty? ? "(-1)" : "(" + courses.map{|course| course.id}.join(",") + ")"
@homeworks = @user.homework_banks
elsif params[:type] == "2" #公共题库
- #visible_course = Course.where("is_public = 1 && is_delete = 0")
- #visible_course_ids = visible_course.empty? ? "(-1)" : "(" + visible_course.map{|course| course.id}.join(",") + ")"
@homeworks = HomeworkBank.where(:is_public => true)
- # elsif params[:type] == "3" #申请题库
- # none_visible_course = Course.where("is_delete = 1")
- # none_visible_course_ids = none_visible_course.empty? ? "(-1)" : "(" + none_visible_course.map{|course| course.id}.join(",") + ")"
- # #apply_homeworks = ApplyHomework.where("user_id = ?",@user.id).order('created_at desc')
- # #homework_ids = apply_homeworks.empty? ? "(-1)" : "(" + apply_homeworks.map{|ah| ah.homework_common_id}.join(",") + ")"
- # #@homeworks = HomeworkCommon.where("id in #{homework_ids} and course_id not in #{none_visible_course_ids}")
- #
- # sql = "SELECT homework_commons.* FROM homework_commons INNER JOIN apply_homeworks as ah ON homework_commons.id = ah.homework_common_id where ah.user_id = #{@user.id} and homework_commons.course_id not in #{none_visible_course_ids} order by ah.created_at desc"
- # @homeworks = HomeworkCommon.find_by_sql(sql)
end
- if params[:property]
- @homeworks = @homeworks.where(:homework_type => params[:property].to_i)
- # all_homework_ids = @homeworks.empty? ? "(-1)" : "(" + @homeworks.map{|h| h.id}.join(",") + ")"
- # if params[:property] == "1"
- # @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 1")
- # #@homeworks = @homeworks.where("homework_type = 1").reorder("#{@order} #{@b_sort}")
- # elsif params[:property] == "2"
- # @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 2")
- # #@homeworks = @homeworks.where("homework_type = 2").reorder("#{@order} #{@b_sort}")
- # elsif params[:property] == "3"
- # @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 3")
- # #@homeworks = @homeworks.where("homework_type = 3").reorder("#{@order} #{@b_sort}")
- # end
- end
- @homeworks = @homeworks.reorder("#{@order} #{@b_sort}")
+ @homeworks = @homeworks.reorder("created_at desc")
@type = params[:type] ? params[:type] : '1'
- @property = params[:property]
- @is_import = params[:is_import]
- @limit = params[:is_import].to_i == 1 ? 15 : 10
+ @limit = 10
@is_remote = true
@hw_count = @homeworks.count
@hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
@@ -1266,58 +1297,12 @@ class UsersController < ApplicationController
#导入作业,确定按钮
def user_select_homework
- homework = HomeworkBank.find_by_id params[:checkMenu]
- #homework_detail_programing = homework.homework_detail_programing
- #homework_detail_group = homework.homework_detail_group
- @homework = HomeworkCommon.new
- @select_course = params[:select_course] || 0
- if homework
- @ref_homework = homework
- @homework.name = homework.name
- @homework.description = homework.description
- #@homework.end_time = homework.end_time
- @homework.homework_type = homework.homework_type
- #@homework.course_id = homework.course_id
- homework.attachments.each do |attachment|
- att = attachment.copy
- att.container_id = nil
- att.container_type = nil
- att.copy_from = attachment.id
- att.save
- @homework.attachments << att
+ params[:checkMenu].each do |homework_bank|
+ homework = HomeworkBank.find_by_id homework_bank
+ @select_course = Course.find params[:select_course]
+ if homework && @select_course
+ quote_homework_bank homework, @select_course
end
-
- #if homework_detail_programing
- if homework.homework_type == 2
- @homework.homework_detail_programing = HomeworkDetailPrograming.new
- @homework_detail_programing = @homework.homework_detail_programing
- #@homework_detail_programing.ta_proportion = homework_detail_programing.ta_proportion
- @homework_detail_programing.language = homework.language
- homework.homework_bank_tests.each_with_index do |homework_test|
- if homework_test.test_type
- @homework.homework_tests << HomeworkTest.new(
- input: homework_test.input,
- output: homework_test.output
- )
- else
- @homework.homework_samples << HomeworkSample.new(
- input: homework_test.input,
- output: homework_test.output
- )
- end
- end
- end
- #end
-
- #if homework_detail_group
- if homework.homework_type == 3
- @homework.homework_detail_group = HomeworkDetailGroup.new
- @homework_detail_group = @homework.homework_detail_group
- @homework_detail_group.min_num = homework.min_num
- @homework_detail_group.max_num = homework.max_num
- @homework_detail_group.base_on_project = homework.base_on_project
- end
- #end
end
respond_to do |format|
format.js
@@ -1682,6 +1667,7 @@ class UsersController < ApplicationController
redirect_to signin_url
return
end
+ update_onclick_time
# 自己访问自己的页面才更新消息状态
UserFeedbackMessage.where("user_id =? and viewed =? and journals_for_message_type =? ", User.current.id, 0, "JournalsForMessage").update_all(:viewed => true)
# end
@@ -1709,7 +1695,7 @@ class UsersController < ApplicationController
# end
# end
@state = false
- render :layout=>'new_base_user'
+ render :layout => 'edu_new_base_user'
end
#给某人留言
@@ -2097,147 +2083,313 @@ class UsersController < ApplicationController
end
def show
- if User.current == @user
- # 点击小铃铛,更新点击时间
- update_onclick_time if params[:click_user_message] == 'true'
- # 全部设为已读
- # 自己的主页显示消息
- messages_all = MessageAll.where(:user_id => @user.id)
- @message_count = messages_all.count
- # REDO:已删除的内容应该在页面中显示不点击
- @message_all_pages = Paginator.new @message_count, per_page_option, params['page']
- @message_alls = messages_all.includes(:message).
- limit(@message_all_pages.per_page).
- offset(@message_all_pages.offset).
- reorder("#{MessageAll.table_name}.created_at desc")
+ @blog_list = @user.blog.articles.reorder("#{BlogComment.table_name}.sticky desc,#{BlogComment.table_name}.created_at desc")
+ @blog_count = @blog_list.count
+ @blog_list = @blog_list.limit(3)
+ watch_query = User.watched_by(@user.id)
+ @user_watchlist_count = watch_query.count()
+ @user_watchlist = watch_query.order("#{Watcher.table_name}.id desc").limit(12)
+ fan_query = @user.watcher_users
+ @user_fanlist_count = fan_query.count()
+ @user_fanlist = fan_query.order("#{Watcher.table_name}.id desc").limit(12)
- @unsolved_issues_count = Issue.where(:assigned_to_id => @user.id, :status_id => [1, 2, 4, 6]).includes(:author, :project).count
+ show_all = @user == User.current || User.current.admin?
- my_course_ids = StudentsForCourse.includes(:course).where("student_id = #{@user.id} and courses.is_delete = 0").blank? ? "(-1)" : "(" + StudentsForCourse.includes(:course).
- where("student_id = #{@user.id} and courses.is_delete = 0").map{|sc| sc.course_id}.join(",") + ")"
- # 用户待完成的作业
- homeworks = HomeworkCommon.where("course_id in #{my_course_ids} and publish_time <= '#{Time.now}'")
- homework_ids = homeworks.blank? ? "(-1)" : "(" + homeworks.map{|homework| homework.id}.join(",") + ")"
- student_works = StudentWork.where("user_id = #{@user.id} and homework_common_id in #{homework_ids} and work_status != 0")
- @unfinished_homework_count = homeworks.count - student_works.count
- # 用户待完成的测验
- exercises = Exercise.where("course_id in #{my_course_ids} and exercise_status = 2")
- exercise_users = ExerciseUser.where(:user_id => @user.id, :exercise_id => exercises.map{|ex| ex.id})
- @unfinished_test_count = exercises.count - exercise_users.count
- # 用户待完成的问卷
- polls = Poll.where("polls_type = 'Course' and polls_group_id in #{my_course_ids} and polls_status = 2")
- poll_users = PollUser.where(:user_id => @user.id, :poll_id => polls.map{|poll| poll.id})
- @unfinished_poll_count = polls.count - poll_users.count
- # 用户待匿评的作品
- homeworks = HomeworkCommon.includes(:homework_detail_manual).where("homework_commons.course_id in #{my_course_ids} and homework_detail_manuals.comment_status = 2")
- student_work_scores = @user.student_works_scores.where("reviewer_role = 3")
- anonymous_evaluation_ids = student_work_scores.blank? ? "(-1)" : "(" + student_work_scores.map{|st| st.student_work_id}.join(",") + ")"
- unfinished_evaluations = @user.student_works_evaluation_distributions.where("student_work_id not in #{anonymous_evaluation_ids}")
- @anonymous_evaluation_count = StudentWork.where(:id => unfinished_evaluations.map{|ev| ev.student_work_id}, :homework_common_id => homeworks.map{|hw| hw.id}).count
- # 待评阅的作业 暂不做
- # @unreview_homework = 1
+ # 我创建的实训数
+ @create_num = (show_all ? Shixun.where(:user_id => @user).count : Shixun.where(:user_id => @user).visible.count)
+ # 我合作的实训数
+ coop_id = Shixun.find_by_sql("select shixun_id from shixun_members where user_id=#{@user.id} and role = 2").map(&:shixun_id) # 合作者的实训id
+ @cooperative_num = (show_all ? Shixun.where(:id => coop_id).count : Shixun.where(:id => coop_id).visible.count)
+ # 我挑战的实训数
+ ch_id = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
+ @challenge_num = (show_all ? Shixun.where(:id => ch_id).count : Shixun.where(:id => ch_id).visible.count)
+ # 我的所有课程数
+ @all_courses_count = @user.courses.not_deleted_not_end.count
+ # 我创建的课程数
+ @create_courses_count = @user.courses.not_deleted_not_end.select{ |course| @user.has_teacher_role(course)}.count
+ # 我参与的课程数
+ @join_courses_count = @all_courses_count - @create_courses_count
- # 待审批的申请
- #applied_message_count = AppliedMessage.where(:applied_type => ["Organization", "AppliedContest", "StudentWorksScoresAppeal", "AppliedProject", "ApplyAddSchools"], :user_id => User.current.id, :status => 0).count
- #applied_course_message_count = CourseMessage.where(:user_id => User.current.id, :course_message_type => "JoinCourseRequest", :status => 0).count
- # applied_pull_request_message_count = ForgeMessage.where(:user_id => User.current.id, :forge_message_type => "PullRequest", :status => [1,3]).count
- # @applied_message_alls_count = applied_message_count + applied_course_message_count + applied_pull_request_message_count
- user_id = User.current.id
- sql = "SELECT * FROM `message_alls` ma left join `forge_messages` fm on ma.message_id=fm.id
- left join `course_messages` cm on ma.message_id=cm.id left join `applied_messages` apm on ma.message_id=apm.id
- where (ma.user_id =#{user_id} and ma.message_type = 'ForgeMessage' and fm.forge_message_type='PullRequest' and fm.status=0 and fm.user_id=#{user_id} ) or
- (ma.user_id=#{user_id} and ma.message_type='AppliedMessage' and apm.applied_type in ('Organization', 'AppliedContest', 'StudentWorksScoresAppeal', 'AppliedProject', 'ApplyAddSchools') and apm.user_id =#{user_id} and apm.status =0 ) or
- (ma.user_id=#{user_id} and ma.message_type='CourseMessage' and cm.course_message_type='JoinCourseRequest' and cm.status=0 and cm.user_id=#{user_id} );"
- message_alls = MessageAll.find_by_sql(sql)
- @applied_message_alls_count = message_alls.count
+ # 合作者及创建者
+ ids = Shixun.find_by_sql("select shixun_id from shixun_members where user_id=#{@user.id}")
+ # 已挑战过
+ ids2 = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
+ ids = ids.map{|shixun| shixun.shixun_id} unless ids.blank?
+ ids2 = ids2.map{|shixun| shixun.id} unless ids2.blank?
+ id = ids + ids2
+ id = id.uniq
+ if show_all
+ @shixuns = Shixun.where(:id => id).order("updated_at desc")
else
- # 看别人的主页显示动态
- #更新用户申请成为课程老师或教辅消息的状态
- if params[:course_id] != nil
- join_course_messages = CourseMessage.where("course_id =? and course_message_type =? and user_id =? and course_message_id =? and viewed =?",
- params[:course_id], 'JoinCourseRequest', User.current.id, @user.id, false)
- join_course_messages.update_all(:viewed => true)
- end
- shield_project_ids = ShieldActivity.select("shield_id").where("container_type='User' and container_id=#{@user.id} and shield_type='Project'").map(&:shield_id)
- shield_course_ids = ShieldActivity.select("shield_id").where("container_type='User' and container_id=#{@user.id} and shield_type='Course'").map(&:shield_id)
- @page = params[:page] ? params[:page].to_i + 1 : 0
- user_project_ids = (@user.favorite_projects.visible.map{|project| project.id}-shield_project_ids).empty? ? "(-1)" : "(" + (@user.favorite_projects.visible.map{|project| project.id}-shield_project_ids).join(",") + ")"
- user_course_ids = (@user.favorite_courses.visible.where("is_delete = 0").map{|course| course.id}-shield_course_ids).empty? ? "(-1)" : "(" + (@user.favorite_courses.visible.where("is_delete = 0").map{|course| course.id}-shield_course_ids).join(",") + ")"
- course_types = "('Message','News','HomeworkCommon','Poll','Course','JournalsForMessage')"
- project_types = "('Message','Issue','Project')"
- principal_types = "JournalsForMessage"
- container_type = ''
- act_type = ''
- # 他的动态
- sql = "user_id = #{@user.id} and ((container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types}) or (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types}))"
- if params[:type].present?
- case params[:type]
- when "course_homework"
- container_type = 'Course'
- act_type = 'HomeworkCommon'
- when "course_news"
- container_type = 'Course'
- act_type = 'News'
- when "course_message"
- container_type = 'Course'
- act_type = 'Message'
- when "course_poll"
- container_type = 'Course'
- act_type = 'Poll'
- when "course_journals"
- container_type = 'Course'
- act_type = 'JournalsForMessage'
- when "project_issue"
- container_type = 'Project'
- act_type = 'Issue'
- when "project_message"
- container_type = 'Project'
- act_type = 'Message'
- when "user_journals"
- container_type = 'Principal'
- act_type = 'JournalsForMessage'
- when "current_user"
- container_type = 'Principal'
- act_type = 'Principal'
- when "all"
- container_type = 'all'
- act_type = 'all'
- end
- end
- if container_type != '' && container_type != 'all'
- if container_type == 'Course'
- sql = "container_type = '#{container_type}' and container_id in #{user_course_ids} and act_type = '#{act_type}'"
- elsif container_type == 'Project'
- sql = "container_type = '#{container_type}' and container_id in #{user_project_ids} and act_type = '#{act_type}'"
- elsif container_type == 'Principal' && act_type == 'JournalsForMessage'
- sql = "container_type = '#{container_type}' and act_type= '#{act_type}' and container_id = #{@user.id}"
- elsif container_type == 'Principal' && act_type == 'Principal'
- sql = "user_id = #{@user.id} and ((container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types}) or (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types}))"
- end
- if User.current != @user
- sql += " and user_id = #{@user.id}"
- end
- else
- if User.current != @user
- blog_ids = "("+@user.blog.id.to_s+")"
- else
- blog_ids = "("+@user.blog.id.to_s+","+((User.watched_by(@user.id).count == 0 )? '0' :User.watched_by(@user.id).map{|u| u.blog.id}.join(','))+")"
- end
- sql = "(container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types})" +
- "or (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types}) "+
- "or (container_type = 'Principal' and act_type= '#{principal_types}' and container_id = #{@user.id}) " +
- "or (container_type = 'Blog' and act_type= 'BlogComment' and container_id in #{blog_ids})"
- if container_type != 'all' && User.current != @user
- sql = "user_id = #{@user.id} and(" + sql + ")"
- end
- end
- @user_activities_count = UserActivity.where("#{sql}").order('updated_at desc').count
- @user_activities = UserActivity.where("#{sql}").order('updated_at desc').limit(10).offset(@page * 10)
- @type = params[:type]
+ @shixuns = Shixun.where(:status => [2, 3], :id => id).order("updated_at desc")
end
+ @limit = 5
+ @is_remote = true
+ @shixuns_count = @shixuns.count
+ @shixuns_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
+ @offset ||= @shixuns_pages.offset
+ @shixuns = paginateHelper @shixuns, @limit
+ # if User.current == @user
+ # # 点击小铃铛,更新点击时间
+ # update_onclick_time if params[:click_user_message] == 'true'
+ # # 全部设为已读
+ # # 自己的主页显示消息
+ # messages_all = MessageAll.where(:user_id => @user.id)
+ # @message_count = messages_all.count
+ # # REDO:已删除的内容应该在页面中显示不点击
+ # @message_all_pages = Paginator.new @message_count, per_page_option, params['page']
+ # @message_alls = messages_all.includes(:message).
+ # limit(@message_all_pages.per_page).
+ # offset(@message_all_pages.offset).
+ # reorder("#{MessageAll.table_name}.created_at desc")
+ #
+ # @unsolved_issues_count = Issue.where(:assigned_to_id => @user.id, :status_id => [1, 2, 4, 6]).includes(:author, :project).count
+ #
+ # my_course_ids = StudentsForCourse.includes(:course).where("student_id = #{@user.id} and courses.is_delete = 0").blank? ? "(-1)" : "(" + StudentsForCourse.includes(:course).
+ # where("student_id = #{@user.id} and courses.is_delete = 0").map{|sc| sc.course_id}.join(",") + ")"
+ # # 用户待完成的作业
+ # homeworks = HomeworkCommon.where("course_id in #{my_course_ids} and publish_time <= '#{Time.now}'")
+ # homework_ids = homeworks.blank? ? "(-1)" : "(" + homeworks.map{|homework| homework.id}.join(",") + ")"
+ # student_works = StudentWork.where("user_id = #{@user.id} and homework_common_id in #{homework_ids} and work_status != 0")
+ # @unfinished_homework_count = homeworks.count - student_works.count
+ # # 用户待完成的测验
+ # exercises = Exercise.where("course_id in #{my_course_ids} and exercise_status = 2")
+ # exercise_users = ExerciseUser.where(:user_id => @user.id, :exercise_id => exercises.map{|ex| ex.id})
+ # @unfinished_test_count = exercises.count - exercise_users.count
+ # # 用户待完成的问卷
+ # polls = Poll.where("polls_type = 'Course' and polls_group_id in #{my_course_ids} and polls_status = 2")
+ # poll_users = PollUser.where(:user_id => @user.id, :poll_id => polls.map{|poll| poll.id})
+ # @unfinished_poll_count = polls.count - poll_users.count
+ # # 用户待匿评的作品
+ # homeworks = HomeworkCommon.includes(:homework_detail_manual).where("homework_commons.course_id in #{my_course_ids} and homework_detail_manuals.comment_status = 2")
+ # student_work_scores = @user.student_works_scores.where("reviewer_role = 3")
+ # anonymous_evaluation_ids = student_work_scores.blank? ? "(-1)" : "(" + student_work_scores.map{|st| st.student_work_id}.join(",") + ")"
+ # unfinished_evaluations = @user.student_works_evaluation_distributions.where("student_work_id not in #{anonymous_evaluation_ids}")
+ # @anonymous_evaluation_count = StudentWork.where(:id => unfinished_evaluations.map{|ev| ev.student_work_id}, :homework_common_id => homeworks.map{|hw| hw.id}).count
+ # # 待评阅的作业 暂不做
+ # # @unreview_homework = 1
+ #
+ # # 待审批的申请
+ # #applied_message_count = AppliedMessage.where(:applied_type => ["Organization", "AppliedContest", "StudentWorksScoresAppeal", "AppliedProject", "ApplyAddSchools"], :user_id => User.current.id, :status => 0).count
+ # #applied_course_message_count = CourseMessage.where(:user_id => User.current.id, :course_message_type => "JoinCourseRequest", :status => 0).count
+ # # applied_pull_request_message_count = ForgeMessage.where(:user_id => User.current.id, :forge_message_type => "PullRequest", :status => [1,3]).count
+ # # @applied_message_alls_count = applied_message_count + applied_course_message_count + applied_pull_request_message_count
+ # user_id = User.current.id
+ # sql = "SELECT * FROM `message_alls` ma left join `forge_messages` fm on ma.message_id=fm.id
+ # left join `course_messages` cm on ma.message_id=cm.id left join `applied_messages` apm on ma.message_id=apm.id
+ # where (ma.user_id =#{user_id} and ma.message_type = 'ForgeMessage' and fm.forge_message_type='PullRequest' and fm.status=0 and fm.user_id=#{user_id} ) or
+ # (ma.user_id=#{user_id} and ma.message_type='AppliedMessage' and apm.applied_type in ('Organization', 'AppliedContest', 'StudentWorksScoresAppeal', 'AppliedProject', 'ApplyAddSchools') and apm.user_id =#{user_id} and apm.status =0 ) or
+ # (ma.user_id=#{user_id} and ma.message_type='CourseMessage' and cm.course_message_type='JoinCourseRequest' and cm.status=0 and cm.user_id=#{user_id} );"
+ # message_alls = MessageAll.find_by_sql(sql)
+ # @applied_message_alls_count = message_alls.count
+ # else
+ # # 看别人的主页显示动态
+ # #更新用户申请成为课程老师或教辅消息的状态
+ # if params[:course_id] != nil
+ # join_course_messages = CourseMessage.where("course_id =? and course_message_type =? and user_id =? and course_message_id =? and viewed =?",
+ # params[:course_id], 'JoinCourseRequest', User.current.id, @user.id, false)
+ # join_course_messages.update_all(:viewed => true)
+ # end
+ # shield_project_ids = ShieldActivity.select("shield_id").where("container_type='User' and container_id=#{@user.id} and shield_type='Project'").map(&:shield_id)
+ # shield_course_ids = ShieldActivity.select("shield_id").where("container_type='User' and container_id=#{@user.id} and shield_type='Course'").map(&:shield_id)
+ # @page = params[:page] ? params[:page].to_i + 1 : 0
+ # user_project_ids = (@user.favorite_projects.visible.map{|project| project.id}-shield_project_ids).empty? ? "(-1)" : "(" + (@user.favorite_projects.visible.map{|project| project.id}-shield_project_ids).join(",") + ")"
+ # user_course_ids = (@user.favorite_courses.visible.where("is_delete = 0").map{|course| course.id}-shield_course_ids).empty? ? "(-1)" : "(" + (@user.favorite_courses.visible.where("is_delete = 0").map{|course| course.id}-shield_course_ids).join(",") + ")"
+ # course_types = "('Message','News','HomeworkCommon','Poll','Course','JournalsForMessage')"
+ # project_types = "('Message','Issue','Project')"
+ # principal_types = "JournalsForMessage"
+ # container_type = ''
+ # act_type = ''
+ # # 他的动态
+ # sql = "user_id = #{@user.id} and ((container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types}) or (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types}))"
+ # if params[:type].present?
+ # case params[:type]
+ # when "course_homework"
+ # container_type = 'Course'
+ # act_type = 'HomeworkCommon'
+ # when "course_news"
+ # container_type = 'Course'
+ # act_type = 'News'
+ # when "course_message"
+ # container_type = 'Course'
+ # act_type = 'Message'
+ # when "course_poll"
+ # container_type = 'Course'
+ # act_type = 'Poll'
+ # when "course_journals"
+ # container_type = 'Course'
+ # act_type = 'JournalsForMessage'
+ # when "project_issue"
+ # container_type = 'Project'
+ # act_type = 'Issue'
+ # when "project_message"
+ # container_type = 'Project'
+ # act_type = 'Message'
+ # when "user_journals"
+ # container_type = 'Principal'
+ # act_type = 'JournalsForMessage'
+ # when "current_user"
+ # container_type = 'Principal'
+ # act_type = 'Principal'
+ # when "all"
+ # container_type = 'all'
+ # act_type = 'all'
+ # end
+ # end
+ # if container_type != '' && container_type != 'all'
+ # if container_type == 'Course'
+ # sql = "container_type = '#{container_type}' and container_id in #{user_course_ids} and act_type = '#{act_type}'"
+ # elsif container_type == 'Project'
+ # sql = "container_type = '#{container_type}' and container_id in #{user_project_ids} and act_type = '#{act_type}'"
+ # elsif container_type == 'Principal' && act_type == 'JournalsForMessage'
+ # sql = "container_type = '#{container_type}' and act_type= '#{act_type}' and container_id = #{@user.id}"
+ # elsif container_type == 'Principal' && act_type == 'Principal'
+ # sql = "user_id = #{@user.id} and ((container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types}) or (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types}))"
+ # end
+ # if User.current != @user
+ # sql += " and user_id = #{@user.id}"
+ # end
+ # else
+ # if User.current != @user
+ # blog_ids = "("+@user.blog.id.to_s+")"
+ # else
+ # blog_ids = "("+@user.blog.id.to_s+","+((User.watched_by(@user.id).count == 0 )? '0' :User.watched_by(@user.id).map{|u| u.blog.id}.join(','))+")"
+ # end
+ # sql = "(container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types})" +
+ # "or (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types}) "+
+ # "or (container_type = 'Principal' and act_type= '#{principal_types}' and container_id = #{@user.id}) " +
+ # "or (container_type = 'Blog' and act_type= 'BlogComment' and container_id in #{blog_ids})"
+ # if container_type != 'all' && User.current != @user
+ # sql = "user_id = #{@user.id} and(" + sql + ")"
+ # end
+ # end
+ # @user_activities_count = UserActivity.where("#{sql}").order('updated_at desc').count
+ # @user_activities = UserActivity.where("#{sql}").order('updated_at desc').limit(10).offset(@page * 10)
+ # @type = params[:type]
+ # end
+ respond_to do |format|
+ format.js
+ format.html {render :layout => 'base_edu_user'}
+ end
+ end
+
+ # @params: index表示 "实训" 或 "课程" 那个的筛选
+ # filter 表示筛选的条件[challenge => "我挑战的", create => "我创建的", cooperative => "合作者"]
+ def shixuns_or_courses_filter
+ if params[:index] == "shixun"
+ if params[:filter] == "challenge"
+ # 已挑战过
+ id = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
+ if @user == User.current || User.current.admin?
+ @shixuns = Shixun.where(:id => id).order("updated_at desc")
+ else
+ @shixuns = Shixun.where(:id => id).visible.order("updated_at desc")
+ end
+ elsif params[:filter] == "create"
+ if @user == User.current || User.current.admin?
+ @shixuns = Shixun.where(:user_id => @user).order("updated_at desc")
+ else
+ @shixuns = Shixun.where(:user_id => @user).visible.order("updated_at desc")
+ end
+ elsif params[:filter] == "cooperative"
+ # 合作者的实训id
+ id = Shixun.find_by_sql("select shixun_id from shixun_members where user_id=#{@user.id} and role = 2").map(&:shixun_id)
+ if @user == User.current || User.current.admin?
+ @shixuns = Shixun.where(:id => id).order("updated_at desc")
+ else
+ @shixuns = Shixun.where(:id => id).visible.order("updated_at desc")
+ end
+ elsif params[:filter] == "all"
+ # 合作者及创建者
+ ids = Shixun.find_by_sql("select shixun_id from shixun_members where user_id=#{@user.id}")
+ # 已挑战过
+ ids2 = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
+ ids = ids.map{|shixun| shixun.shixun_id} unless ids.blank?
+ ids2 = ids2.map{|shixun| shixun.id} unless ids2.blank?
+ id = ids + ids2
+ id = id.uniq
+ if @user == User.current || User.current.admin?
+ @shixuns = Shixun.where(:id => id).order("updated_at desc")
+ else
+ @shixuns = Shixun.where(:id => id).visible.order("updated_at desc")
+ end
+ end
+ @limit = 5
+ @is_remote = true
+ @shixuns_count = @shixuns.count
+ @shixuns_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
+ @offset ||= @shixuns_pages.offset
+ @shixuns = paginateHelper @shixuns, @limit
+ elsif params[:index] == "course"
+ if params[:filter] == "manage"
+ @courses = @user.courses.not_deleted_not_end.order("updated_at desc").select{ |course| @user.has_teacher_role(course)}
+ elsif params[:filter] == "join"
+ @courses = @user.courses.not_deleted_not_end.order("updated_at desc").select{ |course| !@user.has_teacher_role(course)}
+ elsif params[:filter] == "all"
+ @courses = @user.courses.not_deleted_not_end.order("updated_at desc")
+ end
+ @limit = 5
+ @is_remote = true
+ @courses_count = @courses.count
+ @courses_pages = Paginator.new @courses_count, @limit, params['page'] || 1
+ @offset ||= @courses_pages.offset
+ @courses = paginateHelper @courses, @limit
+ end
+
+ respond_to do |format|
+ format.js
+ end
+ end
+
+ def growth_record
+ games = @user.games.where(:status => 2)
+ challenge_tags = ChallengeTag.where(:challenge_id => games.map(&:challenge_id))
+ games = @user.games.where(:challenge_id => Challenge.where(:id => challenge_tags.map(&:challenge_id)).map(&:id))
+ @user_tags = @user.experiences.where(:container_id => games.map(&:id)).reorder("created_at desc")
+ #@user_tags = @user.experiences.reorder("created_at desc")
+ @limit = 20
+ @is_remote = true
+ @tags_count = @user_tags.count
+ @tags_pages = Paginator.new @tags_count, @limit, params['page'] || 1
+ @offset ||= @tags_pages.offset
+ @user_tags = paginateHelper @user_tags, @limit
+ respond_to do |format|
+ format.js
+ format.html {render :layout => 'base_edu_user'}
+ end
+ end
+
+ def user_experience
+ @user_experiences = @user.experiences.where("score > 0").reorder("created_at desc")
+ @limit = 20
+ @is_remote = true
+ @experiences_count = @user_experiences.count
+ @experiences_pages = Paginator.new @experiences_count, @limit, params['page'] || 1
+ @offset ||= @experiences_pages.offset
+ @user_experiences = paginateHelper @user_experiences, @limit
+ end
+
+ def user_grade
+ @type = params[:type] ? params[:type].to_i : 1
+ @user_grades = @type == 1 ? @user.grades.where("score > 0").reorder("created_at desc") : @user.grades.where("score < 0").reorder("created_at desc")
+ @limit = 20
+ @is_remote = true
+ @grades_count = @user_grades.count
+ @grades_pages = Paginator.new @grades_count, @limit, params['page'] || 1
+ @offset ||= @grades_pages.offset
+ @user_grades = paginateHelper @user_grades, @limit
+ end
+
+ def user_show_course_list
+ @courses = @user.courses.not_deleted_not_end.order("updated_at desc")
+ @courses_count = @courses.count
+ @limit = 5
+ @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 {render :layout => 'new_base_user'}
end
end
@@ -2953,16 +3105,15 @@ class UsersController < ApplicationController
@user = User.current
if !params[:search].nil?
search = "%#{params[:search].to_s.strip.downcase}%"
- @course = @user.courses.not_deleted.where(" #{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like :p",:p=>search)
+ @course = @user.courses.not_deleted_not_end.where(" #{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like :p",:p=>search)
else
- @course = @user.courses.not_deleted
+ @course = @user.courses.not_deleted_not_end
end
@search = params[:search]
@type = params[:type]
#这里仅仅是传递需要发送的资源id
@send_id = params[:send_id]
@send_ids = params[:checkbox1] || params[:send_ids]
- @hidden_unproject = hidden_unproject_infos
respond_to do |format|
format.js
end
@@ -3040,60 +3191,61 @@ class UsersController < ApplicationController
else
@flag = false
end
- @order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
- @score = @b_sort == "desc" ? "asc" : "desc"
- user_project_ids = User.current.projects.map {|p| p.id}
- user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源
- if(params[:type] == "1") # 我的资源
- # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
- if params[:status] == "2"
- @attachments = get_course_resources(User.current.id, user_course_ids, @order, @score)
- elsif params[:status] == "3"
- @attachments = get_project_resources(User.current.id, user_project_ids, @order, @score)
- elsif params[:status] == "4"
- @attachments = get_attch_resources(User.current.id, @order, @score)
- elsif params[:status] == "5"
- @attachments = get_principal_resources(User.current.id, @order, @score)
- else
- # 公共资源库:所有公开资源或者我上传的私有资源
- @attachments = get_my_resources(User.current.id, user_course_ids, user_project_ids, @order, @score)
- end
- elsif (params[:type].blank? || params[:type] == "6") # 公共资源
- if params[:status] == "2"
- @attachments = get_course_resources_public( user_course_ids, @order, @score)
- elsif params[:status] == "3"
- @attachments = get_project_resources_public(user_project_ids, @order, @score)
- elsif params[:status] == "4"
- @attachments = get_attch_resources_public(@order, @score)
- elsif params[:status] == "5"
- @attachments = get_principal_resources_public(@order, @score)
- else
- # 公共资源库:所有公开资源或者我上传的私有资源
- @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
- end
- # elsif params[:type] == "2"
- # apply_ids = ApplyResource.where("user_id =? and status =?", params[:id], 2).map { |ar| ar.attachment_id}
- # if params[:status] == "2"
- # resource_type = "'Course'"
- # elsif params[:status] == "3"
- # resource_type = "'Project'"
- # elsif params[:status] == "5"
- # resource_type = "'Principal'"
- # else
- # resource_type = "'Project','OrgSubfield','Principal','Course'"
- # end
- # @attachments = get_my_private_resources(apply_ids, resource_type, @order, @score)
- end
- @type = params[:type]
- @limit = 25
- @path = user_resource_user_path(User.current, :type => @type)
- @user = User.current
- @is_remote = true
- @atta_count = @attachments.count
- @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
- @offset ||= @atta_pages.offset
- #@curse_attachments_all = @all_attachments[@offset, @limit]
- @attachments = paginateHelper @attachments,25
+ # @order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
+ # @score = @b_sort == "desc" ? "asc" : "desc"
+ # user_project_ids = User.current.projects.map {|p| p.id}
+ # user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源
+ # if(params[:type] == "1") # 我的资源
+ # # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
+ # if params[:status] == "2"
+ # @attachments = get_course_resources(User.current.id, user_course_ids, @order, @score)
+ # elsif params[:status] == "3"
+ # @attachments = get_project_resources(User.current.id, user_project_ids, @order, @score)
+ # elsif params[:status] == "4"
+ # @attachments = get_attch_resources(User.current.id, @order, @score)
+ # elsif params[:status] == "5"
+ # @attachments = get_principal_resources(User.current.id, @order, @score)
+ # else
+ # # 公共资源库:所有公开资源或者我上传的私有资源
+ # @attachments = get_my_resources(User.current.id, user_course_ids, user_project_ids, @order, @score)
+ # end
+ # elsif (params[:type].blank? || params[:type] == "6") # 公共资源
+ # if params[:status] == "2"
+ # @attachments = get_course_resources_public( user_course_ids, @order, @score)
+ # elsif params[:status] == "3"
+ # @attachments = get_project_resources_public(user_project_ids, @order, @score)
+ # elsif params[:status] == "4"
+ # @attachments = get_attch_resources_public(@order, @score)
+ # elsif params[:status] == "5"
+ # @attachments = get_principal_resources_public(@order, @score)
+ # else
+ # # 公共资源库:所有公开资源或者我上传的私有资源
+ # @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
+ # end
+ # # elsif params[:type] == "2"
+ # # apply_ids = ApplyResource.where("user_id =? and status =?", params[:id], 2).map { |ar| ar.attachment_id}
+ # # if params[:status] == "2"
+ # # resource_type = "'Course'"
+ # # elsif params[:status] == "3"
+ # # resource_type = "'Project'"
+ # # elsif params[:status] == "5"
+ # # resource_type = "'Principal'"
+ # # else
+ # # resource_type = "'Project','OrgSubfield','Principal','Course'"
+ # # end
+ # # @attachments = get_my_private_resources(apply_ids, resource_type, @order, @score)
+ # end
+ # @type = params[:type]
+ # @limit = 25
+ # @path = user_resource_user_path(User.current, :type => @type)
+ # @user = User.current
+ # @is_remote = true
+ # @atta_count = @attachments.count
+ # @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
+ # @offset ||= @atta_pages.offset
+ # #@curse_attachments_all = @all_attachments[@offset, @limit]
+ # @attachments = paginateHelper @attachments,25
+ @course = @ori.course
respond_to do |format|
format.js
end
@@ -3552,7 +3704,7 @@ class UsersController < ApplicationController
def destroy
@user.destroy
respond_to do |format|
- format.html { redirect_back_or_default(admin_users_path) }
+ format.html { redirect_back_or_default(params[:back_url]) }
format.api { render_api_ok }
end
end
@@ -3665,24 +3817,52 @@ class UsersController < ApplicationController
end
###add by huang
def user_watchlist
- limit = 10;
- query = User.watched_by(@user.id);
- @obj_count = query.count();
- @obj_pages = Paginator.new @obj_count,limit,params['page']
- @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all();
- @action = 'watch'
- render :template=>'users/user_fanslist',:layout=>'new_base_user'
+ watch_query = User.watched_by(@user.id)
+ @user_watchlist_count = watch_query.count
+ @user_watchlist = watch_query.order("#{Watcher.table_name}.id desc")
+ fan_query = @user.watcher_users
+ @user_fanlist_count = fan_query.count
+ @limit = 20
+ @is_remote = true
+ @watchlist_pages = Paginator.new @user_watchlist_count, @limit, params['page'] || 1
+ @offset ||= @watchlist_pages.offset
+ @user_watchlist = paginateHelper @user_watchlist, @limit
+ respond_to do |format|
+ format.html {render :layout => 'base_edu_user'}
+ format.js
+ end
end
###add by huang
def user_fanslist
- limit = 10;
- query = @user.watcher_users;
- @obj_count = query.count();
- @obj_pages = Paginator.new @obj_count,limit,params['page']
- @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all();
- @action = 'fans'
- render :layout=>'new_base_user'
+ watch_query = User.watched_by(@user.id)
+ @user_watchlist_count = watch_query.count
+ fan_query = @user.watcher_users
+ @user_fanlist_count = fan_query.count
+ @user_fanlist = fan_query.order("#{Watcher.table_name}.id desc")
+
+ @limit = 20
+ @is_remote = true
+ @fans_pages = Paginator.new @user_fanlist_count, @limit, params['page'] || 1
+ @offset ||= @fans_pages.offset
+ @user_fanlist = paginateHelper @user_fanlist, @limit
+ respond_to do |format|
+ format.html {render :layout => 'base_edu_user'}
+ format.js
+ end
end
+
+ def user_wathlist_and_fanslist
+ watch_query = User.watched_by(@user.id)
+ @user_watchlist_count = watch_query.count
+ @user_watchlist = watch_query.order("#{Watcher.table_name}.id desc")
+ fan_query = @user.watcher_users
+ @user_fanlist_count = fan_query.count
+ @user_fanlist = fan_query.order("#{Watcher.table_name}.id desc")
+ respond_to do |format|
+ format.html {render :layout => 'base_edu_user'}
+ end
+ end
+
def user_visitorlist
limit = 10;
#query = @user.watcher_users;
@@ -4466,7 +4646,7 @@ class UsersController < ApplicationController
private
def show_system_message
- # 系统消息总显示在最前面,显示周期30天
+ # 系统消息总显示在最前面,显示周期30天
@system_messages = SystemMessage.where("created_at > ?", Time.now - 86400 * 30)
end
diff --git a/app/controllers/watchers_controller.rb b/app/controllers/watchers_controller.rb
index 6f0d96dfa..1464819cb 100644
--- a/app/controllers/watchers_controller.rb
+++ b/app/controllers/watchers_controller.rb
@@ -21,36 +21,70 @@ class WatchersController < ApplicationController
def watch
s = WatchesService.new
- watchables = s.watch params.merge(:current_user_id => User.current.id)
if params[:action_name] == 'watch'
- limit = 10;
- query = User.watched_by(params[:target_id]);
- @obj_count = query.count();
+ limit = 10
+ query = User.watched_by(params[:target_id])
+ @obj_count = query.count
@obj_pages = Paginator.new @obj_count,limit,params['page']
- @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all();
+ @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all
@action = 'watch'
elsif params[:action_name] == 'fans'
- limit = 10;
- query = User.find(params[:target_id]).watcher_users;
- @obj_count = query.count();
+ limit = 10
+ query = User.find(params[:target_id]).watcher_users
+ @obj_count = query.count
@obj_pages = Paginator.new @obj_count,limit,params['page']
- @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all();
+ @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all
@action = 'fans'
else
- if params[:target_id]
+ if params[:target_id] && params[:user_watcher].blank?
+ watchables = s.watch params.merge(:current_user_id => User.current.id)
@user = User.find(params[:target_id])
+ watch_query = User.watched_by(@user.id)
+ @user_watchlist_count = watch_query.count
+ @user_watchlist = watch_query.order("#{Watcher.table_name}.id desc").limit(12)
+ fan_query = @user.watcher_users
+ @user_fanlist_count = fan_query.count
+ @user_fanlist = fan_query.order("#{Watcher.table_name}.id desc").limit(12)
end
end
-
if params[:object_type] == 'project'
@project = Project.find(params[:object_id])
respond_to do |format|
format.js
end
+ elsif params[:user_watcher] == "user_fanslist"
+ @watched = User.find(params[:target_id].to_i)
+ @user = User.find(params[:object_id].to_i)
+ @watched.add_watcher(@user)
+ watch_query = User.watched_by(@user.id)
+ @user_watchlist_count = watch_query.count
+ fan_query = @user.watcher_users
+ @user_fanlist_count = fan_query.count
+ @user_fanlist = fan_query.order("#{Watcher.table_name}.id desc")
+
+ @limit = 20
+ @is_remote = true
+ @fans_pages = Paginator.new @user_fanlist_count, @limit, params['page'] || 1
+ @offset ||= @fans_pages.offset
+ @user_fanlist = paginateHelper @user_fanlist, @limit
+ respond_to do |format|
+ format.js
+ end
else
respond_to do |format|
format.html { redirect_to_referer_or {render :text => (true ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
- format.js { render :partial => 'set_watcher', :locals => {:user => User.current, :watched => watchables,:params=>params,:opt=>'add',:list => @list,:action_name=>params[:action_name],:page=>params[:page],:count=>@obj_count} }
+ format.js { render :partial => 'set_watcher',
+ :locals => {
+ :user => User.current,
+ :watched => watchables,
+ :params => params,
+ :opt =>'add',
+ :list => @list,
+ :action_name => params[:action_name],
+ :page => params[:page],
+ :count => @obj_count
+ }
+ }
end
end
rescue Exception => e
@@ -66,22 +100,28 @@ class WatchersController < ApplicationController
s = WatchesService.new
watchables = s.unwatch params.merge(:current_user_id => User.current.id)
if params[:action_name] == 'watch'
- limit = 10;
- query = User.watched_by(params[:target_id]);
- @obj_count = query.count();
+ limit = 10
+ query = User.watched_by(params[:target_id])
+ @obj_count = query.count()
@obj_pages = Paginator.new @obj_count,limit,params['page']
- @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all();
+ @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all()
@action = 'watch'
elsif params[:action_name] == 'fans'
- limit = 10;
- query = User.find(params[:target_id]).watcher_users;
- @obj_count = query.count();
+ limit = 10
+ query = User.find(params[:target_id]).watcher_users
+ @obj_count = query.count()
@obj_pages = Paginator.new @obj_count,limit,params['page']
- @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all();
+ @list = query.order("#{Watcher.table_name}.id desc").limit(limit).offset(@obj_pages.offset).all()
@action = 'fans'
else
- if params[:target_id]
+ if params[:target_id] && params[:user_watcher].blank?
@user = User.find(params[:target_id])
+ watch_query = User.watched_by(@user.id)
+ @user_watchlist_count = watch_query.count()
+ @user_watchlist = watch_query.order("#{Watcher.table_name}.id desc").limit(4)
+ fan_query = @user.watcher_users
+ @user_fanlist_count = fan_query.count()
+ @user_fanlist = fan_query.order("#{Watcher.table_name}.id desc").limit(4)
end
end
if params[:object_type] == 'project'
@@ -89,6 +129,41 @@ class WatchersController < ApplicationController
respond_to do |format|
format.js
end
+ elsif params[:user_watcher] == "user_watchlist"
+ @watched = User.find(params[:target_id].to_i)
+ @user = User.find(params[:object_id].to_i)
+ @watched.remove_watcher(@user)
+ watch_query = User.watched_by(@user.id)
+ @user_watchlist_count = watch_query.count
+ @user_watchlist = watch_query.order("#{Watcher.table_name}.id desc")
+ fan_query = @user.watcher_users
+ @user_fanlist_count = fan_query.count
+ @limit = 20
+ @is_remote = true
+ @watchlist_pages = Paginator.new @user_watchlist_count, @limit, params['page'] || 1
+ @offset ||= @watchlist_pages.offset
+ @user_watchlist = paginateHelper @user_watchlist, @limit
+ respond_to do |format|
+ format.js
+ end
+ elsif params[:user_watcher] == "user_fanslist"
+ @watched = User.find(params[:target_id].to_i)
+ @user = User.find(params[:object_id].to_i)
+ @watched.remove_watcher(@user)
+ watch_query = User.watched_by(@user.id)
+ @user_watchlist_count = watch_query.count
+ fan_query = @user.watcher_users
+ @user_fanlist_count = fan_query.count
+ @user_fanlist = fan_query.order("#{Watcher.table_name}.id desc")
+
+ @limit = 20
+ @is_remote = true
+ @fans_pages = Paginator.new @user_fanlist_count, @limit, params['page'] || 1
+ @offset ||= @fans_pages.offset
+ @user_fanlist = paginateHelper @user_fanlist, @limit
+ respond_to do |format|
+ format.js
+ end
else
respond_to do |format|
format.html { redirect_to_referer_or {render :text => (false ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
@@ -103,7 +178,7 @@ class WatchersController < ApplicationController
end
#set_watcher(@watchables, User.current, false)
end
-
+
def join
if User.current.logged?
course = Project.find(params[:object_id])
@@ -111,7 +186,7 @@ class WatchersController < ApplicationController
members = []
members << Member.new(:role_ids => [5], :user_id => User.current.id)
course.members << members
-
+
StudentsForCourse.create(:student_id => User.current.id, :course_id => params[:object_id])
else
end
@@ -121,13 +196,13 @@ class WatchersController < ApplicationController
format.js { render :partial => 'set_join', :locals => {:user => User.current, :course => Project.find(params[:object_id])} }
end
end
-
+
def unjoin
if User.current.logged?
-
+
@member = Member.where('project_id = ? and user_id = ?', params[:object_id], User.current.id)
@member.first.destroy
-
+
joined = StudentsForCourse.where('student_id = ? and course_id = ?', User.current.id, params[:object_id])
joined.each do |join|
join.destroy
@@ -169,6 +244,8 @@ class WatchersController < ApplicationController
end
end
+ # params user_watcher 用户关注列表
+ # user_fans 用户粉丝列表
def destroy
@watched.set_watcher(User.find(params[:user_id]), false)
respond_to do |format|
diff --git a/app/controllers/welcome_controller.rb b/app/controllers/welcome_controller.rb
index 9f243e71a..fe6e7588e 100644
--- a/app/controllers/welcome_controller.rb
+++ b/app/controllers/welcome_controller.rb
@@ -1,294 +1,298 @@
-# Redmine - project management software
-# Copyright (C) 2006-2013 Jean-Philippe Lang
-#
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-
-class WelcomeController < ApplicationController
- # layout "base_welcome"
- include ApplicationHelper
- include WelcomeHelper
- helper :project_score
- caches_action :robots, :course, :contest, expires_in: 2.hours, layout: false
- #before_filter :find_first_page, :only => [:index]
- # before_filter :fake, :only => [:index, :course]
- before_filter :entry_select, :only => [:index]
-
- def index
- @welcome = true
- render :layout => 'login_bigdata'
- end
-
- def robots
- @projects = Project.all_public.active
- render :layout => false, :content_type => 'text/plain'
- end
-
- def course
- redirect_to signin_path
- return
- #
- # @course_page = FirstPage.find_by_page_type('course')
- # @school_id = params[:school_id] || User.current.user_extensions.school.try(:id) || 117
- # @logoLink ||= logolink()
- end
-
- def logolink()
- @course_page = FirstPage.find_by_page_type('course')
- logo = get_avatar?(@course_page)
- id = params[:school_id]
- logo_link = ""
- if id.nil? && (User.current.user_extensions.nil? || User.current.user_extensions.school.nil?)
- if logo
- logo_link = url_to_avatar(@course_page)
- else
- logo_link = '/images/transparent.png'
- end
-
- else
- if id == "0"
- if logo
- logo_link = url_to_avatar(@course_page)
- else
- logo_link = '/images/transparent.png'
- end
- else
- if id.nil?
- if School.find(User.current.user_extensions.school.id).logo_link.nil?
- logo_link = '/images/transparent.png'
- else
- logo_link = School.find(User.current.user_extensions.school.id).logo_link
- end
- else
- logo_link = School.find(id).logo_link
-
- end
- end
- end
- return logo_link
- end
-
-
- def contest
- redirect_to signin_path
- return
-
- # @contest_page = FirstPage.find_by_page_type('contest')
- # @contest_notifications = Contestnotification.order("created_at desc").limit(5)
- end
-
- def search
- @name = params[:q]
- @search_type = params[:search_type]
- page = (params[:page] || 1).to_i
-
- @users_count = User.search(@name).results.total
- @syllabus_count = Syllabus.search(@name).results.total
- @course_count = Course.search(@name).results.total
- @attach_count = Attachment.search(@name).results.total
- @project_count = Project.search(@name).results.total
- @memo_count = Memo.search(@name).results.total
- @total_count = Elasticsearch::Model.search({
- query: {
- multi_match: {
- query: @name,
- type:"most_fields",
- operator: "or",
- fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
- }
- },
- highlight: {
- pre_tags: [''],
- post_tags: [' '],
- fields: {
- login: {},
- firstname: {},
- lastname: {},
- title:{},
- name:{},
- description:{},
- filename:{},
- subject:{},
- content:{}
- }
- }
- },[User,Syllabus,Course,Attachment,Project,Memo] ).results.total
-
-
- case params[:search_type]
- when 'all'
- if (page-1)*20 >= @total_count
- page = 1
- params[:page] = "1"
- end
- @alls = Elasticsearch::Model.search({
- query: {
- multi_match: {
- query: @name,
- type:"most_fields",
- operator: "or",
- fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
- }
- },
- highlight: {
- pre_tags: [''],
- post_tags: [' '],
- fields: {
- login: {},
- firstname: {},
- lastname: {},
- title:{},
- name:{},
- description:{},
- filename:{},
- subject:{},
- content:{}
- }
- }
- },[User,Syllabus,Course,Attachment,Project,Memo] ).page(page).per(20).results
- when 'user'
- if (page-1)*20 >= @users_count
- page = 1
- params[:page] = "1"
- end
- @users = User.search(@name).page(page).per(20)
- when 'syllabus'
- if (page-1)*20 >= @syllabus_count
- page = 1
- params[:page] = "1"
- end
- @syllabuses = Syllabus.search(@name).page(page).per(20).results
- when 'project'
- if (page-1)*20 >= @project_count
- page = 1
- end
- @projects = Project.search(@name).page(page).per(20).results
- when 'course'
- if (page-1)*20 >= @course_count
- page = 1
- params[:page] = "1"
- end
- @courses = Course.search(@name).page(page).per(20).results
- when 'attachment'
- if (page-1)*20 >= @attach_count
- page = 1
- params[:page] = "1"
- end
- @attachments = Attachment.search(@name).page(page).per(20).results
- when 'memo'
- if (page-1)*20 >= @memo_count
- page = 1
- params[:page] = "1"
- end
- @memos = Memo.search(@name).page(page).per(20).results
- else
- if (page-1)*20 >= @total_count
- page = 1
- params[:page] = "1"
- end
- @alls = Elasticsearch::Model.search({
- query: {
- multi_match: {
- query: @name,
- type:"most_fields",
- operator: "or",
- fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
- }
- },
- highlight: {
- pre_tags: [''],
- post_tags: [' '],
- fields: {
- login: {},
- firstname: {},
- lastname: {},
- title:{},
- name:{},
- description:{},
- filename:{},
- subject:{},
- content:{}
- }
- }
- },[User,Syllabus,Course,Attachment,Project,Memo] ).page(page).per(20).results
-
- end
-
-
-
- # search_type = params[:search_type].to_sym unless search_condition.blank?
- # search_by = params[:search_by]
- #
- # if search_type.nil? && params[:contests_search] && params[:name] != ""
- # search_type = :contests
- # search_condition = params[:name]
- # end
-
- respond_to do |format|
- format.js
- format.html{ render :layout=>'users_base'}
- end
- end
-
- private
- # 判断网站的入口,是课程 course 则跳过index去渲染 course 方法
- def entry_select
- # url = request.original_url.gsub('/','')
- # if url.include?(Setting.url_course.gsub('/',''))
- # if @first_page.show_course == 1
- # course
- # render :course
- # else
- # render_404
- # end
- #
- # return 0
- # elsif url.include?(Setting.url_contest.gsub('/',''))
- # if @first_page.show_contest == 1
- # contest
- # render :contest
- # else
- # render_404
- # end
- #
- # return 0
- # elsif url.include?(Setting.url_user.gsub('/',''))
- # #redirect_to(:controller => "users", :action => "index")
- # end
-
-
- end
-
- # def render(*args)
- # _fake if @fake_filter
- # super
- # end
-
- # private
-
- # def fake
- # @fake_filter = true
- # end
-
- # # 骗子方法
- # def _fake
- # instance_variables.map { |variable|
- # if variable.to_s =~ /Count$/
- # self.instance_variable_set(variable.to_sym,
- # ("1" + (self.instance_variable_get(variable.to_sym).to_s)).to_i)
- # end
- # }
- # end
-
-end
+# Redmine - project management software
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+class WelcomeController < ApplicationController
+ # layout "base_welcome"
+ include ApplicationHelper
+ include WelcomeHelper
+ helper :project_score
+ caches_action :robots, :course, :contest, expires_in: 2.hours, layout: false
+ #before_filter :find_first_page, :only => [:index]
+ # before_filter :fake, :only => [:index, :course]
+ before_filter :entry_select, :only => [:index]
+ skip_before_filter :check_authentication, :only => [:index]
+
+ def index
+ # @welcome是因为有的页面不需要导航
+ @welcome = true
+ @courses = Course.where(:homepage_show => 1).limit(6)
+ @shixuns = Shixun.where(:homepage_show => 1).limit(6)
+ render :layout => 'login_bigdata'
+ end
+
+ def robots
+ @projects = Project.all_public.active
+ render :layout => false, :content_type => 'text/plain'
+ end
+
+ def course
+ redirect_to signin_path
+ return
+ #
+ # @course_page = FirstPage.find_by_page_type('course')
+ # @school_id = params[:school_id] || User.current.user_extensions.school.try(:id) || 117
+ # @logoLink ||= logolink()
+ end
+
+ def logolink()
+ @course_page = FirstPage.find_by_page_type('course')
+ logo = get_avatar?(@course_page)
+ id = params[:school_id]
+ logo_link = ""
+ if id.nil? && (User.current.user_extensions.nil? || User.current.user_extensions.school.nil?)
+ if logo
+ logo_link = url_to_avatar(@course_page)
+ else
+ logo_link = '/images/transparent.png'
+ end
+
+ else
+ if id == "0"
+ if logo
+ logo_link = url_to_avatar(@course_page)
+ else
+ logo_link = '/images/transparent.png'
+ end
+ else
+ if id.nil?
+ if School.find(User.current.user_extensions.school.id).logo_link.nil?
+ logo_link = '/images/transparent.png'
+ else
+ logo_link = School.find(User.current.user_extensions.school.id).logo_link
+ end
+ else
+ logo_link = School.find(id).logo_link
+
+ end
+ end
+ end
+ return logo_link
+ end
+
+
+ def contest
+ redirect_to signin_path
+ return
+
+ # @contest_page = FirstPage.find_by_page_type('contest')
+ # @contest_notifications = Contestnotification.order("created_at desc").limit(5)
+ end
+
+ def search
+ @name = params[:q]
+ @search_type = params[:search_type]
+ page = (params[:page] || 1).to_i
+
+ @users_count = User.search(@name).results.total
+ @syllabus_count = Syllabus.search(@name).results.total
+ @course_count = Course.search(@name).results.total
+ @attach_count = Attachment.search(@name).results.total
+ @project_count = Project.search(@name).results.total
+ @memo_count = Memo.search(@name).results.total
+ @total_count = Elasticsearch::Model.search({
+ query: {
+ multi_match: {
+ query: @name,
+ type:"most_fields",
+ operator: "or",
+ fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
+ }
+ },
+ highlight: {
+ pre_tags: [''],
+ post_tags: [' '],
+ fields: {
+ login: {},
+ firstname: {},
+ lastname: {},
+ title:{},
+ name:{},
+ description:{},
+ filename:{},
+ subject:{},
+ content:{}
+ }
+ }
+ },[User,Syllabus,Course,Attachment,Project,Memo] ).results.total
+
+
+ case params[:search_type]
+ when 'all'
+ if (page-1)*20 >= @total_count
+ page = 1
+ params[:page] = "1"
+ end
+ @alls = Elasticsearch::Model.search({
+ query: {
+ multi_match: {
+ query: @name,
+ type:"most_fields",
+ operator: "or",
+ fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
+ }
+ },
+ highlight: {
+ pre_tags: [''],
+ post_tags: [' '],
+ fields: {
+ login: {},
+ firstname: {},
+ lastname: {},
+ title:{},
+ name:{},
+ description:{},
+ filename:{},
+ subject:{},
+ content:{}
+ }
+ }
+ },[User,Syllabus,Course,Attachment,Project,Memo] ).page(page).per(20).results
+ when 'user'
+ if (page-1)*20 >= @users_count
+ page = 1
+ params[:page] = "1"
+ end
+ @users = User.search(@name).page(page).per(20)
+ when 'syllabus'
+ if (page-1)*20 >= @syllabus_count
+ page = 1
+ params[:page] = "1"
+ end
+ @syllabuses = Syllabus.search(@name).page(page).per(20).results
+ when 'project'
+ if (page-1)*20 >= @project_count
+ page = 1
+ end
+ @projects = Project.search(@name).page(page).per(20).results
+ when 'course'
+ if (page-1)*20 >= @course_count
+ page = 1
+ params[:page] = "1"
+ end
+ @courses = Course.search(@name).page(page).per(20).results
+ when 'attachment'
+ if (page-1)*20 >= @attach_count
+ page = 1
+ params[:page] = "1"
+ end
+ @attachments = Attachment.search(@name).page(page).per(20).results
+ when 'memo'
+ if (page-1)*20 >= @memo_count
+ page = 1
+ params[:page] = "1"
+ end
+ @memos = Memo.search(@name).page(page).per(20).results
+ else
+ if (page-1)*20 >= @total_count
+ page = 1
+ params[:page] = "1"
+ end
+ @alls = Elasticsearch::Model.search({
+ query: {
+ multi_match: {
+ query: @name,
+ type:"most_fields",
+ operator: "or",
+ fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
+ }
+ },
+ highlight: {
+ pre_tags: [''],
+ post_tags: [' '],
+ fields: {
+ login: {},
+ firstname: {},
+ lastname: {},
+ title:{},
+ name:{},
+ description:{},
+ filename:{},
+ subject:{},
+ content:{}
+ }
+ }
+ },[User,Syllabus,Course,Attachment,Project,Memo] ).page(page).per(20).results
+
+ end
+
+
+
+ # search_type = params[:search_type].to_sym unless search_condition.blank?
+ # search_by = params[:search_by]
+ #
+ # if search_type.nil? && params[:contests_search] && params[:name] != ""
+ # search_type = :contests
+ # search_condition = params[:name]
+ # end
+
+ respond_to do |format|
+ format.js
+ format.html{ render :layout=>'users_base'}
+ end
+ end
+
+ private
+ # 判断网站的入口,是课程 course 则跳过index去渲染 course 方法
+ def entry_select
+ # url = request.original_url.gsub('/','')
+ # if url.include?(Setting.url_course.gsub('/',''))
+ # if @first_page.show_course == 1
+ # course
+ # render :course
+ # else
+ # render_404
+ # end
+ #
+ # return 0
+ # elsif url.include?(Setting.url_contest.gsub('/',''))
+ # if @first_page.show_contest == 1
+ # contest
+ # render :contest
+ # else
+ # render_404
+ # end
+ #
+ # return 0
+ # elsif url.include?(Setting.url_user.gsub('/',''))
+ # #redirect_to(:controller => "users", :action => "index")
+ # end
+
+
+ end
+
+ # def render(*args)
+ # _fake if @fake_filter
+ # super
+ # end
+
+ # private
+
+ # def fake
+ # @fake_filter = true
+ # end
+
+ # # 骗子方法
+ # def _fake
+ # instance_variables.map { |variable|
+ # if variable.to_s =~ /Count$/
+ # self.instance_variable_set(variable.to_sym,
+ # ("1" + (self.instance_variable_get(variable.to_sym).to_s)).to_i)
+ # end
+ # }
+ # end
+
+end
diff --git a/app/controllers/words_controller.rb b/app/controllers/words_controller.rb
index f8d1290f4..49b006460 100644
--- a/app/controllers/words_controller.rb
+++ b/app/controllers/words_controller.rb
@@ -342,23 +342,23 @@ class WordsController < ApplicationController
def leave_homework_message
if User.current.logged?
@user = User.current
- @homework_common = HomeworkCommon.find(params[:id]);
+ @homework = HomeworkCommon.find(params[:id]);
if params[:homework_message].size>0 && User.current.logged? && @user
- feedback = HomeworkCommon.add_homework_jour(@user, params[:homework_message], params[:id], @homework_common.id)
+ feedback = HomeworkCommon.add_homework_jour(@user, params[:homework_message], params[:id], @homework.id)
if (feedback.errors.empty?)
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,feedback[:id],OwnerTypeHelper::JOURNALSFORMESSAGE
end
- @homework_common.update_column('updated_at', Time.now)
- update_course_activity(@homework_common.class,@homework_common.id)
- update_user_activity(@homework_common.class,@homework_common.id)
- update_org_activity(@homework_common.class,@homework_common.id)
+ @homework.update_column('updated_at', Time.now)
+ update_course_activity(@homework.class,@homework.id)
+ update_user_activity(@homework.class,@homework.id)
+ update_org_activity(@homework.class,@homework.id)
respond_to do |format|
format.js{
@user_activity_id = params[:user_activity_id].to_i
@hw_status = params[:hw_status].to_i if params[:hw_status]
- @is_teacher = User.current.allowed_to?(:as_teacher, @homework_common.course) || User.current.admin?
+ @is_teacher = User.current.allowed_to?(:as_teacher, @homework.course) || User.current.admin?
}
end
else
@@ -375,7 +375,7 @@ class WordsController < ApplicationController
if User.current.logged?
@user = User.current
reply = JournalsForMessage.find params[:id].to_i
- @homework_common = HomeworkCommon.find reply.jour_id
+ @homework = HomeworkCommon.find reply.jour_id
if params[:reply_message].size>0 && User.current.logged? && @user
options = {:notes => params[:reply_message], :reply_id => reply.user_id,:user_id => @user.id,:m_parent_id => params[:id].to_i,:m_reply_id => params[:id].to_i, :root_id => reply.root_id}
feedback = HomeworkCommon.add_homework_jour(@user, params[:reply_message], reply.jour_id, reply.root_id, options)
@@ -384,15 +384,15 @@ class WordsController < ApplicationController
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,feedback[:id],OwnerTypeHelper::JOURNALSFORMESSAGE
end
- @homework_common.update_column('updated_at', Time.now)
- update_course_activity(@homework_common.class,@homework_common.id)
- update_user_activity(@homework_common.class,@homework_common.id)
- update_org_activity(@homework_common.class,@homework_common.id)
+ @homework.update_column('updated_at', Time.now)
+ update_course_activity(@homework.class,@homework.id)
+ update_user_activity(@homework.class,@homework.id)
+ update_org_activity(@homework.class,@homework.id)
respond_to do |format|
format.js{
@user_activity_id = params[:user_activity_id].to_i
@hw_status = params[:hw_status].to_i if params[:hw_status]
- @is_teacher = User.current.allowed_to?(:as_teacher, @homework_common.course) || User.current.admin?
+ @is_teacher = User.current.allowed_to?(:as_teacher, @homework.course) || User.current.admin?
}
end
else
@@ -514,8 +514,19 @@ class WordsController < ApplicationController
if params[:text].size>0 && @user
# @user.add_jour(me, params[:text])
#私信
+ if params[:shixun_name]
+ game_id = params[:game_id]
+ message = params[:text]
+ admin_id = User.where(:admin => 1).first.try(:id)
+ user_ids = [admin_id, params[:shixun_author_id].to_i]
+ user_ids.each do |user_id|
+ JournalsForMessage.create(:jour_id => game_id, :jour_type => "Game", :user_id => user_id, :notes => message, :reply_id => 0, :status => true, :is_readed => false, :private => 1)
+ end
+ else
message = "【未收到激活邮件的用户反馈,用户邮箱:"+me.mail+"】 "+params[:text]
@user.journals_for_messages << JournalsForMessage.new(:user_id => me.id, :notes => message, :reply_id => 0, :status => true, :is_readed => false, :private => 1)
+ end
+
else
status = 0
end
@@ -524,6 +535,7 @@ class WordsController < ApplicationController
render_403
end
end
+
private
diff --git a/app/helpers/api_helper.rb b/app/helpers/api_helper.rb
index f322fdb8c..119c3c920 100644
--- a/app/helpers/api_helper.rb
+++ b/app/helpers/api_helper.rb
@@ -205,6 +205,45 @@ module ApiHelper
end
+ # 获取当前时间
+ def time_from_future time
+ lastUpdateTime = time.to_i*1000
+
+ currentTime = Time.now.to_i*1000
+ timePassed = lastUpdateTime - currentTime;
+ timeIntoFormat = 0
+ updateAtValue = ""
+ if timePassed < 0
+ updateAtValue = "马上"
+ elsif timePassed < ONE_MINUTE
+ updateAtValue = "1分钟"
+ elsif timePassed < ONE_HOUR
+ timeIntoFormat = timePassed / ONE_MINUTE
+ updateAtValue = timeIntoFormat.to_s + "分钟"
+ elsif (timePassed < ONE_DAY)
+ timeIntoFormat = timePassed / ONE_HOUR
+ updateAtValue = timeIntoFormat.to_s + "小时"
+ elsif (timePassed < ONE_MONTH)
+ timeIntoFormat = timePassed / ONE_DAY
+ updateAtValue = timeIntoFormat.to_s + "天"
+ elsif (timePassed < ONE_YEAR)
+ timeIntoFormat = timePassed / ONE_MONTH
+ updateAtValue = timeIntoFormat.to_s + "个月"
+ else
+ timeIntoFormat = timePassed / ONE_YEAR
+ updateAtValue = timeIntoFormat.to_s + "年"
+ end
+ updateAtValue
+ end
+
+ # 计算到结束还有多长时间 **天**小时**分
+ def how_much_time time
+ result = ""
+ result = ((time - Time.now.to_i).to_i / (24*60*60)).to_s + " 天 "
+ result += (((time - Time.now.to_i).to_i % (24*60*60)) / (60*60)).to_s + " 小时 "
+ result += ((((time - Time.now.to_i).to_i % (24*60*60)) % (60*60)) / 60).to_s + " 分 "
+ end
+
#日期转换为时间
def convert_to_time date, num
if num == 0
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index e9de11325..96c4e3683 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -33,6 +33,226 @@ module ApplicationHelper
extend Forwardable
def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
+ # 作品列表的提交状态
+ def list_work_status status
+ case status
+ when 0
+ str = "未提交"
+ when 1
+ str = "按时提交 "
+ when 2
+ str = "延时提交 "
+ end
+ end
+
+
+ # 判断TPM的代码是否被修改了
+ def tpm_is_modified myshixun, shixun_gpid
+ g = Gitlab.client
+ myshixun_commit_id = myshixun.commit_id
+ if myshixun_commit_id.blank?
+ myshixun_commit_id = g.commits(myshixun.gpid).last.try(:id)
+ myshixun.update_column(:commit_id, myshixun_commit_id)
+ end
+ shixun_commit_id = g.commits(shixun_gpid).first.try(:id)
+ result = myshixun_commit_id != shixun_commit_id ? true :false
+ return result
+ end
+
+ # 定义当前关卡是否有权开启下一关
+ # :实训若发布了,必须通过当前关卡才能查看下一关
+ # :未发布的实训,除了最后一关,其它的关卡都可以进入下一关
+ def show_next_stage?(game, shixun_status)
+ if game.is_final_game? || ([2,3].include?(shixun_status.to_i) && game.try(:status) != 2)
+ false
+ else
+ true
+ end
+ end
+
+ # 适用与已经用url_safe编码后,回调字符串形式
+ def tran_base64_decode64 str
+ if str.blank?
+ str
+ else
+ Base64.decode64(str.tr("-_", "+/")).force_encoding("utf-8")
+ end
+ end
+
+ def open_webssh
+ # 如果我webssh类型, 开启webssh
+ jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
+ uri = URI("#{jenkins_shixuns}/jenkins-exec/webssh/getConnectInfo")
+ user_id = User.current.id
+ params = {userID:user_id}
+ res = uri_exec uri, params
+ return [host, port, username, password]
+ end
+
+ # 中间层启动那种语言容器的类型
+ # language 语言 exec_path 需要编译的文件路径
+ def post_tomcat_language language, exec_path
+ if language == "Html" && !exec_path.blank?
+ case exec_path.split(".")[1].downcase
+ when "c"
+ "C"
+ when "cpp"
+ 'C++'
+ when "py"
+ 'Python2.7'
+ else
+ "Java"
+ end
+ elsif exec_path.blank?
+ "Java"
+ else
+ language
+ end
+ end
+
+ # 若实训有更改,则修改已发不实训的标记为已更改
+ # shixun_modifies表中1表示已更改,进入myshixun需要强制重置,0表示没有修改
+ # type 0:表示已经是最新的了;1:表示已经有修改
+ # res返回结果0表示正确,-1表示有异常
+ def add_shixun_modify_status shixun, type
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ # 更新测试集
+ gameInfo = shixun.gameInfo
+ uri ="#{shixun_tomcat}/bridge/game/publishGame"
+ # 更新脚本
+ tpiList =[]
+ myshixuns = shixun.myshixuns
+ if myshixuns.present?
+ myshixuns.each do |myshixun|
+ logger.info("tpiID is #{myshixun.id}")
+ tpiID = myshixun.id
+ instanceGitURL = git_myshixun_url_ip(myshixun, myshixun.try(:user_id))
+ logger.info("instanceGitURL is #{instanceGitURL}")
+ tpiList << {:tpiID => tpiID, :instanceGitURL => instanceGitURL}
+ logger.info("###############{tpiList.to_json unless tpiList.blank?}")
+ end
+ end
+ tpiList = Base64.urlsafe_encode64(tpiList.to_json) unless tpiList.blank?
+ params = {:gameInfo => "#{gameInfo}", :tpiList => "#{tpiList}" }
+ logger.info("%%%%%%%%%%%%params is #{params}")
+ # end
+ res = uri_exec uri, params
+ if res && res['code'].to_i != 0
+ raise("实训云平台繁忙(繁忙等级:90)")
+ end
+ shixun_modify_status_without_publish shixun, type
+ end
+
+ def shixun_modify_status_publish shixun, type
+ shixun_tomcat = Redmine::Configuration['shixun_tomcat']
+ # 更新测试集
+ gameInfo = shixun.gameInfo
+ uri ="#{shixun_tomcat}/bridge/game/publishGame"
+ # 更新脚本
+ tpiList =[]
+ myshixuns = shixun.myshixuns
+ if myshixuns.present?
+ myshixuns.each do |myshixun|
+ logger.info("tpiID is #{myshixun.id}")
+ tpiID = myshixun.id
+ instanceGitURL = git_myshixun_url_ip(myshixun, myshixun.try(:user_id))
+ logger.info("instanceGitURL is #{instanceGitURL}")
+ tpiList << {:tpiID => tpiID, :instanceGitURL => instanceGitURL}
+ logger.info("###############{tpiList.to_json unless tpiList.blank?}")
+ end
+ end
+ tpiList = Base64.urlsafe_encode64(tpiList.to_json) unless tpiList.blank?
+ params = {:gameInfo => "#{gameInfo}", :tpiList => "#{tpiList}" }
+ logger.info("%%%%%%%%%%%%params is #{params}")
+ # end
+ res = uri_exec uri, params
+ if res && res['code'].to_i != 0
+ raise("实训云平台繁忙(繁忙等级:90)")
+ end
+ end
+
+ # 仅仅产生记录,用于已执行publish的方法
+ # ShixunModify中status 1:表示有更改,开启实训的时候需要重置,0:表示不需要重置或已重置完成
+ def shixun_modify_status_without_publish shixun, type
+ myshixuns = shixun.myshixuns
+ unless myshixuns.blank?
+ myshixuns.each do |myshixun|
+ shixun_modify = ShixunModify.where(:shixun_id => shixun.id, :myshixun_id => myshixun.id).first
+ if shixun_modify.nil?
+ ShixunModify.create!(:shixun_id => shixun.id, :myshixun_id => myshixun.id, :status => type)
+ else
+ shixun_modify.update_attributes!(:status => type)
+ end
+ end
+ end
+ end
+
+ # 通关后,把最后一次成功的代码存到数据库
+ # type 0 创始内容, 1 最新内容
+ def game_passed_code game_id, path, myshixun_gpid, type
+ g = Gitlab.client
+ rev = rev.nil? ? "master" : rev
+ file_content = g.files(myshixun_gpid, path, rev).content
+ if file_content.blank?
+ # gitlab缺陷:forked完成,短暂时间内取不了内容的,所以做一个小轮询,间隔0.1秒
+ # 超过2秒则失败,需通过页面刷新
+ for i in 0..30 do
+ sleep(0.1)
+ file_content = g.files(myshixun_gpid, path, rev).content
+ unless file_content.blank?
+ break
+ end
+ end
+ end
+ file_content = tran_base64_decode64(file_content)
+ game_code = GameCode.where(:game_id => game_id).first
+ if game_code.nil?
+ if type == 0
+ GameCode.create!(:game_id => game_id, :original_code => file_content, :path => path)
+ else
+ # 这种情况正常是不会出现的,因为没创建成功抛异常,之所以这样写为了防止异常没处理的问题
+ GameCode.create!(:game_id => game_id, :original_code => file_content, :new_code => file_content, :path => path)
+ end
+ else
+ game_code.update_attribute(:new_code, file_content)
+ end
+ end
+
+ # 判断用户是否认证
+ def check_authentication
+ # return true
+ # if params[:action] == "on_search" || params[:action] == "apply_trail" # 之所以这样处理是为了避开account页面ajax加载
+ # return true
+ # end
+ authentication = User.where(:id => User.current.id, :certification => 1).first
+ user_identity = User.current.try(:user_extensions).try(:identity)
+ if user_identity.blank? || authentication.blank?
+ redirect_to my_account_path
+ return
+ end
+ end
+
+ def match_specific_symbol(str)
+ str.gsub(" ", " ").gsub(/\r\n$/, " ").gsub("\r\n", " ").gsub(/\t/, " ").html_safe
+ end
+
+ # 积分表中建立记录行为,有过奖励则不重复奖励
+ def reward_grade(user, container_id, container_type, score)
+ grade = Grade.where(:user_id => user.id, :container_id => container_id, :container_type => container_type).first
+ if grade.nil?
+ Grade.create!(:user_id => user.id, :container_id => container_id, :container_type => container_type, :score => score)
+ user.update_column(:grade, (score.to_i + user.grade.to_i))
+ end
+ end
+
+ def reward_experience(user, container_id, container_type, score)
+ experience = Experience.where(:user_id => user.id, :container_id => container_id, :container_type => container_type).first
+ if experience.nil?
+ Experience.create!(:user_id => user.id, :container_id => container_id, :container_type => container_type, :score => score)
+ user.update_column(:experience, (score.to_i + user.experience.to_i))
+ end
+ end
+
# codeMirror语言转换
def language_switch language
case language
@@ -49,7 +269,120 @@ module ApplicationHelper
end
end
+ # 实训语言的种类
+ def shixun_language
+ ["Java", "C", "C++", "Python2.7", "Python3.6", "MySQL/Java", "Html", "JFinal", "Docker", "Ethereum", "Dynamips", "MachineLearning", "Verilog","Spark","MySQL/Python3.6","PHP","PHP/Web"]
+ end
+
+ # 实训试用专业
+ def shixun_major_option
+ content = []
+ content << ["选择实训适用的专业", 0]
+ content << ["计算机科学与技术", 635]
+ content << ["软件工程", 636]
+ content << ["网络工程", 637]
+ content << ["信息安全", 638]
+ content << ["物联网工程", 639]
+ content << ["信息工程", 622]
+ content << ["通信工程", 619]
+ end
+
+ # 实训面向学员
+ def shixun_trainee
+ content = []
+ content << ["初级学员", 1]
+ content << ["中级学员", 2]
+ content << ["高级学员", 3]
+ content << ["顶级学员", 4]
+ end
+
+ # 班级设置排序中文
+ def switch_to_chinese word
+ case word
+ when "boards"
+ result = "讨论区"
+ when "news"
+ result = "通知"
+ when "homework"
+ result = "作业"
+ when "exercises"
+ result = "试卷"
+ when "poll"
+ result = "问卷"
+ when "statistics"
+ result = "统计"
+ when "attachment"
+ result ="资源"
+ end
+ return result
+ end
+
+ def allow_to_view_challenge challenge, shixun
+ # 判断对应关卡的game是否开启,如果开启则允许查看
+ game_count = Game.where(:challenge_id => challenge, :user_id => User.current, :status => [0,1,2]).count
+ if game_count > 0
+ return true
+ else
+ return false
+ end
+ end
+
+ # 已通过的关卡数
+ def had_passed_changllenge_count shixun, user
+ myshixun = Myshixun.where(:shixun_id => shixun.id, :user_id => user.id).first
+ if myshixun.nil?
+ 0
+ elsif 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 == 2}.count + 1]
+ else
+ myshixun.games.select{|game| game.status == 2}.count
+ end
+ end
+
+ # 已通过的关卡数 返回int类型(包含查看参考答案的)
+ def had_passed_changllenge_num shixun, user
+ myshixun = Myshixun.where(:shixun_id => shixun.id, :user_id => user.id).first
+ if myshixun.nil?
+ 0
+ else
+ myshixun.games.select{|game| game.status == 2}.count
+ end
+ end
+
+ # 已通过的关卡数 返回int类型(未查看参考答案)
+ def had_passed_no_ans_changllenge_num shixun, user
+ myshixun = Myshixun.where(:shixun_id => shixun.id, :user_id => user.id).first
+ if myshixun.nil?
+ 0
+ else
+ myshixun.games.select{|game| game.status == 2 && !game.answer_open}.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)
+ end
+
+ # 获取某个myshixun的得分
+ def sum_myshixun_score myshixun_id
+ Game.find_by_sql("SELECT sum(final_score) as total_score FROM `games` where myshixun_id=#{myshixun_id}").first.try(:total_score)
+ end
+
# myshixun 最高分
def top_score shixun, position
Game.find_by_sql("SELECT max(final_score) as top_score FROM `games` g, `challenges` c where g.challenge_id = c.id and c.position=#{position} and g.myshixun_id in (SELECT id FROM `myshixuns` ms where ms.shixun_id=#{shixun.id})").first.try(:top_score)
@@ -75,13 +408,6 @@ module ApplicationHelper
Game.find_by_sql("SELECT * FROM `outputs` op, `games` g, `myshixuns` m where op.game_id = g.id and g.stage='#{position}' and m.parent_id = '#{shixun.id}';")
end
-
-
- # 平均耗时
- def shixun_avg
-
- end
-
# 平均耗时
def game_avg_day created_at, updated_at
time = (updated_at - created_at).to_i
@@ -102,29 +428,37 @@ module ApplicationHelper
# 耗时:天、小时、分
# 小于1分钟则不显示
- def game_spend_time start_time, end_time
- time = (end_time - start_time).to_i
+ def game_spend_time time
day = time / 86400
hour = time % (24*60*60) / (60*60)
min = time % (24*60*60) % (60*60) / 60
+ sec = time % (24*60*60) % (60*60) % 60
if day < 1
if hour < 1
- if time < 1
- time = time == 0 ? "--" : "小于1分钟"
+ if min < 1
+ if sec < 1
+ time = "--"
+ else
+ time = "#{sec}秒"
+ end
else
- time = "#{min} 分钟"
+ time = "#{min}分钟 #{sec}秒"
end
else
- time = "#{hour}小时 : #{min}分"
+ time = "#{hour}小时 #{min}分钟 #{sec}秒"
end
else
- time = "#{day}天 : #{hour}小时 : #{min}分"
+ time = "#{day}天 #{hour}小时 #{min}分钟 #{sec}秒"
end
return time
end
+ def consume_time time
+ time.strftime('%Y/%m/%d %H:%M:%S')
+ end
+
def avg_spend_time shixun_id, position
- Game.find_by_sql("SELECT avg(g.updated_at - g.created_at) as avg_time FROM `games` g, `challenges` c where c.id=g.challenge_id and g.status =2 and c.position = #{position} and g.myshixun_id in (SELECT id FROM `myshixuns` where shixun_id= #{shixun_id});").first.try(:avg_time).to_i
+ Game.find_by_sql("SELECT avg(g.end_time - g.open_time) as avg_time FROM `games` g, `challenges` c where c.id=g.challenge_id and g.status =2 and c.position = #{position} and g.myshixun_id in (SELECT id FROM `myshixuns` where shixun_id= #{shixun_id});").first.try(:avg_time).to_i
end
# 已闯关
@@ -180,11 +514,198 @@ module ApplicationHelper
gitUrl = gitlab_address.to_s+"/"+project.owner.to_s+"/"+ rep_identify + "."+"git"
end
+ def git_shixun_url shixun, login
+ rep_identify = Repository.where(:shixun_id => shixun.id, :type => "Repository::Gitlab").first.try(:identifier)
+ gitlab_address = Redmine::Configuration['gitlab_address']
+ gitUrl = gitlab_address.to_s+"/"+login+"/"+ rep_identify + "."+"git"
+ end
+
+ def git_shixun_url_ip shixun, login
+ rep_identify = Repository.where(:shixun_id => shixun.id, :type => "Repository::Gitlab").first.try(:identifier)
+ gitlab_address = Redmine::Configuration['gitlab_address_ip']
+ gitUrl = gitlab_address.to_s+"/"+login+"/"+ rep_identify + "."+"git"
+ end
+
+ def git_myshixun_url_ip myshixun, user_id
+ login = User.where(:id => user_id).first.try(:login)
+ rep_identify = Repository.where(:myshixun_id => myshixun.id, :type => "Repository::Gitlab").first.try(:identifier)
+ gitlab_address = Redmine::Configuration['gitlab_address_ip']
+ gitUrl = gitlab_address.to_s+"/"+login+"/"+ rep_identify + "."+"git"
+ end
+
+ # myshixun git url by domain
+ def git_myshixun_url myshixun, user_id
+ login = User.where(:id => user_id).first.try(:login)
+ rep_identify = Repository.where(:myshixun_id => myshixun.id, :type => "Repository::Gitlab").first.try(:identifier)
+ gitlab_address = Redmine::Configuration['gitlab_address']
+ gitUrl = gitlab_address.to_s+"/"+login+"/"+ rep_identify + "."+"git"
+ end
+
def uri_exec uri, params
- res = Net::HTTP.post_form(uri, params).body
+ begin
+ logger.error("@parmas is #{params}, url is #{uri}")
+ uri = URI.parse(URI.encode(uri.strip))
+ res = Net::HTTP.post_form(uri, params).body
+ res = JSON.parse(res)
+ rescue => e
+ logger.error("failed to create challenge by 'generatePipelineScriptForChallenge'! #{e}")
+ raise("实训云平台繁忙(繁忙等级:84)")
+ end
+ end
+
+ def uri_json_exec uri, params
+ Net::HTTP.start(uri.hostname, uri.port) {|http|
+ http.post(uri.path, params.to_json)
+ }
+
+ http = Net::HTTP.new(uri.host, uri.port)
+ res = Net::HTTP.post(uri, params.to_json).body
res = JSON.parse(res)
end
+ def last_reply_time container_id
+ message = Message.where(:root_id => container_id).order("created_on desc").first
+ time = message.created_on
+ return time
+ end
+
+ def judge_Chinese_num str
+ cn_reg = /[\u4e00-\u9fa5]{1}/
+ cn_number = str.scan(cn_reg).size
+ en_number = str.size - cn_number
+ size = 1.9* cn_number + en_number
+ end
+
+ # homework_common状态
+ # 0:挂起;1:提交中;2:匿评中;3:评阅中
+ def new_homework_common_status status
+ case status
+ when 0
+ "未发布"
+ when 1
+ "提交中"
+ when 2
+ "补交中"
+ when 3
+ "匿评中"
+ when 4
+ "申诉中"
+ when 5
+ "评阅中"
+ when 6
+ "已结束"
+ end
+ end
+
+ # 作业不同状态的不同样式
+ def homework_status_color status
+ style = ""
+ case status
+ when '未发布'
+ style = 'edu-filter-btn-yellow'
+ when '提交中'
+ style = 'edu-filter-btn-blue'
+ when '补交中'
+ style = 'edu-filter-btn-orange'
+ when '匿评中'
+ style = 'edu-filter-btn-green'
+ when '申诉中'
+ style = 'edu-filter-btn-red'
+ when '评阅中'
+ style = 'edu-filter-btn-green'
+ when '已结束', '已截止'
+ style = 'edu-filter-btn-end'
+ when '已开启补交'
+ style = 'edu-filter-btn-late'
+ when '未开启补交'
+ style = 'edu-filter-btn-no-late'
+ end
+ end
+
+ # 判断作业有多少人提交了
+ #
+ def had_commit_studentwork_count homework_common
+ StudentWork.where("work_status !=? and homework_common_id=? and is_delete = 0",0, homework_common.id).count
+ end
+
+ # 未提交作品数统计
+ def had_uncommit_studentwork_count homework_common
+ homework_common.course.student.count - homework_common.student_works.where("work_status !=?", 0).count
+ end
+
+ # 未评阅
+ def had_unevaluate_count homework_common
+ #count = StudentWorksScore.find_by_sql("SELECT count(distinct student_work_id) as count FROM student_works_scores sws, student_works sw, homework_commons hc where hc.id =#{homework_common.id} and sw.homework_common_id=hc.id and sw.is_delete = 0 and sws.student_work_id = sw.id and sws.user_id=#{User.current.id};").first.try(:count).to_i
+ has_comment = User.current.student_works_scores.where(:student_work_id => homework_common.student_works.map(&:id), :reviewer_role => [1, 2]).group_by(&:student_work_id).count
+ student_count = homework_common.student_works.count
+ return student_count - has_comment
+ end
+
+ # 该阶段还有多长时间结束/距下一阶段还有多长时间
+ def homework_curr_time homework_common
+ result = {}
+ status = ""
+ time = ""
+ ho_detail_manual = homework_common.homework_detail_manual
+ if ho_detail_manual
+ case ho_detail_manual.comment_status
+ when 0
+ status = "未发布"
+ when 1
+ if homework_common.end_time && homework_common.end_time >= Time.now
+ status = "提交中"
+ time = how_much_time(homework_common.end_time)
+ end
+ when 3
+ if ho_detail_manual.evaluation_end && ho_detail_manual.evaluation_end > Time.now
+ status = "匿评中"
+ time = how_much_time(ho_detail_manual.evaluation_end)
+ end
+ when 4
+ if ho_detail_manual.appeal_time && ho_detail_manual.appeal_time > Time.now
+ status = "申诉中"
+ time = how_much_time(ho_detail_manual.appeal_time)
+ end
+ when 5
+ if homework_common.archive_time && homework_common.archive_time > Time.now
+ status = "评阅中"
+ time = how_much_time(homework_common.archive_time)
+ end
+ when 6
+ status = "已结束"
+ time = format_time homework_common.archive_time
+ end
+ end
+ if status == "" && homework_common.allow_late && homework_common.archive_time > Time.now
+ time = how_much_time homework_common.archive_time
+ end
+ result[:status] = status
+ result[:time] = time
+ result
+ end
+
+ # 试卷:该阶段还有多长时间结束/距下一阶段还有多长时间
+ def exercise_curr_time exercise
+ result = {}
+ status = ""
+ time = ""
+ case exercise.exercise_status
+ when 1
+ status = "未发布"
+ when 2
+ if exercise.end_time && exercise.end_time >= Time.now
+ status = "提交中"
+ time = how_much_time(exercise.end_time)
+ end
+ when 3
+ status = "已截止"
+ time = format_time exercise.end_time
+ end
+ result[:status] = status
+ result[:time] = time
+ result
+ end
+
# 公共分页
def paginator_list objs, objs_count, limit, is_remote
@is_remote = is_remote
@@ -245,6 +766,17 @@ module ApplicationHelper
course.homework_commons.select{|hc| hc.score_open == 0}.count > 0 ? true : false
end
+ def welcome_course_message_count course_id
+ board_id = Board.where(:course_id => course_id).first.try(:id)
+ message_count = Message.where(:board_id => board_id).count
+ return message_count
+ end
+
+ # 可以查看到资源库的资源
+ def welcome_course_file_count course
+ course.attachments.count
+ end
+
# 隐藏项目以外的信息
# return: true 显示,false 不显示
def hidden_unproject_infos
@@ -275,8 +807,28 @@ module ApplicationHelper
Myshixun.where(:user_id => User.current.id, :shixun_id => shixun.id).count > 0 ? true : false
end
+ # 用户必须登录;必须创建了关卡;有实践任务的必须提交了版本库代码
def allow_shixun_exec shixun
- (User.current.logged? && User.current.id != shixun.user_id && shixun.status == 1)
+ g = Gitlab.client
+ result = User.current.logged? && shixun.challenges.count > 0
+ if shixun.challenges.where(:st => 0).count > 0
+ result = result && g.trees(shixun.gpid).count.to_i > 0
+ end
+ result
+ end
+
+ # 判断当前用户是否可以开始实战
+ def link_to_shixun_exec myshixun, shixun, str
+ is_modify = ShixunModify.where(:myshixun_id => myshixun.try(:id), :shixun_id => shixun.try(:id), :status => 1).first.blank?
+ if User.current.mail.blank?
+ link_to str, "javascript:void(0);", :onclick => "notice_box_redirect('#{security_settings_path}', '开启实训,请先绑定邮箱')", :class => "fr shixun-task-btn task-btn-orange mr15", :target => "_blank"
+ else
+ if is_modify || myshixun.blank?
+ link_to str, shixun_exec_shixun_path(shixun), :class => "fr shixun-task-btn task-btn-orange mr15", :target => "_blank"
+ else
+ link_to str, "javascript:void(0);", :onclick => "sure_box_redirect('#{myshixun_reset_myshixun_path(myshixun)}', '实训已经更新啦,系统正在为您重置')", :class => "fr shixun-task-btn task-btn-orange mr15"
+ end
+ end
end
# 通过系统外部邮箱查找用户,如果用户不存在则用邮箱替换
@@ -329,6 +881,14 @@ module ApplicationHelper
super
end
+ # 重置user_path,目的是将id转换成用户名
+ # def shixun_path(resource, parameters = {})
+ # if Fixnum === resource
+ # resource = Shixun.find(resource)
+ # end
+ # super
+ # end
+
# 历史数据(老版本库数据)处理完则可以修改该放放
def get_rep_identifier_by_project project
identifier = Repository.where(:project_id => project.id, :type => "Repository::Gitlab").first.try(:identifier)
@@ -371,7 +931,7 @@ module ApplicationHelper
end
# 项目issue列表导出Excel功能
- def issue_list_xls issues
+ def issue_list_xls issues
xls_report = StringIO.new
book = Spreadsheet::Workbook.new
sheet1 = book.create_worksheet :name => "issues"
@@ -485,7 +1045,7 @@ module ApplicationHelper
score = obj.issue_num * 4 + obj.issue_journal_num + (obj.changeset_num||0) * 4 + obj.board_num * 2 + obj.board_message_num + obj.attach_num * 5
end
- # 获取组织成员中文名字
+ # 获取组织成员中文名字
def get_org_member_role_name member
unless member.roles[0].nil?
case member.roles[0].name
@@ -695,7 +1255,7 @@ module ApplicationHelper
name = h(user.name(options[:format]))
else
name = h(user.show_name)
- end
+ end
link_to name, {:controller=> 'users', :action => 'show', id: user.id, host: Setting.host_user}, :class => "pro_info_p"
else
h(user.to_s)
@@ -1098,7 +1658,7 @@ module ApplicationHelper
def render_flash_messages
s = ''
flash.each do |k,v|
- s << content_tag('div', v.html_safe, :class => "flash #{k}", :id => "flash_#{k}")
+ s << content_tag('div', v.html_safe, :class => "alert alert-orange mb15 mt15", :id => "flash_#{k}")
end
s.html_safe
end
@@ -1302,7 +1862,7 @@ module ApplicationHelper
def authority_pubilic_for_files(project, file)
@result = false
if (is_project_manager?(User.current.id, @project.id) && User.current.allowed_to?(:manage_files, project)) || file.author_id == User.current.id || User.current.admin &&
- project_contains_attachment?(project,file) && file.container_id == project.id && file.container_type == "Project"
+ project_contains_attachment?(project,file) && file.container_id == project.id && file.container_type == "Project"
@result = true
end
return @result
@@ -1547,22 +2107,40 @@ module ApplicationHelper
if args.empty?
title = @html_title || []
if @project
- title << (@project.name.nil? ? "让创新更美好" : @project.name)
+ title << (@project.name.nil? ? "创新源于实践" : @project.name)
elsif @welcome
- title << "高校教育大数据服务平台"
+ 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 << ("在线课堂")
elsif @contest
- title << (@contest.name.nil? ? "让创新更美好" : @contest.name)
+ title << (@contest.name.nil? ? "创新源于实践" : @contest.name)
+ elsif @shixun
+ title << (@shixun.name.nil? ? "全部实训" : @shixun.name)
+ elsif @my_shixun
+ title << ("我的实训")
+ elsif params[:controller] == "shixuns" && params[:action] == "index"
+ title << ("全部实训")
+ elsif @subject
+ title << (@subject.name.nil? ? "实训路径" : @subject.name)
+ elsif params[:controller] == "subjects" && params[:action] == "index"
+ title << ("实训路径")
elsif @organization
- title << (@organization.name.nil? ? "让创新更美好" : @organization.name)
+ title << (@organization.name.nil? ? "创新源于实践" : @organization.name)
elsif @forum || params[:controller] == "forums"
- title << "问吧"
+ title << "论坛"
+ elsif @my_syllabuses
+ title << "我的课堂"
elsif @user
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?
@@ -1574,12 +2152,12 @@ module ApplicationHelper
elsif !@receive_homeworks.blank?
title << @receive_homeworks
else
- title << @user.try(:realname)
+ title << @user.show_name
end
elsif @syllabus
- title << @syllabus.title
+ title << (@syllabus.title.nil? ? "在线课堂" : @syllabus.title)
else
- title << (User.current.id == 2 ? "未登录" : User.current.try(:realname))
+ title << (User.current.id == 2 ? "未登录" : User.current.show_name)
end
# if first_page.nil? || first_page.web_title.nil?
# title << Setting.app_title unless Setting.app_title == title.last
@@ -2220,6 +2798,19 @@ module ApplicationHelper
link_to l(:button_delete), url, options
end
+ def update_status_link(user)
+ url = {:controller => 'users', :action => 'update', :id => user, :page => params[:page], :status => params[:status], :tab => nil}
+
+ if user.locked?
+ link_to "解锁", url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :put, :class => 'mr10 link-color-blue'
+ elsif user.registered?
+ link_to "激活", url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :put, :class => 'mr10 link-color-blue'
+ elsif user != User.current
+ link_to "加锁", url.merge(:user => {:status => User::STATUS_LOCKED}), :method => :put, :class => 'mr10 link-color-blue'
+ end
+ end
+
+
def delete_version_link(url, options={})
options = {
:method => :delete,
@@ -2288,7 +2879,7 @@ module ApplicationHelper
def check_all_links(form_name)
link_to_function_none(l(:button_check_all), "checkAll('#{form_name}', true)") + " ".html_safe + " | "+ " ".html_safe +
- link_to_function_none(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
+ link_to_function_none(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
end
# 本次修改,修改为只显示关闭的所占%比
@@ -2302,8 +2893,8 @@ module ApplicationHelper
content_tag('span',
content_tag('tr',
(pcts[0] > 0 ? content_tag('span', '', :style => "width: #{pcts[0]}%;", :class => 'roadmap_progressbar_inner', :title => "已关闭:#{pcts[0]}%") : ''.html_safe) #+
- # (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done', :title => "开发中:#{pcts[1]}%") : ''.html_safe) +
- #(pcts[1] > 0 ? content_tag('span', '', :style => "width: #{pcts[1]}%;", :class => 'roadmap_progressbar ml5', :title => "未完成:#{pcts[1]}%") : ''.html_safe), :style => "width: #{width}"
+ # (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done', :title => "开发中:#{pcts[1]}%") : ''.html_safe) +
+ #(pcts[1] > 0 ? content_tag('span', '', :style => "width: #{pcts[1]}%;", :class => 'roadmap_progressbar ml5', :title => "未完成:#{pcts[1]}%") : ''.html_safe), :style => "width: #{width}"
), :class => 'roadmap_progressbar ml5').html_safe
# + content_tag('p', legend, :class => 'percent').html_safe
end
@@ -2442,11 +3033,11 @@ module ApplicationHelper
end
end
- if sources && !sources.empty?
- super(sources, options)
- else
- ''
- end
+ if sources && !sources.empty?
+ super(sources, options)
+ else
+ ''
+ end
end
def content_for(name, content = nil, &block)
@@ -2501,7 +3092,7 @@ module ApplicationHelper
# Returns the javascript tags that are included in the html layout head
def javascript_heads
- tags = javascript_include_tag('jquery-1.8.3-ui-1.9.2-ujs-2.0.3', 'application', 'jquery.colorbox-min')
+ tags = javascript_include_tag('jquery-1.8.3-ui-1.9.2-ujs-2.0.3', 'application', 'jquery.colorbox-min', 'baiduTemplate')
unless User.current.pref.warn_on_leaving_unsaved == '0'
tags << "\n".html_safe + javascript_tag("$(window).load(function(){ warnLeavingUnsaved('#{escape_javascript l(:text_warn_on_leaving_unsaved)}'); });")
end
@@ -2567,6 +3158,77 @@ module ApplicationHelper
end
# Endof Tao's code
+ # cxt
+ # 获取认证照片
+ def url_to_auth_img(user_id, type)
+ if File.exist?(disk_auth_filename("UserAuthentication",user_id,type))
+ File.join(relative_path,avatar_directory("UserAuthentication"), auth_filename(user_id,type))
+ else
+ File.join(relative_path,avatar_directory("UserAuthentication"),type)
+ end
+ end
+
+ def identity_authentication_status user
+ authorization = ApplyAction.where(:user_id => user, :container_type => "TrialAuthorization").last
+ case user.try(:certification)
+ when 0
+ if authorization.try(:status) == 0
+ "处理中"
+ else
+ "未授权"
+ end
+ when 1
+ "已授权"
+ when 2
+ "被拒绝"
+ end
+ end
+
+ def user_certification_status user
+ status = ""
+ if user.authentication
+ status = "已实名认证"
+ else
+ apply_auth = ApplyUserAuthentication.where(:user_id => user.id, :auth_type => 1).last
+ if apply_auth && apply_auth.status == 0
+ status = "实名认证中"
+ elsif apply_auth && apply_auth.status == 2
+ status = "实名认证未通过"
+ else
+ status = "未实名认证"
+ end
+ end
+ end
+
+ def pro_certification_status user
+ status = ""
+ if user.professional_certification
+ status = "已职业认证"
+ else
+ apply_auth = ApplyUserAuthentication.where(:user_id => user.id, :auth_type => 2).last
+ if apply_auth && apply_auth.status == 0
+ status = "职业认证中"
+ elsif apply_auth && apply_auth.status == 2
+ status = "职业认证未通过"
+ else
+ status = "未职业认证"
+ end
+ end
+ end
+
+ def shixun_authentication_status shixun
+ case shixun.try(:status)
+ when 0,nil
+ "编辑中"
+ when 1
+ "待审核"
+ when 2
+ "已发布"
+ when 3
+ "已关闭"
+ end
+ end
+
def date_format_local(time)
date = time.strftime("%Y年%m月%d日")
end
@@ -2652,6 +3314,32 @@ module ApplicationHelper
end
end
+ def resource_bank_candown resource,type
+ candown = false
+ if resource.is_public
+ candown = true
+ end
+ if type == 'syllabus'
+ candown = syllabus_course_member(User.current, resource.course) || User.current.admin?
+ end
+ candown
+ end
+
+ # 课程某个班级的成员
+ def syllabus_course_member user, course
+ result = false
+ syllabus = course.syllabus
+ if syllabus
+ syllabus.courses.each do |course|
+ if user.member_of_course?(course)
+ result = true
+ return result
+ end
+ end
+ end
+ result
+ end
+
def attachment_candown attachment
candown = false
if attachment.container
@@ -2713,6 +3401,10 @@ module ApplicationHelper
else
candown = (attachment.is_public == 1 || attachment.is_public == true)
end
+ else
+ if attachment.container_type == "Shixun"
+ candown = true
+ end
end
candown
end
@@ -3065,48 +3757,48 @@ module ApplicationHelper
def anonymous_comment_link(bid, course)
link = case bid.comment_status
- when 0
- confirm_info = "开启匿评后学生将不能对作品进行提交、修改、删除等操作\n"
- confirm_info += anonymous_comment_notice(bid,course)
- confirm_info += '是否确定开启匿评?'
- link_to '启动匿评', start_anonymous_comment_bid_path(bid), id: "#{bid.id}_start_anonymous_comment", remote: true, :confirm => confirm_info, disable_with: '加载中...'
- when 1
- confirm_info = "关闭匿评后所有同学将不能继续进行匿评,且将公开已提交作品列表\n"
- confirm_info += anonymous_comment_notice(bid,course)
- confirm_info += '是否确定关闭匿评?'
- link_to '关闭匿评', stop_anonymous_comment_bid_path(bid), id: "#{bid.id}_stop_anonymous_comment", remote: true, :confirm => confirm_info
- when 2
- '匿评结束'
- end
+ when 0
+ confirm_info = "开启匿评后学生将不能对作品进行提交、修改、删除等操作\n"
+ confirm_info += anonymous_comment_notice(bid,course)
+ confirm_info += '是否确定开启匿评?'
+ link_to '启动匿评', start_anonymous_comment_bid_path(bid), id: "#{bid.id}_start_anonymous_comment", remote: true, :confirm => confirm_info, disable_with: '加载中...'
+ when 1
+ confirm_info = "关闭匿评后所有同学将不能继续进行匿评,且将公开已提交作品列表\n"
+ confirm_info += anonymous_comment_notice(bid,course)
+ confirm_info += '是否确定关闭匿评?'
+ link_to '关闭匿评', stop_anonymous_comment_bid_path(bid), id: "#{bid.id}_stop_anonymous_comment", remote: true, :confirm => confirm_info
+ when 2
+ '匿评结束'
+ end
content_tag('span', link, id: "#{bid.id}_anonymous_comment")
end
def anonymous_comment_notice(bid, course)
- case bid.comment_status
- when 0
- @student_size ||= searchStudent(course).size
- @homework_size = bid.homeworks.size
- percent = @homework_size.to_f / (@student_size == 0 ? 1 : @student_size)
- confirm_info = "目前#{@student_size}个学生,总共提交了#{@homework_size}份作品,占#{number_to_percentage(percent * 100, precision: 1)}\n"
- when 1
- @homework_evaluations = 0
- bid.homeworks.map { |homework| @homework_evaluations += homework.homework_evaluations.count}
- teachers = "("
- teacher_members = searchTeacherAndAssistant(course)
- teacher_members.each do |member|
- if member == teacher_members.last
- teachers += member.user_id.to_s + ")"
- else
- teachers += member.user_id.to_s + ","
- end
- end
- @has_evaluations = 0
- bid.homeworks.map { |homework| @has_evaluations += homework.rates(:quality).where("seems_rateable_rates.rater_id not in #{teachers}").count}
+ case bid.comment_status
+ when 0
+ @student_size ||= searchStudent(course).size
+ @homework_size = bid.homeworks.size
+ percent = @homework_size.to_f / (@student_size == 0 ? 1 : @student_size)
+ confirm_info = "目前#{@student_size}个学生,总共提交了#{@homework_size}份作品,占#{number_to_percentage(percent * 100, precision: 1)}\n"
+ when 1
+ @homework_evaluations = 0
+ bid.homeworks.map { |homework| @homework_evaluations += homework.homework_evaluations.count}
+ teachers = "("
+ teacher_members = searchTeacherAndAssistant(course)
+ teacher_members.each do |member|
+ if member == teacher_members.last
+ teachers += member.user_id.to_s + ")"
+ else
+ teachers += member.user_id.to_s + ","
+ end
+ end
+ @has_evaluations = 0
+ bid.homeworks.map { |homework| @has_evaluations += homework.rates(:quality).where("seems_rateable_rates.rater_id not in #{teachers}").count}
- percent = @has_evaluations.to_f / (@homework_evaluations == 0 ? 1 : @homework_evaluations)
- confirm_info = "目前总共分配了#{@homework_evaluations}份匿评作品,已评价#{@has_evaluations}份作品,占#{number_to_percentage(percent * 100, precision: 1)}\n"
- end
- confirm_info
+ percent = @has_evaluations.to_f / (@homework_evaluations == 0 ? 1 : @homework_evaluations)
+ confirm_info = "目前总共分配了#{@homework_evaluations}份匿评作品,已评价#{@has_evaluations}份作品,占#{number_to_percentage(percent * 100, precision: 1)}\n"
+ end
+ confirm_info
end
def get_technical_title user
@@ -3242,12 +3934,12 @@ module ApplicationHelper
link = link_to "启动匿评","javascript:void(0)", :class => "wpostOptionLink", :title => "作业截止日期之前不可以启动匿评"
elsif homework.student_works.has_committed.count >= 2 && homework.homework_detail_manual#作业份数大于2
case homework.homework_detail_manual.comment_status
- when 1
- link = link_to '启动匿评', Setting.protocol + "://" + Setting.host_name + "/homework_common/" + homework.id.to_s + "/alert_anonymous_comment?hw_status=" + hw_status.to_s + "&user_activity_id=" + user_activity_id.to_s, id: "#{homework.id}_start_anonymous_comment", remote: true, disable_with: '加载中...',:class => 'wpostOptionLink'
- when 2
- link = link_to '关闭匿评', Setting.protocol + "://" + Setting.host_name + "/homework_common/" + homework.id.to_s + "/alert_anonymous_comment?hw_status=" + hw_status.to_s + "&user_activity_id=" + user_activity_id.to_s, id: "#{homework.id}_stop_anonymous_comment", remote: true,:class => 'wpostOptionLink'
- when 3
- # link = link_to "匿评结束","javascript:void(0)", :class => "postOptionLink", :title => "匿评结束"
+ when 1
+ link = link_to '启动匿评', Setting.protocol + "://" + Setting.host_name + "/homework_common/" + homework.id.to_s + "/alert_anonymous_comment?hw_status=" + hw_status.to_s + "&user_activity_id=" + user_activity_id.to_s, id: "#{homework.id}_start_anonymous_comment", remote: true, disable_with: '加载中...',:class => 'wpostOptionLink'
+ when 2
+ link = link_to '关闭匿评', Setting.protocol + "://" + Setting.host_name + "/homework_common/" + homework.id.to_s + "/alert_anonymous_comment?hw_status=" + hw_status.to_s + "&user_activity_id=" + user_activity_id.to_s, id: "#{homework.id}_stop_anonymous_comment", remote: true,:class => 'wpostOptionLink'
+ when 3
+ # link = link_to "匿评结束","javascript:void(0)", :class => "postOptionLink", :title => "匿评结束"
end
else
link = link_to "启动匿评","javascript:void(0)", :class => "wpostOptionLink", :title => "学生提交作业数大于等于2时才可以启动匿评"
@@ -3294,50 +3986,55 @@ module ApplicationHelper
if User.current.logged?
if User.current.member_of_course?(homework.course)
if is_teacher #老师显示作品数量
- link_to "作品(#{count})", student_work_index_url_in_org(homework.id, 2), :class => "c_blue"
+ link_to "作品 (#{count})".html_safe, student_work_index_url_in_org(homework.id, 2), :class => "c_blue homepagePostSubmit"
else #学生显示提交作品、修改作品等按钮
work = cur_user_works_for_homework homework
project = cur_user_projects_for_homework homework
- if work.nil? && homework.end_time >= Time.now
- if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
- link_to "提交作品(#{count})","javascript:void(0)", :class => 'c_grey',:style=>"cursor:not-allowed",:title => '请先关联项目再提交作品'
+ if homework.homework_type == 4
+ if work.nil?
+ link_to "开始实战(#{count})", shixun_path(homework.homework_commons_shixuns.shixun),:class => 'c_blue homepagePostSubmit',:target => "_blank"
else
- link_to "提交作品(#{count})", new_student_work_url_without_domain(homework.id),:class => 'c_blue'
+ myshixun = Myshixun.find work.myshixun_id
+ is_modify = ShixunModify.where(:myshixun_id => myshixun.try(:id), :shixun_id => myshixun.shixun.try(:id), :status => 1).first
+ if myshixun && is_modify.blank?
+ link_to "继续实战(#{count})", myshixun_game_path(myshixun.current_task, :myshixun_id => myshixun), :class => "c_blue homepagePostSubmit", :target => "_blank"
+ elsif myshixun
+ link_to "继续实战(#{count})", 'javascript:void(0);', :onclick => "sure_box_redirect('#{myshixun_reset_myshixun_path(myshixun)}', '实训已经更新啦,系统正在为您重置');", :class => "c_blue homepagePostSubmit"
+ end
+ #link_to "继续实战(#{count})", myshixun_game_path(myshixun.current_task, :myshixun_id => myshixun), :class => "c_blue homepagePostSubmit",:target => "_blank" if myshixun
+ end
+ elsif work.nil? && homework.end_time >= Time.now
+ if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
+ link_to "提交作品(#{count})","javascript:void(0)", :class => 'c_grey homepagePostSubmit',:style=>"cursor:not-allowed",:title => '请先关联项目再提交作品'
+ else
+ link_to "提交作品(#{count})", new_student_work_url_without_domain(homework.id),:class => 'c_blue homepagePostSubmit'
end
elsif work.nil? && homework.end_time < Time.now
- if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
- link_to "补交作品(#{count})","javascript:void(0)", :class => 'c_grey',:style=>"cursor:not-allowed",:title => '请先关联项目再补交作品'
- else
- link_to "补交作品(#{count})", new_student_work_url_without_domain(homework.id),:class => 'c_red'
- end
- else
- if homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 2 && StudentWorksEvaluationDistribution.where("student_work_id = #{work.id}").count > 0 #匿评作业,且作业状态不是在开启匿评之前
- if homework.homework_type != 3
- link_to "作品匿评", student_work_index_url_in_org(homework.id, 2), :class => 'c_blue', :title => "开启匿评后不可修改作品"
+ if homework.allow_late && homework.homework_detail_manual.comment_status < 6
+ if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
+ link_to "补交作品(#{count})","javascript:void(0)", :class => 'c_grey homepagePostSubmit',:style=>"cursor:not-allowed",:title => '请先关联项目再补交作品'
else
- work_ids = "(" + homework.student_works.has_committed.map(&:id).join(",") + ")"
- if User.current.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count > 0
- link_to "作品匿评", student_work_index_url_in_org(homework.id, 2), :class => 'c_blue', :title => "开启匿评后不可修改作品"
- else
- link_to "查看作品(#{count})",student_work_index_url_in_org(homework.id, 2), :class => 'c_blue', :title => "匿评开启后提交的作品不参与匿评"
- end
+ link_to "补交作品(#{count})", new_student_work_url_without_domain(homework.id),:class => 'c_red homepagePostSubmit'
end
- elsif homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 3
- link_to "查看作品(#{count})",student_work_index_url_in_org(homework.id, 2), :class => 'c_blue', :title => "匿评已结束"
- elsif homework.homework_type == 2 && homework.end_time >= Time.now#编程作业不能修改作品
- link_to "修改作品(#{count})", new_student_work_url_without_domain(homework.id),:class => 'c_blue'
+ end
+ elsif work
+ work_ids = "(" + homework.student_works.has_committed.map(&:id).join(",") + ")"
+ if homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 3 && User.current.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count > 0 #匿评作业,且作业状态不是在开启匿评之前
+ link_to "作品匿评", student_work_index_url_in_org(homework.id, 2), :class => 'c_blue homepagePostSubmit', :title => "开启匿评后不可修改作品"
+ elsif homework.homework_detail_manual && homework.homework_detail_manual.comment_status > 3
+ link_to "查看作品(#{count})",student_work_index_url_in_org(homework.id, 2), :class => 'c_blue homepagePostSubmit', :title => "匿评已结束"
elsif homework.end_time >= Time.now && work.user_id == User.current.id
- link_to "修改作品(#{count})", edit_student_work_url_without_domain(work.id),:class => 'c_blue'
+ link_to "修改作品(#{count})", edit_student_work_url_without_domain(work.id),:class => 'c_blue homepagePostSubmit'
else
- link_to "查看作品(#{count})", student_work_index_url_in_org(homework.id, 2), :class => 'c_blue', :title => "作业截止后不可修改作品"
+ link_to "查看作品(#{count})", student_work_index_url_in_org(homework.id, 2), :class => 'c_blue homepagePostSubmit', :title => "作业截止后不可修改作品"
end
end
end
else
- link_to "作品(#{count})", "javascript:void(0)", :class => "c_blue", :onclick => "notice_sure_box('您不是班级成员,不能提交作品 请先从老师处获取邀请码后加入班级,再提交作品')"
+ link_to "作品 (#{count})".html_safe, "javascript:void(0)", :class => "c_blue homepagePostSubmit", :onclick => "notice_sure_box('您不是班级成员,不能提交作品 请先从老师处获取邀请码后加入班级,再提交作品')"
end
else
- link_to "作品(#{count})", "javascript:void(0)", :class => "c_blue", :onclick => "login_notice_box('#{signin_url_without_domain}');"
+ link_to "作品 (#{count})".html_safe, "javascript:void(0)", :class => "c_blue homepagePostSubmit", :onclick => "login_notice_box('#{signin_url_without_domain}');"
end
end
@@ -3384,33 +4081,33 @@ module ApplicationHelper
if User.current.allowed_to?(:as_teacher, homework.course)
link_to "查看作品", student_work_index_url_in_org(homework.id, 2), :class => 'hw_btn_green fr mt5', :title => "查看作品", :target => '_blank'
else User.current.member_of_course?(homework.course)
- work = cur_user_works_for_homework homework
- project = cur_user_projects_for_homework homework
- if work.nil? && homework.end_time >= Time.now
- if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
- link_to "关联项目", student_work_index_url_in_org(homework.id, 1), :class => 'hw_btn_green fr mt5',:title => '查看分组作业详情', :target => '_blank'
- else
- link_to "提交作品", new_student_work_url_without_domain(homework.id),:class => 'hw_btn_green fr mt5', :target => '_blank'
- end
- elsif work.nil? && homework.end_time < Time.now
- if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
- link_to "关联项目", student_work_index_url_in_org(homework.id, 1), :class => 'hw_btn_green fr mt5',:title => '查看分组作业详情', :target => '_blank'
- else
- link_to "补交作品", new_student_work_url_without_domain(homework.id),:class => 'btn_orange_big fr mt5', :target => '_blank'
- end
+ work = cur_user_works_for_homework homework
+ project = cur_user_projects_for_homework homework
+ if work.nil? && homework.end_time >= Time.now
+ if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
+ link_to "关联项目", student_work_index_url_in_org(homework.id, 1), :class => 'hw_btn_green fr mt5',:title => '查看分组作业详情', :target => '_blank'
else
- if homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 2 #匿评作业,且作业状态不是在开启匿评之前
- link_to "作品匿评", student_work_index_url_in_org(homework.id, 2), :class => 'hw_btn_green fr mt5', :title => "开启匿评后不可修改作品", :target => '_blank'
- elsif homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 3
- link_to "查看作品",student_work_index_url_in_org(homework.id, 2), :class => 'hw_btn_green fr mt5', :title => "匿评已结束", :target => '_blank'
- elsif homework.homework_type == 2 && homework.end_time >= Time.now#编程作业不能修改作品
- link_to "修改作品", new_student_work_url_without_domain(homework.id),:class => 'hw_btn_green fr mt5', :target => '_blank'
- elsif homework.end_time >= Time.now && work.user_id == User.current.id
- link_to "修改作品", edit_student_work_url_without_domain(work.id),:class => 'hw_btn_green fr mt5', :target => '_blank'
- else
- link_to "查看作品", student_work_index_url_in_org(homework.id, 2), :class => 'hw_btn_green fr mt5', :title => "作业截止后不可修改作品", :target => '_blank'
- end
+ link_to "提交作品", new_student_work_url_without_domain(homework.id),:class => 'hw_btn_green fr mt5', :target => '_blank'
end
+ elsif work.nil? && homework.end_time < Time.now
+ if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
+ link_to "关联项目", student_work_index_url_in_org(homework.id, 1), :class => 'hw_btn_green fr mt5',:title => '查看分组作业详情', :target => '_blank'
+ else
+ link_to "补交作品", new_student_work_url_without_domain(homework.id),:class => 'btn_orange_big fr mt5', :target => '_blank'
+ end
+ else
+ if homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 2 #匿评作业,且作业状态不是在开启匿评之前
+ link_to "作品匿评", student_work_index_url_in_org(homework.id, 2), :class => 'hw_btn_green fr mt5', :title => "开启匿评后不可修改作品", :target => '_blank'
+ elsif homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 3
+ link_to "查看作品",student_work_index_url_in_org(homework.id, 2), :class => 'hw_btn_green fr mt5', :title => "匿评已结束", :target => '_blank'
+ elsif homework.homework_type == 2 && homework.end_time >= Time.now#编程作业不能修改作品
+ link_to "修改作品", new_student_work_url_without_domain(homework.id),:class => 'hw_btn_green fr mt5', :target => '_blank'
+ elsif homework.end_time >= Time.now && work.user_id == User.current.id
+ link_to "修改作品", edit_student_work_url_without_domain(work.id),:class => 'hw_btn_green fr mt5', :target => '_blank'
+ else
+ link_to "查看作品", student_work_index_url_in_org(homework.id, 2), :class => 'hw_btn_green fr mt5', :title => "作业截止后不可修改作品", :target => '_blank'
+ end
+ end
end
end
@@ -3448,14 +4145,14 @@ module ApplicationHelper
#获取当前用户在指定作业下提交的作业的集合
def cur_user_works_for_homework homework
work = homework.student_works.where("user_id = ? && work_status != 0",User.current).first
- if homework.homework_type == 3
- pro = homework.student_work_projects.where("user_id = #{User.current.id}").first
- if pro.nil? || pro.student_work_id == "" || pro.student_work_id.nil?
- work = nil
- else
- work = StudentWork.find pro.student_work_id
- end
- end
+ # if homework.homework_type == 3
+ # pro = homework.student_work_projects.where("user_id = #{User.current.id}").first
+ # if pro.nil? || pro.student_work_id == "" || pro.student_work_id.nil?
+ # work = nil
+ # else
+ # work = StudentWork.find pro.student_work_id
+ # end
+ # end
work
end
#获取当前用户在指定作业下关联的项目的集合
@@ -3887,6 +4584,8 @@ def get_reply_by_type type, reply_id
reply = JournalsForMessage.find reply_id
when 'Memo'
reply = Memo.find reply_id
+ when 'Challenge'
+ reply = Discuss.find reply_id
end
reply
end
@@ -4018,47 +4717,47 @@ def sortby_time_countcommon_hassticky topics,sortstr
tmpIndex = 0
tmpTopics.each_with_index do |topic,index|
- if topic.sticky == 0
- if tStart == -1
- if (index != tmpTopics.count-1) && (topic[:infocount] == tmpTopics[index+1][:infocount])
- tStart = index
- end
+ if topic.sticky == 0
+ if tStart == -1
+ if (index != tmpTopics.count-1) && (topic[:infocount] == tmpTopics[index+1][:infocount])
+ tStart = index
+ end
+ else
+ if ((topic[:infocount] == tmpTopics[index-1][:infocount]) && ((index != tmpTopics.count-1) && (topic[:infocount] == tmpTopics[index+1][:infocount])))
+ tEnd = index
else
- if ((topic[:infocount] == tmpTopics[index-1][:infocount]) && ((index != tmpTopics.count-1) && (topic[:infocount] == tmpTopics[index+1][:infocount])))
+ if (topic[:infocount] == tmpTopics[index-1][:infocount])
tEnd = index
- else
- if (topic[:infocount] == tmpTopics[index-1][:infocount])
- tEnd = index
- end
- if tEnd > tStart
- for i in tStart..tEnd
- tmpTopics_1[tmpIndex] = tmpTopics[i]
- tmpIndex = tmpIndex + 1
- end
-
- if sortstr == "created_at"
- tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:created_at].to_i <=> x[:created_at].to_i }
- elsif sortstr == "created_on"
- tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:created_on].to_i <=> x[:created_on].to_i }
- elsif sortstr == "updated_at"
- tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:updated_at].to_i <=> x[:updated_at].to_i }
- elsif sortstr == "updated_on"
- tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:updated_on].to_i <=> x[:updated_on].to_i }
- end
-
- tmpIndex = 0
- for i in tStart..tEnd
- tmpTopics[i] = tmpTopics_1[tmpIndex]
- tmpIndex = tmpIndex + 1
- end
- end
- tStart = -1
- tEnd = -1
- tmpTopics_1 = []
- tmpIndex = 0
end
+ if tEnd > tStart
+ for i in tStart..tEnd
+ tmpTopics_1[tmpIndex] = tmpTopics[i]
+ tmpIndex = tmpIndex + 1
+ end
+
+ if sortstr == "created_at"
+ tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:created_at].to_i <=> x[:created_at].to_i }
+ elsif sortstr == "created_on"
+ tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:created_on].to_i <=> x[:created_on].to_i }
+ elsif sortstr == "updated_at"
+ tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:updated_at].to_i <=> x[:updated_at].to_i }
+ elsif sortstr == "updated_on"
+ tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:updated_on].to_i <=> x[:updated_on].to_i }
+ end
+
+ tmpIndex = 0
+ for i in tStart..tEnd
+ tmpTopics[i] = tmpTopics_1[tmpIndex]
+ tmpIndex = tmpIndex + 1
+ end
+ end
+ tStart = -1
+ tEnd = -1
+ tmpTopics_1 = []
+ tmpIndex = 0
end
end
+ end
end
return tmpTopics
end
@@ -4153,14 +4852,34 @@ def get_work_index(hw,is_teacher)
return index
end
-def get_hw_index(hw,is_teacher)
+def get_ex_index(exercise, course, is_teacher)
if is_teacher
- homeworks = hw.course.homework_commons.order("created_at asc")
+ exercises = course.exercises.order("created_at asc")
else
- homeworks = hw.course.homework_commons.where("publish_time <= '#{Time.now}'").order("created_at asc")
+ exercises = course.exercises.where("exercise_status > 0").order("created_at asc")
end
- hw_ids = homeworks.map{|hw| hw.id} if !homeworks.empty?
- index = hw_ids.index(hw.id)
+ ex_ids = exercises.map{|ex| ex.id} if !exercises.blank?
+ index = ex_ids.index(exercise.id)
+ return index
+end
+
+def get_hw_index(hw,is_teacher,type=0)
+ homework_commons = hw.course.homework_commons
+ if is_teacher
+ if type != 0
+ homeworks = homework_commons.where("homework_commons.homework_type = #{type}").order("publish_time desc")
+ else
+ homeworks = homework_commons.order("publish_time desc")
+ end
+ else
+ if type != 0
+ homeworks = homework_commons.where("homework_commons.homework_type = #{type} and publish_time <= '#{Time.now}'").order("publish_time desc")
+ else
+ homeworks = homework_commons.where("publish_time <= '#{Time.now}'").order("publish_time desc")
+ end
+ end
+ hw_ids = homeworks.map{|hw| hw.id} if !homeworks.blank?
+ index = hw_ids.length - 1 - hw_ids.index(hw.id)
return index
end
@@ -4168,7 +4887,7 @@ def get_hw_status homework_common
str = ""
if homework_common.homework_detail_manual
if homework_common.homework_detail_manual.comment_status == 0 && homework_common.publish_time.nil?
- str += '挂起 '
+ str += '未发布 '
elsif homework_common.homework_detail_manual.comment_status == 0
str += '未发布 '
elsif homework_common.homework_detail_manual.comment_status == 1
@@ -4260,9 +4979,13 @@ def get_contest_group_member_names work
result
end
-def course_syllabus_option user = User.current
- syllabus_members = SyllabusMember.where("user_id = #{user.id}")
- syllabus_ids = syllabus_members.empty? ? "(-1)" : "(" + syllabus_members.map{|mem| mem.syllabus_id}.join(',') + ")"
+def course_syllabus_option syllabus_id = nil
+ syllabus_members = SyllabusMember.where("user_id = #{User.current.id}")
+ syllabus_ids = syllabus_members.map{|mem| mem.syllabus_id}
+ if syllabus_id && !syllabus_ids.include?(syllabus_id)
+ syllabus_ids << syllabus_id
+ end
+ syllabus_ids = syllabus_ids.empty? ? "(-1)" : "(" + syllabus_ids.join(',') + ")"
syllabuses = Syllabus.where("id in #{syllabus_ids}")
type = []
option1 = []
@@ -4284,36 +5007,35 @@ def create_works_list homework
unless homework.course.nil?
students = homework.course.student
if !students.empty? && homework.student_works.empty?
- name = homework.name
- name_str = name + "的作品提交"
- str = ""
- students.each do |student|
- if str != ""
- str += ","
+ name = homework.name
+ name_str = name + "的作品提交"
+ str = ""
+ students.each do |student|
+ if str != ""
+ str += ","
+ end
+ str += "('#{name_str}',#{homework.id},#{student.student_id}, '#{format_time(Time.now)}', '#{format_time(Time.now)}')"
end
- str += "('#{name_str}',#{homework.id},#{student.student_id}, '#{format_time(Time.now)}', '#{format_time(Time.now)}')"
- end
- sql = "insert into student_works (name, homework_common_id,user_id, created_at, updated_at) values" + str
- ActiveRecord::Base.connection.execute sql
+ sql = "insert into student_works (name, homework_common_id,user_id, created_at, updated_at) values" + str
+ ActiveRecord::Base.connection.execute sql
end
end
end
def add_to_homework_bank_f homework
- homework_bank = HomeworkBank.new(:name => homework.name, :description => homework.description, :user_id => homework.user_id, :homework_type => homework.homework_type,
- :quotes => 1, :is_public => homework.course.is_public, :applicable_syllabus => homework.course.syllabus.title, :homework_common_id => homework.id)
+ homework_bank = HomeworkBank.new(:name => homework.name, :description => homework.description, :user_id => User.current.id, :homework_type => homework.homework_type,
+ :quotes => 1, :is_public => homework.course.is_public, :applicable_syllabus => homework.course.course_list_name, :homework_common_id => homework.id,
+ :reference_answer => homework.reference_answer, :course_list_id => homework.course.course_list_id)
if homework.homework_type == 2 && homework.homework_detail_programing
homework_bank.language = homework.homework_detail_programing.language
homework.homework_tests.each_with_index do |homework_test|
homework_bank.homework_bank_tests << HomeworkBankTest.new(
- test_type: 1,
input: homework_test.input,
output: homework_test.output
)
end
homework.homework_samples.each_with_index do |homework_test|
- homework_bank.homework_bank_tests << HomeworkBankTest.new(
- test_type: 0,
+ homework_bank.homework_bank_samples << HomeworkBankSample.new(
input: homework_test.input,
output: homework_test.output
)
@@ -4401,7 +5123,7 @@ def searchstudent_by_name users, name
name = name.to_s.downcase
users.each do |m|
username = m.lastname.to_s.downcase + m.firstname.to_s.downcase
- if(m.login.to_s.downcase.include?(name) || m.user_extensions[:student_id].to_s.downcase.include?(name) || username.include?(name))
+ if(m.login.to_s.downcase.include?(name) || m.user_extensions[:student_id].to_s.downcase.include?(name) || username.include?(name))
mems << m
end
end
@@ -4457,3 +5179,320 @@ def add_reply_adapter obj, options
# end
end
+def sy_resources syllabus
+ courses = syllabus.courses.not_deleted
+ attachments = Attachment.where(:container_type => 'Course', :container_id => courses.map(&:id))
+ resources = ResourceBank.where(:id => attachments.map(&:resource_bank_id))
+ resources
+end
+
+def sy_homeworks syllabus
+ courses = syllabus.courses.not_deleted
+ homeworks = HomeworkCommon.where(:course_id => courses.map(&:id))
+ homeworks = HomeworkBank.where(:id => homeworks.map(&:homework_bank_id))
+ homeworks
+end
+
+# 可以查看到资源库的资源
+def visable_attachemnts_incourse course
+ return[] unless course
+ result = []
+ course.attachments.each do |attachment|
+ if attachment.is_public? && attachment.is_publish == 1 || User.current == attachment.author || User.current.allowed_to?(:as_teacher,course) || (User.current.member_of_course?(course) && attachment.is_publish == 1) || User.current.admin?
+ result << attachment
+ end
+ end
+ result
+end
+
+def visable_course_homework course, type=0
+ if User.current.admin? || User.current.allowed_to?(:as_teacher,course)
+ if type != 0
+ homework_num = course.homework_commons.where(:homework_type => type).count
+ else
+ homework_num = course.homework_commons.where(:homework_type => [1, 4]).count
+ end
+ else
+ if type != 0
+ homework_num = course.homework_commons.where(:homework_type => type).where("publish_time <= '#{Time.now}'").count
+ else
+ homework_num = course.homework_commons.where("homework_type in (1, 4) and publish_time <= '#{Time.now}'").count
+ end
+ end
+ homework_num
+end
+
+#成绩计算
+def set_final_score homework,student_work
+ if homework && homework.homework_detail_manual
+ if homework.homework_type != 2 #非编程作业
+ if homework.teacher_priority == 1 #教师优先
+ if student_work.teacher_score
+ student_work.final_score = student_work.teacher_score
+ student_work.work_score = student_work.teacher_score - student_work.absence_penalty - student_work.late_penalty
+ else
+ if student_work.teaching_asistant_score.nil?
+ student_work.final_score = student_work.student_score
+ elsif student_work.student_score.nil?
+ student_work.final_score = student_work.teaching_asistant_score
+ else
+ ta_proportion = homework.homework_detail_manual.ta_proportion
+ final_ta_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{ta_proportion}")
+ final_s_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
+ final_score = final_ta_score + final_s_score
+ student_work.final_score = format("%.2f",final_score.to_f)
+ end
+ if student_work.final_score
+ score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty - student_work.appeal_penalty
+ student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
+ else
+ student_work.work_score = nil
+ end
+ end
+ else #不考虑教师评分
+ if student_work.teaching_asistant_score.nil?
+ student_work.final_score = student_work.student_score
+ elsif student_work.student_score.nil?
+ student_work.final_score = student_work.teaching_asistant_score
+ else
+ ta_proportion = homework.homework_detail_manual.ta_proportion
+ final_ta_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{ta_proportion}")
+ final_s_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
+ final_score = final_ta_score + final_s_score
+ student_work.final_score = format("%.2f",final_score.to_f)
+ end
+ if student_work.final_score
+ score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty - student_work.appeal_penalty
+ student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
+ else
+ student_work.work_score = nil
+ end
+ end
+ elsif homework.homework_type == 2 && homework.homework_detail_programing #编程作业-----设定:系统评分必定不为空
+ if homework.teacher_priority == 1 #教师优先
+ if student_work.teacher_score
+ student_work.final_score = student_work.teacher_score
+ student_work.work_score = student_work.teacher_score - student_work.absence_penalty - student_work.late_penalty - student_work.appeal_penalty
+ else
+ if student_work.teaching_asistant_score.nil? #教辅未评分
+ if student_work.student_score.nil?
+ student_work.final_score = student_work.system_score
+ else
+ ta_proportion = homework.homework_detail_programing.ta_proportion + homework.homework_detail_manual.ta_proportion / 2
+ final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}")
+ final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
+ final_score = final_sy_score + final_st_score
+ student_work.final_score = format("%.2f",final_score.to_f)
+ end
+ elsif student_work.student_score.nil? #学生未评分
+ if student_work.teaching_asistant_score.nil?
+ student_work.final_score = student_work.system_score
+ else
+ ta_proportion = homework.homework_detail_programing.ta_proportion + (1.0 - homework.homework_detail_manual.ta_proportion - homework.homework_detail_programing.ta_proportion) / 2
+ final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}")
+ final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
+ final_score = final_sy_score + final_ts_score
+ student_work.final_score = format("%.2f",final_score.to_f)
+ end
+ else
+ final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}")
+ final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}")
+ final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") - BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}"))
+ final_score = final_sy_score + final_ts_score + final_st_score
+ student_work.final_score = format("%.2f",final_score.to_f)
+ end
+ if student_work.final_score
+ score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty - student_work.appeal_penalty
+ student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
+ else
+ student_work.work_score = nil
+ end
+ end
+ else #不考虑教师评分
+ if student_work.teaching_asistant_score.nil? #教辅未评分
+ if student_work.student_score.nil?
+ student_work.final_score = student_work.system_score
+ else
+ ta_proportion = homework.homework_detail_programing.ta_proportion + homework.homework_detail_manual.ta_proportion / 2
+ final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}")
+ final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
+ final_score = final_sy_score + final_st_score
+ student_work.final_score = format("%.2f",final_score.to_f)
+ end
+ elsif student_work.student_score.nil? #学生未评分
+ if student_work.teaching_asistant_score.nil?
+ student_work.final_score = student_work.system_score
+ else
+ ta_proportion = homework.homework_detail_programing.ta_proportion + (1.0 - homework.homework_detail_manual.ta_proportion - homework.homework_detail_programing.ta_proportion) / 2
+ final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{ta_proportion}")
+ final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{ta_proportion}"))
+ final_score = final_sy_score + final_ts_score
+ student_work.final_score = format("%.2f",final_score.to_f)
+ end
+ else
+ final_sy_score = BigDecimal.new("#{student_work.system_score || 0}") * BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}")
+ final_ts_score = BigDecimal.new("#{student_work.teaching_asistant_score}") * BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}")
+ final_st_score = BigDecimal.new("#{student_work.student_score}") * (BigDecimal.new('1.0') - BigDecimal.new("#{homework.homework_detail_programing.ta_proportion}") - BigDecimal.new("#{homework.homework_detail_manual.ta_proportion}"))
+ final_score = final_sy_score + final_ts_score + final_st_score
+ student_work.final_score = format("%.2f",final_score.to_f)
+ end
+ if student_work.final_score
+ score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty - student_work.appeal_penalty
+ student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
+ else
+ student_work.work_score = nil
+ end
+ end
+ end
+ end
+end
+
+# 实训作业的评分
+def set_shixun_final_score homework, student_work, answer_open_evaluation
+ unless student_work.work_status == 0
+ shixun = homework.homework_commons_shixuns.shixun
+ passed_count = answer_open_evaluation ? had_passed_changllenge_num(shixun, student_work.user) : had_passed_no_ans_changllenge_num(shixun, student_work.user)
+ final_score =(passed_count.to_f / shixun.challenges.count) * 100
+ student_work.update_column("final_score", format("%.2f",final_score.to_f))
+ score = student_work.final_score - student_work.late_penalty
+ student_work.update_column("work_score", format("%.2f",(score < 0 ? 0 : score).to_f)) if score
+ end
+end
+
+def quote_resource_bank resource, course
+ atta = Attachment.new(:filename => resource.filename, :disk_filename => resource.disk_filename, :filesize => resource.filesize, :digest => resource.digest, :downloads => 0, :is_publish => 0,
+ :author_id => User.current.id, :description => resource.description, :disk_directory => resource.disk_directory, :is_public => 0, :copy_from => resource.copy_from.nil? ? resource.id : resource.copy_from,
+ :quotes => 0, :resource_bank_id => resource.id, :created_on => Time.now, :content_type =>resource.content_type)
+ if course.attachments << atta
+ # 更新引用次数
+ quotes = resource.quotes.to_i + 1
+ resource.update_attribute(:quotes, quotes)
+ end
+end
+
+def quote_homework_bank homework, course
+ new_homework = HomeworkCommon.new(:name => homework.name, :user_id => User.current.id, :description => homework.description, :homework_type => homework.homework_type, :late_penalty => 0,
+ :course_id => course.id, :teacher_priority => 1, :anonymous_comment => 1, :quotes => 0, :is_open => 0, :homework_bank_id => homework.id, :score_open => 1,
+ :anonymous_appeal => 0, :is_public => 0, :reference_answer => homework.reference_answer, :answer_public => 1, :allow_late => 1)
+
+ new_homework.homework_detail_manual = HomeworkDetailManual.new
+ new_homework_detail_manual = new_homework.homework_detail_manual
+ new_homework_detail_manual.te_proportion = 1.0
+ new_homework_detail_manual.ta_proportion = 0
+ new_homework_detail_manual.comment_status = 0
+
+ new_homework_detail_manual.evaluation_num = 0
+ new_homework_detail_manual.absence_penalty = 0
+
+ if new_homework.homework_type == 2
+ new_homework.homework_detail_programing = HomeworkDetailPrograming.new
+ new_homework.homework_detail_programing.ta_proportion = 0
+ new_homework.homework_detail_programing.language = homework.language
+ homework.homework_bank_tests.each_with_index do |homework_test|
+ new_homework.homework_tests << HomeworkTest.new(
+ input: homework_test.input,
+ output: homework_test.output
+ )
+ end
+ homework.homework_bank_samples.each_with_index do |homework_test|
+ new_homework.homework_samples << HomeworkSample.new(
+ input: homework_test.input,
+ output: homework_test.output
+ )
+ end
+ end
+
+ if new_homework.homework_type == 3
+ new_homework.homework_detail_group = HomeworkDetailGroup.new
+ new_homework.homework_detail_group.min_num = homework.min_num
+ new_homework.homework_detail_group.max_num = homework.max_num
+ new_homework.homework_detail_group.base_on_project = homework.base_on_project
+ end
+
+ homework.attachments.each do |attachment|
+ att = attachment.copy
+ att.container_id = nil
+ att.container_type = nil
+ att.author_id = homework.user_id
+ att.copy_from = attachment.id
+ att.save
+ new_homework.attachments << att
+ end
+
+ if new_homework.save
+ if new_homework.homework_type == 4
+ HomeworkCommonsShixuns.create(:homework_common_id => new_homework.id, :shixun_id => homework.homework_bank_shixun.shixun_id)
+ end
+ new_homework_detail_manual.save if new_homework_detail_manual
+ new_homework.homework_detail_programing.save if new_homework.homework_detail_programing
+ new_homework.homework_detail_group.save if new_homework.homework_detail_group
+ homework.update_column(:quotes, homework.quotes+1)
+ 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/avatar_helper.rb b/app/helpers/avatar_helper.rb
index 243207fc7..fd076ad30 100644
--- a/app/helpers/avatar_helper.rb
+++ b/app/helpers/avatar_helper.rb
@@ -39,11 +39,19 @@ module AvatarHelper
def avatar_filename(source_id,image_file)
"#{source_id}" #<< file_extension(image_file)
end
-
+
+ def auth_filename(source_id,type)
+ "#{source_id}#{type}"
+ end
+
def disk_filename(source_type,source_id,image_file=nil)
File.join(storage_path,avatar_directory(source_type),avatar_filename(source_id,image_file))
end
+ def disk_auth_filename(source_type,source_id,type)
+ File.join(storage_path,avatar_directory(source_type),auth_filename(source_id,type))
+ end
+
def copy_course?(source_type, source_id)
file= disk_filename(source_type, source_id)
if source_type == Course && !File.exist?(file)
diff --git a/app/helpers/challenges_helper.rb b/app/helpers/challenges_helper.rb
index 86b0183c9..1d0f815ea 100644
--- a/app/helpers/challenges_helper.rb
+++ b/app/helpers/challenges_helper.rb
@@ -1,2 +1,28 @@
+# encoding: utf-8
module ChallengesHelper
+
+ def difficulty_type difficulty
+ case difficulty
+ when 1
+ "简单"
+ when 2
+ "中等"
+ when 3
+ "复杂"
+ end
+ end
+
+ def find_game_status challenge_id
+ game = Game.where(:challenge_id => challenge_id, :user_id => User.current.id).first
+ case game.try(:status)
+ when 0
+ "待完成 ".html_safe
+ when 1
+ " ".html_safe
+ when 2
+ "已完成 ".html_safe
+ when 3,nil
+ "未开始 ".html_safe
+ end
+ end
end
diff --git a/app/helpers/courses_helper.rb b/app/helpers/courses_helper.rb
index e76dad353..1a19f3180 100644
--- a/app/helpers/courses_helper.rb
+++ b/app/helpers/courses_helper.rb
@@ -12,6 +12,32 @@ module CoursesHelper
#AllPeople = StudentRoles+TeacherRoles
## return people count
+ def student_course_homework_score course, user
+ homework_ids = course.homework_commons.where("homework_type in (1, 4) and publish_time < '#{Time.now}'").map(&:id)
+ score = 0
+ user.student_works.where(:homework_common_id => homework_ids).each do |work|
+ score = score + work.work_score if work.work_score
+ end
+ format("%.1f",score)
+ end
+
+ # 学生的发布资源数
+ def student_course_resource_num course, user
+ num = course.attachments.where(:author_id => user.id).count
+ end
+
+ # 学生的发布帖子数
+ def student_course_message_num course, user
+ num = Message.where(:board_id => course.boards.map(&:id), :author_id => user.id, :parent_id => nil).count
+ end
+
+ # 学生的回复评论数
+ def student_course_reply_num course, user
+ boards_id = course.boards.empty? ? "(-1)" : "(" + course.boards.map(&:id).join(",") + ")"
+ me_num = Message.where("board_id in #{boards_id} and author_id = #{user.id} and parent_id is not null").count
+ jour_num = JournalsForMessage.where(:jour_type => 'HomeworkCommon', :jour_id => course.homework_commons.map(&:id), :user_id => user.id).count
+ num = me_num + jour_num
+ end
# 推荐的精品课程
def excellent_course_recommend new_course
@@ -78,19 +104,42 @@ module CoursesHelper
#生成课程老师成员链接
def course_teacher_link teacher_num
- if User.current.member_of_course?(@course) || User.current.admin?
- link_to "#{teacher_num}", course_member_path(@course, :role => 1), :class => 'sy_cblue', :id => 'teacher_number'
+ if User.current.allowed_to?(:as_teacher, @course) || User.current.member_of_course?(@course)
+ link_to teacher_num, members_course_path(@course), :class => 'ml5 edu-cir-grey-q color-orange05', :id => 'teacher_number'
+ # elsif User.current.member_of_course?(@course)
+ # link_to teacher_num, course_member_path(@course, :role => 't'), :class => 'ml5 edu-cir-grey-q color-orange05', :id => 'teacher_number'
else
- content_tag 'span',teacher_num, :class => 'sy_cblue'
+ content_tag 'span',teacher_num, :class => 'ml5 edu-cir-grey-q color-orange05'
end
end
#生成课程学生列表连接
def course_student_link student_num
- if (User.current.logged? && @course.open_student == 1) || (User.current.member_of_course?(@course)) || User.current.admin?
- link_to "#{student_num}", course_member_path(@course, :role => 2), :class => 'sy_cblue', :id => "student_number"
+ if User.current.allowed_to?(:as_teacher, @course) || User.current.member_of_course?(@course)
+ link_to "#{student_num}", members_course_path(@course, :role => 'as'), :class => 'ml5 edu-cir-grey-q color-orange05', :id => 'student_number'
+ # elsif (User.current.logged? && @course.open_student == 1) || (User.current.member_of_course?(@course))
+ # link_to "#{student_num}", course_member_path(@course, :role => 'as'), :class => 'ml5 edu-cir-grey-q color-orange05', :id => "student_number"
else
- content_tag 'span',student_num, :class => 'sy_cblue'
+ content_tag 'span',student_num, :class => 'ml5 edu-cir-grey-q color-orange05'
+ end
+ end
+
+ # 生成分班列表连接
+ def course_group_link group_num
+ if User.current.allowed_to?(:as_teacher, @course) || User.current.member_of_course?(@course)
+ link_to "#{group_num}", members_course_path(@course, :role => @course.course_groups.first.id), :class => 'ml5 edu-cir-grey-q color-orange03', :id => 'group_number'
+ # elsif (User.current.logged? && @course.open_student == 1) || (User.current.member_of_course?(@course))
+ # link_to "#{group_num}", course_member_path(@course, :role => @course.course_groups.first.id), :class => 'ml5 edu-cir-grey-q color-orange03', :id => "group_number"
+ else
+ content_tag 'span',group_num, :class => 'ml5 edu-cir-grey-q color-orange05'
+ end
+ end
+
+ # 班级结束天数
+ def course_end_date course
+ if course.end_date
+ curr = Time.new
+ ((Date.parse(course.end_date.to_s) - Date.parse(curr.to_s)).to_i)
end
end
@@ -306,7 +355,9 @@ module CoursesHelper
members
end
-
+ def groupCount course
+ course.course_groups.count
+ end
def searchStudent_by_name project, name
#searchPeopleByRoles(project, StudentRoles)
@@ -596,8 +647,10 @@ module CoursesHelper
# 获取动态列表名称
def get_acts_list_type type
case type
- when "homework"
- l(:label_homework_acts)
+ when "common_homework"
+ l(:label_common_homework_acts)
+ when "shixun_homework"
+ l(:label_shixun_homework_acts)
when "news"
l(:label_news_acts)
when "attachment"
@@ -617,7 +670,7 @@ module CoursesHelper
def course_group_option course
type = []
option1 = []
- option1 << "暂无"
+ option1 << "选择分班"
option1 << 0
type << option1
unless course.course_groups.nil?
@@ -794,40 +847,20 @@ module CoursesHelper
url = joined ? join_path(:object_id => course.id) : join_private_courses_courses_path()
method = joined ? 'delete' : 'post'
if joined
- link = link_to(text, url, :remote => true, :method => method, :class => "sy_btn_grey fl", :id => "#{course.id}", :confirm => l(:text_are_you_sure_out))
+ link = link_to(text, url, :remote => true, :method => method, :class => "joinclass", :id => "#{course.id}", :confirm => l(:text_are_you_sure_out))
else
- link = link_to(text, url, :remote => true, :method => method, :id => "#{course.id}", :class => "sy_btn_grey fl")
+ link = link_to(text, url, :remote => true, :method => method, :id => "#{course.id}", :class => "joinclass")
end
else
if User.current.logged?
- link = "#{l(:label_course_join_student)} "
+ link = "#{l(:label_course_join_student)} "
else
- link = link_to(l(:label_course_join_student), signin_url_without_domain, :class => "sy_btn_grey fl ml10")
+ link = link_to(l(:label_course_join_student), signin_url_without_domain, :class => "joinclass")
end
end
link.html_safe
end
- # 可以查看到资源库的资源
- def visable_attachemnts_incourse course
- return[] unless course
- result = []
- course.attachments.each do |attachment|
- if attachment.is_public? && attachment.is_publish == 1 || User.current == attachment.author || User.current.allowed_to?(:as_teacher,course) || (User.current.member_of_course?(course) && attachment.is_publish == 1) || User.current.admin?
- result << attachment
- end
- end
- result
- end
-
- def visable_course_homework course
- if User.current.admin? || User.current.allowed_to?(:as_teacher,course)
- homework_num = course.homework_commons.count
- else
- homework_num = course.homework_commons.where("publish_time <= '#{Time.now}'").count
- end
- homework_num
- end
def zh_course_role role
if role == "TeachingAsistant"
diff --git a/app/helpers/debates_helper.rb b/app/helpers/debates_helper.rb
new file mode 100644
index 000000000..f551d98d1
--- /dev/null
+++ b/app/helpers/debates_helper.rb
@@ -0,0 +1,2 @@
+module DebatesHelper
+end
diff --git a/app/helpers/department_helper.rb b/app/helpers/department_helper.rb
new file mode 100644
index 000000000..fdd36b814
--- /dev/null
+++ b/app/helpers/department_helper.rb
@@ -0,0 +1,2 @@
+module DepartmentHelper
+end
diff --git a/app/helpers/discusses_helper.rb b/app/helpers/discusses_helper.rb
new file mode 100644
index 000000000..544945763
--- /dev/null
+++ b/app/helpers/discusses_helper.rb
@@ -0,0 +1,2 @@
+module DiscussesHelper
+end
diff --git a/app/helpers/exercise_helper.rb b/app/helpers/exercise_helper.rb
index 28dd0b260..203ffd327 100644
--- a/app/helpers/exercise_helper.rb
+++ b/app/helpers/exercise_helper.rb
@@ -1,6 +1,44 @@
# encoding: utf-8
module ExerciseHelper
+ def un_commit_num exercise
+ course = exercise.course
+ exercise.exercise_users.where(:commit_status => 0, :user_id => course.student.map(&:student_id)).count
+ end
+
+ def has_commit_num exercise
+ course = exercise.course
+ exercise.exercise_users.where(:commit_status => 1, :user_id => course.student.map(&:student_id)).count
+ end
+
+ def un_comment_num exercise
+ course = exercise.course
+ exercise.exercise_users.where(:commit_status => 1, :user_id => course.student.map(&:student_id), :subjective_score => -1).count
+ end
+
+ def has_comment_num exercise
+ course = exercise.course
+ exercise.exercise_users.where(:commit_status => 1, :user_id => course.student.map(&:student_id)).count - exercise.exercise_users.where(:commit_status => 1, :user_id => course.student.map(&:student_id), :subjective_score => -1).count
+ end
+
+ def answer_is_correct eq, user
+ is_correct = false
+ case eq.question_type
+ when 1
+ answer = get_user_answer(eq, user)
+ standard_answer = get_user_standard_answer(eq, user)
+ is_correct = !answer.empty? && !standard_answer.empty? && answer.first.exercise_choice.choice_position == standard_answer.first.exercise_choice_id
+ when 2
+ standard_answer = get_user_standard_answer(eq, user)
+ is_correct = !standard_answer.empty? && get_mulscore(eq, user).to_i == standard_answer.first.exercise_choice_id
+ when 3
+ answer = get_user_answer(eq, user)
+ standard_answer = get_user_standard_answer(eq, user)
+ is_correct = !answer.empty? && !standard_answer.empty? && standard_answer.include?(answer.first.answer_text)
+ end
+ is_correct
+ end
+
# 单选
def sigle_selection_standard_answer(params)
size = params.ord - 96
@@ -160,6 +198,17 @@ module ExerciseHelper
uncomplete_question
end
+ def question_commit_status question, user
+ status = ""
+ case question.question_type
+ when 3, 4
+ get_anwser_vote_text(question.id,user.id) == "" ? status = "未答" : status = ""
+ when 1, 2
+ get_user_answer(question,user).empty? ? status = "未答" : status = ""
+ end
+ status
+ end
+
#获取文本题答案
def get_anwser_vote_text(question_id,user_id)
pv = ExerciseAnswer.find_by_exercise_question_id_and_user_id(question_id,user_id)
diff --git a/app/helpers/homework_bank_helper.rb b/app/helpers/homework_bank_helper.rb
new file mode 100644
index 000000000..fbb669ff3
--- /dev/null
+++ b/app/helpers/homework_bank_helper.rb
@@ -0,0 +1,2 @@
+module HomeworkBankHelper
+end
diff --git a/app/helpers/iframes_helper.rb b/app/helpers/iframes_helper.rb
new file mode 100644
index 000000000..349ee337f
--- /dev/null
+++ b/app/helpers/iframes_helper.rb
@@ -0,0 +1,2 @@
+module IframesHelper
+end
diff --git a/app/helpers/kubernete_helper.rb b/app/helpers/kubernete_helper.rb
new file mode 100644
index 000000000..2e3436028
--- /dev/null
+++ b/app/helpers/kubernete_helper.rb
@@ -0,0 +1,2 @@
+module KuberneteHelper
+end
diff --git a/app/helpers/management_helper.rb b/app/helpers/management_helper.rb
new file mode 100644
index 000000000..c313ee671
--- /dev/null
+++ b/app/helpers/management_helper.rb
@@ -0,0 +1,5 @@
+module ManagementHelper
+
+
+
+end
diff --git a/app/helpers/managements_helper.rb b/app/helpers/managements_helper.rb
new file mode 100644
index 000000000..6a15350a7
--- /dev/null
+++ b/app/helpers/managements_helper.rb
@@ -0,0 +1,42 @@
+module ManagementsHelper
+
+ def trial_authorization_status status
+ case status
+ when "0", nil
+ 0
+ when "1"
+ 1
+ when "2"
+ 2
+ else
+ [1,2]
+ end
+ end
+
+ def query_user_status_num status
+ user = (status == 0) ? user = User.all : User.where(:status => status)
+ return user.count
+ end
+
+ def course_list_major_time id
+ Major.where(:id => id).first.try(:name)
+ end
+
+ # params[:id]: course_list_id
+ def get_course_list_major id
+ Major.where(:id => MajorCourse.where(:course_list_id => id).map(&:major_id))
+ end
+
+ def course_list_count id
+ Major.where(:id => id).first.try(:name)
+ end
+
+ def delete_mirror_http del_uri
+ del_uri = URI.parse(URI.encode(del_uri.strip))
+ del_data = {}
+ del_http = Net::HTTP.new del_uri.host, del_uri.port
+ del_req = Net::HTTP::Delete.new(del_uri.request_uri)
+ del_req.form_data = del_data
+ del_res = del_http.start { |http| http.request del_req }
+ end
+end
diff --git a/app/helpers/owner_type_helper.rb b/app/helpers/owner_type_helper.rb
index 110bc3d58..b4fb514c9 100644
--- a/app/helpers/owner_type_helper.rb
+++ b/app/helpers/owner_type_helper.rb
@@ -12,4 +12,9 @@ module OwnerTypeHelper
ArticleHomepage = 11
PROJECT = 12
CONTEST = 13
+ HOMEWORKREFERENCEANSWER = 14
+ STUDENTWORK = 15
+ HOMEWORKBANK = 16
+ SUBJECT = 17
+ EXERCISEQUESTION = 18
end
\ No newline at end of file
diff --git a/app/helpers/shixuns_helper.rb b/app/helpers/shixuns_helper.rb
index 66ffdc9cc..6a9004aca 100644
--- a/app/helpers/shixuns_helper.rb
+++ b/app/helpers/shixuns_helper.rb
@@ -1,5 +1,9 @@
module ShixunsHelper
+ def had_passed_count
+
+ end
+
#显示项目配置菜单
def show_project_memu user
if user.allowed_to?(:edit_project, @shixun)
@@ -13,5 +17,9 @@ module ShixunsHelper
end
result
end
-
+
+ def had_passed_challenge challenge
+ Game.where(:challenge_id => challenge.id, :status => 2).limit(3).reorder("final_score desc")
+ end
+
end
diff --git a/app/helpers/stages_helper.rb b/app/helpers/stages_helper.rb
new file mode 100644
index 000000000..93ca31e89
--- /dev/null
+++ b/app/helpers/stages_helper.rb
@@ -0,0 +1,2 @@
+module StagesHelper
+end
diff --git a/app/helpers/student_work_helper.rb b/app/helpers/student_work_helper.rb
index 89a9455f5..4cdcc2ea3 100644
--- a/app/helpers/student_work_helper.rb
+++ b/app/helpers/student_work_helper.rb
@@ -2,6 +2,18 @@
include UserScoreHelper
module StudentWorkHelper
+ def update_shixun_work_status homework
+ homework.student_works.each do |work|
+ if work.work_status == 0
+ myshixun = Myshixun.where(:shixun_id => homework.homework_commons_shixuns.shixun_id, :user_id => work.user_id).first
+ if myshixun
+ work.update_attributes(:work_status => myshixun.created_at <= homework.end_time ? 1 : 2, :late_penalty => myshixun.created_at <= homework.end_time ? 0 : homework.late_penalty, :commit_time => myshixun.created_at, :myshixun_id => myshixun.id)
+ end
+ end
+ set_shixun_final_score homework, work, homework.homework_detail_manual.answer_open_evaluation
+ end
+ end
+
#获取当前用户的项目列表
def user_projects_option
projects = User.current.projects.visible
@@ -73,13 +85,68 @@ module StudentWorkHelper
str
end
- #获取学生作品的评分记录:同一个教师或教辅只显示未隐藏的评分
+ # 作品的助教评分模式
+ def ta_score_mode homework
+ mode = homework.homework_detail_manual.ta_mode == 1 ? '平均' : '复审'
+ mode
+ end
+
+ #根据传入作业确定显示为编辑作品还是新建作品,或者显示作品数量
+ def user_work_status homework
+ if User.current.logged?
+ if User.current.member_of_course?(homework.course)
+ work = cur_user_works_for_homework homework
+ project = cur_user_projects_for_homework homework
+ if work.nil? && homework.end_time >= Time.now
+ if homework.homework_type == 4
+ #link_to "关联实战", relate_myshixun_student_work_index_path(:homework => homework.id),:class => 'white-btn orange-btn fr mr10 mt8',:remote => true
+ else
+ link_to "提交作品", new_student_work_url_without_domain(homework.id),:class => 'white-btn orange-btn fr mr10 mt8'
+ end
+ elsif work.nil? && homework.end_time < Time.now
+ if homework.allow_late && homework.homework_detail_manual.comment_status < 6
+ if homework.homework_type == 4
+ #link_to "关联实战", relate_myshixun_student_work_index_path(:homework => homework.id),:class => 'white-btn orange-btn fr mr10 mt8',:remote => true
+ else
+ link_to "补交作品", new_student_work_url_without_domain(homework.id),:class => 'white-btn orange-btn fr mr10 mt8'
+ end
+ end
+ elsif work
+ if homework.homework_type == 4
+ myshixun = Myshixun.find work.myshixun_id
+ is_modify = ShixunModify.where(:myshixun_id => myshixun.try(:id), :shixun_id => myshixun.shixun.try(:id), :status => 1).first
+ if myshixun && is_modify.blank?
+ link_to "继续实战", myshixun_game_path(myshixun.current_task, :myshixun_id => myshixun), :class => "white-btn orange-btn fr mr10 mt8", :target => "_blank"
+ elsif myshixun
+ link_to "继续实战", 'javascript:void(0);', :onclick => "sure_box_redirect('#{myshixun_reset_myshixun_path(myshixun)}', '实训已经更新啦,系统正在为您重置');", :class => "white-btn orange-btn fr mr10 mt8"
+ end
+ else
+ if homework.end_time >= Time.now && work.user_id == User.current.id
+ link_to "修改作品", edit_student_work_url_without_domain(work.id),:class => 'white-btn orange-btn fr mr10 mt8'
+ end
+ # work_ids = "(" + homework.student_works.has_committed.map(&:id).join(",") + ")"
+ # if homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 3 && User.current.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count > 0 #匿评作业,且作业状态不是在开启匿评之前
+ # link_to "匿评作品", student_work_index_url_in_org(homework.id, 2), :class => 'white-btn orange-btn fr mr10 mt8', :title => "开启匿评后不可修改作品"
+ # elsif homework.homework_detail_manual && homework.homework_detail_manual.comment_status > 3
+ # link_to "查看作品", student_work_path(work), :class => 'white-btn orange-btn fr mr10 mt8', :title => "匿评已结束"
+ # elsif homework.end_time >= Time.now && work.user_id == User.current.id
+ # link_to "修改作品", edit_student_work_url_without_domain(work.id),:class => 'white-btn orange-btn fr mr10 mt8'
+ # else
+ # link_to "查看作品", student_work_path(work), :class => 'white-btn orange-btn fr mr10 mt8', :title => "作业截止后不可修改作品"
+ # end
+ end
+ end
+ end
+ end
+ end
+
+ #获取学生作品的评分记录:同一个教师或教辅只显示未隐藏的评分、匿评多次评分只取最新一条
def student_work_score_record work
- # sql = "SELECT MAX(id) id FROM student_works_scores WHERE (reviewer_role = 2 OR reviewer_role = 1) AND score IS NOT NULL AND is_hidden = 0 AND student_work_id = #{work.id} GROUP BY user_id"
- # tea_ts_ids = StudentWorksScore.find_by_sql sql
- # tea_ts_ids = tea_ts_ids.empty? ? "(-1)" : "(" + tea_ts_ids.map{|tea| tea.id}.join(",") + ")"
- # scores = work.student_works_scores.where("score IS NULL or reviewer_role = 3 or id in #{tea_ts_ids}").order("updated_at desc")
- scores = work.student_works_scores.where(:is_hidden => false).order("created_at desc")
+ sql = "SELECT MAX(id) id FROM student_works_scores WHERE reviewer_role = 3 AND score IS NOT NULL AND is_hidden = 0 AND student_work_id = #{work.id} GROUP BY user_id"
+ st_ts_ids = StudentWorksScore.find_by_sql sql
+ st_ts_ids = st_ts_ids.empty? ? "(-1)" : "(" + st_ts_ids.map{|tea| tea.id}.join(",") + ")"
+ scores = work.student_works_scores.where("is_hidden = 0 and(reviewer_role = 1 or reviewer_role = 2 or id in #{st_ts_ids})").order("updated_at desc")
+ #scores = work.student_works_scores.where(:is_hidden => false).order("created_at desc")
return scores
end
@@ -106,9 +173,9 @@ module StudentWorkHelper
#传入分数,获取对应颜色
def score_color score
if score
- color = score >= 90 ? "c_red" : "c_green"
+ color = score >= 90 ? "color-red-light" : "color-light-green"
else
- color = "c_grey"
+ color = "color-grey"
end
color
end
@@ -173,15 +240,29 @@ module StudentWorkHelper
return status
end
- def group_student_works student_work, homework
- pros = student_work.student_work_projects.where("is_leader = 0")
+ def group_member_work student_work
+ member_work = nil
+ if student_work.student_work_projects.count > 0
+ member_work = student_work
+ else
+ student_work_pro = StudentWorkProject.where(:user_id => student_work.user_id, :homework_common_id => student_work.homework_common_id).first
+ if student_work_pro
+ member_work = StudentWork.find student_work_pro.student_work_id
+ end
+ end
+ member_work
+ end
+
+ def group_student_works member_work, student_work, homework
+ pros = member_work.student_work_projects.where("user_id != #{student_work.user_id}")
user_ids = pros.empty? ? "(-1)" : "(" + pros.map{|stu|stu.user_id}.join(",") + ")"
student_works = homework.student_works.where("user_id in #{user_ids}")
return student_works
end
def add_score_to_member student_work, homework, new_score
- student_works = group_student_works student_work, homework
+ member_work = group_member_work student_work
+ student_works = group_student_works member_work, student_work, homework
student_works.each do |st_work|
st_work.student_works_scores << StudentWorksScore.create(:user_id => new_score.user_id, :score => new_score.score, :reviewer_role => new_score.reviewer_role, :comment => new_score.comment)
if new_score.reviewer_role == 1
@@ -190,7 +271,7 @@ module StudentWorkHelper
ts_score = StudentWorksScore.find_by_sql("SELECT AVG(score) AS score FROM (SELECT * FROM (SELECT * FROM student_works_scores WHERE student_work_id = #{st_work.id} AND reviewer_role = 2 AND score IS NOT NULL ORDER BY created_at DESC) AS t GROUP BY user_id) AS a")
st_work.teaching_asistant_score = ts_score.first.score.nil? ? nil : ts_score.first.score.try(:round, 2).to_f
else
- st_work.student_score = student_work.student_score
+ st_work.student_score = member_work.student_score
end
st_work.save
end
diff --git a/app/helpers/subjects_helper.rb b/app/helpers/subjects_helper.rb
new file mode 100644
index 000000000..7757cd8d8
--- /dev/null
+++ b/app/helpers/subjects_helper.rb
@@ -0,0 +1,23 @@
+module SubjectsHelper
+ def subject_co_users subject
+ shixuns = Shixun.where(:id => subject.stage_shixuns.map(&:shixun_id))
+ co_users = User.where(:id => shixuns.map(&:user_id)).where("id != #{subject.user_id}")
+ end
+
+ def subject_data subject
+ result = {}
+ subject_choices = 0
+ subject_shixuns = 0
+ subject_score = 0
+ subject.stage_shixuns.each do |stage_shixun|
+ shixun = stage_shixun.shixun
+ subject_choices += shixun.challenges.where(:st => [1, 2]).count
+ subject_shixuns += shixun.challenges.where(:st => 0).count
+ subject_score += shixun.shixun_score
+ end
+ result[:subject_choices] = subject_choices
+ result[:subject_shixuns] = subject_shixuns
+ result[:subject_score] = subject_score
+ result
+ end
+end
diff --git a/app/helpers/syllabuses_helper.rb b/app/helpers/syllabuses_helper.rb
index b9e3d09c1..91b951d46 100644
--- a/app/helpers/syllabuses_helper.rb
+++ b/app/helpers/syllabuses_helper.rb
@@ -51,36 +51,33 @@ module SyllabusesHelper
count
end
- #课程性质下拉框
- def syllabus_type
- type = []
+ def syllabus_type_option
+ content = []
+ option0 = []
+ option0 << "请选择课程性质"
+ option0 << 0
option1 = []
+ option1 << "专业选修课"
+ option1 << 3
option2 = []
+ option2 << "学科必修课"
+ option2 << 2
option3 = []
+ option3 << "公共必修课"
+ option3 << 1
option4 = []
+ option4 << "实践选修课"
+ option4 << 5
option5 = []
- option6 = []
-
- option1 << "请选择"
- option1 << 0
- option2 << "公共必修课"
- option2 << 1
- option3 << "学科必修课"
- option3 << 2
- option4 << "专业选修课"
- option4 << 3
option5 << "实践必修课"
option5 << 4
- option6 << "实践选修课"
- option6 << 5
-
- type << option1
- type << option2
- type << option3
- type << option4
- type << option5
- type << option6
-
- type
+ content << option0
+ content << option1
+ content << option2
+ content << option3
+ content << option4
+ content << option5
+ content
end
+
end
diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb
index 5de7316a5..c4d46a09d 100644
--- a/app/helpers/users_helper.rb
+++ b/app/helpers/users_helper.rb
@@ -325,11 +325,11 @@ module UsersHelper
url = {:controller => 'users', :action => 'update', :id => user, :page => params[:page], :status => params[:status], :tab => nil}
if user.locked?
- link_to l(:button_unlock), url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :put, :class => 'icon icon-unlock'
+ link_to "解锁", url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :put, :class => 'mr10 link-color-blue'
elsif user.registered?
link_to l(:button_activate), url.merge(:user => {:status => User::STATUS_ACTIVE}), :method => :put, :class => 'icon icon-unlock'
elsif user != User.current
- link_to l(:button_lock), url.merge(:user => {:status => User::STATUS_LOCKED}), :method => :put, :class => 'icon icon-lock'
+ link_to "加锁", url.merge(:user => {:status => User::STATUS_LOCKED}), :method => :put, :class => 'mr10 link-color-blue'
end
end
diff --git a/app/helpers/watchers_helper.rb b/app/helpers/watchers_helper.rb
index 8f6d6a8e5..99e2e69c2 100644
--- a/app/helpers/watchers_helper.rb
+++ b/app/helpers/watchers_helper.rb
@@ -262,11 +262,25 @@ module WatchersHelper
content.present? ? content_tag('ul', content, :class => 'watchers') : content
end
-
-
-
-
-
+#用户关注、取消关注
+ def watcher_link_for_user(target, user)
+ return '' unless user && user.logged?
+ watched = target.watched_by?(user)
+ text = watched ? '已关注' : '添加关注'
+ url = watch_path(:object_type => 'user',
+ :object_id => target.id,
+ :target_id => target.id)
+ method = watched ? 'delete' : 'post'
+ id = watched ? 'cancel_watch' : ''
+ title = watched ? '取消关注' : '已关注'
+ if target != user
+ link_to text, url, :remote => true, :method => method, :remote => true,
+ :class => "fr font-14 user_watch",:id => id, :title => title
+ else
+ link_to "关注", "javascript:void(0)", :remote => true, :method => method,
+ :class => "fr font-14 user_watch", :id => id, :title => title
+ end
+ end
# 缺陷跟踪者列表复选框生成
def watchers_checkboxes(object, users, checked=nil)
diff --git a/app/helpers/welcome_helper.rb b/app/helpers/welcome_helper.rb
index e4a2e06c6..2306adb96 100644
--- a/app/helpers/welcome_helper.rb
+++ b/app/helpers/welcome_helper.rb
@@ -22,6 +22,23 @@ module WelcomeHelper
include CoursesHelper
include ProjectsHelper
+ def color_change index
+ case index
+ when 0
+ "edu-index-bg-green"
+ when 1
+ "edu-index-bg-blue"
+ when 2
+ "edu-index-bg-purple"
+ when 3
+ "edu-index-bg-yellow"
+ when 4
+ "edu-index-bg-orange"
+ when 5
+ "edu-index-bg-green"
+ end
+ end
+
def get_timestamp(obj)
if obj.respond_to? :updated_on
:updated_on
diff --git a/app/models/applied_message.rb b/app/models/applied_message.rb
index c5228ce83..93b1d2047 100644
--- a/app/models/applied_message.rb
+++ b/app/models/applied_message.rb
@@ -4,6 +4,7 @@ class AppliedMessage < ActiveRecord::Base
attr_accessible :applied_id, :applied_type, :status, :user_id, :viewed, :applied_user_id, :role, :project_id, :name
belongs_to :applied ,:polymorphic => true
belongs_to :apply_add_schools
+ belongs_to :apply_add_department
belongs_to :user
has_many :message_alls, :class_name => 'MessageAll', :as =>:message, :dependent => :destroy
diff --git a/app/models/apply_action.rb b/app/models/apply_action.rb
new file mode 100644
index 000000000..af19e832b
--- /dev/null
+++ b/app/models/apply_action.rb
@@ -0,0 +1,6 @@
+# status:0 审核中 1 同意 2 拒绝 3 撤销
+class ApplyAction < ActiveRecord::Base
+ default_scope :order => 'updated_at desc'
+ attr_accessible :container_id, :container_type, :dealer_id, :reason, :user_id, :status, :apply_reason
+ belongs_to :user
+end
diff --git a/app/models/apply_add_department.rb b/app/models/apply_add_department.rb
new file mode 100644
index 000000000..5ea5c00ec
--- /dev/null
+++ b/app/models/apply_add_department.rb
@@ -0,0 +1,8 @@
+class ApplyAddDepartment < ActiveRecord::Base
+ belongs_to :school
+ belongs_to :user
+ attr_accessible :name, :remarks, :status, :school_id, :user_id, :department_id
+ has_many :applied_messages, :class_name =>'AppliedMessage', :as => :applied
+ belongs_to :department
+ # status: 0表示未批准; status:1表示已批准; status: 2表示已更改; status: 3表示已拒绝; status: 4表示已更改后废除的部门
+end
diff --git a/app/models/apply_add_schools.rb b/app/models/apply_add_schools.rb
index 60c2c404f..820bd3ce1 100644
--- a/app/models/apply_add_schools.rb
+++ b/app/models/apply_add_schools.rb
@@ -1,8 +1,8 @@
-class ApplyAddSchools < ActiveRecord::Base
- # status:0 未审批 ; 1 已批阅
- attr_accessible :address, :city, :name, :province, :remarks, :school_id, :status
- has_many :applied_messages, :class_name =>'AppliedMessage', :as => :applied
- belongs_to :school
-
- #after_create :send_massage
-end
+class ApplyAddSchools < ActiveRecord::Base
+ # status:0 未审批 ; 1 已批阅, :2 已拒绝
+ attr_accessible :address, :city, :name, :province, :remarks, :school_id, :status
+ has_many :applied_messages, :class_name =>'AppliedMessage', :as => :applied
+ belongs_to :school
+
+ #after_create :send_massage
+end
diff --git a/app/models/apply_user_authentication.rb b/app/models/apply_user_authentication.rb
new file mode 100644
index 000000000..a96ecc251
--- /dev/null
+++ b/app/models/apply_user_authentication.rb
@@ -0,0 +1,6 @@
+class ApplyUserAuthentication < ActiveRecord::Base
+ belongs_to :user
+ # status:0 审核中 1 同意 2 拒绝 3 撤销
+ # auth_type:1 实名认证, 2 职业认证
+ attr_accessible :auth_type, :dealer, :deal_time, :remarks, :status, :user_id
+end
diff --git a/app/models/attachment.rb b/app/models/attachment.rb
index e4e37a8f3..a27a36ac8 100644
--- a/app/models/attachment.rb
+++ b/app/models/attachment.rb
@@ -21,6 +21,7 @@ require 'elasticsearch/model'
class Attachment < ActiveRecord::Base
belongs_to :container, :polymorphic => true
belongs_to :project, foreign_key: 'container_id', conditions: "attachments.container_type = 'Project'"
+ belongs_to :shixun, foreign_key: 'container_id', conditions: "attachments.container_type = 'Shixun'"
belongs_to :course, foreign_key: 'container_id', conditions: "attachments.container_type = 'Course'"
belongs_to :org_subfield, foreign_key: 'container_id', conditions: "attachements.container_type = 'OrgSubfield'"
belongs_to :organization, foreign_key: 'container_id', conditions: "attachements.container_type = 'Organization'"
@@ -28,6 +29,7 @@ class Attachment < ActiveRecord::Base
belongs_to :softapplication, foreign_key: 'container_id', conditions: "attachments.container_type = 'Softapplication'"
belongs_to :author, :class_name => "User", :foreign_key => "author_id"
belongs_to :attachmentstype, :foreign_key => "attachtype",:primary_key => "id"
+ belongs_to :resource_bank
# 被ForgeActivity虚拟关联
has_many :forge_acts, :class_name => 'ForgeActivity',:as =>:forge_act ,:dependent => :destroy
has_many :forwards, :as => :from, :dependent => :destroy
diff --git a/app/models/authentication.rb b/app/models/authentication.rb
new file mode 100644
index 000000000..77cc49b8d
--- /dev/null
+++ b/app/models/authentication.rb
@@ -0,0 +1,8 @@
+class Authentication < ActiveRecord::Base
+ attr_accessible :level, :permissions
+ serialize :permissions, Array
+ has_and_belongs_to_many :users
+ # has_many :users_authenticationses
+ # has_many :users, :through => :users_authenticationses
+
+end
diff --git a/app/models/authentications_users.rb b/app/models/authentications_users.rb
new file mode 100644
index 000000000..3805a6a8a
--- /dev/null
+++ b/app/models/authentications_users.rb
@@ -0,0 +1,3 @@
+class AuthenticationsUsers < ActiveRecord::Base
+ attr_accessible :authentication_id, :user_id
+end
diff --git a/app/models/blog.rb b/app/models/blog.rb
index bd338cdad..7c54b2be7 100644
--- a/app/models/blog.rb
+++ b/app/models/blog.rb
@@ -2,8 +2,8 @@ class Blog < ActiveRecord::Base
# attr_accessible :title, :body
include Redmine::SafeAttributes
belongs_to :user
- has_many :articles, :class_name => 'BlogComment', :conditions => "#{BlogComment.table_name}.parent_id IS NULL ", :order => "#{BlogComment.table_name}.created_on DESC"
- has_many :blog_comments, :dependent => :destroy, :order => "#{BlogComment.table_name}.created_on DESC"
+ has_many :articles, :class_name => 'BlogComment', :conditions => "#{BlogComment.table_name}.parent_id IS NULL ", :order => "#{BlogComment.table_name}.created_at DESC"
+ has_many :blog_comments, :dependent => :destroy, :order => "#{BlogComment.table_name}.created_at DESC"
belongs_to :last_comment, :class_name => 'BlogComment', :foreign_key => :last_comment_id
acts_as_tree :dependent => :nullify
#acts_as_list :scope => '(user_id = #{user_id} AND parent_id #{user_id ? = "#{parent_id}" : "IS NULL"})'
diff --git a/app/models/blog_comment.rb b/app/models/blog_comment.rb
index cf241ce3b..a04c7d208 100644
--- a/app/models/blog_comment.rb
+++ b/app/models/blog_comment.rb
@@ -20,7 +20,7 @@ class BlogComment < ActiveRecord::Base
validates_presence_of :title, :content
validates_length_of :title, :maximum => 255
#validate :cannot_reply_to_locked_comment, :on => :create
- safe_attributes 'title', 'content',"sticky", "locked", "root_id"
+ safe_attributes 'title', 'content',"sticky", "locked", "root_id", 'visits'
after_save :add_user_activity
after_update :update_activity
diff --git a/app/models/challenge.rb b/app/models/challenge.rb
index 35630a1f0..980711d59 100644
--- a/app/models/challenge.rb
+++ b/app/models/challenge.rb
@@ -1,3 +1,5 @@
+#coding=utf-8
+# st 0:实践任务;1:选择题任务
class Challenge < ActiveRecord::Base
default_scope :order => 'position'
belongs_to :shixun,:touch=> true
@@ -6,22 +8,85 @@ class Challenge < ActiveRecord::Base
has_many :test_sets, :dependent => :destroy
has_many :challenge_tags, :dependent => :destroy
has_many :games, :dependent => :destroy
+ has_many :challenge_chooses, :dependent => :destroy
validates_presence_of :subject
- validates_presence_of :score
+ # validates_presence_of :score
validates_presence_of :task_pass
validates_length_of :subject, :maximum => 255
+ def game_difficulty
+ str = "简单"
+ case self.difficulty
+ when 1
+ str = "简单"
+ when 2
+ str = "中等"
+ when 3
+ str = "困难"
+ end
+ str
+ end
+
+ def choose_correct_num
+ num = 0
+ self.challenge_chooses.each do |choose|
+ outputs = ChooseOutputs.where(:challenge_choose_id => choose.id, :user_id => User.current.id).first
+ if outputs.nil?
+ num = nil
+ else
+ num += (outputs.correct ? 1 : 0)
+ end
+ end
+ return num
+ end
+
+ def choose_score
+ score = 0
+ self.challenge_chooses.each do |choose|
+ score += choose.score.to_i
+ end
+ return score
+ end
+
+ def choose_tags_num
+ num = 0
+ self.challenge_chooses.each do |choose|
+ num += choose.challenge_tags.count
+ end
+ return num
+ end
+
def next_challenge
challenge_count = Challenge.where(:shixun_id => self.shixun_id).count
render_404 if self.position ==challenge_count
Challenge.where(:position => (self.position + 1), :shixun_id => self.shixun).first
end
+ def prev_challenge
+ render_404 if self.position == 1
+ Challenge.where(:position => (self.position - 1), :shixun_id => self.shixun).first
+ end
+
def last_challenge
render_404 if self.position < 2
position = self.position - 1
Challenge.where(:position => position, :shixun_id => self.shixun).first
end
+ def current_user_game
+ myshixun = Myshixun.where(:shixun_id => self.shixun.id, :user_id => User.current.id).first
+ game = Game.where(:myshixun_id => myshixun, :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_choose.rb b/app/models/challenge_choose.rb
new file mode 100644
index 000000000..38b7d8685
--- /dev/null
+++ b/app/models/challenge_choose.rb
@@ -0,0 +1,19 @@
+class ChallengeChoose < ActiveRecord::Base
+ # attr_accessible :title, :body
+ # category 1 单选, 2,多选
+ # standard_answer 正确答案 answer: 答题的思路
+ default_scope :order => 'position'
+ belongs_to :challenge
+ has_many :challenge_tags, :dependent => :destroy
+ has_many :challenge_questions, :dependent => :destroy
+ has_one :choose_outputs, :dependent => :destroy
+ #has_many :outputs, :dependent => :destroy
+
+ validates_presence_of :subject
+
+ # 判断当前用户是否答题
+ def current_choose_outputs
+ ChooseOutputs.where(:challenge_choose_id => self.id, :user_id => User.current.id).first
+ end
+
+end
diff --git a/app/models/challenge_question.rb b/app/models/challenge_question.rb
new file mode 100644
index 000000000..3540330b7
--- /dev/null
+++ b/app/models/challenge_question.rb
@@ -0,0 +1,6 @@
+class ChallengeQuestion < ActiveRecord::Base
+ # 选择题的选项内容
+ belongs_to :challenge_choose
+ # right_key 选项是否是答案, position 选项的位置
+ attr_accessible :challenge_choose_id, :option_name, :position, :right_key
+end
diff --git a/app/models/challenge_tag.rb b/app/models/challenge_tag.rb
index 5f5925f92..35b3f5be7 100644
--- a/app/models/challenge_tag.rb
+++ b/app/models/challenge_tag.rb
@@ -1,4 +1,5 @@
class ChallengeTag < ActiveRecord::Base
- attr_accessible :challenge_id, :name
+ attr_accessible :challenge_id, :name, :challenge_choose_id
belongs_to :challenge
+ belongs_to :challenge_choose
end
diff --git a/app/models/choose_outputs.rb b/app/models/choose_outputs.rb
new file mode 100644
index 000000000..9a47a3b25
--- /dev/null
+++ b/app/models/choose_outputs.rb
@@ -0,0 +1,5 @@
+class ChooseOutputs < ActiveRecord::Base
+ # attr_accessible :title, :body
+ # user_id 与 challenge_choose_id 唯一确定用户此题的选项
+ belongs_to :challenge_choose
+end
diff --git a/app/models/course.rb b/app/models/course.rb
index 74d59bf73..5a169be09 100644
--- a/app/models/course.rb
+++ b/app/models/course.rb
@@ -1,533 +1,562 @@
-#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
- #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
- 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
-
- 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 :term,: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'
-
- acts_as_customizable
-
- scope :not_deleted, lambda{where(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 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, :homepage_show
+ #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
+ belongs_to :course_list
+ # 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',
+ 'homepage_show'
+
+ 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 course_list_name
+ self.course_list ? self.course_list.name : ""
+ 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/course_list.rb b/app/models/course_list.rb
new file mode 100644
index 000000000..33ef6ca47
--- /dev/null
+++ b/app/models/course_list.rb
@@ -0,0 +1,7 @@
+class CourseList < ActiveRecord::Base
+ has_many :major_courses
+ has_many :shixun_major_courses
+ has_many :courses
+ belongs_to :user
+ attr_accessible :name, :user_id, :is_admin,:support_shixuns_search
+end
diff --git a/app/models/course_module.rb b/app/models/course_module.rb
new file mode 100644
index 000000000..c5b9c1fac
--- /dev/null
+++ b/app/models/course_module.rb
@@ -0,0 +1,6 @@
+class CourseModule < ActiveRecord::Base
+ # attr_accessible :title, :body
+ belongs_to :course
+ attr_accessible :course_id, :module_type, :position, :hidden
+
+end
diff --git a/app/models/department.rb b/app/models/department.rb
new file mode 100644
index 000000000..4163f6bd3
--- /dev/null
+++ b/app/models/department.rb
@@ -0,0 +1,4 @@
+class Department < ActiveRecord::Base
+ belongs_to :school
+ attr_accessible :name, :school_id
+end
diff --git a/app/models/discipline_category.rb b/app/models/discipline_category.rb
new file mode 100644
index 000000000..26ac6b3c0
--- /dev/null
+++ b/app/models/discipline_category.rb
@@ -0,0 +1,6 @@
+class DisciplineCategory < ActiveRecord::Base
+ attr_accessible :major_level, :name
+
+ has_many :first_level_disciplines
+ has_many :majors
+end
diff --git a/app/models/discuss.rb b/app/models/discuss.rb
new file mode 100644
index 000000000..af5f96601
--- /dev/null
+++ b/app/models/discuss.rb
@@ -0,0 +1,18 @@
+class Discuss < ActiveRecord::Base
+ belongs_to :user
+ attr_accessible :user_id, :content, :dis_id, :dis_type, :parent_id, :praise_count, :root_id, :challenge_id
+
+ has_many :praise_tread, as: :praise_tread_object, dependent: :destroy
+ has_one :praise_tread_cache, as: :object, dependent: :destroy
+ acts_as_tree :foreign_key => 'parent_id'
+ belongs_to :dis, :polymorphic => true
+ validates_presence_of :dis, :user, :content
+
+ def creator_user
+ User.find(self.user_id)
+ end
+
+ def content_detail
+ self.content
+ end
+end
diff --git a/app/models/exercise_question.rb b/app/models/exercise_question.rb
index 5189b0274..c6a4f40df 100644
--- a/app/models/exercise_question.rb
+++ b/app/models/exercise_question.rb
@@ -1,3 +1,4 @@
+#encoding: utf-8
class ExerciseQuestion < ActiveRecord::Base
include Redmine::SafeAttributes
@@ -5,4 +6,17 @@ class ExerciseQuestion < ActiveRecord::Base
has_many :exercise_choices, :order => "#{ExerciseChoice.table_name}.choice_position",:dependent => :destroy
has_many :exercise_answers, :dependent => :destroy
has_many :exercise_standard_answers, :dependent => :destroy
+
+ def question_type_name
+ case self.question_type
+ when 1
+ "单选题"
+ when 2
+ "多选题"
+ when 3
+ "填空题"
+ when 4
+ "简答题"
+ end
+ end
end
diff --git a/app/models/experience.rb b/app/models/experience.rb
new file mode 100644
index 000000000..3f2649587
--- /dev/null
+++ b/app/models/experience.rb
@@ -0,0 +1,5 @@
+class Experience < ActiveRecord::Base
+ attr_accessible :container_id, :container_type, :score, :user_id, :created_at, :updated_at
+
+ belongs_to :user
+end
diff --git a/app/models/first_level_discipline.rb b/app/models/first_level_discipline.rb
new file mode 100644
index 000000000..4e792b2de
--- /dev/null
+++ b/app/models/first_level_discipline.rb
@@ -0,0 +1,6 @@
+class FirstLevelDiscipline < ActiveRecord::Base
+ belongs_to :discipline_category
+ attr_accessible :name
+ has_many :syllabuses
+ has_many :majors
+end
diff --git a/app/models/game.rb b/app/models/game.rb
index 3810c91e9..e278690c4 100644
--- a/app/models/game.rb
+++ b/app/models/game.rb
@@ -1,13 +1,43 @@
class Game < ActiveRecord::Base
# stauts 0: can exe 1:doing 2:successed 3:locked
default_scope :order => 'created_at desc'
- attr_accessible :myshixun_id, :user_id, :status, :final_score, :challenge_id
+ attr_accessible :myshixun_id, :user_id, :status, :final_score, :challenge_id, :open_time, :identifier, :answer_open, :end_time, :retry_status, :resubmit_identifier
belongs_to :myshixun,:touch=> true
belongs_to :user
belongs_to :challenge
has_many :outputs, :dependent => :destroy
+ has_many :choose_output
has_many :test_sets, :dependent => :destroy
- has_many :challenge_samples, :dependent => :destroy
+ has_many :challenge_samples
+ has_one :game_code, :dependent => :destroy
+
+ def had_done
+ myshixun = self.myshixun
+ challenge = self.challenge
+ had_done = (myshixun.games.count == challenge.position && self.status == 2) ? 1 : 0
+ return had_done
+ end
+
+ # id 转换成 challenge'position
+ def to_param
+ identifier
+ end
+
+ def query_index
+ if self.outputs.present?
+ self.outputs.first.try(:query_index).to_i + 1
+ else
+ 1
+ end
+ end
+
+ def last_game
+ challenge = self.challenge
+ last_challenge_id = challenge.last_challenge
+ game = Game.where(:myshixun_id => self.myshixun_id, :challenge_id => last_challenge_id).first
+ render_404 if game.nil?
+ return game
+ end
def next_game
challenge = self.challenge
@@ -17,10 +47,37 @@ class Game < ActiveRecord::Base
return game
end
+ def prev_game
+ challenge = self.challenge
+ prev_challenge_id = challenge.prev_challenge
+ game = Game.where(:myshixun_id => self.myshixun_id, :challenge_id => prev_challenge_id).first
+ render_404 if game.nil?
+ return game
+ end
+
# 获取game最新的一条输出结果
def latest_output
outputs = Output.where(:game_id => self.id).order("created_at desc")
output = outputs.blank? ? nil : outputs.first
return output
end
+
+ def is_final_game?
+ challenge = self.challenge
+ challenge.try(:position).to_i == challenge.shixun.challenges.count ? true : false
+ end
+
+ def choose_correct_num
+ num = 0
+ outputs = self.outputs.where(:query_index => (self.query_index - 1))
+ if outputs.blank?
+ num = nil
+ else
+ outputs.each do |output|
+ num += output.result ? 1 : 0
+ end
+ end
+ return num
+ end
+
end
diff --git a/app/models/game_code.rb b/app/models/game_code.rb
new file mode 100644
index 000000000..cb9eda249
--- /dev/null
+++ b/app/models/game_code.rb
@@ -0,0 +1,4 @@
+class GameCode < ActiveRecord::Base
+ attr_accessible :game_id, :new_code, :original_code, :path
+ belongs_to :game
+end
diff --git a/app/models/grade.rb b/app/models/grade.rb
new file mode 100644
index 000000000..b4fae2b09
--- /dev/null
+++ b/app/models/grade.rb
@@ -0,0 +1,7 @@
+# container_type:
+# Phone-手机注册;Mail-邮箱绑定;Account-完善资料;Answer-查看参考答案;Game-闯关
+class Grade < ActiveRecord::Base
+ attr_accessible :container_id, :container_type, :score, :user_id
+
+ belongs_to :user
+end
diff --git a/app/models/homework_bank.rb b/app/models/homework_bank.rb
index b1e908a1d..0c7cb4816 100644
--- a/app/models/homework_bank.rb
+++ b/app/models/homework_bank.rb
@@ -1,10 +1,34 @@
+#encoding: utf-8
class HomeworkBank < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :user
- has_many :homework_bank_tests
+ belongs_to :syllabus
+ belongs_to :course_list
+ has_many :homework_bank_tests, :dependent => :destroy
+ has_many :homework_bank_samples, :dependent => :destroy
+ has_many :homework_commons
+ has_one :homework_bank_shixun
acts_as_attachable
def language_name
%W(C C++ Python Java).at(self.language.to_i - 1)
end
+
+ def course_list_name
+ self.course_list ? self.course_list.name : ""
+ end
+
+ #作业类型
+ def homework_type_ch
+ type = self.homework_type
+ case type
+ when 1
+ type = "普通"
+ when 2
+ type = "编程"
+ when 3
+ type = "分组"
+ end
+ type
+ end
end
diff --git a/app/models/homework_bank_sample.rb b/app/models/homework_bank_sample.rb
new file mode 100644
index 000000000..7b64f93a9
--- /dev/null
+++ b/app/models/homework_bank_sample.rb
@@ -0,0 +1,4 @@
+class HomeworkBankSample < ActiveRecord::Base
+ belongs_to :homework_bank
+ attr_accessible :input, :output, :homework_bank_id
+end
diff --git a/app/models/homework_bank_shixun.rb b/app/models/homework_bank_shixun.rb
new file mode 100644
index 000000000..3bec23fcd
--- /dev/null
+++ b/app/models/homework_bank_shixun.rb
@@ -0,0 +1,5 @@
+class HomeworkBankShixun < ActiveRecord::Base
+ belongs_to :homework_bank
+ belongs_to :shixun
+ attr_accessible :homework_bank_id, :shixun_id
+end
diff --git a/app/models/homework_common.rb b/app/models/homework_common.rb
index 440eff661..49b9d9fb2 100644
--- a/app/models/homework_common.rb
+++ b/app/models/homework_common.rb
@@ -14,6 +14,7 @@ class HomeworkCommon < ActiveRecord::Base
has_one :homework_detail_manual, :dependent => :destroy
has_one :homework_detail_programing, :dependent => :destroy
has_one :homework_detail_group, :dependent => :destroy
+ has_one :homework_commons_shixuns
has_many :student_work_projects, :dependent => :destroy
has_many :homework_tests, :dependent => :destroy
has_many :homework_samples, :dependent => :destroy
@@ -24,6 +25,7 @@ class HomeworkCommon < ActiveRecord::Base
has_many :praise_tread, as: :praise_tread_object, dependent: :destroy
has_one :praise_tread_cache, as: :object, dependent: :destroy
has_many :acts, :class_name => 'Activity', :as => :act, :dependent => :destroy #用户活动
+ has_and_belongs_to_many :shixuns
# 课程动态
has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy
# 课程消息
@@ -59,6 +61,8 @@ class HomeworkCommon < ActiveRecord::Base
type = "编程"
when 3
type = "分组"
+ when 4
+ type = "实训"
end
type
end
@@ -122,7 +126,7 @@ class HomeworkCommon < ActiveRecord::Base
count = ShieldWechatMessage.where("container_type='User' and container_id=#{m.user_id} and shield_type='Course' and shield_id=#{self.course_id}").count
if count == 0
ws = WechatService.new
- name = self.course.syllabus.nil? ? self.course.name : self.course.syllabus.title+" • "+self.course.name
+ name = self.course.course_list.nil? ? self.course.name : self.course.course_list_name+" • "+self.course.name
ws.homework_message_notice(m.user_id, "homework", self.id, "#{m.user.show_name},#{l(:label_new_homework_template)}", name, "新作业:"+ self.name.html_safe, "作业内容请点击“详情”查看。")
end
end
diff --git a/app/models/homework_commons_shixuns.rb b/app/models/homework_commons_shixuns.rb
new file mode 100644
index 000000000..c55f101c2
--- /dev/null
+++ b/app/models/homework_commons_shixuns.rb
@@ -0,0 +1,5 @@
+class HomeworkCommonsShixuns < ActiveRecord::Base
+ attr_accessible :homework_common_id, :shixun_id
+ belongs_to :homework_common
+ belongs_to :shixun
+end
diff --git a/app/models/homework_detail_manual.rb b/app/models/homework_detail_manual.rb
index 6faa84d40..ffdeda060 100644
--- a/app/models/homework_detail_manual.rb
+++ b/app/models/homework_detail_manual.rb
@@ -1,7 +1,7 @@
#手动评分作业表
-#comment_status: 1:未开启匿评,2:开启匿评,3:匿评结束
+#comment_status: 0:挂起, 1:提交,2:补交(去掉),3:匿评中,4:申诉中,5:评阅中,6:已结束
class HomeworkDetailManual < ActiveRecord::Base
- attr_accessible :ta_proportion, :comment_status, :evaluation_start, :evaluation_end, :evaluation_num, :absence_penalty, :homework_common_id, :no_anon_penalty
+ attr_accessible :ta_proportion, :comment_status, :evaluation_start, :evaluation_end, :evaluation_num, :absence_penalty, :homework_common_id, :no_anon_penalty, :answer_open_evaluation
belongs_to :homework_common
end
diff --git a/app/models/homework_reference_answer.rb b/app/models/homework_reference_answer.rb
new file mode 100644
index 000000000..d3508f0bf
--- /dev/null
+++ b/app/models/homework_reference_answer.rb
@@ -0,0 +1,6 @@
+class HomeworkReferenceAnswer < ActiveRecord::Base
+ belongs_to :homework_common
+ attr_accessible :answer, :homework_common_id
+
+ acts_as_attachable
+end
diff --git a/app/models/import_student.rb b/app/models/import_student.rb
new file mode 100644
index 000000000..add74eca3
--- /dev/null
+++ b/app/models/import_student.rb
@@ -0,0 +1,4 @@
+class ImportStudent < ActiveRecord::Base
+ attr_accessible :course_id, :name, :school_id, :status, :student_number
+ # status 如果用户没有注册状态为0;1:表示用户已有注册,且只有一个账号;2:表示用户已有注册,但是有两个一样的账号
+end
diff --git a/app/models/journals_for_message.rb b/app/models/journals_for_message.rb
index d1f32f82d..885bdc0b8 100644
--- a/app/models/journals_for_message.rb
+++ b/app/models/journals_for_message.rb
@@ -322,6 +322,9 @@ class JournalsForMessage < ActiveRecord::Base
receivers.each do |r|
self.user_feedback_messages << UserFeedbackMessage.new(:user_id => r.id, :journals_for_message_id => self.id, :journals_for_message_type => "Principal", :viewed => false)
end
+ elsif self.jour_type == 'Game'
+ # game不存在回复
+ self.user_feedback_messages << UserFeedbackMessage.new(:user_id => self.user_id, :journals_for_message_id => self.id, :journals_for_message_type => "Game", :viewed => false)
end
end
diff --git a/app/models/mailer.rb b/app/models/mailer.rb
index 49b58c3db..ae67c1da9 100644
--- a/app/models/mailer.rb
+++ b/app/models/mailer.rb
@@ -837,11 +837,20 @@ class Mailer < ActionMailer::Base
:subject => l(:mail_subject_register, Setting.app_title)
end
- def lost_password(token, code="111111")
+ def bind_email(token, code="111111", email)
set_language_if_valid(token.user.language)
@login = token.user.try(:login)
@token = token
@code = code
+ mail :to => email,
+ :subject => l(:mail_subject_bind_mail, Setting.app_title+"("+Setting.host_name+")")
+ end
+
+ def lost_password(token, code="111111")
+ set_language_if_valid(token.user.language)
+ @login = token.user.show_real_name
+ @token = token
+ @code = code
mail :to => token.user.mail,
:subject => l(:mail_subject_lost_password, Setting.app_title)
end
diff --git a/app/models/major.rb b/app/models/major.rb
new file mode 100644
index 000000000..4fe0abff5
--- /dev/null
+++ b/app/models/major.rb
@@ -0,0 +1,34 @@
+# encoding: utf-8
+# major_level 1 研究生 2 本科生 3 专科生
+ class Major < ActiveRecord::Base
+ belongs_to :first_level_discipline
+ belongs_to :discipline_category
+ has_many :major_courses
+ has_many :shixun_major_courses
+ has_many :subjects
+ attr_accessible :major_code, :major_level, :name, :first_level_discipline_id, :discipline_category_id,:support_shixuns,:created_at,:updated_at
+ # 课程的学科门类
+ def major_discipline_category
+ self.discipline_category ? self.discipline_category.name : ''
+ end
+
+ # 课程的一级学科
+ def major_first_level_discipline
+ self.first_level_discipline ? self.first_level_discipline.name : ''
+ end
+
+ # 课程层级
+ def major_major_level
+ type = ""
+ case self.major_level
+ when 1
+ type = "研究生"
+ when 2
+ type = "本科"
+ when 3
+ type = "专科"
+ end
+ type
+ end
+
+ end
diff --git a/app/models/major_course.rb b/app/models/major_course.rb
new file mode 100644
index 000000000..0e9732352
--- /dev/null
+++ b/app/models/major_course.rb
@@ -0,0 +1,5 @@
+class MajorCourse < ActiveRecord::Base
+ belongs_to :course_list
+ belongs_to :major
+ attr_accessible :course_list_id, :major_id
+end
diff --git a/app/models/memo.rb b/app/models/memo.rb
index 1eb8f29aa..dc12fe367 100644
--- a/app/models/memo.rb
+++ b/app/models/memo.rb
@@ -11,7 +11,7 @@ class Memo < ActiveRecord::Base
# 若是主题帖,则内容可以是空
#validates :content, presence: true, if: Proc.new{|o| !o.parent_id.nil? }
validates_length_of :subject, maximum: 50
- validates_length_of :content, maximum: 30000
+
validate :cannot_reply_to_locked_topic, :on => :create
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/mirror_repository.rb b/app/models/mirror_repository.rb
new file mode 100644
index 000000000..bf92b0c08
--- /dev/null
+++ b/app/models/mirror_repository.rb
@@ -0,0 +1,6 @@
+class MirrorRepository < ActiveRecord::Base
+ has_many :mirror_update_records, :dependent => :destroy
+ has_many :mirror_repository_types, :dependent => :destroy
+ # status: 0 未发布 1 已发布
+ attr_accessible :description, :mirrorID, :name, :status, :tag, :main_type, :created_at, :updated_at
+end
diff --git a/app/models/mirror_repository_type.rb b/app/models/mirror_repository_type.rb
new file mode 100644
index 000000000..ff74c4591
--- /dev/null
+++ b/app/models/mirror_repository_type.rb
@@ -0,0 +1,5 @@
+class MirrorRepositoryType < ActiveRecord::Base
+ belongs_to :mirror_type
+ belongs_to :mirror_repository
+ attr_accessible :mirror_type_id, :mirror_repository_id
+end
diff --git a/app/models/mirror_type.rb b/app/models/mirror_type.rb
new file mode 100644
index 000000000..9d78ce4fb
--- /dev/null
+++ b/app/models/mirror_type.rb
@@ -0,0 +1,5 @@
+class MirrorType < ActiveRecord::Base
+ belongs_to :user
+ has_many :mirror_repository_types, :dependent => :destroy
+ attr_accessible :name, :user_id
+end
diff --git a/app/models/mirror_update_record.rb b/app/models/mirror_update_record.rb
new file mode 100644
index 000000000..9ef160e1a
--- /dev/null
+++ b/app/models/mirror_update_record.rb
@@ -0,0 +1,5 @@
+class MirrorUpdateRecord < ActiveRecord::Base
+ belongs_to :user
+ belongs_to :mirror_repository
+ attr_accessible :newDescription, :newName, :newStatus, :newTag, :newType, :oldDescription, :oldName, :oldStatus, :oldTag, :oldType, :user_id, :mirror_repository_id
+end
diff --git a/app/models/myshixun.rb b/app/models/myshixun.rb
index c9894d4ee..1619b9313 100644
--- a/app/models/myshixun.rb
+++ b/app/models/myshixun.rb
@@ -1,33 +1,102 @@
+# status 1:完成实训
class Myshixun < ActiveRecord::Base
- attr_accessible :description, :name, :parent_id, :user_id, :gpid, :forked_from, :visits, :is_public
- has_many :users, :through => :myshixun_members
- has_many :myshixun_members
- has_one :repository
+ attr_accessible :description, :name, :parent_id, :user_id, :gpid, :forked_from, :visits, :is_public, :identifier, :shixun_id
+ # has_many :users, :through => :myshixun_members
+ has_many :myshixun_members, :dependent => :destroy
+ has_one :repository, :dependent => :destroy
has_many :games, :dependent => :destroy, :order => "games.id ASC"
belongs_to :shixun
+ has_one :shixun_modify, :dependent => :destroy
+ has_one :webssh, :dependent => :destroy
+ has_many :student_works
+
+ def total_stage
+ self.games.count
+ end
+
+ def current_stage
+ game = self.games.where(:status => 0).first
+ position = game.blank? ? games.count : game.challenge.try(:position)
+ return position
+ end
+
+ def current_stages
+ game = self.games.where(:status => 1).first
+ position = game.blank? ? 1 : game.challenge.try(:position)
+ return position
+ end
+
+ def done_time
+ time = ""
+ if self.status == 1
+ time = self.games.order("end_time desc").first.try(:end_time)
+ end
+ time
+ end
+
+ def total_spend_time
+ time = 0
+ self.games.each do |game|
+ if game.status == 2
+ time += (game.end_time.to_i - game.open_time.to_i) > 0 ? (game.end_time.to_i - game.open_time.to_i) : 0
+ end
+ end
+ time
+ end
+
+ def total_score
+ score = 0
+ self.games.each do |game|
+ if game.status == 2
+ score += game.final_score.to_i
+ end
+ end
+ score
+ end
+
+ def total_gold
+ score = 0
+ self.games.each do |game|
+ if game.status == 2
+ total_gold =game.answer_open? ? -game.challenge.score.to_i : game.final_score.to_i
+ score += total_gold
+ end
+ end
+ score
+ end
+
+
+ # id 转换成 identifier
+ def to_param
+ identifier
+ end
# 当前任务:一个实训中只可能一个未完成任务(status 0或1只会存在一条记录)
# status:0 可以测评的,正在测评的
# 如果都完成,则当前任务为最后一个任务
def current_task
games = self.games
- current_game = games.select{|game| game.status==1 || game.status==0}.first
+ current_game = games.select{|game| game.status == 1 || game.status == 0}.first
if current_game.blank?
- passed_games = games.select{|game| game.status==2}
- current_game = passed_games.last
+ game_id = '(' + games.map(&:id).join(',') + ')'
+ passed_games = games.find_by_sql("SELECT *, (SELECT c.position from `challenges` c where g.challenge_id = c.id) as pos FROM `games` g where g.status = 2 and g.id in #{game_id} ORDER BY pos desc")
+ current_game = passed_games.first
end
return current_game
end
- def parent
- Shixun.find(self.parent_id)
- rescue ActiveRecord::RecordNotFound
- render_404
- end
-
def owner
User.find(self.user_id)
rescue ActiveRecord::RecordNotFound
render_404
end
+
+ def score
+ game = self.games.where(:status => [0, 1]).first
+ unless game.blank?
+ score = game.challenge.try(:score)
+ end
+ return score
+ end
+
end
diff --git a/app/models/output.rb b/app/models/output.rb
index 67a1d6d09..8f1547cfe 100644
--- a/app/models/output.rb
+++ b/app/models/output.rb
@@ -1,4 +1,8 @@
class Output < ActiveRecord::Base
# attr_accessible :title, :body
- default_scope :order => 'created_at desc'
+ # actual_output 编程题:实际输出, 选择题: 用户提交的答案(如: 014 对应用户选择为A B E)
+ # compile_success 1 表示程序未报错,有正常输出, 0.表示程序抛异常了,报错!
+ default_scope :order => 'query_index desc'
+ belongs_to :game
+ #belongs_to :challenge_choose
end
diff --git a/app/models/reference_material.rb b/app/models/reference_material.rb
new file mode 100644
index 000000000..627f6eeb3
--- /dev/null
+++ b/app/models/reference_material.rb
@@ -0,0 +1,4 @@
+class ReferenceMaterial < ActiveRecord::Base
+ belongs_to :syllabus
+ attr_accessible :book, :editor, :press, :syllabus_id
+end
diff --git a/app/models/repository.rb b/app/models/repository.rb
index 7c09f9f73..a1be972e5 100644
--- a/app/models/repository.rb
+++ b/app/models/repository.rb
@@ -56,7 +56,10 @@ class Repository < ActiveRecord::Base
'path_encoding',
'log_encoding',
'is_default',
- 'type'
+ 'type',
+ 'myshixun_id',
+ 'shixun_id',
+ 'project_id'
safe_attributes 'url',
:if => lambda {|repository, user| repository.new_record?}
@@ -224,6 +227,7 @@ class Repository < ActiveRecord::Base
end
def cat(path, identifier=nil)
+ logger.info("cat content: path is #{path}, identifier is #{identifier}")
scm.cat(path, identifier)
end
diff --git a/app/models/resource_bank.rb b/app/models/resource_bank.rb
new file mode 100644
index 000000000..dac316f46
--- /dev/null
+++ b/app/models/resource_bank.rb
@@ -0,0 +1,5 @@
+class ResourceBank < ActiveRecord::Base
+ belongs_to :course
+ belongs_to :user
+ attr_accessible :course_id, :user_id, :applicable_syllabus, :copy_from, :description, :digest, :discipline_category_id, :disk_directory, :disk_filename, :downloads, :filename, :filesize, :first_level_discipline_id, :is_public, :major_level, :quotes, :attachment_id, :created_at
+end
diff --git a/app/models/school.rb b/app/models/school.rb
index b9a1d88cb..ab0b697c9 100644
--- a/app/models/school.rb
+++ b/app/models/school.rb
@@ -1,9 +1,10 @@
-class School < ActiveRecord::Base
- attr_accessible :name, :province,:pinyin
- has_many :courses
-
- def to_s
- self.name.to_s
- end
-
-end
+class School < ActiveRecord::Base
+ default_scope :order => 'created_at desc'
+ attr_accessible :name, :province, :pinyin, :city, :address, :logo_link,:auto_users_trial,:shool_code
+ has_many :courses
+ has_many :departments, :dependent => :destroy
+
+ def to_s
+ self.name.to_s
+ end
+end
diff --git a/app/models/shixun.rb b/app/models/shixun.rb
index 5ab4e4b99..7ba0ae5ca 100644
--- a/app/models/shixun.rb
+++ b/app/models/shixun.rb
@@ -1,16 +1,111 @@
-# status 控制实训的状态,0:未开启;1: 已开启(TPM)
+# encoding: utf-8
+# status 控制实训的状态,0:编辑;1: 申请发布; 2:正式发布; 3:关闭
+# is_updated 字段为1表示实训的更改可能会影响到后续的评测,0表示更改不会影响后续的评测
+# 繁忙等级参数:80发布实训失败,返回code为-1;81:实训开启的时候fork失败;83:开启实训的时候,openGameInstance返回非0值;84:jenkins系统异常,post数据不成功
+# 85:challenge创建的时候Jenkins处理异常;86:实训评测失败,jenkins返回错误结果; 87:版本库删除异常;88:点击评测失败,没返回数据;89:重置链接jenkins返回失败
+# 90: 更新公共测试用例失败,返回code非0;91:实训有改动,评测的时候初始化数据,返回数据code非0;92:webssh开启失败,接口getConnectInfo返回code值非0
+# 93: 实训断开连接失败,接口deleteSSH返回code值非0
+# 94: 获取评测等待时间失败,接口getWaitingTime返回code值为非0
+# 116:challenge创建关卡的时候返回结果错误
+#
class Shixun < ActiveRecord::Base
- attr_accessible :description, :is_public, :name, :changeset_num, :status, :user_id, :gpid, :language
+ attr_accessible :description, :is_public, :name, :changeset_num, :status, :user_id, :gpid, :language, :identifier, :authentication,
+ :myshixun_count, :propaedeutics, :trainee, :major_id, :homepage_show, :webssh, :hidden, :fork_from, :can_copy
has_many :users, :through => :shixun_members
- has_many :shixun_members
- has_one :repository
- has_many :challenges, :dependent => :destroy, :order => "challenges.id ASC"
- has_many :myshixuns
+ has_many :shixun_members, :dependent => :destroy
+ has_one :repository, :dependent => :destroy
+ has_many :homework_commons_shixunses
+ has_many :challenges, :dependent => :destroy, :order => "challenges.position ASC"
+ has_many :myshixuns, :dependent => :destroy
+ has_many :stage_shixuns, :dependent => :destroy
+ belongs_to :major
+ belongs_to :major_course
+ has_many :shixun_major_courses, :dependent => :destroy
+ has_and_belongs_to_many :homework_commons
+ has_many :discusses, :as => :dis, :dependent => :destroy
+ has_many :shixun_ports
+
+ scope :visible, lambda{where(status: [2,3])}
+
+ include ApplicationHelper
+ # 获取特定格式的实训测试用例
+ # params = {:challengeStage => "#{@challenge.position}", :challengeType => "#{@challenge.evaluation_way.to_i}",
+ # :challengeProgramName => "#{@challenge.exec_path}",
+ # :trainingID => "#{@shixun.id}", :operationEnvironment => @shixun.language}
+ def gameInfo
+ fragments = []
+ testSet = []
+ testCases = []
+ challenges = self.challenges.includes(:test_sets)
+ challenges.each do |challenge|
+ pipeline_script = {:challengeStage => "#{challenge.position}",
+ :challengeType => "#{challenge.evaluation_way.to_i}",
+ :challengeProgramName => "#{challenge.exec_path}"}
+ fragments << pipeline_script
+ # 每一关所有的测试集
+ challenge.test_sets.each do |test_set|
+ test_cases = {:input => test_set.input, :output => test_set.output}
+ testSet << test_cases
+ end
+ test_sets_list = {:challengeStage => challenge.position.to_s, :challengeTestCases => testSet}
+ testCases << test_sets_list
+ testSet = []
+ end
+ gameInfo = {:tpmID => self.id.to_s, :operationEnvironment => "#{self.try(:language)}", :challengeInfo => fragments, :testCases => testCases}
+ gameInfo = Base64.urlsafe_encode64(gameInfo.to_json) unless gameInfo.blank?
+ return gameInfo
+ end
+
+ # id 转换成 identifier
+ def to_param
+ identifier
+ end
+
+ def shixun_trainee
+ trainee = ""
+ case self.trainee
+ when 1
+ trainee = "初级学员"
+ when 2
+ trainee = "中级学员"
+ when 3
+ trainee = "高级学员"
+ when 4
+ trainee = "顶级学员"
+ end
+ trainee
+ end
def owner
User.find(self.user_id)
rescue ActiveRecord::RecordNotFound
render_404
end
+
+ def shixun_score
+ score = 0
+ self.challenges.each do |challenge|
+ score += challenge.score.to_i
+ end
+ score
+ end
+
+ def shixun_status
+ status = ""
+ case self.status
+ when 0
+ status = "编辑中"
+ when 1
+ status = "审核中"
+ when 2
+ status = "已发布"
+ when 3
+ status = "已关闭"
+ end
+ end
+
+ def collaborators
+ self.shixun_members.select{|member| member.role == 2} unless self.shixun_members.blank?
+ end
end
diff --git a/app/models/shixun_major_course.rb b/app/models/shixun_major_course.rb
new file mode 100644
index 000000000..83305a09b
--- /dev/null
+++ b/app/models/shixun_major_course.rb
@@ -0,0 +1,6 @@
+class ShixunMajorCourse < ActiveRecord::Base
+ belongs_to :shixun
+ belongs_to :major
+ belongs_to :course_list
+ #attr_accessible :course_list
+end
diff --git a/app/models/shixun_member.rb b/app/models/shixun_member.rb
index c39c2521c..beab86fff 100644
--- a/app/models/shixun_member.rb
+++ b/app/models/shixun_member.rb
@@ -1,4 +1,5 @@
class ShixunMember < ActiveRecord::Base
+ # role 实训角色: 1 创建者 2 合作者
attr_accessible :shixun_id, :user_id, :role
belongs_to :shixun
belongs_to :user
diff --git a/app/models/shixun_modify.rb b/app/models/shixun_modify.rb
new file mode 100644
index 000000000..e92edbc1b
--- /dev/null
+++ b/app/models/shixun_modify.rb
@@ -0,0 +1,4 @@
+class ShixunModify < ActiveRecord::Base
+ attr_accessible :myshixun_id, :shixun_id, :status
+ belongs_to :myshixun
+end
diff --git a/app/models/shixun_port.rb b/app/models/shixun_port.rb
new file mode 100644
index 000000000..d7e04b397
--- /dev/null
+++ b/app/models/shixun_port.rb
@@ -0,0 +1,4 @@
+class ShixunPort < ActiveRecord::Base
+ attr_accessible :port, :shixun_id
+ belongs_to :shixun
+end
diff --git a/app/models/stage.rb b/app/models/stage.rb
new file mode 100644
index 000000000..d284c62e9
--- /dev/null
+++ b/app/models/stage.rb
@@ -0,0 +1,7 @@
+class Stage < ActiveRecord::Base
+ belongs_to :subject
+ belongs_to :user
+ attr_accessible :description, :name, :position, :subject_id, :user_id
+
+ has_many :stage_shixuns, :dependent => :destroy, :order => "stage_shixuns.position ASC"
+end
diff --git a/app/models/stage_shixun.rb b/app/models/stage_shixun.rb
new file mode 100644
index 000000000..8ad272e08
--- /dev/null
+++ b/app/models/stage_shixun.rb
@@ -0,0 +1,6 @@
+class StageShixun < ActiveRecord::Base
+ belongs_to :subject
+ belongs_to :stage
+ belongs_to :shixun
+ attr_accessible :position, :subject_id, :stage_id, :shixun_id
+end
diff --git a/app/models/student_work.rb b/app/models/student_work.rb
index 9ea0e75eb..8bb374ffc 100644
--- a/app/models/student_work.rb
+++ b/app/models/student_work.rb
@@ -1,6 +1,7 @@
#学生提交作品表 #work_status :0 未提交 1 已提交 2 迟交 3 分组作品复制的组员作品
class StudentWork < ActiveRecord::Base
- attr_accessible :name, :description, :homework_common_id, :user_id, :final_score, :teacher_score, :student_score, :teaching_asistant_score, :system_score, :work_score, :project_id, :is_test, :simi_id, :simi_value, :work_status, :commit_time, :late_penalty, :absence_penalty, :re_commit
+ attr_accessible :name, :description, :homework_common_id, :user_id, :final_score, :teacher_score, :student_score, :teaching_asistant_score, :system_score, :work_score, :project_id, :is_test, :simi_id,
+ :simi_value, :work_status, :commit_time, :late_penalty, :absence_penalty, :re_commit, :late_reason, :group_id, :myshixun_id
belongs_to :homework_common
belongs_to :user
@@ -12,9 +13,10 @@ class StudentWork < ActiveRecord::Base
# course's message
has_many :course_messages, :class_name =>'CourseMessage', :as => :course_message, :dependent => :destroy
has_many :attachments, :dependent => :destroy
+ belongs_to :myshixun
scope :has_committed, lambda{where("work_status != 0 and work_status != 3")}
- scope :no_copy, lambda{where("work_status != 3")}
+ scope :all_commit, lambda{where("work_status != 0")}
before_destroy :delete_praise
before_save :set_program_score, :set_src
@@ -49,7 +51,7 @@ class StudentWork < ActiveRecord::Base
#成绩计算
def set_final_score homework,student_work
- if homework && homework.homework_detail_manual
+ if homework && homework.homework_type != 4 && homework.homework_detail_manual
if homework.homework_type != 2 #非编程作业
if homework.teacher_priority == 1 #教师优先
if student_work.teacher_score
@@ -176,16 +178,16 @@ class StudentWork < ActiveRecord::Base
#更新course_homework_statistics中的avg_score和total_score
def update_avg_sum_score
- course_homework_statistics = CourseHomeworkStatistics.where(:user_id => self.user_id, :course_id => self.homework_common.course_id).first
- if course_homework_statistics
- course = self.homework_common.course
- homework_ids = course.homework_commons.empty? ? "(-1)" : "(" + course.homework_commons.map{|hw| hw.id}.join(",") + ")"
- student_works = StudentWork.where("homework_common_id in #{homework_ids} and work_status !=0")
- user = self.user
- average_score = user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first.score : 0
- total_score = user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first.score : 0
- course_homework_statistics.update_attributes(:average_score => average_score, :total_score => total_score)
- end
+ # course_homework_statistics = CourseHomeworkStatistics.where(:user_id => self.user_id, :course_id => self.homework_common.course_id).first
+ # if course_homework_statistics
+ # course = self.homework_common.course
+ # homework_ids = course.homework_commons.empty? ? "(-1)" : "(" + course.homework_commons.map{|hw| hw.id}.join(",") + ")"
+ # student_works = StudentWork.where("homework_common_id in #{homework_ids} and work_status !=0")
+ # user = self.user
+ # average_score = user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first.score : 0
+ # total_score = user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first.score : 0
+ # course_homework_statistics.update_attributes(:average_score => average_score, :total_score => total_score)
+ # end
end
# status == 0 : delay
diff --git a/app/models/students_for_course.rb b/app/models/students_for_course.rb
index f3e0cb530..14071a3be 100644
--- a/app/models/students_for_course.rb
+++ b/app/models/students_for_course.rb
@@ -10,7 +10,7 @@ class StudentsForCourse < ActiveRecord::Base
validates_uniqueness_of :student_id, :scope => :course_id
after_destroy :delete_student_works, :delete_course_homework_statistic
- after_create :recovery_student_works, :create_student_works, :create_course_homework_statistic, :create_course_contribute_score
+ after_create :recovery_student_works, :create_student_works, :create_exercise_users
#退出班级或删除学生时隐藏学生的作品
def delete_student_works
@@ -23,50 +23,91 @@ class StudentsForCourse < ActiveRecord::Base
#加入班级时还原作品
def recovery_student_works
course = self.course
- homework_ids = course.homework_commons.blank? ? "(-1)" : "(" + course.homework_commons.map{|hw| hw.id}.join(",") + ")"
- student_works = StudentWork.where("user_id = #{self.student_id} && homework_common_id in #{homework_ids}")
+ homework_ids = course.homework_commons.map(&:id)
+ student_works = StudentWork.where(:user_id => self.student_id, :homework_common_id => homework_ids)
student_works.update_all(:is_delete => 0)
end
#加入班级时创建已发布作业的作品
def create_student_works
course = self.course
- course.homework_commons.includes(:homework_detail_manual).where("homework_detail_manuals.comment_status > 0").each do |hw|
- if hw.homework_type != 3 && hw.student_works.where("user_id = #{self.student_id}").count == 0
- hw.student_works << StudentWork.new(:user_id => self.student_id, :name => hw.name.to_s+"的作品提交", :work_status => 0)
+ str = ""
+ homeworks = course.homework_commons.includes(:homework_detail_manual).where("homework_detail_manuals.comment_status != 0")
+ if homeworks.count != 0
+ homeworks.each do |hw|
+ if hw.student_works.where("user_id = #{self.student_id}").count == 0
+ if str != ""
+ str += ","
+ end
+ #if hw.homework_type == 4
+ #myshixun = Myshixun.where(:shixun_id => hw.homework_commons_shixuns.shixun_id, :user_id => self.student_id).first
+ # if myshixun
+ # str += "('#{hw.name}的作品提交',#{hw.id},#{self.student_id}, 1, #{myshixun.id}, '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
+ # else
+ # str += "('#{hw.name}的作品提交',#{hw.id},#{self.student_id}, 0, null, null, '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
+ # end
+ #else
+ str += "('#{hw.name}的作品提交',#{hw.id},#{self.student_id}, 0, null, null, '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
+ #end
+ end
+ end
+ if str != ""
+ sql = "insert into student_works (name, homework_common_id, user_id, work_status, myshixun_id, commit_time, created_at, updated_at) values" + str
+ ActiveRecord::Base.connection.execute sql
+ end
+ end
+ end
+
+ # 加入班级时创建已发布试卷的作品
+ def create_exercise_users
+ course = self.course
+ str = ""
+ exercises = course.exercises.where("exercise_status > 1")
+ if exercises.count != 0
+ exercises.each do |ex|
+ if ex.exercise_users.where("user_id = #{self.student_id}").count == 0
+ if str != ""
+ str += ","
+ end
+ str += "(#{ex.id},#{self.student_id}, 0, '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
+ end
+ end
+ if str != ""
+ sql = "insert into exercise_users (exercise_id, user_id, commit_status, created_at, updated_at) values" + str
+ ActiveRecord::Base.connection.execute sql
end
end
end
#加入班级时创建一条记录
def create_course_homework_statistic
- if CourseHomeworkStatistics.where(:user_id => self.student_id, :course_id => self.course_id).count == 0
- course = self.course
- user = self.student
- hw_count = course.homework_commons.includes(:homework_detail_manual).where("homework_detail_manuals.comment_status > 0").count
- homework_ids = course.homework_commons.empty? ? "(-1)" : "(" + course.homework_commons.map{|hw| hw.id}.join(",") + ")"
- student_works = StudentWork.where("homework_common_id in #{homework_ids} and work_status !=0")
- is_eva_homeworks = course.homework_commons.includes(:homework_detail_manual).where("homework_commons.anonymous_comment = 0 and homework_detail_manuals.comment_status = 2")
- is_eva_student_works = StudentWork.where(:homework_common_id => is_eva_homeworks.map{|hw| hw.id})
- has_eva_homeworks = course.homework_commons.includes(:homework_detail_manual).where("homework_commons.anonymous_comment = 0 and homework_detail_manuals.comment_status = 3")
- has_eva_student_works = StudentWork.where(:homework_common_id => has_eva_homeworks.map{|hw| hw.id})
-
- committed_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status != 0").count
- un_commit_work_num = (hw_count - committed_work_num) < 0 ? 0 : (hw_count - committed_work_num)
- late_commit_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status = 2").count
- absence_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => has_eva_student_works.map(&:id)).count -
- user.student_works_scores.where(:reviewer_role => 3, :student_work_id => has_eva_student_works.map(&:id)).group_by(&:student_work_id).count
- absence_evaluation_work_num = absence_evaluation_work_num < 0 ? 0 : absence_evaluation_work_num
- un_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => is_eva_student_works.map(&:id)).count -
- user.student_works_scores.where(:reviewer_role => 3, :student_work_id => is_eva_student_works.map(&:id)).group_by(&:student_work_id).count
- un_evaluation_work_num = un_evaluation_work_num < 0 ? 0 : un_evaluation_work_num
- appeal_num = user.student_works_scores.where(:student_work_id => student_works.map(&:id), :appeal_status => 3).count
- average_score = user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first.score : 0
- total_score = user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first.score : 0
- CourseHomeworkStatistics.create(:course_id => course.id, :user_id => user.id, :committed_work_num => committed_work_num, :un_commit_work_num => un_commit_work_num,
- :late_commit_work_num => late_commit_work_num, :absence_evaluation_work_num => absence_evaluation_work_num, :un_evaluation_work_num => un_evaluation_work_num,
- :appeal_num => appeal_num, :average_score => average_score, :total_score => total_score)
- end
+ # if CourseHomeworkStatistics.where(:user_id => self.student_id, :course_id => self.course_id).count == 0
+ # course = self.course
+ # user = self.student
+ # hw_count = course.homework_commons.includes(:homework_detail_manual).where("homework_detail_manuals.comment_status > 0").count
+ # homework_ids = course.homework_commons.empty? ? "(-1)" : "(" + course.homework_commons.map{|hw| hw.id}.join(",") + ")"
+ # student_works = StudentWork.where("homework_common_id in #{homework_ids} and work_status !=0")
+ # is_eva_homeworks = course.homework_commons.includes(:homework_detail_manual).where("homework_commons.anonymous_comment = 0 and homework_detail_manuals.comment_status = 2")
+ # is_eva_student_works = StudentWork.where(:homework_common_id => is_eva_homeworks.map{|hw| hw.id})
+ # has_eva_homeworks = course.homework_commons.includes(:homework_detail_manual).where("homework_commons.anonymous_comment = 0 and homework_detail_manuals.comment_status = 3")
+ # has_eva_student_works = StudentWork.where(:homework_common_id => has_eva_homeworks.map{|hw| hw.id})
+ #
+ # committed_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status != 0").count
+ # un_commit_work_num = (hw_count - committed_work_num) < 0 ? 0 : (hw_count - committed_work_num)
+ # late_commit_work_num = user.student_works.where("homework_common_id in #{homework_ids} and work_status = 2").count
+ # absence_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => has_eva_student_works.map(&:id)).count -
+ # user.student_works_scores.where(:reviewer_role => 3, :student_work_id => has_eva_student_works.map(&:id)).group_by(&:student_work_id).count
+ # absence_evaluation_work_num = absence_evaluation_work_num < 0 ? 0 : absence_evaluation_work_num
+ # un_evaluation_work_num = user.student_works_evaluation_distributions.where(:student_work_id => is_eva_student_works.map(&:id)).count -
+ # user.student_works_scores.where(:reviewer_role => 3, :student_work_id => is_eva_student_works.map(&:id)).group_by(&:student_work_id).count
+ # un_evaluation_work_num = un_evaluation_work_num < 0 ? 0 : un_evaluation_work_num
+ # appeal_num = user.student_works_scores.where(:student_work_id => student_works.map(&:id), :appeal_status => 3).count
+ # average_score = user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("AVG(student_works.work_score) as score").first.score : 0
+ # total_score = user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first ? user.student_works.where(:id => student_works.map(&:id)).select("SUM(student_works.work_score) as score").first.score : 0
+ # CourseHomeworkStatistics.create(:course_id => course.id, :user_id => user.id, :committed_work_num => committed_work_num, :un_commit_work_num => un_commit_work_num,
+ # :late_commit_work_num => late_commit_work_num, :absence_evaluation_work_num => absence_evaluation_work_num, :un_evaluation_work_num => un_evaluation_work_num,
+ # :appeal_num => appeal_num, :average_score => average_score, :total_score => total_score)
+ # end
end
def delete_course_homework_statistic
@@ -74,23 +115,23 @@ class StudentsForCourse < ActiveRecord::Base
end
def create_course_contribute_score
- ccs = CourseContributorScore.where("course_id =? and user_id =?", self.course_id, self.student_id).first
- unless ccs
- course = self.course
- user_id = self.student_id
- message_num = Message.find_by_sql("select DISTINCT me.* from messages me, boards b where b.id = me.board_id and b.course_id = #{course.id} and b.project_id = '-1' and me.author_id = #{user_id} and me.parent_id is null;").count
- message_reply_num = Message.find_by_sql("select DISTINCT me.* from messages me, boards b where b.id = me.board_id and b.course_id = #{course.id} and b.project_id = '-1' and me.author_id = #{user_id} and me.parent_id is not null").count
- news_reply_num = Comment.find_by_sql("select cm.* from comments cm, news n where cm.author_id = #{user_id} and n.course_id = #{course.id} and cm.commented_id = n.id and cm.commented_type ='News'").count
-
- resource_num = Attachment.find_by_sql("SELECT * FROM `attachments` where container_id = #{course.id} and author_id = #{user_id} and container_type ='Course'").count
- journal_num = JournalsForMessage.where("user_id =? and jour_id =? and jour_type =?", user_id, course.id, "Course").count
- journal_reply_num = JournalsForMessage.where("user_id =? and jour_id =? and jour_type =? and m_parent_id is not null", user_id, course.id, "Course").count
- homework_ids = course.homework_commons.empty? ? "(-1)" : "(" + course.homework_commons.map(&:id).join(',') + ")"
- homework_journal_num = JournalsForMessage.where("user_id =? and jour_id in #{homework_ids} and jour_type =?", user_id, "HomeworkCommon").count
- news_num = News.where("author_id = #{user_id} and course_id =#{course.id}").count
- total = message_num*2 + message_reply_num*1 + news_reply_num*1 + news_num*1 + resource_num*5 + journal_num*1 + homework_journal_num*1
- CourseContributorScore.create(:course_id => self.course_id, :user_id => self.student_id, :message_num => message_num, :message_reply_num => message_reply_num, :news_reply_num => news_reply_num,
- :resource_num => resource_num, :journal_num => journal_num, :journal_reply_num => journal_reply_num, :total_score => total, :homework_journal_num => homework_journal_num, :news_num => news_num)
- end
+ # ccs = CourseContributorScore.where("course_id =? and user_id =?", self.course_id, self.student_id).first
+ # unless ccs
+ # course = self.course
+ # user_id = self.student_id
+ # message_num = Message.find_by_sql("select DISTINCT me.* from messages me, boards b where b.id = me.board_id and b.course_id = #{course.id} and b.project_id = '-1' and me.author_id = #{user_id} and me.parent_id is null;").count
+ # message_reply_num = Message.find_by_sql("select DISTINCT me.* from messages me, boards b where b.id = me.board_id and b.course_id = #{course.id} and b.project_id = '-1' and me.author_id = #{user_id} and me.parent_id is not null").count
+ # news_reply_num = Comment.find_by_sql("select cm.* from comments cm, news n where cm.author_id = #{user_id} and n.course_id = #{course.id} and cm.commented_id = n.id and cm.commented_type ='News'").count
+ #
+ # resource_num = Attachment.find_by_sql("SELECT * FROM `attachments` where container_id = #{course.id} and author_id = #{user_id} and container_type ='Course'").count
+ # journal_num = JournalsForMessage.where("user_id =? and jour_id =? and jour_type =?", user_id, course.id, "Course").count
+ # journal_reply_num = JournalsForMessage.where("user_id =? and jour_id =? and jour_type =? and m_parent_id is not null", user_id, course.id, "Course").count
+ # homework_ids = course.homework_commons.empty? ? "(-1)" : "(" + course.homework_commons.map(&:id).join(',') + ")"
+ # homework_journal_num = JournalsForMessage.where("user_id =? and jour_id in #{homework_ids} and jour_type =?", user_id, "HomeworkCommon").count
+ # news_num = News.where("author_id = #{user_id} and course_id =#{course.id}").count
+ # total = message_num*2 + message_reply_num*1 + news_reply_num*1 + news_num*1 + resource_num*5 + journal_num*1 + homework_journal_num*1
+ # CourseContributorScore.create(:course_id => self.course_id, :user_id => self.student_id, :message_num => message_num, :message_reply_num => message_reply_num, :news_reply_num => news_reply_num,
+ # :resource_num => resource_num, :journal_num => journal_num, :journal_reply_num => journal_reply_num, :total_score => total, :homework_journal_num => homework_journal_num, :news_num => news_num)
+ # end
end
end
diff --git a/app/models/subject.rb b/app/models/subject.rb
new file mode 100644
index 000000000..fc4fa393c
--- /dev/null
+++ b/app/models/subject.rb
@@ -0,0 +1,55 @@
+class Subject < ActiveRecord::Base
+ #status :0 编辑中 1 审核中 2 发布
+ belongs_to :user
+ belongs_to :course_list
+ belongs_to :major
+ attr_accessible :description, :name, :status, :visits, :user_id, :course_list_id, :major_id, :learning_notes, :introduction
+
+ has_many :stages, :dependent => :destroy, :order => "stages.id ASC"
+ has_many :stage_shixuns, :dependent => :destroy
+
+ def subject_choices
+ count = 0
+ self.stage_shixuns.each do |stage_shixun|
+ shixun = stage_shixun.shixun
+ count += shixun.challenges.where(:st => [1, 2]).count
+ end
+ count
+ end
+
+ def subject_shixuns
+ count = 0
+ self.stage_shixuns.each do |stage_shixun|
+ shixun = stage_shixun.shixun
+ count += shixun.challenges.where(:st => 0).count
+ end
+ count
+ end
+
+ def subject_challenges
+ count = 0
+ self.stage_shixuns.each do |stage_shixun|
+ shixun = stage_shixun.shixun
+ count += shixun.challenges.count
+ end
+ count
+ end
+
+ def subject_users
+ count = 0
+ self.stage_shixuns.each do |stage_shixun|
+ shixun = stage_shixun.shixun
+ count += shixun.myshixuns.count
+ end
+ count
+ end
+
+ def subject_score
+ score = 0
+ self.stage_shixuns.each do |stage_shixun|
+ shixun = stage_shixun.shixun
+ score += shixun.shixun_score
+ end
+ score
+ end
+end
diff --git a/app/models/syllabus.rb b/app/models/syllabus.rb
index ea5d44dfd..223e19917 100644
--- a/app/models/syllabus.rb
+++ b/app/models/syllabus.rb
@@ -1,129 +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 :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
- attr_accessible :description, :user_id, :title, :eng_name, :syllabus_type, :credit, :hours, :theory_hours, :practice_hours, :applicable_major, :pre_course
- safe_attributes 'title','user', 'description', 'eng_name', 'syllabus_type', 'credit', 'hours', 'theory_hours', 'practice_hours', 'credit', 'applicable_major', 'pre_course'
-
- 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_type_str
- case self.syllabus_type
- when 1
- type = "公共必修课"
- when 2
- type = "学科必修课"
- when 3
- type = "专业选修课"
- when 4
- type = "实践必修课"
- when 5
- type = "实践选修课"
- end
- type
- 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,:support_shixuns
+ 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/models/syllabus_update_record.rb b/app/models/syllabus_update_record.rb
new file mode 100644
index 000000000..f5d2481e4
--- /dev/null
+++ b/app/models/syllabus_update_record.rb
@@ -0,0 +1,6 @@
+class SyllabusUpdateRecord < ActiveRecord::Base
+ belongs_to :user
+ belongs_to :syllabus
+ #property 1:描述 2:参考资料
+ attr_accessible :property, :syllabus_id, :user_id
+end
diff --git a/app/models/test_set.rb b/app/models/test_set.rb
index b42172970..86ae6887b 100644
--- a/app/models/test_set.rb
+++ b/app/models/test_set.rb
@@ -1,4 +1,5 @@
class TestSet < ActiveRecord::Base
- attr_accessible :challenge_id, :input, :output, :game_id
+ default_scope :order => 'id asc'
+ attr_accessible :challenge_id, :input, :output, :game_id, :actual_output, :is_public, :result, :position
belongs_to :challenge
end
diff --git a/app/models/tiding.rb b/app/models/tiding.rb
new file mode 100644
index 000000000..68c2f841d
--- /dev/null
+++ b/app/models/tiding.rb
@@ -0,0 +1,19 @@
+# 使用请了解以下描述,不清楚请@Hjqreturn
+#
+# user_id: 信息接收人
+# trigger_user_id: 信息的触发者,具体情况可能有所不同。eg:产生消息的用户ID;处理消息的用户ID等
+# container_id:消息实体的ID。eg:issue的id
+# container_type:消息实体的类型。eg:“Issue","Board"
+# parent_container_id:消息实体的父实体消息的id,是为了生成url时使用,避免反复查数据库。eg:message中的board 的id
+# parent_container_type:消息实体的父实体消息类型,便于分类。eg:“Message","Board"
+# belong_container_id:消息实体所属的实体ID。eg:project_id,course_id,organization_id
+# belong_container_type:消息实体所属的实体类型。eg:“Project”,“Course”,"Shixun"
+# status:消息实体的状态。eg:“已处理”,“未处理”
+# viewed:消息是否已读。eg:1 -> 已读; 0 -> 未读
+#
+class Tiding < ActiveRecord::Base
+ attr_accessible :belong_container_id, :belong_container_type, :container_id, :container_type, :parent_container_id,
+ :parent_container_type, :status, :trigger_user_id, :user_id, :viewed
+
+
+end
diff --git a/app/models/user.rb b/app/models/user.rb
index f023fde4b..8afdf1c34 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,3 +1,4 @@
+# encoding: utf-8
# Redmine - project management software
# Copyright (C) 2006-2013 Jean-Philippe Lang
#
@@ -86,7 +87,9 @@ class User < Principal
# ['all', :label_user_mail_option_all],
# ['none', :label_user_mail_option_none]
# ]
-
+ # has_many :users_authenticationses
+ # has_many :authentications, :through => :users_authenticationses
+ has_and_belongs_to_many :authentications, :order => "#{Authentication.table_name}.level"
has_many :homework_users
has_many :homework_attaches, :through => :homework_users
has_many :homework_evaluations
@@ -124,8 +127,12 @@ class User < Principal
has_many :contestant_work_scores
has_many :contestant_work_projects
+ has_many :shixuns, :through => :shixun_members
has_many :shixun_members, :dependent => :destroy
has_many :challenges, :dependent => :destroy
+ has_many :games, :dependent => :destroy
+
+ has_many :subjects
has_and_belongs_to_many :groups, :after_add => Proc.new {|user, group| group.user_added(user)},
:after_remove => Proc.new {|user, group| group.user_removed(user)}
@@ -196,9 +203,16 @@ class User < Principal
#####
has_many :shares ,:dependent => :destroy
+ has_many :grades
+ has_many :experiences
+
+ ###
+ has_many :apply_actions, :dependent => :destroy
+
has_one :user_wechat
has_one :sso
+ has_many :apply_user_authentication
# add by zjc
has_one :level, :class_name => 'UserLevels', :dependent => :destroy
@@ -209,7 +223,6 @@ class User < Principal
scope :visible, lambda {|*args|
nil
}
-
acts_as_attachable :view_permission => :view_files,
:delete_permission => :manage_files
acts_as_customizable
@@ -251,6 +264,7 @@ class User < Principal
validates_presence_of :login, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false
validates_uniqueness_of :mail, :if => Proc.new { |user| user.mail_changed? && user.mail.present? }, :case_sensitive => false
+ validates_uniqueness_of :phone, :if => Proc.new { |user| user.phone_changed? && user.phone.present? }, :case_sensitive => false
# Login must contain letters, numbers, underscores only
validates_format_of :login, :with => /\A[a-z0-9_\-\.]*\z/i
validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT
@@ -300,6 +314,11 @@ class User < Principal
end
end
}
+ def challenge_tags
+ games = self.games.where(:id => self.experiences.map(&:container_id), :status => 2)
+ challenge_tags = ChallengeTag.where(:challenge_id => games.map(&:challenge_id)).where("name != ''")
+ end
+
def self.search(query)
__elasticsearch__.search(
{
@@ -420,6 +439,11 @@ class User < Principal
messages_count = course_count + contest_count + forge_count + user_feedback_count + user_memo_count + system_messages_count + at_count + org_count + applied_count + blog_message_count
end
+ # 用户的学校名称
+ def school_name
+ (!self.user_extensions.school_id.blank? && self.user_extensions.school) ? self.user_extensions.school.name : ""
+ end
+
# 查询指派给我的缺陷记录
def issue_status_update
self.status_updates
@@ -474,8 +498,17 @@ class User < Principal
end
def show_name
+ if self.show_realname
+ name = lastname + firstname
+ else
+ name = nickname
+ end
+ name.blank? ? login : name
+ end
+
+ def show_real_name
name = lastname + firstname
- name.empty? || name.nil? ? login : name
+ name.blank? ? login : name
end
def show_occupation
@@ -537,6 +570,20 @@ class User < Principal
self.read_attribute(:identity_url)
end
+ # 判断用户的身份
+ def identity
+ ue = self.user_extensions
+ unless ue.blank?
+ if ue.identity == 0
+ result = ue.technical_title ? ue.technical_title : "老师"
+ elsif ue.identity == 1
+ result = "学生"
+ else
+ result = ue.technical_title ? ue.technical_title : "专业人士"
+ end
+ end
+ end
+
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
VALID_PHONE_REGEX = /^1\d{10}$/
# VALID_EMAIL_REGEX = /^[0-9a-zA-Z_-]+@[0-9a-zA-Z_-]+(\.[0-9a-zA-Z_-]+)+$/
@@ -605,6 +652,16 @@ class User < Principal
name_formatter[:order].map {|field| "#{table}.#{field}"}
end
+ # 186***2342
+ def user_phone
+ phone.nil? || (phone && phone.empty?) ? "" : phone.gsub(/(\d{3})\d{4}(\d{4})/, '\1****\2')
+ end
+
+ # 8***2@qq.com
+ def user_mail
+ mail.nil? || (mail && mail.empty?) ? "" : mail.gsub(/(.{1}).+(.{1}@.+)/, '\1****\2')
+ end
+
# Return user's full name for display
def realname(formatter = nil)
f = self.class.name_formatter(formatter)
@@ -615,10 +672,6 @@ class User < Principal
end
end
- def nickname(formatter = nil)
- login.nil? || (login && login.empty?) ? "AnonymousUser" : login
- end
-
def name(formatter = nil)
login
end
@@ -835,6 +888,10 @@ class User < Principal
!logged?
end
+ def system_authentication?
+ self.authentication.blank? ? false : true
+ end
+
# Returns user's membership for the given project
# or nil if the user is not a member of project
def membership(project)
@@ -902,16 +959,21 @@ class User < Principal
projects.to_a.include?(project)
end
+ # 超级管理员或者创建者
+ def manager_of_subject?(subject)
+ (subject.user == User.current || User.current.admin?) ? true : false
+ end
+
+
# 超级管理员或者role为1
def manager_of_shixun?(shixun)
- member = ShixunMember.where(:user_id => self.id, :shixun_id => shixun.id, :role => 1)
+ member = ShixunMember.where(:user_id => self.id, :shixun_id => shixun, :role => [1,2])
(!member.blank? || User.current.admin?) ? true : false
end
# 超级管理员或者role为1
def manager_of_myshixun?(myshixun)
- member = MyshixunMember.where(:user_id => self.id, :myshixun_id => myshixun.id, :role => 1)
- (!member.blank? || User.current.admin?) ? true : false
+ (User.current.id == myshixun.user_id || User.current.admin?) ? true : false
end
def member_of_course?(course)
@@ -1076,6 +1138,17 @@ class User < Principal
end
end
+ #是否是老师(不包括助教)
+ def teacher_of_course(course)
+ member = course.members.where("user_id = #{self.id}").first
+ if !member.nil?
+ role = MemberRole.where("member_id = #{member.id} and role_id in (3, 9)")
+ !role.blank?
+ else
+ return false
+ end
+ end
+
#是否具有老师角色
def has_teacher_role(course)
member = course.members.where("user_id = #{self.id}").first
@@ -1198,7 +1271,12 @@ class User < Principal
'language',
'custom_field_values',
'custom_fields',
- 'identity_url'
+ 'identity_url',
+ 'phone',
+ 'authentication',
+ 'nickname',
+ 'professional_certification',
+ 'ID_number'
safe_attributes 'status',
'auth_source_id',
@@ -1352,21 +1430,21 @@ class User < Principal
# 为新注册用户发送留言
# 只发三条没可以不用delay job,而且这个最好是注册的时候就能看到
def add_new_jour
- Rails.logger.info "add_new_jour_delay!!!!!!!!!"
- if Setting.find_by_name("hidden_non_project") && Setting.find_by_name("hidden_non_project").value != "0"
- if Message.where("id=19504").any? and Message.where("id=19291").any? and Message.where("id=19292").any?
- lead_message1 = Message.find(19292)
- notes1 = lead_message1.content
- lead_message2 = Message.find(19291)
- notes2 = lead_message2.content
- lead_message3 = Message.find(19504)
- notes3 = lead_message3.content
- #user_id 默认为课程使者创建
- self.journals_for_messages << JournalsForMessage.new(:user_id => 1, :notes => notes1, :reply_id => 0, :status => true, :is_readed => false, :private => 0)
- self.journals_for_messages << JournalsForMessage.new(:user_id => 1, :notes => notes2, :reply_id => 0, :status => true, :is_readed => false, :private => 0)
- self.journals_for_messages << JournalsForMessage.new(:user_id => 1, :notes => notes3, :reply_id => 0, :status => true, :is_readed => false, :private => 0)
- end
- end
+ # Rails.logger.info "add_new_jour_delay!!!!!!!!!"
+ # if Setting.find_by_name("hidden_non_project") && Setting.find_by_name("hidden_non_project").value != "0"
+ # if Message.where("id=19504").any? and Message.where("id=19291").any? and Message.where("id=19292").any?
+ # lead_message1 = Message.find(19292)
+ # notes1 = lead_message1.content
+ # lead_message2 = Message.find(19291)
+ # notes2 = lead_message2.content
+ # lead_message3 = Message.find(19504)
+ # notes3 = lead_message3.content
+ # #user_id 默认为课程使者创建
+ # self.journals_for_messages << JournalsForMessage.new(:user_id => 1, :notes => notes1, :reply_id => 0, :status => true, :is_readed => false, :private => 0)
+ # self.journals_for_messages << JournalsForMessage.new(:user_id => 1, :notes => notes2, :reply_id => 0, :status => true, :is_readed => false, :private => 0)
+ # self.journals_for_messages << JournalsForMessage.new(:user_id => 1, :notes => notes3, :reply_id => 0, :status => true, :is_readed => false, :private => 0)
+ # end
+ # end
# self.delay.add_new_jour_delay
end
diff --git a/app/models/user_extensions.rb b/app/models/user_extensions.rb
index a02b1ac6a..6beafa0b8 100644
--- a/app/models/user_extensions.rb
+++ b/app/models/user_extensions.rb
@@ -3,14 +3,15 @@
identity字段含义
0 教师教授
1 学生
- 2 企业
- 3 开发者
+ 2 专业人士
+ #3 开发者
=end
class UserExtensions < ActiveRecord::Base
validate :school, presence: true
belongs_to :user
belongs_to :school, :class_name => 'School', :foreign_key => :school_id
+ belongs_to :department
attr_accessible :user_id,:birthday,:brief_introduction,:gender,:location,:occupation,:work_experience,:zip_code,:identity, :technical_title,:student_id
validates_length_of :description, :maximum => 255
validates_length_of :brief_introduction, :maximum => 255
@@ -45,9 +46,9 @@ class UserExtensions < ActiveRecord::Base
when 1
user_identity = l(:label_account_identity_student)
when 2
- user_identity = l(:label_account_identity_enterprise)
+ user_identity = l(:label_account_identity_professional)
when 3
- user_identity = l(:label_account_identity_developer)
+ user_identity = l(:label_account_identity_professional)
else
user_identity = ''
end
@@ -58,9 +59,9 @@ class UserExtensions < ActiveRecord::Base
when 1
user_identity = l(:label_account_identity_student)
when 2
- user_identity = l(:label_account_identity_enterprise)
+ user_identity = l(:label_account_identity_professional)
when 3
- user_identity = l(:label_account_identity_developer)
+ user_identity = l(:label_account_identity_professional)
else
user_identity = ''
end
@@ -83,6 +84,23 @@ class UserExtensions < ActiveRecord::Base
end
end
-
+ def user_technical_title
+ if self.technical_title
+ title = self.technical_title
+ else
+ case self.identity
+ when 0
+ title = l(:label_account_identity_teacher)
+ when 1
+ title = l(:label_account_identity_student)
+ when 2
+ title = l(:label_account_identity_professional)
+ when 3
+ title = l(:label_account_identity_professional)
+ else
+ title = ''
+ end
+ end
+ end
end
diff --git a/app/models/webssh.rb b/app/models/webssh.rb
new file mode 100644
index 000000000..5a3efd946
--- /dev/null
+++ b/app/models/webssh.rb
@@ -0,0 +1,4 @@
+class Webssh < ActiveRecord::Base
+ attr_accessible :host, :myshixun_id, :password, :port, :username
+ belongs_to :myshixun
+end
diff --git a/app/services/courses_service.rb b/app/services/courses_service.rb
index 20d7409de..f23a48366 100644
--- a/app/services/courses_service.rb
+++ b/app/services/courses_service.rb
@@ -110,7 +110,7 @@ class CoursesService
#双重身份 学生列表中不显示
# unless (params[:role] == '2' && role_ids.length >= 2)
- users << {:id => m.user.id, :img_url => img_url, :nickname => m.user.login, :gender => gender,
+ users << {:id => m.user.id, :img_url => img_url, :nickname => m.user.nickname, :gender => gender,
:work_unit => work_unit, :mail => m.user.mail, :location => location,
role_name: m.roles.first.name,
name: m.user.show_name,
@@ -138,7 +138,7 @@ class CoursesService
work_unit = get_user_work_unit user
location = get_user_location user
roles_ids = m.content.split(",")
- reviewers << {:id => user.id, :img_url => img_url, :nickname => user.login, :gender => gender,
+ reviewers << {:id => user.id, :img_url => img_url, :nickname => user.nickname, :gender => gender,
:work_unit => work_unit, :mail => user.mail, :location => location,
role_name: "",
name: user.show_name,
@@ -168,7 +168,7 @@ class CoursesService
work_unit = get_user_work_unit user
location = get_user_location user
roles_ids = messages.content.split(",")
- info = {:id => user.id, :img_url => img_url, :nickname => user.login, :gender => gender,
+ info = {:id => user.id, :img_url => img_url, :nickname => user.nickname, :gender => gender,
:work_unit => work_unit, :mail => user.mail, :location => location,
role_name: "",
name: user.show_name,
@@ -358,20 +358,30 @@ class CoursesService
@course.send(:safe_attributes=, params[:course], current_user)
#@course.safe_attributes(current_user,params[:course])
#@course.password = params[:course][:password]
+ @course.name = params[:course][:name]
@course.tea_id = current_user.id
- @course.syllabus_id = params[:syllabus_id].to_i
- @course.term = params[:term]
- @course.time = params[:time]
- @course.end_term = params[:end_term]
- @course.end_time = params[:end_time]
+ #@course.syllabus_id = params[:syllabus_id].to_i
+ #@course.term = params[:term]
+ #@course.time = params[:time]
+ #@course.end_term = params[:end_term]
+ #@course.end_time = params[:end_time]
#@course.school_id = params[:occupation]
@course.school_id = current_user.user_extensions.school_id
- @course.setup_time = params[:setup_time]
- @course.endup_time = params[:endup_time]
- @course.class_period = params[:class_period].to_i
+ #@course.setup_time = params[:setup_time]
+ #@course.endup_time = params[:endup_time]
+ @course.class_period = params[:period].to_i if params[:period]
+ @course.credit = params[:credit] if params[:credit]
+ @course.end_date = params[:end_date] if params[:end_date]
params[:course][:is_public] ? @course.is_public = 1 : @course.is_public = 0
- params[:course][:open_student] ? @course.open_student = 1 : @course.open_student = 0
- params[:course][:publish_resource] ? @course.publish_resource = 1 : @course.publish_resource = 0
+ @course.open_student = 0
+ @course.publish_resource = 1
+ if CourseList.where(:name => params[:course][:course_list].strip).count > 0
+ @course.course_list_id = CourseList.where(:name => params[:course][:course_list].strip).first.id
+ else
+ course_list = CourseList.create(:name => params[:course][:course_list].strip, :user_id => User.current.id, :is_admin => 0)
+ @course.course_list_id = course_list.id
+ end
+
else
end
@@ -380,6 +390,7 @@ class CoursesService
@trackers = Tracker.sorted.all
if @course && @course.save
+ #copy_avatar(@course, @course.syllabus)
#unless User.current.admin?
r = Role.givable.find_by_id(Setting.new_project_user_role_id.to_i) || Role.givable.first
m = Member.new(:user => current_user, :roles => [r])
@@ -418,23 +429,31 @@ class CoursesService
course.send(:safe_attributes=, params[:course], current_user)
#course.safe_attributes = params[:course]
#course.password = params[:course][:password]
+ course.name = params[:course][:name]
+ #course.tea_id = current_user.id
#course.syllabus_id = params[:syllabus_id].to_i
- course.time = params[:time]
- course.term = params[:term]
- course.end_time = params[:end_time]
- course.end_term = params[:end_term]
- course.class_period = params[:class_period].to_i
+ #course.time = params[:time]
+ #course.term = params[:term]
+ #course.end_time = params[:end_time]
+ #course.end_term = params[:end_term]
+ course.class_period = params[:period].to_i if params[:period]
+ course.credit = params[:credit] if params[:credit]
+ course.end_date = params[:end_date] if params[:end_date]
params[:course][:is_public] ? course.is_public = 1 : course.is_public = 0
- params[:course][:open_student] ? course.open_student = 1 : course.open_student = 0
- params[:course][:publish_resource] ? course.publish_resource = 1 : course.publish_resource = 0
+ if CourseList.where(:name => params[:course][:course_list].strip).count > 0
+ course.course_list_id = CourseList.where(:name => params[:course][:course_list].strip).first.id
+ else
+ course_list = CourseList.create(:name => params[:course][:course_list].strip, :user_id => User.current.id, :is_admin => 0)
+ course.course_list_id = course_list.id
+ end
if course.save
- if params[:course][:is_public] == '0'
- course_status = CourseStatus.find_by_course_id(course.id)
- course_status.destroy if course_status
- elsif params[:course][:is_public] == '1'
+ if params[:course][:is_public]
course_status = CourseStatus.find_by_course_id(course.id)
course_status.destroy if course_status
course_status = CourseStatus.create(:course_id => course.id, :grade => 0)
+ else
+ course_status = CourseStatus.find_by_course_id(course.id)
+ course_status.destroy if course_status
end
end
{:course => course,:img_url => url_to_avatar(course),:current_user_is_member => current_user.member_of_course?(course),:current_user_is_teacher => is_course_teacher(current_user,course)}
@@ -565,7 +584,7 @@ class CoursesService
type = "review_class_member"
end
- name = course.syllabus.nil? ? course.name : course.syllabus.title+" • "+course.name
+ name = course.course_list.nil? ? course.name : course.course_list_name+" • "+course.name
ws = WechatService.new
ws.class_notice user.id, type, course.id, title,name, user.show_name, format_time(Time.now), content, remark,uid
@@ -574,7 +593,7 @@ class CoursesService
#多个角色加入课程
def join_course_roles params,current_user
- course = Course.find_by_invite_code(params[:invite_code]) if params[:invite_code]
+ course = Course.find_by_invite_code(params[:invite_code].strip) if params[:invite_code]
go_coursegroup_flag = 0
course_id = 0
@@ -663,18 +682,18 @@ class CoursesService
#----------------微信通知----------------------
- if role_ids.include?("7") || role_ids.include?("9")
- tea_user = User.find(course.tea_id)
- count = ShieldWechatMessage.where("container_type='User' and container_id=#{tea_user.id} and shield_type='Course' and shield_id=#{course.id}").count
- if count == 0
-
- rolename = role_ids.include?("7") ? "助教" : "教师"
- content = current_user.show_name + "申请以"+rolename+"身份加入班级,等待您的审批。"
- name = course.syllabus.nil? ? course.name : course.syllabus.title+" • "+course.name
- ws = WechatService.new
- ws.class_notice tea_user.id, "review_class_member", course.id, "班级成员审批通知。", name, tea_user.show_name, format_time(Time.now), content, "点击查看申请详情。",current_user.id
- end
- end
+ # if role_ids.include?("7") || role_ids.include?("9")
+ # tea_user = User.find(course.tea_id)
+ # count = ShieldWechatMessage.where("container_type='User' and container_id=#{tea_user.id} and shield_type='Course' and shield_id=#{course.id}").count
+ # if count == 0
+ #
+ # rolename = role_ids.include?("7") ? "助教" : "教师"
+ # content = current_user.show_name + "申请以"+rolename+"身份加入班级,等待您的审批。"
+ # name = course.course_list.nil? ? course.name : course.course_list_name+" • "+course.name
+ # ws = WechatService.new
+ # ws.class_notice tea_user.id, "review_class_member", course.id, "班级成员审批通知。", name, tea_user.show_name, format_time(Time.now), content, "点击查看申请详情。",current_user.id
+ # end
+ # end
#--------------------------------------------
if is_stu
diff --git a/app/services/projects_service.rb b/app/services/projects_service.rb
index f3679aa22..97f67e114 100644
--- a/app/services/projects_service.rb
+++ b/app/services/projects_service.rb
@@ -215,7 +215,7 @@ class ProjectsService
gender = user.user_extensions.gender.nil? ? 0 : user.user_extensions.gender
work_unit = get_user_work_unit user
location = get_user_location user
- review_members << {:id => user.id, :img_url => img_url, :nickname => user.login, :gender => gender,
+ review_members << {:id => user.id, :img_url => img_url, :nickname => user.nickname, :gender => gender,
:work_unit => work_unit, :mail => user.mail, :location => location,
role_name: "",
name: user.show_name,
@@ -244,7 +244,7 @@ class ProjectsService
gender = user.user_extensions.gender.nil? ? 0 : user.user_extensions.gender
work_unit = get_user_work_unit user
location = get_user_location user
- info = {:id => user.id, :img_url => img_url, :nickname => user.login, :gender => gender,
+ info = {:id => user.id, :img_url => img_url, :nickname => user.nickname, :gender => gender,
:work_unit => work_unit, :mail => user.mail, :location => location,
role_name: "",
name: user.show_name,
diff --git a/app/services/users_service.rb b/app/services/users_service.rb
index 1a7601ec9..85f026537 100644
--- a/app/services/users_service.rb
+++ b/app/services/users_service.rb
@@ -99,7 +99,7 @@ class UsersService
gender = @user.user_extensions.gender.nil? ? 0 : @user.user_extensions.gender
work_unit = get_user_work_unit @user
location = get_user_location @user
- {:id => @user.id, :img_url => img_url,:realname => @user.realname, :nickname => @user.login, :gender => gender, :work_unit => work_unit, :mail => @user.mail, :location => location, :brief_introduction => @user.user_extensions.brief_introduction}
+ {:id => @user.id, :img_url => img_url,:realname => @user.realname, :nickname => @user.nickname, :gender => gender, :work_unit => work_unit, :mail => @user.mail, :location => location, :brief_introduction => @user.user_extensions.brief_introduction}
end
#忘记密码
diff --git a/app/views/account/_change_user_email.html.erb b/app/views/account/_change_user_email.html.erb
index 337516f61..e50ba6f16 100644
--- a/app/views/account/_change_user_email.html.erb
+++ b/app/views/account/_change_user_email.html.erb
@@ -55,18 +55,5 @@
}
});
- function submit_user_emails(){
- if($mail_correct == false){
- return
- }else{
- $.get('<%= account_change_email_path(:user_id => @user.id) %>',
- { valid: "mail",
- value: document.getElementById("user_mail").value },
- function (data){
- $("#user_email_show").html(data.email);
- hideModal();
- return;
- });
- }
- }
+
\ No newline at end of file
diff --git a/app/views/account/_has_authentication.html.erb b/app/views/account/_has_authentication.html.erb
new file mode 100644
index 000000000..f42f6ca6b
--- /dev/null
+++ b/app/views/account/_has_authentication.html.erb
@@ -0,0 +1,79 @@
+
+ <% if !@user.authentication && @apply_user_auth && @apply_user_auth.status == 0 %>
+ 审核中 我们将在1个工作日内完成审核,通过审核后您的资料会显示“已认证”
+ <% elsif @user.authentication %>
+ 已认证
+ <% end %>
+
+<% if false %>
+ <%= render :partial => "welcome/one_btn_mask_pop",
+ :locals => {
+ :tip1 => "更多功能,需要经过管理员的授权审核",
+ :tip2 => "认证申请已提交,我们将在1个工作日内完成审核",
+ :btn => "试用申请",
+ :url => "javascript:void(0);"
+ }
+ %>
+<% end %>
+
+
+
1.上传图片
+ <% if !@user.authentication %>
+
+
2.审核并完成认证
+ <% else %>
+
+
2.审核并完成认证
+ <% end %>
+
+
+
+
职业证明:
+
+
+ 如:教师证、学生证、工作证
+ 请根据你基本资料中填写的职业、职称和单位名称,上传匹配的证件照片
+
+
+
+
+
+
提交认证申请
+
+
diff --git a/app/views/account/_pro_certification_form.html.erb b/app/views/account/_pro_certification_form.html.erb
new file mode 100644
index 000000000..853b29803
--- /dev/null
+++ b/app/views/account/_pro_certification_form.html.erb
@@ -0,0 +1,441 @@
+
+
职业认证
+
+ 1 填写认证信息 >
+ 2 人工审核 >
+ 3 认证结果
+
+
+
+
以下信息通过审核后将不能再次修改,提交后请耐心等待核查
+ <%= form_for :user, :url => apply_pro_certification_account_path, :method => :post, :html => {:id => 'my_pro_certification_form'} do |f| %>
+
+
+ * 职业:
+
+ 请选择职业
+ 教师
+ 学生
+ 专业人士
+
+
+ 请选择职称
+ 教授
+ 副教授
+ 讲师
+ 助教
+
+
+ 请选择职称
+ 企业管理者
+ 部门管理者
+ 高级工程师
+ 工程师
+ 助理工程师
+
+
+
+ 请选择你的职业/职称
+
+
+ * 学号:
+
+
+
+ 学号不能为空
+
+
+ * 单位名称:
+
+
+ 你的单位不在列表中?请点击申请添加
+
+ 请从下拉列表中选择你的单位
+
+
+ 部门名称:
+
+
+ 你的部门不在列表中?请点击申请添加
+
+
+
+
+ * 职业证正面照:
+ <%= file_field_tag 'avatar[image]',
+ :id => "upload_img_pro",
+ :style => 'display:none;',#added by young
+ :size => "1",
+ :multiple => false,
+ :onchange => 'addInputAvatar(this);',
+ :data => {
+ :max_file_size => Setting.authentication_img_max_size.to_i.kilobytes,
+ :max_file_size_message => l(:error_user_auth_too_big, :max_size => number_to_human_size(Setting.authentication_img_max_size.to_i.kilobytes)),
+ :max_concurrent_uploads => Redmine::Configuration['max_concurrent_ajax_uploads'].to_i,
+ :file_type => Redmine::Configuration['pic_types'].to_s,
+ :type_support_message => l(:error_pic_type),
+ :upload_path => upload_avatar_path(:format => 'js'),
+ :description_placeholder => nil ,# l(:label_optional_description)
+ :source_type => 'UserAuthentication',
+ :source_id => @user.id.to_s,
+ :auth_type => 'PRO',
+ :is_direct => 1
+ } %>
+
+ +选择文件
+
+
+
+ 请上传学生证或职工证正面照片,确保证件上的姓名、编号和头像清晰可辨认。查看示例>> png/jpg/bmp格式,不超过2MB
+
+
+
+
+ <%= image_tag(url_to_auth_img(0, 'PRO'), :width => 200, :height => 150, :id => 'nh_source_pro') %>
+
+
+
+
+
+
+
+
+ 确认提交
+
+
+ <% end %>
+
+
+
+<% if !User.current.user_extensions.nil? %>
+ <% identity = User.current.user_extensions.identity %>
+ <% title = User.current.user_extensions.technical_title %>
+<% else %>
+ <% identity = "" %>
+ <% title = "" %>
+<% end %>
+
+
\ No newline at end of file
diff --git a/app/views/account/_user_auth_form.html.erb b/app/views/account/_user_auth_form.html.erb
new file mode 100644
index 000000000..b5dbcd74d
--- /dev/null
+++ b/app/views/account/_user_auth_form.html.erb
@@ -0,0 +1,110 @@
+
+
实名认证
+
+ 1 填写认证信息 >
+ 2 人工审核 >
+ 3 认证结果
+
+
+
+
以下信息通过审核后将不能再次修改,提交后请耐心等待核查
+
温馨提示:尊敬的用户,您提交的数据将会被加密,请放心填写。
+ <%= form_for :user, :url => apply_auth_account_path, :method => :post, :html => {:id => 'my_user_auth_form'} do |f| %>
+
+
+ * 真实姓名:
+
+ 姓名不能为空
+
+
+
+ 所填姓名需与身份证上的姓名保持一致
+
+
+ * 性别:
+ <% if User.current.user_extensions && User.current.user_extensions.gender && User.current.user_extensions.gender == 1 %>
+
+
+ 男
+
+
+
+ 女
+
+ <% else %>
+
+
+ 男
+
+
+
+ 女
+
+ <% end %>
+
+
+ * 身份证号:
+
+ 身份证号填写有误
+
+
+
+ 请使用二代身份证,身份证号为18位 同一身份证号只能认证一次
+
+
+ * 持身份证正面头部照:
+ <%= file_field_tag 'avatar[image]',
+ :id => "upload_img_id",
+ :style => 'display:none;',#added by young
+ :size => "1",
+ :multiple => false,
+ :onchange => 'addInputAvatar(this);',
+ :data => {
+ :max_file_size => Setting.authentication_img_max_size.to_i.kilobytes,
+ :max_file_size_message => l(:error_user_auth_too_big, :max_size => number_to_human_size(Setting.authentication_img_max_size.to_i.kilobytes)),
+ :max_concurrent_uploads => Redmine::Configuration['max_concurrent_ajax_uploads'].to_i,
+ :file_type => Redmine::Configuration['pic_types'].to_s,
+ :type_support_message => l(:error_pic_type),
+ :upload_path => upload_avatar_path(:format => 'js'),
+ :description_placeholder => nil ,# l(:label_optional_description)
+ :source_type => 'UserAuthentication',
+ :source_id => @user.id.to_s,
+ :auth_type => 'ID',
+ :is_direct => 1
+ } %>
+
+ +选择文件
+
+
+
+ 请上传手持身份证正面的原件照片,确保身份证上的姓名、身份证号码和头像清晰可辨认。查看示例>> png/jpg/bmp格式,不超过2MB
+
+
+
+
+ <%= image_tag(url_to_auth_img(0, 'ID'), :width => 200, :height => 150, :id => 'nh_source_id') %>
+
+
+
+
+
+
+
+
+ 确认提交
+
+
+ <% end %>
+
+
+
\ No newline at end of file
diff --git a/app/views/account/agreement.html.erb b/app/views/account/agreement.html.erb
index ac0b9906c..2bb958120 100644
--- a/app/views/account/agreement.html.erb
+++ b/app/views/account/agreement.html.erb
@@ -1,29 +1,29 @@
<%= stylesheet_link_tag 'css/public'%>
-
Trustie服务协议
+
服务协议
尊敬的用户,您好!
-欢迎使用Trustie平台,在您使用Trustie平台前,请您认真阅读并遵守《Trustie服务协议》(以下简称"本协议"),请您务必审慎阅读、充分理解协议的各条款内容。
-当您在注册过程中点击查看"看过并同意本服务协议",按照注册流程成功注册为Trustie平台的用户即表示您已充分阅读、理解并完全接受本协议中的全部条款。您承诺接受并遵守本协议的约定,届时您不应以未阅读本协议的内容等理由,主张本协议无效或本协议中的某些条款无效,或要求撤销本协议。
-
一、Trustie平台权利和义务
-
1、尊重用户隐私:尊重用户隐私,保障用户隐私安全是Trustie平台的一项基本政策;
-2、管理平台用户:Trustie平台依据国家法律、地方法律和国际法律等的标准以及本行业的规则来管理平台注册用户;
-3、处理用户反馈:Trustie平台的相关人员会及时处理用户反馈的问题并给予及时回复。
+欢迎使用本网站,在您使用本网站前,请您认真阅读并遵守《服务协议》(以下简称"本协议"),请您务必审慎阅读、充分理解协议的各条款内容。
+当您在注册过程中点击查看"看过并同意本服务协议",按照注册流程成功注册为网站的用户即表示您已充分阅读、理解并完全接受本协议中的全部条款。您承诺接受并遵守本协议的约定,届时您不应以未阅读本协议的内容等理由,主张本协议无效或本协议中的某些条款无效,或要求撤销本协议。
+
一、本网站权利和义务
+
1、尊重用户隐私:尊重用户隐私,保障用户隐私安全是网站的一项基本政策;
+2、管理网站用户:网站依据国家法律、地方法律和国际法律等的标准以及本行业的规则来管理网站注册用户;
+3、处理用户反馈:网站的相关人员会及时处理用户反馈的问题并给予及时回复。
二、用户权利和义务
-
用户在使用Trustie平台的过程中,必须遵守如下原则:
+
用户在使用网站的过程中,必须遵守如下原则:
1、遵守中国的有关法律和法规;
2、使用网络服务不作非法用途;
3、不干扰和混乱网络服务;
4、遵守所有使用网络服务的网络协议、规定、程序和惯例;
5、不传输任何非法的、骚扰性的、中伤他人的、辱骂性的、恐吓性的、伤害性的、庸俗的,淫秽等信息资料;
6、不传输任何教唆他人构成犯罪行为的资料;
-7、用户不得故意或者过失损害Trustie平台合法权利和利益。及时回复。
+7、用户不得故意或者过失损害网站合法权利和利益。及时回复。
三、关于责任
-
鉴于网络服务的特殊性,用户同意Trustie团队有权在事先通知的情况下,变更、中断、升级部分网络服务。Trustie团队不担保网络服务不会中断,但承诺在用户可承受的时间内快速恢复服务,同时确保用户数据的安全性和可靠性。
+
鉴于网络服务的特殊性,本网站有权在事先通知的情况下,变更、中断、升级部分网络服务。本网站不担保网络服务不会中断,但承诺在用户可承受的时间内快速恢复服务,同时确保用户数据的安全性和可靠性。
四、服务条款的修改
-
Trustie团队保留在必要时对本协议修改的权利,一旦发生变动,这些条款可由Trustie团队及时更新,且毋须另行通知,修改后的条款一旦在网页上公布即有效代替原来的服务条款。您可随时查阅最新版服务条款。
-
本协议最终解释权归Trustie团队所有。
+
本网站保留在必要时对本协议修改的权利,一旦发生变动,这些条款可由网站项目组及时更新,且毋须另行通知,修改后的条款一旦在网页上公布即有效代替原来的服务条款。您可随时查阅最新版服务条款。
+
本协议最终解释权归本网站所有。
diff --git a/app/views/account/apply_trail.js.erb b/app/views/account/apply_trail.js.erb
new file mode 100644
index 000000000..82cdc09cb
--- /dev/null
+++ b/app/views/account/apply_trail.js.erb
@@ -0,0 +1 @@
+$("body").append('<%= j( render :partial => 'welcome/one_btn_mask_pop', :locals => {:btn => "确定", :tip1 => @tip, :url => "#{my_account_path()}"}) %>');
\ No newline at end of file
diff --git a/app/views/account/authentication.html.erb b/app/views/account/authentication.html.erb
new file mode 100644
index 000000000..18e89b424
--- /dev/null
+++ b/app/views/account/authentication.html.erb
@@ -0,0 +1,148 @@
+
+ <% if !@user.authentication && @apply_user_auth.nil? %>
+
+
实名认证
+
+
+
+
当前账号尚未实名认证
+
请完成实名认证以更好地享受智能教学服务
+
立即认证
+
+
+ <% elsif !@user.authentication && @apply_user_auth && @apply_user_auth.status == 0 %>
+
+
+
+
实名认证
+
+ 1 填写认证信息 >
+ 2 人工审核 >
+ 3 认证结果
+
+
+
+
认证中 我们将在1个工作日内完成审核,通过审核后页面会显示“已认证”
+
+
+
+ 认证信息
+
+
+
+
+ 真实姓名:
+ <%= @user.show_real_name %>
+
+
+ 性别:
+ <%= @user.user_extensions && @user.user_extensions.gender && @user.user_extensions.gender == 1 ? '女' : '男' %>
+
+
+ 身份证号码:
+ <%= @user.try(:ID_number) %>
+
+
+ 手持身份证正面头部照:
+ 已上传查看 <%= image_tag(url_to_auth_img(@user.id, 'ID'), :width => 200, :height => 150, :id => "upload_id_image", :class => "none") %>
+
+
+
+
若您想重新认证,请先撤销本次认证申请
+
+
+ <% elsif !@user.authentication && @apply_user_auth && @apply_user_auth.status == 2 %>
+
+
+
实名认证
+
+ 1 填写认证信息 >
+ 2 人工审核 >
+ 3 认证结果
+
+
+
+
未通过 原因:<%= @apply_user_auth.remarks %>
+
+
+
+
+ 认证信息
+
+
+
+
+ 真实姓名:
+ <%= @user.show_real_name %>
+
+
+ 性别:
+ <%= @user.user_extensions && @user.user_extensions.gender && @user.user_extensions.gender == 1 ? '女' : '男' %>
+
+
+ 身份证号码:
+ <%= @user.try(:ID_number) %>
+
+
+ 手持身份证正面头部照:
+ 已上传查看 <%= image_tag(url_to_auth_img(@user.id, 'ID'), :width => 200, :height => 150, :id => "upload_id_image", :class => "none") %>
+
+
+
+
若您想重新认证,请点击这里
+
+
+ <% elsif @user.authentication %>
+
+
+
实名认证
+
+ 1 填写认证信息 >
+ 2 人工审核 >
+ 3 认证结果
+
+
+
+
已认证
+
+
+
+
+ 认证信息
+
+
+
+
+ 真实姓名:
+ <%= @user.show_real_name %>
+
+
+ 性别:
+ <%= @user.user_extensions && @user.user_extensions.gender && @user.user_extensions.gender == 1 ? '女' : '男' %>
+
+
+ 身份证号码:
+ <%= @user.try(:ID_number) %>
+
+
+ 手持身份证正面头部照:
+ 已上传查看 <%= image_tag(url_to_auth_img(@user.id, 'ID'), :width => 200, :height => 150, :id => "upload_id_image", :class => "none") %>
+
+
+
+
+
+ <% end %>
+
+
+ <%= render :partial => "account/user_auth_form" %>
+
+
+
+
diff --git a/app/views/account/avatar.html.erb b/app/views/account/avatar.html.erb
new file mode 100644
index 000000000..4fd128767
--- /dev/null
+++ b/app/views/account/avatar.html.erb
@@ -0,0 +1,186 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/views/account/change_or_bind.html.erb b/app/views/account/change_or_bind.html.erb
new file mode 100644
index 000000000..4050c8a1b
--- /dev/null
+++ b/app/views/account/change_or_bind.html.erb
@@ -0,0 +1,85 @@
+
+
+ <%= form_tag(bind_email_or_phone_path, :id => 'bind_email_or_phone_form') do %>
+
+ <% if @type == 'phone' %>
+
手机绑定
+
+
+ ×
+ 设置新手机号,并验证
+
+
+ <% elsif @type == 'mail' %>
+
邮箱绑定
+
+
+ ×
+ 设置新邮箱地址,并验证
+
+
+ <% end %>
+ <% end %>
+
+
+
+
+
\ No newline at end of file
diff --git a/app/views/account/change_psd.html.erb b/app/views/account/change_psd.html.erb
new file mode 100644
index 000000000..7b5348a5f
--- /dev/null
+++ b/app/views/account/change_psd.html.erb
@@ -0,0 +1,38 @@
+
+
+ <% if( !@act.nil? && @act == 'password') %>
+ <%= render_flash_messages %>
+ <% end %>
+
+
\ No newline at end of file
diff --git a/app/views/account/email_activation.html.erb b/app/views/account/email_activation.html.erb
index c7a7dfb79..6fc4c3c14 100644
--- a/app/views/account/email_activation.html.erb
+++ b/app/views/account/email_activation.html.erb
@@ -5,8 +5,8 @@
激活邮箱账号
<%= link_to '首页', home_path %>
- |
- <%= link_to "帮助中心", "#{Setting.protocol}://#{Setting.host_name}/forums/1/memos/1168" %>
+
@@ -16,7 +16,7 @@
您的账号尚未激活,请先登录您的邮箱,激活您的账号
只需要登录邮箱(<%= @user.mail %> ),点击链接激活即可
- 立即去邮箱激活账号
+ 立即去邮箱激活账号
还没有收到激活账号邮件?
@@ -24,13 +24,13 @@
2:再次发送验证邮件
3:如果仍然没有收到注册验证邮件,请更换邮件地址
- <%= link_to '重新发送激活邮件 '.html_safe, { :controller => 'account', :action => 'resendmail', :user => @user},:id => 'resend_email_a', :class => 'task-btn fl mr20', :remote => true, :method => 'get' %>
- 更换邮件地址
+ <%= link_to '重新发送激活邮件 '.html_safe, { :controller => 'account', :action => 'resendmail', :user => @user},:id => 'resend_email_a', :class => 'task-btn-email fl mr20', :remote => true, :method => 'get' %>
+ 更换邮件地址
- 确定
+ 确定
请输入正确的邮箱
@@ -60,4 +60,10 @@
}
}
}
+ //跳转到指定的邮箱登录页面
+ $(function(){
+ var uurl = '<%= email %>';
+ uurl = gotoEmail(uurl);
+ $("#user_email_link").attr("href", "http://"+uurl);
+ });
\ No newline at end of file
diff --git a/app/views/account/email_valid.html.erb b/app/views/account/email_valid.html.erb
index 77d7e8642..65892e8f3 100644
--- a/app/views/account/email_valid.html.erb
+++ b/app/views/account/email_valid.html.erb
@@ -5,8 +5,8 @@
激活邮箱账号
<%= link_to '首页', home_path %>
- |
- <%= link_to "帮助中心", "#{Setting.protocol}://#{Setting.host_name}/forums/1/memos/1168" %>
+
+ <%#= link_to "帮助中心", "#{Setting.protocol}://#{Setting.host_name}/forums/1/memos/1168" %>
@@ -14,7 +14,7 @@
激活邮件已发送
只需要登录邮箱(<%= @user.mail %> ),点击链接激活即可
-
立即去邮箱激活账号
+
立即去邮箱激活账号
还没有收到激活账号邮件?
@@ -22,13 +22,13 @@
2:再次发送验证邮件
3:如果仍然没有收到注册验证邮件,请更换邮件地址
- <%= link_to '重新发送激活邮件 '.html_safe, { :controller => 'account', :action => 'resendmail', :user => @user},:id => 'resend_email_a', :class => 'task-btn fl mr20', :remote => true, :method => 'get' %>
- 更换邮件地址
+ <%= link_to '重新发送激活邮件 '.html_safe, { :controller => 'account', :action => 'resendmail', :user => @user},:id => 'resend_email_a', :class => 'task-btn-email fl mr20', :remote => true, :method => 'get' %>
+ 更换邮件地址
- 确定
+ 确定
请输入正确的邮箱
@@ -58,4 +58,11 @@
}
}
}
+
+ $(function(){
+ var uurl = '<%= email %>';
+ console.log(uurl);
+ uurl = gotoEmail(uurl);
+ $("#user_email_link").attr("href", "http://"+uurl);
+ });
diff --git a/app/views/account/login.html.erb b/app/views/account/login.html.erb
index df1250a67..f513edf67 100644
--- a/app/views/account/login.html.erb
+++ b/app/views/account/login.html.erb
@@ -1,21 +1,13 @@
-
-
+
@@ -33,34 +25,37 @@
diff --git a/app/views/account/lost_password.html.erb b/app/views/account/lost_password.html.erb
index d94f41c44..6a188dc30 100644
--- a/app/views/account/lost_password.html.erb
+++ b/app/views/account/lost_password.html.erb
@@ -3,14 +3,15 @@
找回密码
<%= link_to '首页', home_path %>
- |
- <%= link_to "帮助中心", "#{Setting.protocol}://#{Setting.host_name}/forums/1/memos/1168" %>
+
+ <%#= link_to "帮助中心", "#{Setting.protocol}://#{Setting.host_name}/forums/1/memos/1168" %>
-
+
\ No newline at end of file
diff --git a/app/views/account/professional_certification.html.erb b/app/views/account/professional_certification.html.erb
new file mode 100644
index 000000000..50ba81dad
--- /dev/null
+++ b/app/views/account/professional_certification.html.erb
@@ -0,0 +1,166 @@
+
+ <% if !@user.professional_certification && @apply_user_auth.nil? %>
+
+
职业认证
+
+
+
+
当前账号尚未职业认证
+
请完成职业认证以激活单位购买的高级功能
+
立即认证
+
+
+ <% elsif !@user.professional_certification && @apply_user_auth && @apply_user_auth.status == 0 %>
+
+
+
+
职业认证
+
+ 1 填写认证信息 >
+ 2 人工审核 >
+ 3 认证结果
+
+
+
+
认证中 我们将在1个工作日内完成审核,通过审核后页面会显示“已认证”
+
+
+
+ 认证信息
+
+
+
+
+ 职业:
+ <%= @user.user_extensions.show_identity %>
+
+
+ 职称/学号:
+ <%= @user.user_extensions && @user.user_extensions.identity && @user.user_extensions.identity == 1 ? @user.user_extensions.try(:student_id) : @user.user_extensions.try(:technical_title) %>
+
+
+ 单位/学校名称:
+ <%= @user.user_extensions.school ? @user.user_extensions.school.try(:name) : '' %>
+
+
+ 部门/学院名称:
+ <%= @user.user_extensions.department ? @user.user_extensions.department.try(:name) : '' %>
+
+
+ 职业证正面照:
+ 已上传查看 <%= image_tag(url_to_auth_img(@user.id, 'PRO'), :width => 200, :height => 150, :id => "upload_pro_image", :class => "none") %>
+
+
+
+
若您想重新认证,请先撤销本次认证申请
+
+
+ <% elsif !@user.professional_certification && @apply_user_auth && @apply_user_auth.status == 2 %>
+
+
+
职业认证
+
+ 1 填写认证信息 >
+ 2 人工审核 >
+ 3 认证结果
+
+
+
+
未通过 原因:<%= @apply_user_auth.remarks %>
+
+
+
+
+ 认证信息
+
+
+
+
+ 职业:
+ <%= @user.user_extensions.show_identity %>
+
+
+ 职称/学号:
+ <%= @user.user_extensions && @user.user_extensions.identity && @user.user_extensions.identity == 1 ? @user.user_extensions.try(:student_id) : @user.user_extensions.try(:technical_title) %>
+
+
+ 单位/学校名称:
+ <%= @user.user_extensions.school ? @user.user_extensions.school.try(:name) : '' %>
+
+
+ 部门/学院名称:
+ <%= @user.user_extensions.department ? @user.user_extensions.department.try(:name) : '' %>
+
+
+ 职业证正面照:
+ 已上传查看 <%= image_tag(url_to_auth_img(@user.id, 'PRO'), :width => 200, :height => 150, :id => "upload_pro_image", :class => "none") %>
+
+
+
+
若您想重新认证,请点击这里
+
+
+ <% elsif @user.professional_certification %>
+
+
+
职业认证
+
+ 1 填写认证信息 >
+ 2 人工审核 >
+ 3 认证结果
+
+
+
+
已认证
+
+
+
+
+ 认证信息
+
+
+
+
+ 职业:
+ <%= @user.user_extensions.show_identity %>
+
+
+ 职称/学号:
+ <%= @user.user_extensions && @user.user_extensions.identity && @user.user_extensions.identity == 1 ? @user.user_extensions.try(:student_id) : @user.user_extensions.try(:technical_title) %>
+
+
+ 单位/学校名称:
+ <%= @user.user_extensions.school ? @user.user_extensions.school.try(:name) : '' %>
+
+
+ 部门/学院名称:
+ <%= @user.user_extensions.department ? @user.user_extensions.department.try(:name) : '' %>
+
+
+ 职业证正面照:
+ 已上传查看 <%= image_tag(url_to_auth_img(@user.id, 'PRO'), :width => 200, :height => 150, :id => "upload_pro_image", :class => "none") %>
+
+
+
+
若您想重新认证,请点击这里
+
+
+ <% end %>
+
+
+ <%= render :partial => "account/pro_certification_form" %>
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/views/account/reset_psd.html.erb b/app/views/account/reset_psd.html.erb
index cd4a5536b..ab00efc8e 100644
--- a/app/views/account/reset_psd.html.erb
+++ b/app/views/account/reset_psd.html.erb
@@ -18,12 +18,11 @@
<%= form_tag(account_reset_psd_path, :remote => true, :method => 'post') do %>
-
-
+
-
至少8位由字母或特殊符号和数字结合
+
新密码8-16位,区分大小写字母
diff --git a/app/views/account/security_settings.html.erb b/app/views/account/security_settings.html.erb
new file mode 100644
index 000000000..13f6fe657
--- /dev/null
+++ b/app/views/account/security_settings.html.erb
@@ -0,0 +1,40 @@
+
+
+ 手机绑定
+ <% if @user.phone.blank? %>
+ 未绑定
+
+ 绑定
+ <% else %>
+ 已绑定
+ 您绑定的手机:<%= @user.user_phone %>
+ 更改
+ <% end %>
+
+
+ 邮箱绑定
+ <% if @user.mail.blank? %>
+ 未绑定
+
+ 绑定
+ <% else %>
+ 已绑定
+ 您绑定的邮箱:<%= @user.user_mail %>
+ 更改
+ <% end %>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/views/account/user_join.html.erb b/app/views/account/user_join.html.erb
index 66437dfa1..1b32e71b5 100644
--- a/app/views/account/user_join.html.erb
+++ b/app/views/account/user_join.html.erb
@@ -1,279 +1,304 @@
-
-
-
+
+
+
diff --git a/app/views/admin/_audit_authentication_list.html.erb b/app/views/admin/_audit_authentication_list.html.erb
new file mode 100644
index 000000000..bf141ac0e
--- /dev/null
+++ b/app/views/admin/_audit_authentication_list.html.erb
@@ -0,0 +1,58 @@
+<% @unapproved_user.each_with_index do |apply_user, index| %>
+ <% user = User.find(apply_user.user_id) %>
+
+
+ <%= image_tag(url_to_avatar(user), :class => "fl with10 edu-ad-user", :alt => "头像", :width => "50", :height => "50" ) %>
+
+
+
+
+ <%= user.show_real_name %>
+ <%= time_from_now(apply_user.updated_at) %>
+ <%= apply_user.status == 1 ? "已同意" : "已拒绝" %>
+
+
+ 身份证号:<%= user.ID_number %>
+
+
+ <% if !user.user_extensions.school_id.blank? && user.user_extensions.school %>
+ <%= user.user_extensions.school.name %><%= user.user_extensions.department ? ' - '+user.user_extensions.department.name.to_s : '' %>
+ <% end %>
+ <% if user.user_extensions && user.user_extensions.identity %>
+ <%= user.identity %>
+ <% if user.user_extensions.identity == 1 && user.user_extensions.try(:student_id) %>
+ <%= user.user_extensions.try(:student_id) %>
+ <% end %>
+ <% end %>
+
+
+ <%= image_tag(url_to_auth_img(user.id, 'ID'), :width => 200, :height => 150, :class => 'edu-renzheng-img fl mr20') %>
+
+ <% if apply_user.status == 2 %>
+ 原因:<%= apply_user.remarks %>
+ <% end %>
+
+
+
+<% end %>
+
+
+
+ <%= pagination_links_full @unapproved_user_pages, @unapproved_user_count, :per_page_links => false, :remote => @is_remote, :flag => true, :is_new => true %>
+
+
+
+
+
\ No newline at end of file
diff --git a/app/views/admin/_authentication_list.html.erb b/app/views/admin/_authentication_list.html.erb
new file mode 100644
index 000000000..d35d2b6e6
--- /dev/null
+++ b/app/views/admin/_authentication_list.html.erb
@@ -0,0 +1,71 @@
+<% unless @unapproved_user.blank? %>
+ <% @unapproved_user.each do |apply_user| %>
+ <% user = User.find(apply_user.user_id) %>
+
+
+ <%= image_tag(url_to_avatar(user), :class => "fl with10 edu-ad-user", :alt => "头像", :width => "50", :height => "50" ) %>
+
+
+
+
+ <%= user.show_real_name %>
+ <%= time_from_now(apply_user.updated_at) %>
+ 拒绝
+ 同意
+
+
+ 身份证号:<%= user.ID_number %>
+
+
+ <% if !user.user_extensions.school_id.blank? && user.user_extensions.school %>
+ <%= user.user_extensions.school.name %><%= user.user_extensions.department ? ' - '+user.user_extensions.department.name.to_s : '' %>
+ <% end %>
+ <% if user.user_extensions && user.user_extensions.identity %>
+ <%= user.identity %>
+ <% if user.user_extensions.identity == 1 && user.user_extensions.try(:student_id) %>
+ <%= user.user_extensions.try(:student_id) %>
+ <% end %>
+ <% end %>
+
+
+ <%= image_tag(url_to_auth_img(user.id, 'ID'), :width => 200, :height => 150, :class => 'edu-renzheng-img fl mr20') %>
+
+
+
+ 原因:
+
+
+
+ 确定
+ 取消
+
+
+
+
+
+ <% end %>
+<% else %>
+ <%= render :partial => "welcome/no_data" %>
+<% end %>
+
+
+
+ <%= pagination_links_full @unapproved_user_pages, @unapproved_user_count, :per_page_links => false, :remote => @is_remote, :flag => true, :is_new => true %>
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/views/admin/_tab_applied_departments.erb b/app/views/admin/_tab_applied_departments.erb
new file mode 100644
index 000000000..8fb1783ca
--- /dev/null
+++ b/app/views/admin/_tab_applied_departments.erb
@@ -0,0 +1,6 @@
+
+
+ <%= link_to '未审批', {:action => 'applied_departments'}, class: "#{current_page?(unapplied_departments_path)? 'selected' : nil }" %>
+ <%= link_to '已审批', {:action => 'has_applied_departments'}, class: "#{current_page?(applied_departments_path)? 'selected' : nil }" %>
+
+
\ No newline at end of file
diff --git a/app/views/admin/agree_authentication.js.erb b/app/views/admin/agree_authentication.js.erb
new file mode 100644
index 000000000..53bfcb733
--- /dev/null
+++ b/app/views/admin/agree_authentication.js.erb
@@ -0,0 +1 @@
+$("#authentication_list").html("<%= j( render :partial => "admin/authentication_list" ) %>");
\ No newline at end of file
diff --git a/app/views/admin/applied_departments.html.erb b/app/views/admin/applied_departments.html.erb
new file mode 100644
index 000000000..34ec11da3
--- /dev/null
+++ b/app/views/admin/applied_departments.html.erb
@@ -0,0 +1,94 @@
+
+ <%=l(:label_applied_departments)%>
+
+
+<%= render 'tab_applied_departments' %>
+
+<%= form_tag({}, :method => :get) do %>
+
+
+ 部门名称:
+
+ <%= 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 => 'applied_departments'}, :class => 'icon icon-reload' %>
+
+<% end %>
+
+
+
+
+ <%= pagination_links_full @apply_pages, @apply_count ,:per_page_links => true, :remote => false, :flag => true %>
+
\ No newline at end of file
diff --git a/app/views/admin/has_applied_departments.html.erb b/app/views/admin/has_applied_departments.html.erb
new file mode 100644
index 000000000..f0082ac5f
--- /dev/null
+++ b/app/views/admin/has_applied_departments.html.erb
@@ -0,0 +1,83 @@
+
+ <%=l(:label_applied_departments)%>
+
+
+<%= render 'tab_applied_departments' %>
+
+<%= form_tag({}, :method => :get) do %>
+
+
+ 部门名称:
+
+ <%= 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 => 'has_applied_departments'}, :class => 'icon icon-reload' %>
+
+<% end %>
+
+
+
+
+ <%= pagination_links_full @has_apply_pages, @has_apply_count ,:per_page_links => true, :remote => false, :flag => true %>
+
\ No newline at end of file
diff --git a/app/views/admin/identity_authentication.html.erb b/app/views/admin/identity_authentication.html.erb
new file mode 100644
index 000000000..d0f8f9805
--- /dev/null
+++ b/app/views/admin/identity_authentication.html.erb
@@ -0,0 +1,135 @@
+
+
+
+
+
+
+
+
+
+
+
+ <%= render :partial => "admin/authentication_list" %>
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/views/admin/identity_authentication.js.erb b/app/views/admin/identity_authentication.js.erb
new file mode 100644
index 000000000..82b62fd42
--- /dev/null
+++ b/app/views/admin/identity_authentication.js.erb
@@ -0,0 +1,30 @@
+var nTabIcon_1 = $("#edu-tab-con-1");
+var nTabIcon_2 = $("#edu-tab-con-2");
+var nTabNav_1 = $("#edu-tab-nav-1");
+var nTabNav_2 = $("#edu-tab-nav-2");
+var nAudit = $("#audit_all_authentication").parent();
+
+<% if params[:type] == "0" %>
+ $("#authentication_list").html("<%= j( render :partial => "admin/authentication_list" ) %>");
+ nTabNav_1.addClass("edu-tab-hover");
+ nTabNav_2.removeClass("edu-tab-hover");
+ nTabIcon_1.show();
+ nTabIcon_2.hide();
+<% else %>
+ $("#audit_authentication_list").html("<%= j( render :partial => "admin/audit_authentication_list" ) %>");
+ nTabNav_1.removeClass("edu-tab-hover");
+ nTabNav_2.addClass("edu-tab-hover");
+ nTabIcon_1.hide();
+ nTabIcon_2.show();
+ /* -------------------------- 未审批(全部、同意、拒绝点击时动态样式) ------------------------------ */
+ if(<%= params[:type] == "1" %>){
+ nAudit.find(".active").removeClass("active");
+ $("#audit_agree_authentication").addClass("active");
+ }else if(<%= params[:type] == "2" %>){
+ nAudit.find(".active").removeClass("active");
+ $("#audit_reject_authentication").addClass("active");
+ }else{
+ nAudit.find(".active").removeClass("active");
+ $("#audit_all_authentication").addClass("active");
+ }
+<% end %>
\ No newline at end of file
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) %>
-
-
- <%= l(:field_status) %> :
-
- <%= select_tag 'status', project_status_options_for_select(@status), :class => "small", :onchange => "this.form.submit(); return false;" %>
-
- <%= l(:label_project) %>:
-
- <%= 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 %>
-
-
-
-
-
-
-<% 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/admin/shixun_authentication.js.erb b/app/views/admin/shixun_authentication.js.erb
new file mode 100644
index 000000000..ecb54991b
--- /dev/null
+++ b/app/views/admin/shixun_authentication.js.erb
@@ -0,0 +1,5 @@
+<% if @shixun.authentication %>
+ $("#shixun_authentication_<%= params[:index] %>").html("已认证");
+<% else %>
+ $("#shixun_authentication_<%= params[:index]%>").html("认证");
+<% end %>
diff --git a/app/views/admin/shixuns.html.erb b/app/views/admin/shixuns.html.erb
new file mode 100644
index 000000000..513f2c705
--- /dev/null
+++ b/app/views/admin/shixuns.html.erb
@@ -0,0 +1,49 @@
+<%= stylesheet_link_tag 'jquery/jquery-ui-1.9.2', :media => 'all' %>
+实训列表
+<%#= render 'admin/tab_excellent_courses' %>
+
+
+
+
+
+
diff --git a/app/views/attachments/_activity_attach.html.erb b/app/views/attachments/_activity_attach.html.erb
index ad87d28bf..162eb239b 100644
--- a/app/views/attachments/_activity_attach.html.erb
+++ b/app/views/attachments/_activity_attach.html.erb
@@ -1,21 +1,19 @@
-
<% if activity.attachments.any? %>
<% activity.attachments.each do |attachment| %>
-
-
-
- <%= link_to_short_attachment attachment,:length=> 58, :class => 'hidden link_file_a fl newsBlue mw380', :download => true %>
-
-
- (
- <%= number_to_human_size attachment.filesize %>)
-
- <% user_name = attachment.author.show_name.empty? ? attachment.author : attachment.author.show_name %>
-
- <%= link_to h(truncate(user_name, length: 15, omission: '...')),user_path(attachment.author),:class => "linkBlue2" %>,
- <%= format_time(attachment.created_on) %>
-
-
+
+
+
+ <%= link_to_short_attachment attachment,:length=> 58, :class => 'color-grey', :download => true %>
+ (
+ <%= number_to_human_size attachment.filesize %>)
+
+ <% user_name = attachment.author.show_real_name.empty? ? attachment.author : attachment.author.show_real_name %>
+
+ <%= link_to h(truncate(user_name, length: 15, omission: '...')),user_path(attachment.author),:class => "color-grey" %>,
+ <%= format_time(attachment.created_on) %>
+
+
+
<% end %>
<% end %>
\ No newline at end of file
diff --git a/app/views/attachments/_show_attachment_history.html.erb b/app/views/attachments/_show_attachment_history.html.erb
index f4bf75339..e30e0a98e 100644
--- a/app/views/attachments/_show_attachment_history.html.erb
+++ b/app/views/attachments/_show_attachment_history.html.erb
@@ -1,12 +1,11 @@
-
-
-
diff --git a/app/views/blog_comments/_simple_ke_reply_form.html.erb b/app/views/blog_comments/_simple_ke_reply_form.html.erb
index 17a68b2a0..7f92e0ec9 100644
--- a/app/views/blog_comments/_simple_ke_reply_form.html.erb
+++ b/app/views/blog_comments/_simple_ke_reply_form.html.erb
@@ -1,28 +1,28 @@
-
-
<%= link_to image_tag(url_to_avatar(User.current), :width => "33", :height => "33"), user_path(User.current), :alt => "用户头像" %>
-
-
+
+
<%= link_to image_tag(url_to_avatar(User.current), :width => "33", :height => "33"), user_path(User.current), :alt => "用户头像" %>
+
+
\ No newline at end of file
diff --git a/app/views/blog_comments/quote.js.erb b/app/views/blog_comments/quote.js.erb
index 6d3264a22..958c32124 100644
--- a/app/views/blog_comments/quote.js.erb
+++ b/app/views/blog_comments/quote.js.erb
@@ -1,8 +1,9 @@
-if($("#reply_message_<%= @blogComment.id%>").length > 0) {
+if($("#reply_message_<%= @blogComment.id%>").html() == "") {
+ $(".reply_to_message").html("");
$("#reply_message_<%= @blogComment.id%>").replaceWith("<%= escape_javascript(render :partial => 'blog_comments/simple_ke_reply_form', :locals => {:reply => @blogComment,:temp =>@temp,:course_id=>@course_id}) %>");
$(function(){
sd_create_editor_from_data(<%= @blogComment.id%>,null,"100%", "<%=@blogComment.class.to_s%>");
});
-}else if($("#reply_to_message_<%= @blogComment.id%>").length >0) {
- $("#reply_to_message_<%= @blogComment.id%>").replaceWith("");
+}else {
+ $("#reply_message_<%= @reply.id%>").html("");
}
\ No newline at end of file
diff --git a/app/views/blogs/_homepage.html.erb b/app/views/blogs/_homepage.html.erb
index 2b921c7a4..6eea11e82 100644
--- a/app/views/blogs/_homepage.html.erb
+++ b/app/views/blogs/_homepage.html.erb
@@ -1,98 +1,98 @@
-
-
- <% if activity.author.id == User.current.id%>
-
-
-
-
-
- <%= link_to(
- l(:button_edit_homepage),
- {:controller => 'blog_comments',:action => 'edit',:user_id=>activity.author_id,:blog_id=>activity.blog_id, :id => activity.id, :is_homepage => 1},
- :class => 'postOptionLink'
- ) if User.current && User.current.id == activity.author.id %>
-
-
- <%= link_to(
- l(:button_delete_homepage),
- {:controller => 'blog_comments',:action => 'destroy',:user_id=>activity.author_id,:blog_id=>activity.blog_id, :id => activity.id},
- :method => :delete,
- :data => {:confirm => l(:text_are_you_sure)},
- :class => 'postOptionLink'
- ) if User.current && User.current.id == activity.author.id %>
-
-
- <%= link_to(
- l(:button_cancel_homepage),
- {:controller => 'blogs',:action => 'cancel_homepage',:user_id=>activity.author_id,:id=>activity.blog_id, :article_id => activity.id},
- :method => :post,
- :class => 'postOptionLink'
- ) if User.current && User.current.id == activity.blog.author_id %>
-
-
-
-
-
- <%end%>
-
- <%= link_to activity.title.to_s.html_safe, user_blog_blog_comment_path(:user_id=>activity.author_id,
- :blog_id=>activity.blog.id,:id=>activity), :class=> "postGrey", :style => 'text-align:center;' %>
-
- <%=render :partial =>"users/intro_content", :locals=>{:user_activity_id =>user_activity_id, :content=>activity.content} %>
-
-
-
-
-
-
- <% all_repies = BlogComment.where("root_id = #{activity.id}").reorder("created_on desc") %>
- <% count = all_repies.count %>
- <% no_children_comments = get_no_children_comments all_repies %>
-
- <%= render :partial => 'users/reply_banner', :locals => {:count => count, :activity => activity, :user_activity_id => user_activity_id, :homepage => 1, :expand_more =>no_children_comments[:three_more]} %>
-
- <% if count > 0 %>
-
- <%= render :partial => 'users/message_replies', :locals => {:comments => no_children_comments[:no_children_comments], :user_activity_id => user_activity_id, :type => 'BlogComment', :activity_id =>activity.id, :homepage => 1, :user_id => activity.author_id}%>
-
- <% end %>
-
- <% if activity.locked == false && User.current.logged?%>
-
-
<%= link_to image_tag(url_to_avatar(User.current), :width => "33", :height => "33"), user_path(activity.author_id), :alt => "用户头像" %>
-
- <% if User.current.logged? %>
-
- <%= form_for('new_form',:url => {:controller => 'blog_comments', :action => 'reply', :user_id=>activity.author_id,:blog_id=>activity.blog_id,:id=>activity.id,:homepage=>1},:method => "post", :remote => true) do |f|%>
-
-
-
-
-
-
-
-
-
发送
-
-
- <% end%>
-
- <% else %>
- <%= render :partial => "users/show_unlogged" %>
- <% end %>
-
-
-
-
- <% end %>
-
-
-
\ No newline at end of file
diff --git a/app/views/boards/_contest_boardlist.html.erb b/app/views/boards/_contest_boardlist.html.erb
index 96a6af0e0..d45566ae2 100644
--- a/app/views/boards/_contest_boardlist.html.erb
+++ b/app/views/boards/_contest_boardlist.html.erb
@@ -1,6 +1,6 @@
-
+
讨论区列表
排序:
diff --git a/app/views/boards/_contest_new.html.erb b/app/views/boards/_contest_new.html.erb
index fcc6b1c5d..e27cace77 100644
--- a/app/views/boards/_contest_new.html.erb
+++ b/app/views/boards/_contest_new.html.erb
@@ -122,7 +122,7 @@
diff --git a/app/views/boards/_course_new.html.erb b/app/views/boards/_course_new.html.erb
index ddb0fea27..91bb5c852 100644
--- a/app/views/boards/_course_new.html.erb
+++ b/app/views/boards/_course_new.html.erb
@@ -8,8 +8,7 @@
if(!regexTopicSubject()) {
result=false;
return result;
- }
- if(params.content!=undefined){
+ } else if(params.content!=undefined){
if(params.content.isEmpty()){
result=false;
}
@@ -88,7 +87,7 @@
//paramsHeight = params.kindutil.removeUnit(this.height);
edit.iframe.height(150);
this.resize(null, Math.max((params.kindutil.IE ? body.scrollHeight : body.offsetHeight) , 150));
- elocalStorage(message_content_editor,'topic_course_<%=course.id %>');
+ elocalStorage(message_content_editor,'topic_course_<%=course.id %>','des');
}
}).loadPlugin('paste');
return editor;
@@ -122,16 +121,16 @@
<%if User.current.allowed_to?(:as_teacher, course) %>
- <%= f.check_box :sticky, :value => topic.sticky %>
- <%= label_tag 'message_sticky', l(:label_board_sticky) %>
- <%= f.check_box :locked, :value => topic.locked %>
- <%= label_tag 'message_locked', l(:label_board_locked) %>
+ <%= f.check_box :sticky, :value => topic.sticky, :class => 'magic-checkbox fl' %>
+ <%= label_tag 'message_sticky', l(:label_board_sticky), :class => 'fl' %>
+ <%= f.check_box :locked, :value => topic.locked, :class => 'magic-checkbox fl' %>
+ <%= label_tag 'message_locked', l(:label_board_locked), :class => 'fl ml10' %>
<% end %>
@@ -155,8 +154,8 @@
-
-
+
+
diff --git a/app/views/boards/_course_show.html.erb b/app/views/boards/_course_show.html.erb
index 33f4fbd2e..f102e2f36 100644
--- a/app/views/boards/_course_show.html.erb
+++ b/app/views/boards/_course_show.html.erb
@@ -1,44 +1,13 @@
-
-
-