Merge branch 'develop' into cs_optimize_txz

Conflicts:
	app/views/layouts/new_base.html.erb
	app/views/layouts/new_base_user.html.erb
	app/views/users/_user_resource_info.html.erb
cs_optimize_txz
Tim 9 years ago
commit 1658f78a7b

@ -0,0 +1 @@
{"access_token":"oEEf8ZKAB8Y2G0o_xnTPkPJHKKk8iHkLC-f5ptvQ2nCMj9IpC86ivLD2-p38GfOkuG-HuQp3pWZqhs3NJXUMdPLWsr5k67hPZYuqg4ozLccx0xdLswapj0mn8ovZhK1tKIKiAFAOMO","expires_in":7200,"got_token_at":1467012449}

4
.gitignore vendored

@ -6,6 +6,8 @@
/config/database.yml /config/database.yml
/config/configuration.yml /config/configuration.yml
/config/additional_environment.rb /config/additional_environment.rb
/config/menu.yml
/config/wechat.yml
/files/* /files/*
/log/* /log/*
@ -31,3 +33,5 @@ vendor/cache
/tags /tags
/config/initializers/gitlab_config.rb /config/initializers/gitlab_config.rb
1234567 1234567
public/javascripts/wechat/node_modules/
.ruby-version

@ -1,25 +0,0 @@
<html>
<head>
<title>
Client
</title>
</head>
<body>
<hr />
<h2>这是一张图片</h2>
<p>photo<a href="http://10.0.47.15:3000/shares/new?access_token='2d3dda45dsd'&comment='verygood'&title=davide&share_type=1&url=http://www.baidu.com"> Share A </a></p>
<hr />
<h2>这是一段视频</h2>
<p>Text<a href="http://10.0.47.15:3000/shares/new?access_token=2d3dda45dsd&comment=verygood&title=kaka&share_type=2&url=http://www.sina.com"> Share B </a></p>
<hr />
<h2>这是一篇文章</h2>
<p>Text<a href="http://10.0.47.15:3000/shares/new?access_token=2d3dda45dsd&comment=verygood&title=pepe&share_type=3&url=http://www.sina.com"> Share C </a></p>
<hr />
</body>
</html>

@ -1,13 +1,19 @@
source 'https://rubygems.org/' source 'https://ruby.taobao.org/'
### 这里执行bundle config mirror.https://rubygems.org https://gems.ruby-china.org 切换到ruby-china源
unless RUBY_PLATFORM =~ /w32/ unless RUBY_PLATFORM =~ /w32/
# unix-like only # unix-like only
gem 'iconv' gem 'iconv'
if RUBY_PLATFORM =~ /darwin/
gem "rmagick", "= 2.15.4" ## osx must be this version
else
gem "rmagick", "= 2.13.1" ## centos yum install ImageMagick-devel
end
gem 'certified'
gem 'net-ssh', '2.9.1'
gem 'jenkins_api_client'
gem 'nokogiri'
end end
gem 'certified'
gem 'wechat',path: 'lib/wechat' gem 'wechat',path: 'lib/wechat'
gem 'grack', path:'lib/grack' gem 'grack', path:'lib/grack'
gem 'gitlab', path: 'lib/gitlab-cli' gem 'gitlab', path: 'lib/gitlab-cli'
@ -31,7 +37,6 @@ gem 'acts-as-taggable-on', '2.4.1'
gem 'spreadsheet' gem 'spreadsheet'
gem 'ruby-ole' gem 'ruby-ole'
gem 'rails_kindeditor',path:'lib/rails_kindeditor' gem 'rails_kindeditor',path:'lib/rails_kindeditor'
#gem "rmagick", ">= 2.0.0"
gem 'binding_of_caller' gem 'binding_of_caller'
gem 'chinese_pinyin' gem 'chinese_pinyin'
# gem 'sunspot_rails', '~> 1.3.3' # gem 'sunspot_rails', '~> 1.3.3'
@ -81,7 +86,7 @@ group :assets do
gem 'coffee-rails', '~> 3.2.1' gem 'coffee-rails', '~> 3.2.1'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes # See https://github.com/sstephenson/execjs#readme for more supported runtimes
gem 'therubyracer', :platforms => :ruby # gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3' gem 'uglifier', '>= 1.0.3'
end end

@ -1,3 +1,5 @@
#coding=utf-8
module Mobile module Mobile
require_relative 'middleware/error_handler' require_relative 'middleware/error_handler'
require_relative 'apis/auth' require_relative 'apis/auth'
@ -16,11 +18,13 @@ module Mobile
require_relative 'apis/blog_comments' require_relative 'apis/blog_comments'
require_relative 'apis/new_comment' require_relative 'apis/new_comment'
require_relative 'apis/praise' require_relative 'apis/praise'
require_relative 'apis/resources'
class API < Grape::API class API < Grape::API
version 'v1', using: :path version 'v1', using: :path
format :json format :json
content_type :json, "application/json;charset=UTF-8" content_type :json, "application/json;charset=UTF-8"
use ActionDispatch::Session::CookieStore
use Mobile::Middleware::ErrorHandler use Mobile::Middleware::ErrorHandler
helpers do helpers do
@ -29,16 +33,26 @@ module Mobile
end end
def authenticate! def authenticate!
raise('Unauthorized. Invalid or expired token.') unless current_user raise('Unauthorized. 用户认证失败.') unless current_user
end
def session
env['rack.session']
end end
def current_user def current_user
openid = params[:openid]
if openid
uw = UserWechat.find_by_openid(params[:openid])
return uw.user if uw
end
token = ApiKey.where(access_token: params[:token]).first token = ApiKey.where(access_token: params[:token]).first
if token && !token.expired? if token && !token.expired?
@current_user = User.find(token.user_id) return User.find(token.user_id)
else
nil
end end
nil
end end
end end
@ -58,9 +72,9 @@ module Mobile
mount Apis::BlogComments mount Apis::BlogComments
mount Apis::NewComment mount Apis::NewComment
mount Apis::Praise mount Apis::Praise
mount Apis::Resources
#add_swagger_documentation ({api_version: 'v1', base_path: 'http://u06.shellinfo.cn/trustie/api'}) add_swagger_documentation ({api_version: 'v1', base_path: '/api'}) if Rails.env.development?
#add_swagger_documentation ({api_version: 'v1', base_path: '/api'}) if Rails.env.development?
end end
end end

@ -9,38 +9,24 @@ module Mobile
params do params do
requires :page, type: Integer requires :page, type: Integer
requires :openid, type: String requires :token, type: String
end end
post do post do
user = UserWechat.find_by_openid(params[:openid]).user authenticate!
=begin
shield_project_ids = ShieldActivity.where("container_type='User' and container_id=#{user.id} and shield_type='Project'").map(&:shield_id)
shield_course_ids = ShieldActivity.where("container_type='User' and container_id=#{user.id} and shield_type='Course'").map(&:shield_id)
page = params[:page] ? params[:page] : 0
user_project_ids = (user.projects.visible.map{|project| project.id}-shield_project_ids).empty? ? "(-1)" : "(" + (user.projects.visible.map{|project| project.id}-shield_project_ids).join(",") + ")"
user_course_ids = (user.courses.visible.map{|course| course.id}-shield_course_ids).empty? ? "(-1)" : "(" + (user.courses.visible.map{|course| course.id}-shield_course_ids).join(",") + ")"
course_types = "('Message','News','HomeworkCommon','Poll','Course')"
project_types = "('Message','Issue','ProjectCreateInfo')"
principal_types = "JournalsForMessage"
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(','))+")" user = current_user
activities = UserActivity.where("(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})").order('updated_at desc')
=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_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) 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] : 0 page = params[:page] ? params[:page] : 0
user_project_ids = (user.projects.map{|project| project.id}-shield_project_ids).empty? ? "(-1)" : "(" + (user.projects.map{|project| project.id}-shield_project_ids).join(",") + ")" user_project_ids = (user.projects.where("status = 1").map{|project| project.id}-shield_project_ids).empty? ? "(-1)" : "(" + (user.projects.where("status = 1").map{|project| project.id}-shield_project_ids).join(",") + ")"
user_course_ids = (user.courses.map{|course| course.id}-shield_course_ids).empty? ? "(-1)" : "(" + (user.courses.map{|course| course.id}-shield_course_ids).join(",") + ")" user_course_ids = (user.courses.where("is_delete = 0").map{|course| course.id}-shield_course_ids).empty? ? "(-1)" : "(" + (user.courses.where("is_delete = 0").map{|course| course.id}-shield_course_ids).join(",") + ")"
course_types = "('Message','News','HomeworkCommon','Poll','Course')" course_types = "('Message','News','HomeworkCommon','Poll','Course')"
project_types = "('Message','Issue','ProjectCreateInfo')" project_types = "('Message','Issue','Project')"
principal_types = "JournalsForMessage" principal_types = "JournalsForMessage"
watched_user_ids = User.watched_by(user.id).count == 0 ? " " : ("," + User.watched_by(user.id).map{|u| u.id.to_s }.join(',')) watched_user_ids = User.watched_by(user.id).count == 0 ? " " : ("," + User.watched_by(user.id).map{|u| u.id.to_s }.join(','))
user_ids = "(" + user.id.to_s + watched_user_ids + ")" user_ids = "(" + user.id.to_s + watched_user_ids + ")"
watched_user_blog_ids = Blog.select("id").where("author_id in #{user_ids}").map { |blog| blog.id}.join(",") watched_user_blog_ids = Blog.select("id").where("author_id in #{user_ids}").count == 0 ? " " :Blog.select("id").where("author_id in #{user_ids}").map { |blog| blog.id}.join(",")
blog_ids = "(" + watched_user_blog_ids + ")" blog_ids = "(" + watched_user_blog_ids + ")"
activities = UserActivity.where("(container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types})" + activities = UserActivity.where("(container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types})" +

@ -14,8 +14,9 @@ module Mobile
optional :token, type: String optional :token, type: String
end end
get do get do
authenticate!
cs = CoursesService.new cs = CoursesService.new
courses = cs.course_list(params,current_user.nil? ? User.find(2):current_user) courses = cs.user_courses_list(current_user)
present :data, courses, with: Mobile::Entities::Course present :data, courses, with: Mobile::Entities::Course
present :status, 0 present :status, 0
end end
@ -98,25 +99,19 @@ module Mobile
desc "加入课程" desc "加入课程"
params do params do
requires :token, type: String requires :token, type: String
requires :course_password, type: String requires :invite_code, type: String, desc: '邀请码'
end end
post ":id" do post "join" do
authenticate! authenticate!
cs = CoursesService.new cs = CoursesService.new
status = cs.join_course({:object_id => params[:id],:course_password => params[:course_password]},current_user) status = cs.join_course({role: "10", openid: params[:openid], invite_code: params[:invite_code]}, current_user)
out = {status: status[:state]} {
message = case status[:state] status: status[:state],
when 0; "加入成功" messsge:CoursesService::JoinCourseError.message(status[:state])
when 1; "密码错误" }
when 2; "课程已过期 请联系课程管理员重启课程。(在配置课程处)"
when 3; "您已经加入了课程"
when 4; "您加入的课程不存在"
when 5; "您还未登录"
else; "未知错误,请稍后再试"
end
out.merge(message: message)
end end
desc "退出课程" desc "退出课程"
params do params do
requires :token, type: String requires :token, type: String
@ -202,6 +197,7 @@ module Mobile
end end
route_param :id do route_param :id do
get do get do
authenticate!
cs = CoursesService.new cs = CoursesService.new
course = cs.show_course(params,(current_user.nil? ? User.find(2):current_user)) course = cs.show_course(params,(current_user.nil? ? User.find(2):current_user))
#course = Course.find(params[:id]) #course = Course.find(params[:id])
@ -389,7 +385,16 @@ module Mobile
end end
desc '获取测验列表'
params do
requires :token, type:String
end
get ':course_id/exercises' do
authenticate!
exercises = Course.find(params[:course_id]).exercises
present :data,exercises,with:Mobile::Entities::Exercise
present :status,0
end
end end
end end

@ -8,7 +8,8 @@ module Mobile
desc "get special issuse" desc "get special issuse"
get ':id' do get ':id' do
user = UserWechat.find_by_openid(params[:openid]).user authenticate!
user = current_user
issue = Issue.find params[:id] issue = Issue.find params[:id]
present :data, issue, with: Mobile::Entities::Issue,user: user present :data, issue, with: Mobile::Entities::Issue,user: user
present :status, 0 present :status, 0

@ -7,7 +7,8 @@ module Mobile
desc "get special journal" desc "get special journal"
get ':id' do get ':id' do
user = UserWechat.find_by_openid(params[:openid]).user authenticate!
user = current_user
jour = JournalsForMessage.find params[:id] jour = JournalsForMessage.find params[:id]
present :data, jour, with: Mobile::Entities::Jours,user: user present :data, jour, with: Mobile::Entities::Jours,user: user
present :status, 0 present :status, 0

@ -7,7 +7,8 @@ module Mobile
desc "get special topic" desc "get special topic"
get ':id' do get ':id' do
user = UserWechat.find_by_openid(params[:openid]).user authenticate!
user = current_user
message = Message.find params[:id] message = Message.find params[:id]
present :data, message, with: Mobile::Entities::Message,user: user present :data, message, with: Mobile::Entities::Message,user: user
present :status, 0 present :status, 0

@ -11,12 +11,12 @@ module Mobile
params do params do
requires :type, type: String requires :type, type: String
requires :content, type: String requires :content, type: String
requires :openid, type: String requires :token, type: String
end end
post ':id' do post ':id' do
authenticate!
type = params[:type] type = params[:type]
result = 1 result = 1
current_user = UserWechat.find_by_openid(params[:openid]).user
if params[:content]!="" && current_user if params[:content]!="" && current_user
case type case type
when "HomeworkCommon" when "HomeworkCommon"

@ -7,7 +7,8 @@ module Mobile
desc "get special news" desc "get special news"
get ':id' do get ':id' do
user = UserWechat.find_by_openid(params[:openid]).user authenticate!
user = current_user
news = News.find params[:id] news = News.find params[:id]
present :data, news, with: Mobile::Entities::News,user: user present :data, news, with: Mobile::Entities::News,user: user
present :status, 0 present :status, 0

@ -9,12 +9,13 @@ module Mobile
params do params do
requires :type, type: String requires :type, type: String
requires :openid, type: String requires :token, type: String
end end
post ':id' do post ':id' do
authenticate!
obj_id = params[:id] obj_id = params[:id]
obj_type = params[:type] obj_type = params[:type]
user = UserWechat.find_by_openid(params[:openid]).user user = current_user
pts = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",obj_id,obj_type.to_s,user.id).first pts = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",obj_id,obj_type.to_s,user.id).first
if pts.blank? if pts.blank?
praise_or_cancel(obj_type,obj_id,user,1) praise_or_cancel(obj_type,obj_id,user,1)

@ -0,0 +1,55 @@
#coding=utf-8
module Mobile
module Apis
class Resources < Grape::API
resource :resources do
desc '获取所有课件'
params do
requires :token, type: String
end
get do
authenticate!
data = current_user.course_attachments
present :data, data, with: Mobile::Entities::Attachment
present :status, 0
end
desc '获取所有作业'
params do
requires :token, type: String
end
get 'homeworks' do
authenticate!
homeworks = current_user.homework_commons
present :data, homeworks, with: Mobile::Entities::Homework
present :status, 0
end
desc '获取所有测验'
params do
requires :token, type: String
end
get 'exercies' do
authenticate!
exercises = current_user.exercises
present :data, exercises, with: Mobile::Entities::Exercise
present :status, 0
end
end
end
end
end

@ -4,6 +4,48 @@ module Mobile
class Users < Grape::API class Users < Grape::API
resource :users do resource :users do
desc "查询是否已绑定"
params do
requires :openid, type: String, desc: 'wechat openid'
end
post 'isbind' do
openid = params[:openid]
uw = UserWechat.where(openid: openid).first
raise "还未绑定trustie帐户" unless uw
user = uw.user
::ApiKey.delete_all(user_id: user.id)
key = ::ApiKey.create!(user_id: user.id)
present status: 0, token: key.access_token
end
desc "绑定微信用户"
params do
requires :login, type: String, desc: 'username'
requires :password, type: String, desc: 'password'
end
post 'wxbind' do
openid = session[:wechat_openid]
logger.debug "openid ============== #{openid}"
raise "无法获取到openid,请在微信中打开本页面" unless openid
uw = UserWechat.where(openid: openid).first
raise "此微信号已绑定用户(#{uw.user.login}), 不能重复绑定" if uw
user, last_login_on = User.try_to_login(params[:login], params[:password])
raise "用户名或密码错误,请重新输入" unless user
#补全用户信息
raise "此用户已经绑定过公众号, 请换一个帐户试试" if user.user_wechat
UserWechat.create!(
openid: openid,
user: user
)
# ws = WechatService.new
# ws.binding_succ_notice(user.id, "您已成功绑定Trustie平台", user.login, format_time(Time.now))
present status: 0, message: '您已成功绑定Trustie平台'
end
desc "注册用户" desc "注册用户"
params do params do
requires :login, type: String, desc: 'username' requires :login, type: String, desc: 'username'

@ -7,7 +7,8 @@ module Mobile
desc "get one homework" desc "get one homework"
get ':id' do get ':id' do
user = UserWechat.find_by_openid(params[:openid]).user authenticate!
user = current_user
homework = HomeworkCommon.find params[:id] homework = HomeworkCommon.find params[:id]
present :data, homework, with: Mobile::Entities::Whomework,user: user present :data, homework, with: Mobile::Entities::Whomework,user: user
present :status, 0 present :status, 0

@ -14,7 +14,7 @@ module Mobile
else else
case f case f
when :user_act when :user_act
if ac.act_type == "ProjectCreateInfo" if ac.act_type == "Project"
ac unless ac.nil? ac unless ac.nil?
else else
ac.act unless ac.nil? || ac.act.nil? ac.act unless ac.nil? || ac.act.nil?
@ -41,11 +41,11 @@ module Mobile
end end
when :description when :description
if ac.act_type == "HomeworkCommon" || ac.act_type == "Issue" || ac.act_type == "News" if ac.act_type == "HomeworkCommon" || ac.act_type == "Issue" || ac.act_type == "News"
ac.act.description unless ac.nil? || ac.act.nil? strip_html(ac.act.description) unless ac.nil? || ac.act.nil?
elsif ac.act_type == "Message" || ac.act_type == "BlogComment" elsif ac.act_type == "Message" || ac.act_type == "BlogComment"
ac.act.content unless ac.nil? || ac.act.nil? strip_html(ac.act.content) unless ac.nil? || ac.act.nil?
elsif ac.act_type == "JournalsForMessage" elsif ac.act_type == "JournalsForMessage"
ac.act.notes unless ac.nil? || ac.act.nil? strip_html(ac.act.notes) unless ac.nil? || ac.act.nil?
end end
when :latest_update when :latest_update
time_from_now ac.updated_at unless ac.nil? time_from_now ac.updated_at unless ac.nil?
@ -84,10 +84,10 @@ module Mobile
elsif ac.container_type == "Project" elsif ac.container_type == "Project"
case ac.act_type case ac.act_type
when "Issue" when "Issue"
"项目缺陷" "项目问题"
when "Message" when "Message"
"项目讨论区" "项目讨论区"
when "ProjectCreateInfo" when "Project"
"项目" "项目"
end end
end end
@ -98,10 +98,11 @@ module Mobile
end end
expose :act_type #缺陷/作业/讨论区/留言等类型 expose :act_type #缺陷/作业/讨论区/留言等类型
expose :act_id expose :act_id
expose :id
expose :container_type #课程/项目/博客/个人 expose :container_type #课程/项目/博客/个人
expose :author, using: Mobile::Entities::User do |a, opt| #用户信息 expose :author, using: Mobile::Entities::User do |a, opt| #用户信息
if a.is_a? ::UserActivity if a.is_a? ::UserActivity
if a.act_type == "ProjectCreateInfo" if a.act_type == "Project"
get_user(get_project(a.act_id).user_id) get_user(get_project(a.act_id).user_id)
elsif !a.act.nil? elsif !a.act.nil?
if a.act_type == 'Issue' || a.act_type == 'News' || a.act_type == 'Message' || a.act_type == 'BlogComment' if a.act_type == 'Issue' || a.act_type == 'News' || a.act_type == 'Message' || a.act_type == 'BlogComment'

@ -45,6 +45,8 @@ module Mobile
course_expose :tea_id course_expose :tea_id
course_expose :term course_expose :term
course_expose :time course_expose :time
course_expose :invite_code
course_expose :qrcode
course_expose :updated_at course_expose :updated_at
course_expose :course_student_num course_expose :course_student_num
expose :teacher, using: Mobile::Entities::User do |c, opt| expose :teacher, using: Mobile::Entities::User do |c, opt|

@ -0,0 +1,8 @@
module Mobile
module Entities
class Exercise < Grape::Entity
expose :exercise_name
expose :exercise_description
end
end
end

@ -26,6 +26,8 @@ module Mobile
u.nil? || u.user_extensions.nil? ? "" : u.user_extensions.student_id u.nil? || u.user_extensions.nil? ? "" : u.user_extensions.student_id
when :realname when :realname
u.nil? ? "" : get_user_realname(u) u.nil? ? "" : get_user_realname(u)
when :name
u.nil? ? "" : u.show_name
end end
end end
end end
@ -57,6 +59,11 @@ module Mobile
user_expose :student_num user_expose :student_num
# 活跃值 # 活跃值
user_expose :active_count user_expose :active_count
user_expose :role_name
user_expose :name
end end
end end

@ -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/

@ -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/

@ -0,0 +1,3 @@
// Place all the styles related to the QualityAnalyses controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -0,0 +1,3 @@
// Place all the styles related to the syllabuses controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/

@ -239,14 +239,23 @@ class AccountController < ApplicationController
end end
def resendmail def resendmail
result = {:status=>1, :email=>""}
user = User.find(params[:user]) if params[:user] user = User.find(params[:user]) if params[:user]
result[:email] = user.mail
token = Token.new(:user => user, :action => "register") token = Token.new(:user => user, :action => "register")
if token.save if token.save
Mailer.run.register(token) # Mailer.run.register(token)
Mailer.register(token).deliver
else else
yield if block_given? yield if block_given?
result[:status] = 0
end end
render :json => result
end
def email_activation
end end
private private
@ -264,6 +273,7 @@ class AccountController < ApplicationController
if user.nil? if user.nil?
invalid_credentials invalid_credentials
elsif user.status == 2 elsif user.status == 2
@user = user
invalid_credentials_new invalid_credentials_new
elsif user.new_record? elsif user.new_record?
onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id }) onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
@ -375,8 +385,9 @@ class AccountController < ApplicationController
def invalid_credentials_new def invalid_credentials_new
logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}" logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
flash[:error] = l(:notice_account_invalid_creditentials_new) # flash[:error] = l(:notice_account_invalid_creditentials_new)
render signin_path(:login=>true) # render signin_path(:login=>true)
render :action => 'email_activation'
end end
# Register a user for email activation. # Register a user for email activation.

@ -67,12 +67,15 @@ class AdminController < ApplicationController
def excellent_all_courses def excellent_all_courses
name = params[:name] name = params[:name]
@order = "" @order = ""
if params[:order] == 'asc' @sort = ""
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) asc, c.id desc") 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] @order = params[:order]
elsif params[:order] == 'desc' @sort = params[:sort]
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) DESC, c.id desc") 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] @order = params[:order]
@sort = params[:sort]
else else
courses = Course.like(name).order('created_at desc') courses = Course.like(name).order('created_at desc')
end end
@ -99,6 +102,22 @@ class AdminController < ApplicationController
end 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 def course_resource_list

@ -363,7 +363,11 @@ class ApplicationController < ActionController::Base
when "contest" when "contest"
return true return true
when "Course" when "Course"
allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false) if @attachment.get_status_by_attach(User.current.id) == 2
return true
else
allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false)
end
else else
return true return true
end end
@ -912,4 +916,11 @@ class ApplicationController < ActionController::Base
call_hook(:controller_account_success_authentication_after, {:user => user }) call_hook(:controller_account_success_authentication_after, {:user => user })
end end
def user_unlogged_check
if !User.current.logged?
render(:partial => 'organizations/unlogged_tip')
return false
end
true
end
end end

@ -68,7 +68,7 @@ class AtController < ApplicationController
end end
def find_project(id) def find_project(id)
return [] if id<0 return [] if id.to_i<0
at_persons = Project.find(id).users at_persons = Project.find(id).users
at_persons.delete_if { |u| u.id == User.current.id } at_persons.delete_if { |u| u.id == User.current.id }
end end

@ -265,6 +265,10 @@ class AttachmentsController < ApplicationController
@history.save #历史记录保存完毕 @history.save #历史记录保存完毕
#将最新保存的记录 数据替换到 需要修改的文件记录 #将最新保存的记录 数据替换到 需要修改的文件记录
@old_attachment.attributes = @attachment.attributes.dup.except("id","container_id","container_type","is_public","downloads", "quotes") @old_attachment.attributes = @attachment.attributes.dup.except("id","container_id","container_type","is_public","downloads", "quotes")
# 如果附件描述被修改,则保存附件
unless params[:description] == @attachment.description
@old_attachment.description = params[:description]
end
@old_attachment.save @old_attachment.save
#删除当前记录 #删除当前记录
@attachment.delete @attachment.delete
@ -608,7 +612,7 @@ class AttachmentsController < ApplicationController
@attachment.container.board.course) @attachment.container.board.course)
@course = @attachment.container.board.course @course = @attachment.container.board.course
else else
unless @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' 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'
@project = @attachment.project @project = @attachment.project
end end
end end

@ -125,7 +125,9 @@ class BoardsController < ApplicationController
if @order.to_i == 2 if @order.to_i == 2
@type = 2 @type = 2
@topics.each do |topic| @topics.each do |topic|
topic[:infocount] = get_praise_num(topic) + (topic.parent ? topic.parent.children.count : topic.children.count) all_comments = []
count=get_all_children(all_comments, topic).count
topic[:infocount] = get_praise_num(topic) + count
if topic[:infocount] < 0 if topic[:infocount] < 0
topic[:infocount] = 0 topic[:infocount] = 0
end end

@ -74,7 +74,7 @@ class CoursesController < ApplicationController
else else
@state = 5 #未登录 @state = 5 #未登录
end end
@object_id = params[:object_id] @object_id = @course.id if @course
respond_to do |format| respond_to do |format|
format.js #{ render :partial => 'set_join', :locals => {:user => @user, :course => @course, :object_id => params[:object_id]} } format.js #{ render :partial => 'set_join', :locals => {:user => @user, :course => @course, :object_id => params[:object_id]} }
end end
@ -162,6 +162,7 @@ class CoursesController < ApplicationController
@subPage_title = l :label_student_list @subPage_title = l :label_student_list
@canShowCode = User.current.allowed_to?(:as_teacher,@course) && params[:role] != '1' @canShowCode = User.current.allowed_to?(:as_teacher,@course) && params[:role] != '1'
# @is_remote = true # @is_remote = true
@sort_type = 'score'
@score_sort_by = "desc" @score_sort_by = "desc"
q = "#{params[:name].strip}" q = "#{params[:name].strip}"
if params[:incourse] if params[:incourse]
@ -185,9 +186,11 @@ class CoursesController < ApplicationController
group.course_id = @course.id group.course_id = @course.id
group.save group.save
end end
@sort_type = 'score'
@score_sort_by = "desc"
@canShowCode = User.current.allowed_to?(:as_teacher,@course) && params[:role] != '1' @canShowCode = User.current.allowed_to?(:as_teacher,@course) && params[:role] != '1'
@is_remote = true @is_remote = true
@members = student_homework_score(0,0, 10,"desc") @members = student_homework_score(0,0, 10,@score_sort_by)
@course_groups = @course.course_groups @course_groups = @course.course_groups
end end
@ -196,7 +199,9 @@ class CoursesController < ApplicationController
@subPage_title = l :label_student_list @subPage_title = l :label_student_list
@canShowCode = isCourseTeacher(User.current.id,@course) && params[:role] != '1' @canShowCode = isCourseTeacher(User.current.id,@course) && params[:role] != '1'
@is_remote = true @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 @course_groups = @course.course_groups
end end
@ -281,6 +286,7 @@ class CoursesController < ApplicationController
@render_file = 'new_member_list' @render_file = 'new_member_list'
@canShowCode = isCourseTeacher(User.current.id,@course) && params[:role] != '1' @canShowCode = isCourseTeacher(User.current.id,@course) && params[:role] != '1'
@is_remote = true @is_remote = true
@sort_type = 'score'
@score_sort_by = "desc" @score_sort_by = "desc"
if params[:group_id] && params[:group_id] != "0" if params[:group_id] && params[:group_id] != "0"
@group = CourseGroup.find(params[:group_id]) @group = CourseGroup.find(params[:group_id])
@ -298,6 +304,7 @@ class CoursesController < ApplicationController
@render_file = 'new_member_list' @render_file = 'new_member_list'
@score_sort_by = "desc" @score_sort_by = "desc"
@sort_type = params[:sort_type] ? params[:sort_type] : "score"
@canShowCode = User.current.allowed_to?(:as_teacher,@course) && params[:role] != '1' @canShowCode = User.current.allowed_to?(:as_teacher,@course) && params[:role] != '1'
@role = params[:role].nil? ? '2':params[:role] @role = params[:role].nil? ? '2':params[:role]
@is_remote = true @is_remote = true
@ -312,7 +319,7 @@ class CoursesController < ApplicationController
if @course.open_student == 1 || User.current.member_of_course?(@course) if @course.open_student == 1 || User.current.member_of_course?(@course)
@subPage_title = l :label_student_list @subPage_title = l :label_student_list
page = params[:page].nil? ? 0 : (params['page'].to_i - 1) page = params[:page].nil? ? 0 : (params['page'].to_i - 1)
@all_members = student_homework_score(0,page, 10,"desc") @all_members = student_homework_score(0,page, 10,@score_sort_by,@sort_type)
@members = @all_members @members = @all_members
else else
render_403 render_403
@ -334,7 +341,7 @@ class CoursesController < ApplicationController
def export_course_member_excel def export_course_member_excel
@all_members = student_homework_score(0,0,0,"desc") @all_members = student_homework_score(0,0,0,"desc")
@homeworks = @course.homework_commons.order("created_at asc") @homeworks = @course.homework_commons.where("publish_time <= '#{Date.today}'").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}_#{@course.time.to_s + @course.term}#{l(:excel_member_list)}";
respond_to do |format| respond_to do |format|
@ -350,28 +357,29 @@ class CoursesController < ApplicationController
@subPage_title = l :label_student_list @subPage_title = l :label_student_list
@render_file = 'new_member_list' @render_file = 'new_member_list'
@is_remote = true @is_remote = true
@sort_type = params[:sort_type] if params[:sort_type]
@score_sort_by = params[:sort_by] if params[:sort_by] @score_sort_by = params[:sort_by] if params[:sort_by]
@search_name = params[:search_name] if params[:search_name] @search_name = params[:search_name] if params[:search_name]
group_id = params[:group_id] group_id = params[:group_id]
if !@search_name.nil? if !@search_name.nil?
if group_id == '0' if group_id == '0'
page = params[:page].nil? ? 0 : (params['page'].to_i - 1) page = params[:page].nil? ? 0 : (params['page'].to_i - 1)
@results = searchmember_by_name(student_homework_score(0,0,0,@score_sort_by), @search_name) @results = searchmember_by_name(student_homework_score(0,0,0,@score_sort_by,@sort_type), @search_name)
@result_count = @results.count @result_count = @results.count
# @results = paginateHelper @results, 10 # @results = paginateHelper @results, 10
else else
@group = CourseGroup.find(group_id) @group = CourseGroup.find(group_id)
@results = searchmember_by_name(student_homework_score(group_id, 0, 0,@score_sort_by),@search_name) @results = searchmember_by_name(student_homework_score(group_id, 0, 0,@score_sort_by,@sort_type),@search_name)
@result_count = @results.count @result_count = @results.count
# @results = paginateHelper @results, 10 # @results = paginateHelper @results, 10
end end
else else
if group_id == '0' if group_id == '0'
page = params[:page].nil? ? 0 : (params['page'].to_i - 1) page = params[:page].nil? ? 0 : (params['page'].to_i - 1)
@results = student_homework_score(0,page, 10,@score_sort_by) @results = student_homework_score(0,page, 10,@score_sort_by,@sort_type)
else else
@group = CourseGroup.find(group_id) @group = CourseGroup.find(group_id)
@results = student_homework_score(group_id, 0, 0,@score_sort_by) @results = student_homework_score(group_id, 0, 0,@score_sort_by,@sort_type)
end end
end end
end end
@ -384,6 +392,15 @@ class CoursesController < ApplicationController
end end
end end
# 显示每个学生的作业评分详情
def show_member_act_score
@member = Member.find(params[:member_id]) if params[:member_id]
respond_to do |format|
format.html {render :layout => 'course_base'}
format.js
end
end
def handle_course courses, activities def handle_course courses, activities
course_activity_count_array=activities.values() course_activity_count_array=activities.values()
course_array=[] course_array=[]
@ -698,6 +715,7 @@ class CoursesController < ApplicationController
@trackers = Tracker.sorted.all @trackers = Tracker.sorted.all
@course = Course.new @course = Course.new
@course.safe_attributes = params[:course] @course.safe_attributes = params[:course]
@syllabus = Syllabus.where("id = #{params[:syllabus_id].to_i}").first if params[:syllabus_id]
# month = Time.now.month # month = Time.now.month
render :layout => 'new_base' render :layout => 'new_base'
else else
@ -1149,7 +1167,7 @@ class CoursesController < ApplicationController
end end
end end
def student_homework_score(groupid,start_from, nums, score_sort_by) def student_homework_score(groupid,start_from, nums, score_sort_by, sort_type = 'score')
start_from = start_from * nums start_from = start_from * nums
sql_select = "" sql_select = ""
if groupid == 0 if groupid == 0
@ -1159,11 +1177,13 @@ class CoursesController < ApplicationController
WHERE student_works.homework_common_id = homework_commons.id WHERE student_works.homework_common_id = homework_commons.id
AND homework_commons.course_id = #{@course.id} AND homework_commons.course_id = #{@course.id}
AND student_works.user_id = members.user_id AND student_works.user_id = members.user_id
) AS score ) AS score,(SELECT (message_num*2 + message_reply_num*1 + news_reply_num*1 + news_num*1 +
resource_num*5 + journal_num*1 + homework_journal_num*1 ) FROM `course_contributor_scores` AS ccs WHERE ccs.course_id = #{@course.id} AND ccs.user_id = members.user_id
) AS act_score
FROM members FROM members
JOIN students_for_courses JOIN students_for_courses
ON students_for_courses.student_id = members.user_id AND students_for_courses.course_id = members.course_id 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 #{score_sort_by}" WHERE members.course_id = #{@course.id} ORDER BY #{sort_type} #{score_sort_by}"
else else
sql_select = "SELECT members.*,( sql_select = "SELECT members.*,(
SELECT SUM(student_works.work_score) SELECT SUM(student_works.work_score)
@ -1171,11 +1191,13 @@ class CoursesController < ApplicationController
WHERE student_works.homework_common_id = homework_commons.id WHERE student_works.homework_common_id = homework_commons.id
AND homework_commons.course_id = #{@course.id} AND homework_commons.course_id = #{@course.id}
AND student_works.user_id = members.user_id AND student_works.user_id = members.user_id
) AS score ) AS score,(SELECT (message_num*2 + message_reply_num*1 + news_reply_num*1 + news_num*1 +
resource_num*5 + journal_num*1 + homework_journal_num*1 ) FROM `course_contributor_scores` AS ccs WHERE ccs.course_id = #{@course.id} AND ccs.user_id = members.user_id
) AS act_score
FROM members FROM members
JOIN students_for_courses JOIN students_for_courses
ON students_for_courses.student_id = members.user_id AND students_for_courses.course_id = members.course_id 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 = #{groupid} ORDER BY score #{score_sort_by}" WHERE members.course_id = #{@course.id} AND members.course_group_id = #{groupid} ORDER BY #{sort_type} #{score_sort_by}"
end end
sql = ActiveRecord::Base.connection() sql = ActiveRecord::Base.connection()
homework_scores = Member.find_by_sql(sql_select) homework_scores = Member.find_by_sql(sql_select)
@ -1203,7 +1225,7 @@ class CoursesController < ApplicationController
def member_to_xls homeworks, course, members,groups def member_to_xls homeworks, course, members,groups
xls_report = StringIO.new xls_report = StringIO.new
book = Spreadsheet::Workbook.new book = Spreadsheet::Workbook.new
sheet1 = book.create_worksheet :name => "student" sheet1 = book.create_worksheet :name => "总成绩"
blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10 blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
#sheet1.row(0).default_format = blue #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.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)])
@ -1225,8 +1247,7 @@ class CoursesController < ApplicationController
sheet1[5,i+4] = ""+(i+1).to_s+"" sheet1[5,i+4] = ""+(i+1).to_s+""
end end
sheet1[5,homeworks.count+4] = "总成绩" sheet1[5,homeworks.count+4] = "总成绩"
sheet1[5,0] = "排名" sheet1[5,homeworks.count+5] = "活跃度"
sheet1[5,0] = "排名"
count_row = 6 count_row = 6
members.each_with_index do |member, i| members.each_with_index do |member, i|
sheet1[count_row,0]= i+1 sheet1[count_row,0]= i+1
@ -1236,17 +1257,133 @@ class CoursesController < ApplicationController
homeworks.each_with_index do |homework, j| homeworks.each_with_index do |homework, j|
student_works = homework.student_works.where("user_id = #{member.user.id}") student_works = homework.student_works.where("user_id = #{member.user.id}")
if student_works.empty? if student_works.empty?
sheet1[count_row,j+4] = format("%0.2f",0) sheet1[count_row,j+4] = 0
else else
final_score = student_works.first.final_score.nil? ? 0 : student_works.first.final_score final_score = student_works.first.final_score.nil? ? 0 : student_works.first.final_score
score = final_score - student_works.first.absence_penalty - student_works.first.late_penalty score = final_score - student_works.first.absence_penalty - student_works.first.late_penalty
sheet1[count_row,j+4] = format("%0.2f",score <0 ? 0:score) sheet1[count_row,j+4] = score <0 ? 0:score.round(2)
end end
end end
sheet1[count_row,homeworks.count+4] = format("%0.2f",member.score.nil? ? 0:member.score.to_s) sheet1[count_row,homeworks.count+4] = member.score.nil? ? 0:member.score.round(2)
sheet1[count_row,homeworks.count+5] = member.act_score.nil? ? 0:member.act_score
count_row += 1 count_row += 1
end end
homeworks.each_with_index do |home, i|
sheet = book.create_worksheet :name => "#{i+1}次作业"
sheet[0,0] = "课程编号"
sheet[0,1] = course.id
sheet[1,0] = "课程学期"
sheet[1,1] = course.time.to_s+""+course.term
sheet[2,0] = "课程名称"
sheet[2,1] = course.name
sheet[3,0] = "教师团队"
sheet[3,1] = (searchTeacherAndAssistant course).map{|member| member.user.show_name}.join('、')
sheet[4,0] = "主讲教师"
sheet[4,1] = course.teacher.show_name
sheet[4,0] = "作业批次"
sheet[4,1] = "#{i+1}次作业"
sheet[4,0] = "作业名称"
sheet[4,1] = home.name
if home.homework_type == 1 #普通作业
if home.anonymous_comment ==0
sheet.row(5).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(5).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 = 6
items = home.student_works.order("work_score desc")
items.each_with_index do |stu, j|
sheet[count_row,0]= j + 1
sheet[count_row,1] = stu.user.show_name
sheet[count_row,2] = stu.user.login
sheet[count_row,3] = stu.user.user_extensions.student_id
sheet[count_row,4] = stu.name
sheet[count_row,5] = strip_html stu.description
sheet[count_row,6] = stu.teacher_score.nil? ? l(:label_without_score) : stu.teacher_score.round(2)
sheet[count_row,7] = stu.teaching_asistant_score.nil? ? l(:label_without_score) : stu.teaching_asistant_score.round(2)
if home.anonymous_comment ==0
sheet[count_row,8] = stu.student_score.nil? ? l(:label_without_score) : stu.student_score.round(2)
sheet[count_row,9] = (home.teacher_priority == 1 && !stu.teacher_score.nil?) ? 0 : stu.absence_penalty
sheet[count_row,10] = (home.teacher_priority == 1 && !stu.teacher_score.nil?) ? 0 : stu.late_penalty
sheet[count_row,11] = stu.work_score.nil? ? l(:label_without_score) : stu.work_score.round(2)
sheet[count_row,12] = format_time(stu.created_at)
else
sheet[count_row,8] = (home.teacher_priority == 1 && !stu.teacher_score.nil?) ? 0 : stu.late_penalty
sheet[count_row,9] = stu.work_score.nil? ? l(:label_without_score) : stu.work_score.round(2)
sheet[count_row,10] = format_time(stu.created_at)
end
count_row += 1
end
elsif home.homework_type == 2 #编程作业
if home.anonymous_comment ==0
sheet.row(5).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(5).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 = 6
items = home.student_works.order("work_score desc")
items.each_with_index do |stu, j|
sheet[count_row,0]= j + 1
sheet[count_row,1] = stu.user.show_name
sheet[count_row,2] = stu.user.login
sheet[count_row,3] = stu.user.user_extensions.student_id
sheet[count_row,4] = stu.name
sheet[count_row,5] = stu.description
sheet[count_row,6] = stu.teacher_score.nil? ? l(:label_without_score) : stu.teacher_score.round(2)
sheet[count_row,7] = stu.teaching_asistant_score.nil? ? l(:label_without_score) : stu.teaching_asistant_score.round(2)
sheet[count_row,8] = stu.system_score.nil? ? l(:label_without_score) : stu.system_score.round(2)
if home.anonymous_comment ==0
sheet[count_row,9] = stu.student_score.nil? ? l(:label_without_score) : stu.student_score.round(2)
sheet[count_row,10] = (home.teacher_priority == 1 && !stu.teacher_score.nil?) ? 0 : stu.absence_penalty
sheet[count_row,11] = (home.teacher_priority == 1 && !stu.teacher_score.nil?) ? 0 : stu.late_penalty
sheet[count_row,12] = stu.work_score.nil? ? l(:label_without_score) : stu.work_score.round(2)
sheet[count_row,13] = format_time(stu.created_at)
else
sheet[count_row,9] = (home.teacher_priority == 1 && !stu.teacher_score.nil?) ? 0 : stu.late_penalty
sheet[count_row,10] = stu.work_score.nil? ? l(:label_without_score) : stu.work_score.round(2)
sheet[count_row,11] = format_time(stu.created_at)
end
count_row += 1
end
elsif home.homework_type == 3 #分组作业
if home.anonymous_comment ==0
sheet.row(5).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(5).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 = 6
items = home.student_works.order("work_score desc")
items.each_with_index do |stu, j|
sheet[count_row,0] = j + 1
sheet[count_row,1] = get_group_member_names stu
sheet[count_row,2] = stu.name
sheet[count_row,3] = (stu.project_id == 0 || stu.project_id.nil?) ? l(:excel_no_project) : stu.project.name
sheet[count_row,4] = strip_html stu.description
sheet[count_row,5] = stu.teacher_score.nil? ? l(:label_without_score) : stu.teacher_score.round(2)
sheet[count_row,6] = stu.teaching_asistant_score.nil? ? l(:label_without_score) : stu.teaching_asistant_score.round(2)
if home.anonymous_comment ==0
sheet[count_row,7] = stu.student_score.nil? ? l(:label_without_score) : stu.student_score.round(2)
sheet[count_row,8] = (home.teacher_priority == 1 && !stu.teacher_score.nil?) ? 0 : stu.absence_penalty
sheet[count_row,9] = (home.teacher_priority == 1 && !stu.teacher_score.nil?) ? 0 : stu.late_penalty
sheet[count_row,10] = stu.work_score.nil? ? l(:label_without_score) : stu.work_score.round(2)
sheet[count_row,11] = format_time(stu.created_at)
else
sheet[count_row,7] = (home.teacher_priority == 1 && !stu.teacher_score.nil?) ? 0 : stu.late_penalty
sheet[count_row,8] = stu.work_score.nil? ? l(:label_without_score) : stu.work_score.round(2)
sheet[count_row,9] = format_time(stu.created_at)
end
count_row += 1
end
end
end
=begin =begin
group0 = CourseGroup.new(); group0 = CourseGroup.new();
group0.id = 0; group0.id = 0;

@ -49,6 +49,11 @@ class ExerciseController < ApplicationController
return return
end end
@exercise = Exercise.find params[:id] @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? @is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
exercise_end = @exercise.end_time > Time.now exercise_end = @exercise.end_time > Time.now
if @exercise.time == -1 if @exercise.time == -1

@ -26,7 +26,7 @@ class FilesController < ApplicationController
before_filter :authorize, :except => [:create,:getattachtype,:quote_resource_show,:search,:searchone4reload,:search_project,:quote_resource_show_project, before_filter :authorize, :except => [:create,:getattachtype,:quote_resource_show,:search,:searchone4reload,:search_project,:quote_resource_show_project,
:search_tag_attachment,:subfield_upload_file,:search_org_subfield_tag_attachment, :search_tag_attachment,:subfield_upload_file,:search_org_subfield_tag_attachment,
:search_tag_attachment,:quote_resource_show_org_subfield,:find_org_subfield_attache, :search_tag_attachment,:quote_resource_show_org_subfield,:find_org_subfield_attache,
:search_files_in_subfield,:upload_files_menu,:file_hidden,:republish_file] :search_files_in_subfield,:upload_files_menu,:file_hidden,:republish_file,:update_file_description]
helper :sort helper :sort
include SortHelper include SortHelper
@ -256,6 +256,13 @@ class FilesController < ApplicationController
@order = "" @order = ""
@is_remote = false @is_remote = false
if params[:project_id] if params[:project_id]
# 更新资源申请消息为已读
# ar_ids = ApplyResource.where("user_id =? and container_id =? and container_type =?", User.current.id, params[:project_id].to_i, "Project").map{|ar| ar.id}
# cms = CourseMessage.where("course_message_type =? and user_id =? and course_message_id in (#{ar_ids.empty? ? '0': ar_ids.join(',')})", "ApplyResource", User.current.id)
# cms.each do |cm|
# cm.update_column(:viewed, true)
# end
# over
@page = params[:page] ? params[:page].to_i + 1 : 2 @page = params[:page] ? params[:page].to_i + 1 : 2
@container_type = 0 @container_type = 0
if params[:sort] if params[:sort]
@ -476,6 +483,7 @@ class FilesController < ApplicationController
if !attachments.empty? && attachments[:files] && tag_name != "" if !attachments.empty? && attachments[:files] && tag_name != ""
attachments[:files].each do |attachment| attachments[:files].each do |attachment|
attachment.tag_list.add(tag_name) attachment.tag_list.add(tag_name)
attachment.description = params[:description]
attachment.save attachment.save
end end
end end
@ -486,6 +494,7 @@ class FilesController < ApplicationController
if !attachments.empty? && attachments[:files] && tag_name != "" if !attachments.empty? && attachments[:files] && tag_name != ""
attachments[:files].each do |attachment| attachments[:files].each do |attachment|
attachment.tag_list.add(tag_name) attachment.tag_list.add(tag_name)
attachment.description = params[:description]
attachment.save attachment.save
end end
end end
@ -593,6 +602,7 @@ class FilesController < ApplicationController
if !attachments.empty? && attachments[:files] && tag_name != "" if !attachments.empty? && attachments[:files] && tag_name != ""
attachments[:files].each do |attachment| attachments[:files].each do |attachment|
attachment.tag_list.add(tag_name) attachment.tag_list.add(tag_name)
attachment.description = params[:description]
attachment.save attachment.save
end end
end end
@ -603,6 +613,7 @@ class FilesController < ApplicationController
if !attachments.empty? && attachments[:files] && tag_name != "" if !attachments.empty? && attachments[:files] && tag_name != ""
attachments[:files].each do |attachment| attachments[:files].each do |attachment|
attachment.tag_list.add(tag_name) attachment.tag_list.add(tag_name)
attachment.description = params[:description]
attachment.save attachment.save
end end
end end
@ -904,5 +915,10 @@ class FilesController < ApplicationController
def upload_files_menu def upload_files_menu
end end
def update_file_description
@attachment = Attachment.find(params[:id])
@attachment.description = params[:description]
@attachment.save
end
end end

@ -14,21 +14,23 @@ class HomeworkCommonController < ApplicationController
#unless params[:page] #unless params[:page]
# update_homework_time(@course.homework_commons) # update_homework_time(@course.homework_commons)
#end #end
search = "%#{params[:search].to_s.strip.downcase}%"
@new_homework = HomeworkCommon.new @new_homework = HomeworkCommon.new
@new_homework.homework_detail_manual = HomeworkDetailManual.new @new_homework.homework_detail_manual = HomeworkDetailManual.new
@new_homework.course = @course @new_homework.course = @course
@page = params[:page] ? params[:page].to_i + 1 : 0 @page = params[:page] ? params[:page].to_i + 1 : 0
@is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@course)) @is_teacher = User.current.logged? && (User.current.admin? || User.current.allowed_to?(:as_teacher,@course))
if @is_teacher if @is_teacher
@homeworks = @course.homework_commons.order("updated_at desc").limit(10).offset(@page * 10) #@homeworks = @course.homework_commons.order("created_at desc").limit(10).offset(@page * 10)
@homework_commons = @course.homework_commons.order("created_at desc") @homework_commons = @course.homework_commons.where("name like '%#{search}%'").order("created_at desc")
else else
@homeworks = @course.homework_commons.where("publish_time <= '#{Date.today}'").order("updated_at desc").limit(10).offset(@page * 10) #@homeworks = @course.homework_commons.where("publish_time <= '#{Date.today}'").order("created_at desc").limit(10).offset(@page * 10)
@homework_commons = @course.homework_commons.where("publish_time <= '#{Date.today}'").order("created_at desc") @homework_commons = @course.homework_commons.where("name like '%#{search}%' and publish_time <= '#{Date.today}'").order("created_at desc")
end end
@is_student = User.current.logged? && (User.current.admin? || (User.current.member_of_course?(@course) && !@is_teacher)) @is_student = User.current.logged? && (User.current.admin? || (User.current.member_of_course?(@course) && !@is_teacher))
@is_new = params[:is_new] @is_new = params[:is_new]
@homeworks = paginateHelper @homework_commons,10
#设置at已读 #设置at已读
@homeworks.each do |homework| @homeworks.each do |homework|
homework.journals_for_messages.each do |j| homework.journals_for_messages.each do |j|
@ -291,9 +293,9 @@ class HomeworkCommonController < ApplicationController
def open_student_works def open_student_works
if @homework.is_open == 0 if @homework.is_open == 0
@homework.update_attribute(:is_open, 1) @homework.update_column('is_open', 1)
else else
@homework.update_attribute(:is_open, 0) @homework.update_column('is_open', 0)
end end
@user_activity_id = params[:user_activity_id] @user_activity_id = params[:user_activity_id]
@is_in_course = params[:is_in_course] if params[:is_in_course] @is_in_course = params[:is_in_course] if params[:is_in_course]
@ -440,7 +442,7 @@ class HomeworkCommonController < ApplicationController
puts time puts time
s_time = time s_time = time
if format_time(time) > format_time(h.updated_at) if format_time(time) > format_time(h.updated_at)
h.update_attribute(:updated_at, s_time) h.update_column('updated_at', s_time)
end end
end end
end end

@ -44,7 +44,8 @@ class MessagesController < ApplicationController
offset = @topic.children.count(:conditions => ["#{Message.table_name}.id < ?", params[:r].to_i]) offset = @topic.children.count(:conditions => ["#{Message.table_name}.id < ?", params[:r].to_i])
page = 1 + offset / REPLIES_PER_PAGE page = 1 + offset / REPLIES_PER_PAGE
end end
@reply_count = @topic.children.count all_comments = []
@reply_count = get_all_children(all_comments, @topic).count
@reply = Message.new(:subject => "RE: #{@message.subject}") @reply = Message.new(:subject => "RE: #{@message.subject}")
if @course if @course
messages_replies = @topic.children. messages_replies = @topic.children.
@ -137,26 +138,32 @@ class MessagesController < ApplicationController
# Reply to a topic # Reply to a topic
def reply def reply
if params[:reply][:content] == "" if params[:parent_id]
if params[:is_board] parent = Message.find params[:parent_id]
if @project @reply = Message.new
(redirect_to project_boards_path(@project), :notice => l(:label_reply_empty);return) @reply.author = User.current
elsif @course @reply.board = parent.board
(redirect_to course_boards_path(@course), :notice => l(:label_reply_empty);return) @reply.content = params[:content]
end @reply.subject = "RE: #{parent.subject}"
else @reply.reply_id = params[:reply_id]
(redirect_to board_message_url(@board, @topic, :r => @reply), :notice => l(:label_reply_empty);return) # @reply.reply_id = params[:id]
end parent.children << @reply
@topic = params[:activity_id].nil? ? parent : Message.find(params[:activity_id].to_i)
@user_activity_id = params[:user_activity_id] if params[:user_activity_id]
@is_course = params[:is_course] if params[:is_course]
@is_board = params[:is_board] if params[:is_board]
else
@quote = params[:quote][:quote]
@reply = Message.new
@reply.author = User.current
@reply.board = @board
@reply.safe_attributes = params[:reply]
@reply.content = @quote + @reply.content
@reply.subject = "RE: #{@topic.subject}" unless params[:reply][:subject]
@topic.children << @reply
# @reply.reply_id = params[:id]
end end
@quote = params[:quote][:quote]
@reply = Message.new
@reply.author = User.current
@reply.board = @board
@reply.safe_attributes = params[:reply]
@reply.content = @quote + @reply.content
@reply.subject = "RE: #{@topic.subject}" unless params[:reply][:subject]
# @reply.reply_id = params[:id]
@topic.children << @reply
update_course_activity(@topic.class,@topic.id) update_course_activity(@topic.class,@topic.id)
update_user_activity(@topic.class,@topic.id) update_user_activity(@topic.class,@topic.id)
update_forge_activity(@topic.class,@topic.id) update_forge_activity(@topic.class,@topic.id)
@ -182,14 +189,10 @@ class MessagesController < ApplicationController
respond_to do |format| respond_to do |format|
format.js format.js
end end
elsif params[:is_board] return
if @project
redirect_to project_boards_path(@project)
elsif @course
redirect_to course_boards_path(@course)
end
else else
redirect_to board_message_url(@board, @topic, :r => @reply) redirect_to board_message_url(@board, @topic)
return
end end
end end
@ -251,6 +254,17 @@ class MessagesController < ApplicationController
# Delete a messages # Delete a messages
def destroy def destroy
if params[:user_activity_id]
@message.destroy
@topic = Message.find(params[:activity_id].to_i)
@user_activity_id = params[:user_activity_id]
@is_course = params[:is_course]
@is_board = params[:is_board]
respond_to do |format|
format.js
end
return
end
if @project if @project
(render_403; return false) unless @message.destroyable_by?(User.current) (render_403; return false) unless @message.destroyable_by?(User.current)
elsif @course elsif @course
@ -299,12 +313,12 @@ class MessagesController < ApplicationController
end end
def quote def quote
@subject = @message.subject # @subject = @message.subject
@subject = "RE: #{@subject}" unless @subject.starts_with?('RE:') # @subject = "RE: #{@subject}" unless @subject.starts_with?('RE:')
#
@content = "> #{ll(Setting.default_language, :text_user_wrote, @message.author)}\n> " # @content = "> #{ll(Setting.default_language, :text_user_wrote, @message.author)}\n> "
@temp = Message.new # @temp = Message.new
@temp.content = "<blockquote>#{ll(Setting.default_language, :text_user_wrote, @message.author)} <br/>#{@message.content.html_safe}</blockquote>".html_safe # @temp.content = "<blockquote>#{ll(Setting.default_language, :text_user_wrote, @message.author.show_name)} <br/>#{@message.content.html_safe}</blockquote>".html_safe
end end
def preview def preview

@ -127,12 +127,14 @@ class MyController < ApplicationController
end end
@user.safe_attributes = params[:user] @user.safe_attributes = params[:user]
@user.lastname = params[:lastname]
@user.firstname = ""
@user.pref.attributes = params[:pref] @user.pref.attributes = params[:pref]
@user.pref[:no_self_notified] = (params[:no_self_notified] == '1') @user.pref[:no_self_notified] = (params[:no_self_notified] == '1')
#@user.login = params[:login] #@user.login = params[:login]
unless @user.user_extensions.nil? unless @user.user_extensions.nil?
if @user.user_extensions.identity == 2 if @user.user_extensions.identity == 2
@user.firstname = params[:enterprise_name] # @user.firstname = params[:enterprise_name]
end end
end end
@ -144,7 +146,7 @@ class MyController < ApplicationController
# end # end
@se.school_id = params[:occupation] @se.school_id = params[:occupation]
@se.gender = params[:gender] @se.gender = params[:sex]
@se.location = params[:province] if params[:province] @se.location = params[:province] if params[:province]
@se.location_city = params[:city] if params[:city] @se.location_city = params[:city] if params[:city]
@se.identity = params[:identity].to_i if params[:identity] @se.identity = params[:identity].to_i if params[:identity]

@ -1,5 +1,6 @@
class OrgDocumentCommentsController < ApplicationController class OrgDocumentCommentsController < ApplicationController
before_filter :find_organization, :only => [:new, :create, :show, :index] before_filter :find_organization, :only => [:new, :create, :show, :index]
before_filter :authorize_allowed, :only => [:create, :add_reply]
helper :attachments,:organizations helper :attachments,:organizations
layout 'base_org' layout 'base_org'
@ -12,6 +13,7 @@ class OrgDocumentCommentsController < ApplicationController
@org_document_comment = OrgDocumentComment.new(:organization_id => @organization.id, :creator_id => User.current.id) @org_document_comment = OrgDocumentComment.new(:organization_id => @organization.id, :creator_id => User.current.id)
@org_document_comment.title = params[:org_document_comment][:title] @org_document_comment.title = params[:org_document_comment][:title]
@org_document_comment.content = params[:org_document_comment][:content] @org_document_comment.content = params[:org_document_comment][:content]
@org_document_comment.status = params[:org_document_comment][:status] == "on" ? 1 : 0
@org_document_comment.save_attachments(params[:attachments]) @org_document_comment.save_attachments(params[:attachments])
if params[:field_id] if params[:field_id]
@org_document_comment.org_subfield_id = params[:field_id].to_i @org_document_comment.org_subfield_id = params[:field_id].to_i
@ -36,6 +38,11 @@ class OrgDocumentCommentsController < ApplicationController
def show def show
@document = OrgDocumentComment.find(params[:id]) @document = OrgDocumentComment.find(params[:id])
@org_subfield = OrgSubfield.where(:id => @document.org_subfield_id).first
@subfield_content = @organization.org_subfields.order("priority")
respond_to do |format|
format.html {render :layout => (@organization.switch_type && @document && !@document.org_subfield_id.blank?) ? 'base_org_custom' : 'base_org'}
end
end end
def index def index
@ -89,7 +96,12 @@ class OrgDocumentCommentsController < ApplicationController
def add_reply_in_doc def add_reply_in_doc
@document = OrgDocumentComment.find(params[:id]).root @document = OrgDocumentComment.find(params[:id]).root
@comment = OrgDocumentComment.new(:organization_id => @document.organization_id, :creator_id => User.current.id, :reply_id => params[:id]) @comment = OrgDocumentComment.new(:organization_id => @document.organization_id, :creator_id => User.current.id, :reply_id => params[:id])
@comment.content = params[:org_comment][:org_content] if params[:org_comment].blank?
@comment.content = params[:org_content]
else
@comment.content = params[:org_comment][:org_content]
end
@document.children << @comment @document.children << @comment
@document.save @document.save
respond_to do |format| respond_to do |format|
@ -101,8 +113,16 @@ class OrgDocumentCommentsController < ApplicationController
@organization = Organization.find(params[:organization_id]) @organization = Organization.find(params[:organization_id])
end end
def authorize_allowed
unless User.current.logged?
redirect_to signin_url
return
end
end
def destroy def destroy
@org_document_comment = OrgDocumentComment.find(params[:id]) @org_document_comment = OrgDocumentComment.find(params[:id])
@org_sub_id = @org_document_comment.org_subfield_id
org = @org_document_comment.organization org = @org_document_comment.organization
if @org_document_comment.id == org.home_id if @org_document_comment.id == org.home_id
org.update_attributes(:home_id => nil) org.update_attributes(:home_id => nil)

@ -54,4 +54,8 @@ class OrgMemberController < ApplicationController
def index def index
end end
def deleteOrgMember
destroy
end
end end

@ -6,26 +6,41 @@ class OrgSubfieldsController < ApplicationController
if OrgSubfield.where("organization_id=#{params[:organization_id]} and name=?",params[:name]).count == 0 if OrgSubfield.where("organization_id=#{params[:organization_id]} and name=?",params[:name]).count == 0
@res = true @res = true
@organization = Organization.find(params[:organization_id]) @organization = Organization.find(params[:organization_id])
@subfield = OrgSubfield.create(:name => params[:name], :organization_id => params[:organization_id],:priority => @organization.org_subfields.order("priority").last.priority + 1) @subfield = OrgSubfield.create(:name => params[:name], :organization_id => params[:organization_id], :priority => @organization.org_subfields.order("priority").last.priority + 1)
if !params[:sub_dir].blank? if !params[:sub_dir].blank?
sql = "select subfield_subdomain_dirs.* from subfield_subdomain_dirs, org_subfields where subfield_subdomain_dirs.org_subfield_id = org_subfields.id "+ sql = "select subfield_subdomain_dirs.* from subfield_subdomain_dirs, org_subfields where subfield_subdomain_dirs.org_subfield_id = org_subfields.id "+
"and org_subfields.organization_id=#{@organization.id} and subfield_subdomain_dirs.name='#{params[:sub_dir]}'" "and org_subfields.organization_id=#{@organization.id} and subfield_subdomain_dirs.name='#{params[:sub_dir]}'"
if SubfieldSubdomainDir.find_by_sql(sql).count == 0 if SubfieldSubdomainDir.find_by_sql(sql).count == 0
SubfieldSubdomainDir.create(:org_subfield_id => @subfield.id, :name => params[:sub_dir].downcase) SubfieldSubdomainDir.create(:org_subfield_id => @subfield.id, :name => params[:sub_dir].downcase)
end end
end end
@subfield.update_attributes(:field_type => params[:field_type]) #默认类型为帖子
# 如果栏目是教师,不参入类型的配置,定义为右三模式 @subfield.update_attributes(:field_type => params[:field_type]||"Post")
# 新增模块命名规则左边1开头右边2开头以前的不变 # admin配置的类型
# eg23 右三 update_status_by_type(@subfield, params[:field_type]||"Post")
if params[:field_type] == "Comptec"
@subfield.update_attributes(:status => 23)
end
else else
@res = false @res = false
end end
end end
# status类型说明详见SubField
def update_status_by_type subfield, type
case type
when "Resource"
subfield.update_attribute(:status, 6)
when "Comptec"
subfield.update_attribute(:status, 6)
when "Compstu"
subfield.update_attribute(:status, 7)
when "Comppro"
subfield.update_attribute(:status, 5)
when "Compcou"
subfield.update_attribute(:status, 2)
when "Compact"
subfield.update_attribute(:status, 4)
end
end
def show def show
@flag = params[:flag] || false @flag = params[:flag] || false
sort = "" sort = ""
@ -42,6 +57,10 @@ class OrgSubfieldsController < ApplicationController
@org_subfield = OrgSubfield.find_by_sql("select distinct org_subfields.* from org_subfields,"+ @org_subfield = OrgSubfield.find_by_sql("select distinct org_subfields.* from org_subfields,"+
"subfield_subdomain_dirs where org_subfields.id = subfield_subdomain_dirs.org_subfield_id and "+ "subfield_subdomain_dirs where org_subfields.id = subfield_subdomain_dirs.org_subfield_id and "+
" org_subfields.organization_id=#{@organization.id} and subfield_subdomain_dirs.name='#{params[:sub_dir_name]}'").first " org_subfields.organization_id=#{@organization.id} and subfield_subdomain_dirs.name='#{params[:sub_dir_name]}'").first
if @org_subfield.nil?
render_404
return
end
if @org_subfield.field_type == 'Post' if @org_subfield.field_type == 'Post'
@org_subfield_ids = @org_subfield.org_document_comments.map(&:id) << 0 @org_subfield_ids = @org_subfield.org_document_comments.map(&:id) << 0
@org_activities = OrgActivity.where("(org_act_type='OrgDocumentComment'and org_act_id in (#{@org_subfield_ids.join(",")})) || (container_type='OrgSubfield' and container_id=#{@org_subfield.id})").order('updated_at desc').page(params[:page] || 1).per(10) @org_activities = OrgActivity.where("(org_act_type='OrgDocumentComment'and org_act_id in (#{@org_subfield_ids.join(",")})) || (container_type='OrgSubfield' and container_id=#{@org_subfield.id})").order('updated_at desc').page(params[:page] || 1).per(10)

@ -28,7 +28,9 @@ class OrganizationsController < ApplicationController
helper :project_score helper :project_score
helper :issues helper :issues
include UsersHelper include UsersHelper
before_filter :find_organization, :only => [:show, :members, :apply_subdomain, :select_org_layout, :teachers] include OrganizationsHelper
before_filter :find_organization, :only => [:show, :members, :apply_subdomain, :select_org_layout, :teachers, :students, :projects, :courses, :acts]
# before_filter :allow_as_admin, :only => [:students, :teachers, :projects, :courses, :acts]
layout 'base_org' layout 'base_org'
def index def index
@ -76,22 +78,38 @@ class OrganizationsController < ApplicationController
def show def show
# 组织新类型 show_mode判断标准 1为新类型0为旧 # 组织新类型 show_mode判断标准 1为新类型0为旧
if @organization.show_mode.to_i == 1 && params[:org_subfield_id].nil? && params[:list] .nil? if @organization.switch_type && params[:list] .nil?
if @organization.is_public? || User.current.admin? || User.current.member_of_org?(@organization) if @organization.is_public? || User.current.admin? || User.current.member_of_org?(@organization)
# REDO:时间紧,暂时先这样 unless params[:org_subfield_id].nil?
@org_logo_attchment = Attachment.find_by_sql("SELECT * from attachments WHERE container_id = #{@organization.id} and container_type = 'Organization' and attachtype = 0 and filename REGEXP '(.jpg|.png|.bmp|.gif|.jpeg)' ORDER BY created_on desc limit 1").first @org_subfield = OrgSubfield.where(:id => params[:org_subfield_id]).first
@org_banner_attchment = Attachment.find_by_sql("SELECT * from attachments WHERE container_id = #{@organization.id} and container_type = 'Organization' and attachtype = 1 and filename REGEXP '(.jpg|.png|.bmp|.gif|.jpeg)' ORDER BY created_on desc limit 1").first @subfield_acts = get_subfield_acts(@org_subfield)
end
@subfield_content = @organization.org_subfields.order("priority") @subfield_content = @organization.org_subfields.order("priority")
@organization = Organization.find(params[:id]) shield_project_ids = ShieldActivity.where("container_type='Organization' and container_id=#{@organization.id} and shield_type='Project'").map(&:shield_id)
shield_project_ids = ShieldActivity.where("container_type='Organization' and container_id=#{@organization.id} and shield_type='Project'").map(&:shield_id) shield_course_ids = ShieldActivity.where("container_type='Organization' and container_id=#{@organization.id} and shield_type='Course'").map(&:shield_id)
shield_course_ids = ShieldActivity.where("container_type='Organization' and container_id=#{@organization.id} and shield_type='Course'").map(&:shield_id) project_ids = (@organization.projects.map(&:id) - shield_project_ids) << 0
project_ids = (@organization.projects.map(&:id)-shield_project_ids) << 0 course_ids = (@organization.courses.map(&:id) - shield_course_ids) << 0
course_ids = (@organization.courses.map(&:id)-shield_course_ids) << 0 course_types = "('Message','News','HomeworkCommon','Poll','Course')"
course_types = "('Message','News','HomeworkCommon','Poll','Course')" @project_acts = get_project_activities_org @organization, project_ids
@project_acts = get_project_activities_org @organization, project_ids @course_acts = get_course_activities_org @organization, course_ids
@course_acts = get_course_activities_org @organization, course_ids # 精品课程, 不符合条件的组织则不查询
render :layout => 'base_org2' if @organization.org_subfields.where(:field_type => "Compcou", :hide => 0).count > 0
@excellent_courses = Course.find_by_sql("select c.*, (select count(*) from course_activities where course_activities.course_id = c.id) as course_count
from courses c where c.is_delete =0 and c.is_public =1 and is_excellent =1 order by course_count desc limit 5;")
end
# 热门项目
if @organization.org_subfields.where(:field_type => "Comppro", :hide => 0).count > 0
# @excellent_projects = Project.where(:is_public => true, :status => true, :hot => true).order("project_score")
@excellent_projects = Project.find_by_sql("select p.*, (select count(*) from forge_activities where forge_activities.project_id = p.id) as project_count
from projects p where p.status =1 and p.is_public =1 and hot =1 order by project_count desc limit 5;")
end
# 最新动态, 来自我关联的项目和课程
if @organization.org_subfields.where(:field_type => "Compact", :hide => 0).count > 0
@acts = UserActivity.find_by_sql("SELECT * FROM `user_activities` where act_type in ('HomeworkCommon', 'News', 'Message', 'Issue') and
((container_type = 'Course' and container_id in (#{course_ids.join(',')})) or (container_type = 'Project' and container_id in (#{project_ids.join(',')})))
order by created_at desc limit 6;")
end
render :layout => 'base_org_custom'
else else
render_403 render_403
end end
@ -127,7 +145,7 @@ class OrganizationsController < ApplicationController
case params[:type] case params[:type]
when nil when nil
@org_activities = OrgActivity.where("(container_id =? and container_type =?) " + @org_activities = OrgActivity.where("(container_id =? and container_type =?) " +
"or (container_type ='Project' and org_act_type in ('Issue','Message','ProjectCreateInfo') and container_id in (#{project_ids.join(',')})) "+ "or (container_type ='Project' and org_act_type in ('Issue','Message','Project') and container_id in (#{project_ids.join(',')})) "+
"or (container_type ='Course' and org_act_type in #{course_types} and container_id in (#{course_ids.join(',')}))", "or (container_type ='Course' and org_act_type in #{course_types} and container_id in (#{course_ids.join(',')}))",
@organization.id, 'Organization').order('updated_at desc').page(params[:page] || 1).per(10) @organization.id, 'Organization').order('updated_at desc').page(params[:page] || 1).per(10)
when 'project_issue' when 'project_issue'
@ -159,22 +177,12 @@ class OrganizationsController < ApplicationController
end end
def teachers def teachers
unless @organization.allow_set_teachers
render_403
return
end
q = params[:search].nil? ? "" : "#{params[:search].strip}" q = params[:search].nil? ? "" : "#{params[:search].strip}"
@field = OrgSubfield.find(params[:org_subfield_id]) @field = params[:org_subfield_id].nil? ? OrgSubfield.where("organization_id =? and field_type =?", params[:id].to_i, "Comptec").first : OrgSubfield.find(params[:org_subfield_id])
@type = params[:type] @type = params[:type]
if @type == "courses" || @type.nil? if @type.blank?
@org_teachers = User.find_by_sql("select u.*, ue.technical_title, ue.school_id,(select count(*) from courses where courses.tea_id = u.id) as course_count
from users u, user_extensions ue where u.id = ue.user_id and ue.identity=0 and concat(lastname,firstname,login) like '%#{q}%' order by course_count desc")
elsif @type == "students"
@org_teachers = User.find_by_sql("select u.*, ue.technical_title, ue.school_id,(select count(*) from courses where courses.tea_id = u.id) as course_count @org_teachers = User.find_by_sql("select u.*, ue.technical_title, ue.school_id,(select count(*) from courses where courses.tea_id = u.id) as course_count
from users u, user_extensions ue where u.id = ue.user_id and ue.identity=0 and concat(lastname,firstname,login) like '%#{q}%' order by course_count desc") from users u, user_extensions ue where u.id = ue.user_id and ue.identity=0 and concat(lastname,firstname,login) like '%#{q}%' order by course_count desc")
elsif @type == "resources"
@org_teachers = User.find_by_sql("select u.*, ue.technical_title, ue.school_id,(select count(*) from attachments where attachments.author_id = u.id) as course_count
from users u, user_extensions ue where u.id = ue.user_id and ue.identity=0 and concat(lastname,firstname,login) like '%#{q}%' order by course_count desc")
elsif @type == "famous" elsif @type == "famous"
@org_teachers = User.find_by_sql("select u.*, ue.technical_title, ue.school_id,(select count(*) from courses where courses.tea_id = u.id) as course_count @org_teachers = User.find_by_sql("select u.*, ue.technical_title, ue.school_id,(select count(*) from courses where courses.tea_id = u.id) as course_count
from users u, user_extensions ue where u.id = ue.user_id and ue.identity=0 and u.excellent_teacher =1 and concat(lastname,firstname,login) like '%#{q}%' order by course_count desc") from users u, user_extensions ue where u.id = ue.user_id and ue.identity=0 and u.excellent_teacher =1 and concat(lastname,firstname,login) like '%#{q}%' order by course_count desc")
@ -192,6 +200,86 @@ class OrganizationsController < ApplicationController
end end
end end
def students
q = params[:search].nil? ? "" : "#{params[:search].strip}"
@field = params[:org_subfield_id].nil? ? OrgSubfield.where("organization_id =? and field_type =?", params[:id].to_i, "Compstu").first : OrgSubfield.find(params[:org_subfield_id])
@type = params[:type]
if @type.blank?
@org_students = User.find_by_sql("select u.*, ue.student_id, ue.school_id,(select count(*) from courses where courses.tea_id = u.id) as course_count
from users u, user_extensions ue where u.id = ue.user_id and ue.identity= 1 and concat(lastname,firstname,login) like '%#{q}%' order by course_count desc")
elsif @type == "famous"
@org_students = User.find_by_sql("select u.*, ue.student_id, ue.school_id,(select count(*) from courses where courses.tea_id = u.id) as course_count
from users u, user_extensions ue where u.id = ue.user_id and ue.identity= 1 and u.excellent_student =1 and concat(lastname,firstname,login) like '%#{q}%' order by course_count desc")
end
limit = 10
# @is_remote = true
@students_count = @org_students.count
@atta_pages = Paginator.new @students_count, limit, params['page'] || 1
@offset ||= @atta_pages.offset
#@curse_attachments_all = @all_attachments[@offset, @limit]
@org_students = paginateHelper @org_students, limit
respond_to do |format|
format.html
format.js
end
end
def atta_page_public container
limit = 10
@containers_count = container.count
@atta_pages = Paginator.new @containers_count, limit, params['page'] || 1
@offset ||= @atta_pages.offset
@containers = paginateHelper container, limit
respond_to do |format|
format.html
format.js
end
end
def projects
q = params[:search].nil? ? "" : "#{params[:search].strip}"
@field = params[:org_subfield_id].nil? ? OrgSubfield.where("organization_id =? and field_type =?", params[:id].to_i, "Comppro").first : OrgSubfield.find(params[:org_subfield_id])
@type = params[:type]
if @type.blank?
@containers = Project.find_by_sql("select p.*, (select count(*) from forge_activities where forge_activities.project_id = p.id) as project_count
from projects p where p.status =1 and p.is_public =1 and name like '%#{q}%' order by project_count desc;")
elsif @type == "famous"
@containers = Project.find_by_sql("select p.*, (select count(*) from forge_activities where forge_activities.project_id = p.id) as project_count
from projects p where p.status =1 and p.is_public =1 and hot =1 and name like '%#{q}%' order by project_count desc;")
end
atta_page_public @containers
end
def courses
q = params[:search].nil? ? "" : "#{params[:search].strip}"
@field = params[:org_subfield_id].nil? ? OrgSubfield.where("organization_id =? and field_type =?", params[:id].to_i, "Compstu").first : OrgSubfield.find(params[:org_subfield_id])
@type = params[:type]
if @type.blank?
@containers = Course.find_by_sql("select c.*, (select count(*) from course_activities where course_activities.course_id = c.id) as course_count
from courses c where c.is_delete =0 and c.is_public =1 and name like '%#{q}%' order by course_count desc;")
elsif @type == "famous"
@containers = Course.find_by_sql("select c.*, (select count(*) from course_activities where course_activities.course_id = c.id) as course_count
from courses c where c.is_delete =0 and c.is_public =1 and is_excellent = 1 and name like '%#{q}%' order by course_count desc;")
end
atta_page_public @containers
end
def acts
@subfield_content = @organization.org_subfields.order("priority")
@org_subfield = OrgSubfield.where(:id => params[:org_subfield_id]).first
shield_project_ids = ShieldActivity.where("container_type='Organization' and container_id=#{@organization.id} and shield_type='Project'").map(&:shield_id)
shield_course_ids = ShieldActivity.where("container_type='Organization' and container_id=#{@organization.id} and shield_type='Course'").map(&:shield_id)
project_ids = (@organization.projects.map(&:id) - shield_project_ids) << 0
course_ids = (@organization.courses.map(&:id) - shield_course_ids) << 0
@org_acts = UserActivity.find_by_sql("SELECT * FROM `user_activities` where act_type in ('HomeworkCommon', 'News', 'Message', 'Issue') and
((container_type = 'Course' and container_id in (#{course_ids.join(',')})) or (container_type = 'Project' and container_id in (#{project_ids.join(',')})))
order by created_at desc limit 6;")
respond_to do |format|
format.html{render :layout => 'base_org_custom'}
format.js
end
end
def searchmember_by_name members, name def searchmember_by_name members, name
#searchPeopleByRoles(project, StudentRoles) #searchPeopleByRoles(project, StudentRoles)
mems = [] mems = []
@ -322,6 +410,13 @@ class OrganizationsController < ApplicationController
@organization = Organization.find(params[:id]) @organization = Organization.find(params[:id])
end end
def allow_as_admin
unless User.current.admin?
render_403
return
end
end
def setting def setting
@organization = Organization.find(params[:id]) @organization = Organization.find(params[:id])
@ -471,6 +566,18 @@ class OrganizationsController < ApplicationController
end end
end end
def update_field_by_admin
@type = params[:type]
@status = params[:status]
if @type == "project"
@container = Project.find(params[:container])
@status == "reset" ? @container.update_column(:hot, 0) : @container.update_column(:hot, 1)
else
@container = Course.find(params[:container])
@status == "reset" ? @container.update_column(:is_excellent, 0) : @container.update_column(:is_excellent, 1)
end
end
# 设置为名师 # 设置为名师
def set_excellent_teacher def set_excellent_teacher
@ex_teacher = User.find(params[:user]) @ex_teacher = User.find(params[:user])
@ -483,6 +590,16 @@ class OrganizationsController < ApplicationController
@ex_teacher.update_column(:excellent_teacher, 0) @ex_teacher.update_column(:excellent_teacher, 0)
end end
def set_excellent_student
@ex_student = User.find(params[:user])
@ex_student.update_column(:excellent_student, 1)
end
def reset_excellent_student
@ex_student = User.find(params[:user])
@ex_student.update_column(:excellent_student, 0)
end
def hide_org_subfield def hide_org_subfield
@org_subfield = OrgSubfield.find(params[:org_subfield_id]) @org_subfield = OrgSubfield.find(params[:org_subfield_id])
@org_subfield.update_attribute(:hide, 1) @org_subfield.update_attribute(:hide, 1)

@ -423,9 +423,13 @@ class PollController < ApplicationController
# 将其他地方的问卷导出来 # 将其他地方的问卷导出来
def other_poll def other_poll
# 查作者是我,或者作者是当前课程的老师,且不在当前课程内的问卷 进行导入 # 查作者是我,或者作者是当前课程的老师,且不在当前课程内的问卷 进行导入
tea_ids = '(' courses = User.current.courses.select { |course| User.current.allowed_to?(:as_teacher,course)}
tea_ids << Course.find(params[:polls_group_id]).tea_id.to_s << ','<< User.current.id.to_s << ')' course_ids = courses.empty? ? "(-1)" : "(" + courses.map { |course| course.id}.join(',') + ")"
@polls = Poll.where("user_id in #{tea_ids} and polls_type = 'course' and polls_group_id != #{params[:polls_group_id]}") none_courses = User.current.courses.where("is_delete = 1 or #{Course.table_name}.id = #{params[:polls_group_id].to_i}")
none_course_ids = none_courses.empty? ? "(-1)" : "(" + none_courses.map { |course| course.id}.join(',') + ")"
#tea_ids = '('
#tea_ids << Course.find(params[:polls_group_id]).tea_id.to_s << ','<< User.current.id.to_s << ')'
@polls = Poll.where("(user_id = #{User.current.id} or polls_group_id in #{course_ids}) and polls_type = 'course' and polls_group_id not in #{none_course_ids}")
@polls_group_id = params[:polls_group_id] @polls_group_id = params[:polls_group_id]
respond_to do |format| respond_to do |format|
format.js format.js

@ -1,12 +1,12 @@
class PraiseTreadController < ApplicationController class PraiseTreadController < ApplicationController
accept_api_auth :tread_plus,:praise_plus accept_api_auth :tread_plus,:praise_plus
before_filter :require_login,:only => [:praise_plus,:tread_plus] # before_filter :require_login,:only => [:praise_plus,:tread_plus]
before_filter :user_unlogged_check,:only => [:praise_plus,:tread_plus,:praise_minus]
def praise_plus def praise_plus
@obj = nil @obj = nil
@activity = false @activity = false
if request.get? if request.get?
@obj_id = params[:obj_id] @obj_id = params[:obj_id]
@obj_type = params[:obj_type] @obj_type = params[:obj_type]
@ -25,14 +25,14 @@ class PraiseTreadController < ApplicationController
return return
end end
@horizontal = params[:horizontal].downcase == "false" ? false:true if params[:horizontal] @horizontal = params[:horizontal].downcase == "false" ? false:true if params[:horizontal]
if @obj.respond_to?("author_id") # if @obj.respond_to?("author_id")
author_id = @obj.author_id # author_id = @obj.author_id
elsif @obj.respond_to?("user_id") # elsif @obj.respond_to?("user_id")
author_id = @obj.user_id # author_id = @obj.user_id
end # end
unless author_id == User.current.id # unless author_id == User.current.id
praise_tread_plus(@obj_type,@obj_id,1) praise_tread_plus(@obj_type,@obj_id,1)
end # end
respond_to do |format| respond_to do |format|
format.js format.js
end end
@ -131,6 +131,8 @@ class PraiseTreadController < ApplicationController
@obj = Bid.find_by_id(id) @obj = Bid.find_by_id(id)
when 'Contest' when 'Contest'
@obj = Contest.find_by_id(id) @obj = Contest.find_by_id(id)
when 'Syllabus'
@obj = Syllabus.find_by_id(id)
else else
@obj = nil @obj = nil
end end

@ -100,8 +100,8 @@ class ProjectsController < ApplicationController
render_404 render_404
end end
def course def courserender_404
render_404
end end
# Time 2015-01-29 11:19:11 # Time 2015-01-29 11:19:11
@ -299,6 +299,8 @@ class ProjectsController < ApplicationController
if params[:jump] && redirect_to_project_menu_item(@project, params[:jump]) if params[:jump] && redirect_to_project_menu_item(@project, params[:jump])
return return
end end
logger.debug "111111111"*100
# over # over
@author = params[:user_id].blank? ? nil : User.active.find(params[:user_id]) @author = params[:user_id].blank? ? nil : User.active.find(params[:user_id])
@page = params[:page] ? params[:page].to_i + 1 : 0 @page = params[:page] ? params[:page].to_i + 1 : 0
@ -319,6 +321,7 @@ class ProjectsController < ApplicationController
else else
@events_pages = ForgeActivity.includes(:project).where("forge_activities.project_id = ? and projects.is_public = ? and forge_act_type != ? ",@project,1, "Document").order("created_at desc").page(params['page'|| 1]).per(10); @events_pages = ForgeActivity.includes(:project).where("forge_activities.project_id = ? and projects.is_public = ? and forge_act_type != ? ",@project,1, "Document").order("created_at desc").page(params['page'|| 1]).per(10);
end end
logger.debug "2"*100
# g = Gitlab.client # g = Gitlab.client
unless @project.gpid.nil? || @project.project_score.changeset_num == 0 unless @project.gpid.nil? || @project.project_score.changeset_num == 0
# rep_statics_commit = @project.rep_statics.order("commits_num desc") # rep_statics_commit = @project.rep_statics.order("commits_num desc")
@ -332,12 +335,20 @@ class ProjectsController < ApplicationController
@a_commits_del = rep_statics_code.map {|s| s.del.to_i } @a_commits_del = rep_statics_code.map {|s| s.del.to_i }
@a_commits_changeset = rep_statics_code.map {|s| s.changeset.to_i } @a_commits_changeset = rep_statics_code.map {|s| s.changeset.to_i }
g = Gitlab.client g = Gitlab.client
logger.debug "3"*100
begin begin
g_branch = g.project(@project.gpid).default_branch.to_s gid = @project.gpid
rescue logger.debug "31"*100
logger.error("get gitlab project failed!") g_branch = g.project(gid)
logger.debug "4"*100
g_branch = g_branch.default_branch.to_s
logger.debug "5"*100
rescue =>e
logger.error("get gitlab project failed: " + e)
end end
logger.debug "6"*100
@rev = g_branch.nil? ? "master" : g_branch @rev = g_branch.nil? ? "master" : g_branch
logger.debug "7"*100
end end
# 根据对应的请求,返回对应的数据 # 根据对应的请求,返回对应的数据
respond_to do |format| respond_to do |format|
@ -393,7 +404,7 @@ class ProjectsController < ApplicationController
unless @project.gpid.nil? unless @project.gpid.nil?
g = Gitlab.client g = Gitlab.client
@gitlab_branches = g.branches(@project.gpid) @gitlab_branches = g.branches(@project.gpid)
@branch_names = g.branches(@project.gpid).map{|b| b.name} @branch_names = @gitlab_branches.map{|b| b.name}
@gitlab_default_branch = g.project(@project.gpid).default_branch @gitlab_default_branch = g.project(@project.gpid).default_branch
end end
end end
@ -642,12 +653,12 @@ class ProjectsController < ApplicationController
def update def update
@project.safe_attributes = params[:project] @project.safe_attributes = params[:project]
@project.organization_id = params[:organization_id] @project.organization_id = params[:organization_id]
params[:project][:is_public] ? @project.is_public = 1 : @project.is_public = 0 params[:project][:is_public] == "on" ? @project.is_public = 1 : @project.is_public = 0
params[:project][:hidden_repo] ? @project.hidden_repo = 1 : @project.hidden_repo = 0 params[:project][:hidden_repo] == "on" ? @project.hidden_repo = 1 : @project.hidden_repo = 0
# 更新公开私有时同步gitlab公开私有 # 更新公开私有时同步gitlab公开私有
unless @project.gpid.nil? if !@project.gpid.nil? && @project.is_public != (params[:project][:is_public] == "on" ? 1 : 0)
g = Gitlab.client g = Gitlab.client
params[:project][:is_public] ? g.edit_project(@project.gpid, 20, params[:branch]) : g.edit_project(@project.gpid, 0, params[:branch]) params[:project][:is_public] == "on" ? g.edit_project(@project.gpid, 20, params[:branch]) : g.edit_project(@project.gpid, 0, params[:branch])
end end
# end # end
if validate_parent_id && @project.save if validate_parent_id && @project.save

@ -0,0 +1,228 @@
class QualityAnalysisController < ApplicationController
before_filter :find_project_by_project_id#, :except => [:getattachtype]
before_filter :find_quality_analysis, :only => [:edit, :update_jenkins_job]
before_filter :authorize
before_filter :connect_jenkins, :only => [:create, :edit, :update_jenkins_job, :index]
layout "base_projects"
include ApplicationHelper
include QualityAnalysisHelper
require 'jenkins_api_client'
require 'nokogiri'
require 'json'
require 'open-uri'
def show
end
# params 说明:{identifier版本库名}
def create
begin
user_name = User.find(params[:user_id]).try(:login)
identifier = params[:identifier]
rep_id = params[:rep_id]
# job_name and sonar_name 前者为job名字后者为jenkins配置名
job_name = "#{user_name}-#{rep_id}"
sonar_name = "#{user_name}:#{rep_id}"
# Checks if the given job exists in Jenkins.
unless @client.job.exists?(job_name)
@g = Gitlab.client
branch = params[:branch]
language = swith_language_type(params[:language])
path = params[:path].blank? ? "./" : params[:path]
qa = QualityAnalysis.where(:project_id => @project.id, :author_login => user_name).first
version = qa.nil? ? 1 : qa.sonar_version + 1
properties = "sonar.projectKey=#{sonar_name}
sonar.projectName=#{sonar_name}
sonar.projectVersion=#{version}
sonar.sources=#{path}
sonar.language=#{language.downcase}
sonar.sourceEncoding=utf-8"
git_url = @gitlab_address.to_s+"/"+@project.owner.to_s+"/"+ identifier + "."+"git"
# 替换配置文件
@doc = Nokogiri::XML(File.open(File.join(Rails.root, 'tmp', 'config.xml')))
@doc.at_xpath("//hudson.plugins.git.UserRemoteConfig/url").content = git_url
@doc.at_xpath("//hudson.plugins.git.BranchSpec/name").content = "*/#{branch}"
@doc.at_xpath("//hudson.plugins.sonar.SonarRunnerBuilder/properties").content = properties # sonar-properties
# jenkins job创建
jenkins_job = @client.job.create("#{job_name}", @doc.to_xml)
logger.info("Jenkins status of create ==> #{jenkins_job}")
# 将地址作为hook值添加到gitlab
@g.add_project_hook(@project.gpid, @jenkins_address + "/project/#{job_name}")
# job创建完成后自动运行job,如果运行成功则返回200
code = @client.job.build("#{job_name}")
logger.error("build result ==> #{code}")
# 判断调用sonar分析是否成功
# 等待启动时间处理, 最长时间为30分钟
for i in 0..60 do
sleep(60)
@current_build_status = @client.job.get_current_build_status("#{job_name}")
if (@current_build_status != "not_run" || @current_build_status != "running")
break
if i == 60
@build_console_result = false
break
end
end
end
@console_build = @client.job.get_console_output("#{job_name}", build_num = 0, start = 0, mode = 'text')
logger.info("@current_build_status is ==> #{@current_build_status}")
logger.info("@console_build is ==> #{@console_build}")
d = @client.job.delete("#{job_name}") if jenkins_job == '200' && code != '201'
logger.error("delete result ==> #{code}")
if qa.blank? && @current_build_status == "success"
QualityAnalysis.create(:project_id => @project.id, :author_login => user_name, :rep_identifier => identifier,
:sonar_version => version, :path => path, :branch => branch, :language => language, :sonar_name => "#{user_name}:#{rep_id}")
else
qa.update_attribute(:sonar_version, version)
end
end
rescue => e
puts e
end
respond_to do |format|
format.html{redirect_to project_quality_analysis_path(:project_id => @project.id, :resource_id => sonar_name, :branch => branch, :current_build_status => @current_build_status, :job_name => job_name)}
# format.js{redirect_to project_quality_analysis_path(:project_id => @project.id, :resource_id => sonar_name, :branch => branch)}
end
end
# get language type
def swith_language_type language
if language == "c#"
"cs"
elsif language == "python"
"py"
elsif language == "c"
"c++"
else
language
end
end
def edit
@g = Gitlab.client
gitlab_branches = @g.branches(@project.gpid)
@branch_names = gitlab_branches.map{|b| b.name}
@gitlab_default_branch = @g.project(@project.gpid).default_branch
end
# 更新Jenkins job主要包括相关配置文件参数的更新Trustie平台数据的更新
def update_jenkins_job
begin
rep_id = Repository.where(:project_id => @project.id).first.try(:id)
logger.error("#############################===>666")
sonar_name = @quality_analysis.sonar_name
job_name = "#{@quality_analysis.author_login}-#{rep_id}"
version = @quality_analysis.sonar_version
path = params[:path].blank? ? "./" : params[:path]
language = swith_language_type(params[:language])
branch = params[:branch]
identifier = @quality_analysis.rep_identifier
properties = "sonar.projectKey=#{sonar_name}
sonar.projectName=#{sonar_name}
sonar.projectVersion=#{version}
sonar.sources=#{path}
sonar.language=#{language.downcase}
sonar.sourceEncoding=utf-8"
git_url = @gitlab_address.to_s+"/"+@project.owner.to_s+"/"+ identifier + "."+"git"
# modify config.yml
@doc = Nokogiri::XML(File.open(File.join(Rails.root, 'tmp', 'config.xml')))
@doc.at_xpath("//hudson.plugins.git.UserRemoteConfig/url").content = git_url
@doc.at_xpath("//hudson.plugins.git.BranchSpec/name").content = "*/#{branch}"
@doc.at_xpath("//hudson.plugins.sonar.SonarRunnerBuilder/properties").content = properties # sonar-properties
# update成功则返回 200
jenkins_job = @client.job.update("#{job_name}", @doc.to_xml)
get_current_build_status = @client.job.get_current_build_status("Hjqreturn-1280")
logger.error("Failed to update job: ==> #{jenkins_job}") unless jenkins_job == '200'
# 数据更新到Trustie数据库
if jenkins_job == '200'
logger.info("quality_ananlysis will be updated: ==> #{jenkins_job}")
@quality_analysis.path = path
@quality_analysis.language = language
@quality_analysis.branch = branch
@quality_analysis.save
end
rescue Exception => e
logger.error("Update jenkins job: #{e}")
end
respond_to do |format|
format.html{redirect_to project_quality_analysis_path(:project_id => @project.id)}
format.js
end
end
# resource_id: login + @repository.id
def index
begin
@branch = params[:branch]
@resource_id = params[:resource_id]
@sonar_address = Redmine::Configuration['sonar_address']
@jenkins_address = Redmine::Configuration['jenkins_address']
if params[:resource_id].nil?
@name_flag = true
projects_date = open(@sonar_address + "/api/projects/index").read
arr = JSON.parse(projects_date).map {|m| m["nm"]} # eg: ["Hjqreturn:cc_rep", "Hjqreturn:putong", "Hjqreturn:sonar_rep2", "shitou:sonar_rep"]
@quality_analyses = QualityAnalysis.where(:project_id => @project.id).select{|qa| arr.include?(qa.sonar_name)}
else
if params[:current_build_status] == "failure"
job_name = params[:job_name]
@console_build = @client.job.get_console_output("#{job_name}", build_num = 0, start = 0, mode = 'text')["output"]
end
complexity_date = open(@sonar_address + "/api/resources/index?resource=#{@resource_id}&depth=0&metrics=sqale_rating,function_complexity,duplicated_lines_density,comment_lines_density,sqale_index,lines,file_line,files,functions,classes,directories").read
@complexity =JSON.parse(complexity_date).first
issue_date = open(@sonar_address + "/api/resources/index?resource=#{@resource_id}&depth=0&metrics=blocker_violations,critical_violations,major_violations,minor_violations,info_violations,violations").read
@sonar_issues = JSON.parse(issue_date).first
end
rescue => e
puts e
end
end
# Find project of id params[:project_id]
def find_project_by_project_id
@project = Project.find(params[:project_id])
rescue ActiveRecord::RecordNotFound
render_404
end
def find_quality_analysis
begin
@quality_analysis = QualityAnalysis.find(params[:id])
rescue
render_404
end
end
# Authorize the user for the requested action
def authorize(ctrl = params[:controller], action = params[:action], global = false)
unless @project.archived? && @project.gpid.nil?
true
else
render_403 :message => :notice_not_authorized_archived_project
end
end
def connect_jenkins
@gitlab_address = Redmine::Configuration['gitlab_address']
@jenkins_address = Redmine::Configuration['jenkins_address']
# connect jenkins
@client = JenkinsApi::Client.new(:server_url => @jenkins_address, :username => "temp", :password => '123123')
rescue => e
logger.error("failed to connect Jenkins ==> #{e}")
end
end

@ -20,6 +20,8 @@ require 'SVG/Graph/BarHorizontal'
require 'digest/sha1' require 'digest/sha1'
require 'redmine/scm/adapters/abstract_adapter' require 'redmine/scm/adapters/abstract_adapter'
require 'tempfile' require 'tempfile'
require 'json'
require 'open-uri'
class ChangesetNotFound < Exception; end class ChangesetNotFound < Exception; end
class InvalidRevisionParam < Exception; end class InvalidRevisionParam < Exception; end
@ -30,11 +32,13 @@ class RepositoriesController < ApplicationController
menu_item :settings, :only => [:new, :create, :edit, :update, :destroy, :committers] menu_item :settings, :only => [:new, :create, :edit, :update, :destroy, :committers]
default_search_scope :changesets default_search_scope :changesets
before_filter :find_project_by_project_id, :only => [:new, :create, :newrepo, :stats] before_filter :find_project_by_project_id, :only => [:new, :create, :newrepo, :stats, :quality_analysis]
before_filter :find_repository, :only => [:edit, :update, :destroy, :committers] before_filter :find_repository, :only => [:edit, :update, :destroy, :committers]
before_filter :find_project_repository, :except => [:new, :create, :newcreate, :edit, :update, :destroy, :committers, :newrepo, :to_gitlab, :forked, :project_archive] before_filter :find_project_repository, :except => [:new, :create, :newcreate, :edit, :update, :destroy, :committers, :newrepo, :to_gitlab, :forked, :project_archive]
before_filter :find_changeset, :only => [:revision, :add_related_issue, :remove_related_issue] before_filter :find_changeset, :only => [:revision, :add_related_issue, :remove_related_issue]
before_filter :authorize , :except => [:newrepo,:newcreate,:fork, :to_gitlab, :forked, :commit_diff, :project_archive] before_filter :authorize , :except => [:newrepo,:newcreate,:fork, :to_gitlab, :forked, :commit_diff, :project_archive, :quality_analysis]
# 链接gitlab
before_filter :connect_gitlab, :only => [:quality_analysis]
accept_rss_auth :revisions accept_rss_auth :revisions
# hidden repositories filter // 隐藏代码过滤器 # hidden repositories filter // 隐藏代码过滤器
before_filter :check_hidden_repo, :only => [:show, :stats, :revisions, :revision, :diff ] before_filter :check_hidden_repo, :only => [:show, :stats, :revisions, :revision, :diff ]
@ -43,6 +47,7 @@ class RepositoriesController < ApplicationController
helper :project_score helper :project_score
#@root_path = RepositoriesHelper::ROOT_PATH #@root_path = RepositoriesHelper::ROOT_PATH
$g=Gitlab.client $g=Gitlab.client
require 'net/ssh'
rescue_from Redmine::Scm::Adapters::CommandFailed, :with => :show_error_command_failed rescue_from Redmine::Scm::Adapters::CommandFailed, :with => :show_error_command_failed
def new def new
@ -306,6 +311,37 @@ update
end end
end end
def quality_analysis
gitlab_branches = @g.branches(@project.gpid)
@branch_names = gitlab_branches.map{|b| b.name}
@gitlab_default_branch = @g.project(@project.gpid).default_branch
# language = params[:language]
# branch = params[:branch]
# path = params[:path]
# user_name = User.find(@project.user_id).try(:login)
# rep_name = params[:repository_id]
# host = "192.168.0.200"
# port = "1125"
# username = "git"
# password = "123123"
# server_cmd1 = "sh gitclone.sh" + " " + user_name + " " + rep_name
# # 连接到远程主机 foobar
# ssh = Net::SSH.start(host, username, :port => port, :password => password) do |ssh|
# result = ssh.exec!(server_cmd1)
# path = "/home/git/repo/" + user_name + "/" + rep_name
# # sonar 分析
# # server_cmd2
# # 删除clone的版本库
# # server_cmd3
# end
respond_to do |format|
format.js
format.html{
render :layout => "base_projects"
}
end
end
def destroy def destroy
DestroyRepositoryTask.new.destroy(User.current.id, @repository.id) DestroyRepositoryTask.new.destroy(User.current.id, @repository.id)
@repository.hidden = true @repository.hidden = true
@ -325,13 +361,10 @@ update
def show def show
## TODO: the below will move to filter, done. ## TODO: the below will move to filter, done.
if !User.current.member_of?(@project) if !User.current.member_of?(@project) && @project.hidden_repo
if @project.hidden_repo render_403
render_403 return
return -1
end
end end
@entries = @repository.entries(@path, @rev) @entries = @repository.entries(@path, @rev)
@changeset = @repository.find_changeset_by_name(@rev) @changeset = @repository.find_changeset_by_name(@rev)
if request.xhr? if request.xhr?
@ -341,7 +374,7 @@ update
@changesets = g.commits(@project.gpid, :ref_name => @rev) @changesets = g.commits(@project.gpid, :ref_name => @rev)
g_project = g.project(@project.gpid) g_project = g.project(@project.gpid)
# 总的提交数 # 总的提交数
@changesets_all_count = @project.gpid.nil? ? 0 : g_project.commit_count @changesets_all_count = @project.gpid.nil? ? 0 : commit_count(@project, @rev)
@g_default_branch = g_project.default_branch.nil? ? "master" : g_project.default_branch @g_default_branch = g_project.default_branch.nil? ? "master" : g_project.default_branch
# 访问该页面的是会后则刷新 # 访问该页面的是会后则刷新
if @project.project_score.nil? if @project.project_score.nil?
@ -362,6 +395,8 @@ update
# project_path_cut = RepositoriesHelper::PROJECT_PATH_CUT # project_path_cut = RepositoriesHelper::PROJECT_PATH_CUT
# ip = RepositoriesHelper::REPO_IP_ADDRESS # ip = RepositoriesHelper::REPO_IP_ADDRESS
gitlab_address = Redmine::Configuration['gitlab_address'] gitlab_address = Redmine::Configuration['gitlab_address']
# REDO:需优化,仅测试用
@zip_path = Gitlab.endpoint.to_s + "/projects/" + @project.gpid.to_s + "/repository/archive?&private_token=" + Gitlab.private_token
if @repository.type.to_s == "Repository::Gitlab" if @repository.type.to_s == "Repository::Gitlab"
@repos_url = gitlab_address.to_s+"/"+@project.owner.to_s+"/"+@repository.identifier+"."+"git" @repos_url = gitlab_address.to_s+"/"+@project.owner.to_s+"/"+@repository.identifier+"."+"git"
else else
@ -616,6 +651,14 @@ update
project.project_score.update_attribute(:commit_time, date.created_at) project.project_score.update_attribute(:commit_time, date.created_at)
end end
# 链接gitlab
def connect_gitlab
@g = Gitlab.client
unless @project.gpid.nil?
@g_project = @g.project(@project.gpid)
end
end
def find_repository def find_repository
@repository = Repository.find(params[:id]) @repository = Repository.find(params[:id])
@project = @repository.project @project = @repository.project

@ -150,4 +150,55 @@ class SchoolController < ApplicationController
format.js format.js
end end
end end
#申请高校(单位) name:名称 province:省 city:市 address:地址 remarks:备注
def apply_add_school
data = {result:0,name:params[:name],school_id:0}
#0 成功 1参数错误 2名称已存在
data[:result] = 0
#检验参数
if params[:name] == "" || params[:province] == "" || params[:city] == "" || params[:address] == ""
data[:result] = 1
else
school_id = School.find_by_sql("select id from schools where name='#{params[:name]}'").first
if school_id
data[:result] = 2
else
school = School.new
school.name = params[:name].strip
school.pinyin = Pinyin.t(params[:name].strip, splitter: '')
school.save
#status 0未处理 1通过 2拒绝
applyschool = ApplyAddSchools.new
applyschool.school_id = school.id
applyschool.name = school.name
applyschool.province = params[:province]
applyschool.city = params[:city]
applyschool.address = params[:address]
applyschool.remarks = params[:remarks]
applyschool.save
data[:school_id] = school.id
end
end
render :json =>data
end
def search_repeat_schoolname
status = 0
name = params[:name]
if name
school_id = School.find_by_sql("select id from schools where name='#{name}'").first
if school_id
status = 1
end
end
render :json =>status
end
end end

@ -81,6 +81,7 @@ class StudentWorkController < ApplicationController
#根据传入的tIndex确定是第几次测试 #根据传入的tIndex确定是第几次测试
#之后如果觉得很卡 可以改成将结果传回JS再以参数形式传回来 #之后如果觉得很卡 可以改成将结果传回JS再以参数形式传回来
def program_test_ex def program_test_ex
tStarttime = Time.now tStarttime = Time.now
is_test = params[:is_test] == 'true' is_test = params[:is_test] == 'true'
@ -106,108 +107,123 @@ class StudentWorkController < ApplicationController
tEndtime = Time.now tEndtime = Time.now
tUsedtime = (tEndtime.to_i-tStarttime.to_i)*1000+(tEndtime.usec - tStarttime.usec)/1000 tUsedtime = (tEndtime.to_i-tStarttime.to_i)*1000+(tEndtime.usec - tStarttime.usec)/1000
logger.debug "program_test_ex user wait time = #{tUsedtime} 毫秒" logger.debug "program_test_ex user wait time = #{tUsedtime} 毫秒"
#status 0:答案正确 -5program_test_ex 函数出错 -4judge代码出错 -3http超时 -2:编译错误 -1:答案错误 2:程序运行超时
#status 0:答案正确 -3http超时 -2:编译错误 -1:答案错误 2:程序运行超时 resultObj[:status] = -3
CodeTests.create(:homework_id=>@homework.id,:language=>@homework.homework_detail_programing.language,:status=>-3,:wait_time=>tUsedtime,:student_work_id=>student_work.id) CodeTests.create(:homework_id=>@homework.id,:language=>@homework.homework_detail_programing.language,:status=>-3,:wait_time=>tUsedtime,:student_work_id=>student_work.id)
rescue
end #-4 judge代码 出错
if result["status"].to_i != -2 logger.debug "program_test_error 1"
#result["results"].first['output'] = result["results"].first['output'].gsub(" ","□") resultObj[:status] = -4
#result["results"].first['result'] = result["results"].first['result'].gsub(" ","□") tmpstatus = -4
space_replace_1(result["results"].first['output']) CodeTests.create(:homework_id=>@homework.id,:language=>@homework.homework_detail_programing.language,:status=>tmpstatus,:time_used=>0,:wait_time=>0,:student_work_id=>student_work.id)
space_replace_1(result["results"].first['result'])
end end
logger.debug result begin
if resultObj[:status] != -3 && resultObj[:status] != -4
if result["status"].to_i != -2
#result["results"].first['output'] = result["results"].first['output'].gsub(" ","□")
#result["results"].first['result'] = result["results"].first['result'].gsub(" ","□")
space_replace_1(result["results"].first['output'])
space_replace_1(result["results"].first['result'])
end
#-1 默认值 0全部正确并结束 2 超时 -2 编译错误 logger.debug result
resultObj[:status] = -1
resultObj[:results] = result["results"].first #本次测试结果
if result["status"].to_i == -2 #编译错误
result["error_msg"] = result["error_msg"][0..2047]
end
resultObj[:error_msg] = result["error_msg"] #编译错误时的信息
#该状态用于存入CodeTests #-1 默认值 0全部正确并结束 2 超时 -2 编译错误
tmpstatus = -1 resultObj[:status] = -1
if result["status"].to_i == -2 #编译错误 resultObj[:results] = result["results"].first #本次测试结果
resultObj[:results] = result["error_msg"] if result["status"].to_i == -2 #编译错误
resultObj[:status] = -2 result["error_msg"] = result["error_msg"][0..2047]
tmpstatus = -2 end
elsif result["results"][0]["status"].to_i == 2 resultObj[:error_msg] = result["error_msg"] #编译错误时的信息
resultObj[:status] = 2
tmpstatus = 2 #该状态用于存入CodeTests
end tmpstatus = -1
if result["status"].to_i == -2 #编译错误
resultObj[:results] = result["error_msg"]
resultObj[:status] = -2
tmpstatus = -2
elsif result["results"][0]["status"].to_i == 2
resultObj[:status] = 2
tmpstatus = 2
end
if result["status"] == 0 if result["status"] == 0
tmpstatus = 0 tmpstatus = 0
end end
unless student_work.save unless student_work.save
resultObj[:status] = 200 resultObj[:status] = 200
else else
student_work.name = params[:title] student_work.name = params[:title]
student_work.description = params[:src] student_work.description = params[:src]
if Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") < Time.parse(Time.now.to_s).strftime("%Y-%m-%d") if Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") < Time.parse(Time.now.to_s).strftime("%Y-%m-%d")
student_work.late_penalty = @homework.late_penalty student_work.late_penalty = @homework.late_penalty
else else
student_work.late_penalty = 0 student_work.late_penalty = 0
end end
#每次从数据库取出上次的结果加上本次的结果再存入数据库 #每次从数据库取出上次的结果加上本次的结果再存入数据库
if result["status"].to_i != -2 if result["status"].to_i != -2
result["results"].first['user_wait'] = tUsedtime result["results"].first['user_wait'] = tUsedtime
if result["results"][0]["status"].to_i == 2 if result["results"][0]["status"].to_i == 2
result["status"] = 2 result["status"] = 2
end end
end end
status = result["status"] status = result["status"]
if index == 1 if index == 1
student_work_test = student_work.student_work_tests.build(status: status, student_work_test = student_work.student_work_tests.build(status: status,
results: [resultObj[:results]],src: params[:src]) results: [resultObj[:results]],src: params[:src])
student_work_test.save! student_work_test.save!
resultObj[:testid] = student_work_test.id resultObj[:testid] = student_work_test.id
else else
#先从数据库取出result #先从数据库取出result
student_work_test = StudentWorkTest.find(params[:testid]) student_work_test = StudentWorkTest.find(params[:testid])
results = student_work_test.results results = student_work_test.results
results << resultObj[:results] results << resultObj[:results]
student_work_test.results = results student_work_test.results = results
student_work_test.status = (result["status"] != 0 ? result["status"] : student_work_test.status) student_work_test.status = (result["status"] != 0 ? result["status"] : student_work_test.status)
student_work_test.save! student_work_test.save!
status = student_work_test.status status = student_work_test.status
resultObj[:testid] = student_work_test.id resultObj[:testid] = student_work_test.id
end end
#超时或编译错误则直接返回了并存入数据库 #超时或编译错误则直接返回了并存入数据库
if resultObj[:status] == 2 || resultObj[:status] == -2 || index == @homework.homework_tests.size if resultObj[:status] == 2 || resultObj[:status] == -2 || index == @homework.homework_tests.size
if status == 0 if status == 0
resultObj[:status] = 0 resultObj[:status] = 0
end end
student_work.save! student_work.save!
resultObj[:time] = student_work_test.created_at.to_s(:db) resultObj[:time] = student_work_test.created_at.to_s(:db)
resultObj[:index] = student_work.student_work_tests.count resultObj[:index] = student_work.student_work_tests.count
end end
#将每次用户等待时间都存起来以便管理界面显示用 #将每次用户等待时间都存起来以便管理界面显示用
tEndtime = Time.now tEndtime = Time.now
tUsedtime = (tEndtime.to_i-tStarttime.to_i)*1000+(tEndtime.usec - tStarttime.usec)/1000 tUsedtime = (tEndtime.to_i-tStarttime.to_i)*1000+(tEndtime.usec - tStarttime.usec)/1000
logger.debug "program_test_ex user wait time = #{tUsedtime} 毫秒" logger.debug "program_test_ex user wait time = #{tUsedtime} 毫秒"
time_used = 0 time_used = 0
if result["status"].to_i != -2 if result["status"].to_i != -2
#至少一毫秒 #至少一毫秒
time_used = result["results"].first['time_used'] == 0 ? 1:result["results"].first['time_used'] time_used = result["results"].first['time_used'] == 0 ? 1:result["results"].first['time_used']
end
#0:答案正确 -3http超时 -2:编译错误 -1:答案错误 2:程序运行超时
CodeTests.create(:homework_id=>@homework.id,:language=>@homework.homework_detail_programing.language,:status=>tmpstatus,:time_used=>time_used,:wait_time=>tUsedtime,:student_work_id=>student_work.id)
end
end end
#0:答案正确 -3http超时 -2:编译错误 -1:答案错误 2:程序运行超时 rescue
CodeTests.create(:homework_id=>@homework.id,:language=>@homework.homework_detail_programing.language,:status=>tmpstatus,:time_used=>time_used,:wait_time=>tUsedtime,:student_work_id=>student_work.id) #-5 program_test_ex 函数出错
logger.debug "program_test_error 2"
#渲染返回结果 resultObj[:status] = -5
render :json => resultObj tmpstatus = -5
CodeTests.create(:homework_id=>@homework.id,:language=>@homework.homework_detail_programing.language,:status=>tmpstatus,:time_used=>0,:wait_time=>0,:student_work_id=>student_work.id)
end end
#渲染返回结果
render :json => resultObj
end end
end end
end end
@ -358,8 +374,9 @@ class StudentWorkController < ApplicationController
end end
end end
################################################################################################################## ##################################################################################################################
@order,@b_sort,@name,@group = params[:order] || "score",params[:sort] || "desc",params[:name] || "",params[:group] @order,@b_sort,@name,@group = params[:order] || "score",params[:sort] || "desc",params[:name].to_s.strip || "",params[:group]
@homework_commons = @course.homework_commons.where("publish_time <= ?",Time.now.strftime("%Y-%m-%d")).order("created_at desc") @homework_commons = @course.homework_commons.where("publish_time <= ?",Time.now.strftime("%Y-%m-%d")).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_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 == 2 && !@is_teacher #是不是匿评
@show_all = false @show_all = false
@ -373,7 +390,7 @@ class StudentWorkController < ApplicationController
student_in_group = '(' + group_students.map{|user| user.id}.join(',') + ')' student_in_group = '(' + group_students.map{|user| user.id}.join(',') + ')'
end end
#开放作品 || 老师 || 超级管理员 || 禁用匿评&&作业截止&&已提交作品 显示所有列表 #开放作品 || 老师 || 超级管理员 || 禁用匿评&&作业截止&&已提交作品 显示所有列表
if @homework.is_open == 1 || @is_teacher || User.current.admin? || (User.current.member_of_course?(@course) && @homework.anonymous_comment == 1 && Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") < Time.now.strftime("%Y-%m-%d") && !@homework.student_works.where(:user_id => User.current.id).empty?) 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 && Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") < Time.now.strftime("%Y-%m-%d") && !@homework.student_works.where(:user_id => User.current.id).empty?)
if @order == 'lastname' if @order == 'lastname'
@stundet_works = search_homework_member @homework.student_works.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 @stundet_works = search_homework_member @homework.student_works.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' elsif @order == 'student_id'
@ -439,7 +456,7 @@ class StudentWorkController < ApplicationController
@student_work_count = (search_homework_member @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}"),@name).count @student_work_count = (search_homework_member @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}"),@name).count
else else
if @homework.is_open == 1 || @is_teacher || User.current.admin? || (User.current.member_of_course?(@course) && @homework.anonymous_comment == 1 && Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") < Time.now.strftime("%Y-%m-%d") && !@homework.student_works.where(:user_id => User.current.id).empty?) 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 && Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") < Time.now.strftime("%Y-%m-%d") && !@homework.student_works.where(:user_id => User.current.id).empty?)
if @order == 'lastname' if @order == 'lastname'
@stundet_works = search_homework_member @homework.student_works.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 @stundet_works = search_homework_member @homework.student_works.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' elsif @order == 'student_id'
@ -816,7 +833,7 @@ class StudentWorkController < ApplicationController
stu_score = StudentWorksScore.find_by_sql("SELECT AVG(score) AS score FROM (SELECT * FROM (SELECT * FROM student_works_scores WHERE student_work_id = #{@work.id} AND reviewer_role = 3 ORDER BY created_at DESC) AS t GROUP BY user_id) AS a") stu_score = StudentWorksScore.find_by_sql("SELECT AVG(score) AS score FROM (SELECT * FROM (SELECT * FROM student_works_scores WHERE student_work_id = #{@work.id} AND reviewer_role = 3 ORDER BY created_at DESC) AS t GROUP BY user_id) AS a")
@work.student_score = stu_score.first.score.try(:round, 2).to_f @work.student_score = stu_score.first.score.try(:round, 2).to_f
end end
@homework.update_attributes(:updated_at => Time.now) @homework.update_column('updated_at', Time.now)
update_course_activity(@homework.class,@homework.id) update_course_activity(@homework.class,@homework.id)
update_user_activity(@homework.class,@homework.id) update_user_activity(@homework.class,@homework.id)
update_org_activity(@homework.class,@homework.id) update_org_activity(@homework.class,@homework.id)
@ -1079,7 +1096,8 @@ class StudentWorkController < ApplicationController
all_student_ids = "(" + pro.members.map{|member| member.user_id}.join(",") + ")" all_student_ids = "(" + pro.members.map{|member| member.user_id}.join(",") + ")"
end end
all_students = User.where("id in #{all_student_ids}") all_students = User.where("id in #{all_student_ids}")
@commit_student_ids = @homework.student_work_projects.map{|student| student.user_id} 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_work_projects.where("student_work_id != #{student_work_id}").map{|student| student.user_id}
@users = searchstudent_by_name all_students,name @users = searchstudent_by_name all_students,name
respond_to do |format| respond_to do |format|
format.js format.js
@ -1098,6 +1116,20 @@ class StudentWorkController < ApplicationController
end end
end end
def get_user_infor
req = Hash.new(false)
user = User.where("id = #{params[:user_id].to_i}").first
if user
req[:id] = user.id
req[:name] = user.show_name
req[:student_id] = user.user_extensions.student_id
req[:valid] = true
else
req[:valid] = false
end
render :json => req
end
private private
def searchstudent_by_name users, name def searchstudent_by_name users, name
mems = [] mems = []
@ -1177,13 +1209,18 @@ class StudentWorkController < ApplicationController
sheet1 = book.create_worksheet :name => "homework" sheet1 = book.create_worksheet :name => "homework"
blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10 blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
sheet1.row(0).default_format = blue sheet1.row(0).default_format = blue
if @homework.homework_type == 1 #匿评作业 if @homework.homework_type == 1 #普通作业
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_des), if @homework.anonymous_comment ==0
l(:excel_t_score),l(:excel_ta_score), l(:excel_n_score),l(:excel_f_score),l(:excel_commit_time)]) 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_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_user_id),l(:excel_user_name),l(:excel_nickname),l(:excel_student_id),l(:excel_mail),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 = 1 count_row = 1
items.each do |homework| items.each do |homework|
sheet1[count_row,0]=homework.user.id sheet1[count_row,0]=homework.user.id
sheet1[count_row,1] = homework.user.lastname.to_s + homework.user.firstname.to_s sheet1[count_row,1] = homework.user.show_name
sheet1[count_row,2] = homework.user.login sheet1[count_row,2] = homework.user.login
sheet1[count_row,3] = homework.user.user_extensions.student_id sheet1[count_row,3] = homework.user.user_extensions.student_id
sheet1[count_row,4] = homework.user.mail sheet1[count_row,4] = homework.user.mail
@ -1191,18 +1228,31 @@ class StudentWorkController < ApplicationController
sheet1[count_row,6] = strip_html homework.description sheet1[count_row,6] = strip_html homework.description
sheet1[count_row,7] = homework.teacher_score.nil? ? l(:label_without_score) : homework.teacher_score.round(2) 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,8] = homework.teaching_asistant_score.nil? ? l(:label_without_score) : homework.teaching_asistant_score.round(2)
sheet1[count_row,9] = homework.student_score.nil? ? l(:label_without_score) : homework.student_score.round(2) if @homework.anonymous_comment ==0
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,9] = homework.student_score.nil? ? l(:label_without_score) : homework.student_score.round(2)
sheet1[count_row,11] = format_time(homework.created_at) sheet1[count_row,10] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.absence_penalty
sheet1[count_row,11] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.late_penalty
sheet1[count_row,12] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : homework.score.round(2) : l(:label_without_score)
sheet1[count_row,13] = format_time(homework.created_at)
else
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)
end
count_row += 1 count_row += 1
end end
elsif @homework.homework_type == 2 #编程作业 elsif @homework.homework_type == 2 #编程作业
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_des), if @homework.anonymous_comment ==0
l(:excel_t_score),l(:excel_ta_score), l(:excel_s_score),l(:excel_n_score),l(:excel_f_score),l(:excel_commit_time)]) 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_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
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_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 = 1 count_row = 1
items.each do |homework| items.each do |homework|
sheet1[count_row,0]=homework.user.id sheet1[count_row,0]=homework.user.id
sheet1[count_row,1] = homework.user.lastname.to_s + homework.user.firstname.to_s sheet1[count_row,1] = homework.user.show_name
sheet1[count_row,2] = homework.user.login sheet1[count_row,2] = homework.user.login
sheet1[count_row,3] = homework.user.user_extensions.student_id sheet1[count_row,3] = homework.user.user_extensions.student_id
sheet1[count_row,4] = homework.user.mail sheet1[count_row,4] = homework.user.mail
@ -1211,11 +1261,48 @@ class StudentWorkController < ApplicationController
sheet1[count_row,7] = homework.teacher_score.nil? ? l(:label_without_score) : homework.teacher_score.round(2) 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,8] = homework.teaching_asistant_score.nil? ? l(:label_without_score) : homework.teaching_asistant_score.round(2)
sheet1[count_row,9] = homework.system_score.nil? ? l(:label_without_score) : homework.system_score.round(2) sheet1[count_row,9] = homework.system_score.nil? ? l(:label_without_score) : homework.system_score.round(2)
sheet1[count_row,10] = homework.student_score.nil? ? l(:label_without_score) : homework.student_score.round(2) if @homework.anonymous_comment ==0
sheet1[count_row,11] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : homework.score.round(2) : l(:label_without_score) sheet1[count_row,10] = homework.student_score.nil? ? l(:label_without_score) : homework.student_score.round(2)
sheet1[count_row,12] = format_time(homework.created_at) sheet1[count_row,11] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.absence_penalty
sheet1[count_row,12] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.late_penalty
sheet1[count_row,13] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : homework.score.round(2) : l(:label_without_score)
sheet1[count_row,14] = format_time(homework.created_at)
else
sheet1[count_row,10] = (@homework.teacher_priority == 1 && !homework.teacher_score.nil?) ? 0 : homework.late_penalty
sheet1[count_row,11] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : homework.score.round(2) : l(:label_without_score)
sheet1[count_row,12] = format_time(homework.created_at)
end
count_row += 1 count_row += 1
end 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[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
end
end end
book.write xls_report book.write xls_report
xls_report.string xls_report.string

@ -1,8 +1,9 @@
class SubDocumentCommentsController < ApplicationController class SubDocumentCommentsController < ApplicationController
before_filter :find_subdomain_and_subfield, :only => [:new, :create, :show, :index, :destroy, :edit] before_filter :find_subdomain_and_subfield, :only => [:new, :create, :show, :index, :destroy, :edit]
before_filter :find_subfield_content, :only => [:show, :index] before_filter :find_subfield_content, :only => [:show, :index]
before_filter :authorize_allowed, :only => [:create, :add_reply]
helper :attachments,:organizations helper :attachments,:organizations
layout 'base_sub_domain' layout 'base_org_custom'
def new def new
@sub_document_comment = SubDocumentComment.new @sub_document_comment = SubDocumentComment.new
@ -40,7 +41,7 @@ class SubDocumentCommentsController < ApplicationController
if @organization.is_public? || User.current.admin? || User.current.member_of_org?(@organization) if @organization.is_public? || User.current.admin? || User.current.member_of_org?(@organization)
@document = SubDocumentComment.find(params[:id]) @document = SubDocumentComment.find(params[:id])
respond_to do |format| respond_to do |format|
format.html {render :layout => @organization.switch_type ? 'base_sub_domain' : 'base_org'} format.html {render :layout => @organization.switch_type ? 'base_org_custom' : 'base_org'}
end end
else else
render_403 render_403
@ -57,7 +58,7 @@ class SubDocumentCommentsController < ApplicationController
@offset ||= @atta_pages.offset @offset ||= @atta_pages.offset
@documents = paginateHelper @documents,20 @documents = paginateHelper @documents,20
respond_to do |format| respond_to do |format|
format.html {render :layout => @organization.switch_type ? 'base_sub_domain' : 'base_org'} format.html {render :layout => @organization.switch_type ? 'base_org_custom' : 'base_org'}
end end
else else
render_403 render_403
@ -125,6 +126,8 @@ class SubDocumentCommentsController < ApplicationController
def destroy def destroy
@sub_document_comment = SubDocumentComment.find(params[:id]) @sub_document_comment = SubDocumentComment.find(params[:id])
@sub_document_comment.destroy @sub_document_comment.destroy
@sub_domain = @sub_document_comment.sub_domain
@org_subfield = @sub_domain.org_subfield
rescue ActiveRecord::RecordNotFound rescue ActiveRecord::RecordNotFound
respond_to do |format| respond_to do |format|
# format.html{ # format.html{
@ -205,4 +208,11 @@ class SubDocumentCommentsController < ApplicationController
def find_subfield_content def find_subfield_content
@subfield_content = @organization.org_subfields.order("priority") @subfield_content = @organization.org_subfields.order("priority")
end end
def authorize_allowed
unless User.current.logged?
redirect_to signin_url
return
end
end
end end

@ -18,6 +18,9 @@ class SubDomainsController < ApplicationController
else else
@res = false @res = false
end end
respond_to do |format|
format.js
end
end end
def update def update

@ -0,0 +1,172 @@
# encoding: utf-8
class SyllabusesController < ApplicationController
include ApplicationHelper
helper :attachments
include AttachmentsHelper
include CoursesHelper
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, :update_base_info, :delete_syllabus, :delete_des]
def index
user = User.current
@syllabuses = user.syllabuses
end
def show
#@courses = @syllabus.courses
respond_to do |format|
format.js
format.html{render :layout => 'base_syllabus'}
format.api
end
end
def new
@syllabus = Syllabus.new
render :layout => 'new_base'
end
def create
if User.current.user_extensions.identity
@syllabus = Syllabus.new
@syllabus.title = params[:title]
@syllabus.eng_name = params[:eng_name]
@syllabus.user_id = User.current.id
@syllabus.description = Message.where("id = 19412").first.nil? ? '' : Message.where("id = 19412").first.content
if @syllabus && @syllabus.save
respond_to do |format|
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
else
respond_to do |format|
flash[:notice] = l(:notice_create_failed)
format.html { redirect_to new_syllabus_path } #Added by young
format.api { render_validation_errors(@syllabus) }
end
end
end
end
def edit
respond_to do |format|
format.html{render :layout => 'base_syllabus'}
end
end
def delete_syllabus
respond_to do |format|
format.js
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
@syllabus.description = Message.where("id = 19412").first.nil? ? '' : Message.where("id = 19412").first.content
@syllabus.des_status = 0
@syllabus.attachments.destroy_all
if @syllabus.save
redirect_to syllabus_path(@syllabus)
end
end
end
def destroy
if @syllabus && @syllabus.courses.empty?
@syllabus.destroy
redirect_to user_courselist_user_path(User.current.id)
end
end
#班级列表
def syllabus_courselist
@order, @c_sort,@type = params[:order] || 1, params[:sort] || 1, params[:type] || 1
#确定 sort_type
if @order.to_i == @type.to_i
@c_sort = @c_sort.to_i == 1 ? 2 : 1 #1升序 2降序
else
@c_sort = 2
end
sort_name = "updated_on"
sort_type = @c_sort == 1 ? "asc" : "desc"
@courses = User.current.courses.visible.where("is_delete =? and syllabus_id =?", 0, @syllabus.id).select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS #{sort_name}").order("#{sort_name} #{sort_type}")
#根据 作业+资源数排序
if @order.to_i == 2
@type = 2
@courses.each do |course|
course[:infocount] = (User.current.admin? || User.current.allowed_to?(:as_teacher,course)) ? (course.homework_commons.count + visable_attachemnts_incourse(course).count) : (course.homework_commons.where("publish_time <= '#{Date.today}'").count + visable_attachemnts_incourse(course).count)
if course[:infocount] < 0
course[:infocount] = 0
end
end
@c_sort == 1 ? (@courses = @courses.sort{|x,y| x[:infocount] <=> y[:infocount] }) : (@courses = @courses.sort{|x,y| y[:infocount] <=> x[:infocount]})
@courses = sortby_time_countcommon_nosticky @courses,sort_name
else
@type = 1
end
#分页
@limit = 10
@is_remote = true
@atta_count = @courses.count
@atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
@offset ||= @atta_pages.offset
@courses = paginateHelper @courses,@limit
respond_to do |format|
format.js
format.html{render :layout => 'base_syllabus'}
end
end
#修改英文名称
def edit_syllabus_eng_name
if @syllabus
@syllabus.update_column("eng_name",params[:eng_name])
end
respond_to do |format|
format.js
end
end
#编辑属性
def update_base_info
if @syllabus
@syllabus.update_attributes(:credit => params[:credit], :hours => params[:hours], :theory_hours => params[:theory_hours], :practice_hours => params[:practice_hours], :applicable_major => params[:applicable_major], :pre_course => params[:pre_course])
@syllabus.update_attributes(:syllabus_type => params[:syllabus_type])
respond_to do |format|
format.js
end
end
end
private
def find_syllabus
@syllabus = Syllabus.find params[:id]
end
def is_logged
redirect_to signin_path unless User.current.logged?
end
end

@ -13,6 +13,7 @@ class TagsController < ApplicationController
include ForumsHelper include ForumsHelper
include AttachmentsHelper include AttachmentsHelper
include ContestsHelper include ContestsHelper
include SyllabusesHelper
include ActsAsTaggableOn::TagsHelper include ActsAsTaggableOn::TagsHelper
include TagsHelper include TagsHelper
include FilesHelper include FilesHelper
@ -529,6 +530,8 @@ class TagsController < ApplicationController
@obj = Course.find_by_id(@obj_id) @obj = Course.find_by_id(@obj_id)
when '10' when '10'
@obj = Attachment.find_by_id(@obj_id) @obj = Attachment.find_by_id(@obj_id)
when '11'
@obj = Syllabus.find_by_id(@obj_id)
else else
@obj = nil @obj = nil
end end
@ -619,6 +622,9 @@ class TagsController < ApplicationController
when '9' then when '9' then
@obj = Course.find_by_id(obj_id) @obj = Course.find_by_id(obj_id)
@obj_pages, @courses_results, @results_count = for_pagination(get_courses_by_tag(selected_tags)) @obj_pages, @courses_results, @results_count = for_pagination(get_courses_by_tag(selected_tags))
when '11' then
@obj = Syllabus.find_by_id(obj_id)
@obj_pages, @syllabuses_results, @results_count = for_pagination(get_syllabuses_by_tag(selected_tags))
else else
@obj = nil @obj = nil
end end
@ -684,6 +690,8 @@ class TagsController < ApplicationController
return 'Course' return 'Course'
when '10' when '10'
return 'Attachment' return 'Attachment'
when '11'
return 'Syllabus'
else else
render_error :message => e.message render_error :message => e.message
return return

@ -87,7 +87,12 @@ class UsersController < ApplicationController
#展开所有回复 #展开所有回复
def show_all_replies def show_all_replies
@comment = JournalsForMessage.find params[:comment].to_i case params[:type]
when 'JournalsForMessage'
@comment = JournalsForMessage.find params[:comment].to_i
when 'Message'
@comment = Message.find params[:comment].to_i
end
end end
#二级回复 #二级回复
@ -95,13 +100,26 @@ class UsersController < ApplicationController
case params[:type] case params[:type]
when 'HomeworkCommon' when 'HomeworkCommon'
@reply = JournalsForMessage.find params[:reply_id] @reply = JournalsForMessage.find params[:reply_id]
@type = 'HomeworkCommon'
if params[:user_activity_id] if params[:user_activity_id]
@user_activity_id = params[:user_activity_id] @user_activity_id = params[:user_activity_id]
else else
@user_activity_id = -1 @user_activity_id = -1
end end
@is_in_course = params[:is_in_course] @is_in_course = params[:is_in_course].to_i
@course_activity = params[:course_activity].to_i @course_activity = params[:course_activity].to_i
when 'JournalsForMessage'
@reply = JournalsForMessage.find params[:reply_id]
@user_activity_id = params[:user_activity_id]
@activity_id = params[:activity_id]
@type = 'JournalsForMessage'
when 'Message'
@reply = Message.find params[:reply_id]
@user_activity_id = params[:user_activity_id]
@activity_id = params[:activity_id]
@is_course = params[:is_course]
@is_board = params[:is_board]
@type = 'Message'
end end
respond_to do |format| respond_to do |format|
format.js format.js
@ -123,6 +141,23 @@ class UsersController < ApplicationController
end end
#未读消息弹窗
def user_messages_unviewed
@message_alls = []
messages = MessageAll.where("user_id =?", User.current.id).includes(:message).order("created_at desc")
onclick_time = User.current.onclick_time.onclick_time
messages.each do |message_all|
# 未读的消息存放在数组
mess = message_all.message
if (message_all.message_type != "SystemMessage"&& !mess.nil? && (mess.viewed == 0 || !mess.viewed)) || (message_all.message_type == "SystemMessage"&& !mess.nil? && mess.created_at > onclick_time)
unless (message_all.message_type == 'CourseMessage' && mess && mess.course && mess.course.is_delete == 1)
@message_alls << mess
end
break if @message_alls.length == 10
end
end
end
# 用户消息 # 用户消息
# 说明: homework 发布作业message讨论区 news新闻 poll问卷works_reviewers作品评阅works_reply:作品回复,exercise:课程测验 # 说明: homework 发布作业message讨论区 news新闻 poll问卷works_reviewers作品评阅works_reply:作品回复,exercise:课程测验
# issue问题journal缺陷状态更新 forum公共贴吧: user_feedback: 用户留言; new_reply:新闻回复comment # issue问题journal缺陷状态更新 forum公共贴吧: user_feedback: 用户留言; new_reply:新闻回复comment
@ -140,33 +175,41 @@ class UsersController < ApplicationController
update_message_viewed(@user) update_message_viewed(@user)
end end
# @new_message_count = forge_querys.count + forum_querys.count + course_querys.count + user_querys.count # @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(",") + ")"
case params[:type] case params[:type]
when nil when nil
# 系统消息为管理员发送,我的消息中包含有系统消息 # 系统消息为管理员发送,我的消息中包含有系统消息
@message_alls = [] @message_alls = []
messages = MessageAll.where("(user_id =? and message_type !=?) or message_type =?" ,@user.id, "SystemMessage", "SystemMessage").includes(:message).order("created_at desc") messages = MessageAll.where("(user_id =? and message_type !=?) or message_type =?" ,@user.id, "SystemMessage", "SystemMessage").includes(:message).order("created_at desc")
messages.each do |message_all| messages.each do |message_all|
@message_alls << message_all.message mess = message_all.message
unless (message_all.message_type == 'CourseMessage' && mess && mess.course && mess.course.is_delete == 1)
@message_alls << mess
end
end end
when 'unviewed' when 'unviewed'
@message_alls = [] @message_alls = []
messages = MessageAll.where("user_id =?", @user.id).includes(:message).order("created_at desc") messages = MessageAll.where("message_alls.user_id =?", @user.id).includes(:message).order("created_at desc")
messages.each do |message_all| messages.each do |message_all|
# 在点击或者刷新消息列表后未读的消息存放在数组 # 在点击或者刷新消息列表后未读的消息存放在数组
if message_all.message_type != "SystemMessage"&& !message_all.message.nil? && message_all.message.viewed == 0 mess = message_all.message
@message_alls << message_all.message if message_all.message_type != "SystemMessage"&& !mess.nil? && (mess.viewed == 0 || !mess.viewed)
unless (message_all.message_type == 'CourseMessage' && mess && mess.course && mess.course.is_delete == 1)
@message_alls << mess
end
end end
end end
#课程相关消息 #课程相关消息
when 'homework' when 'homework'
@message_alls = CourseMessage.where("course_message_type in ('HomeworkCommon','StudentWorksScore','JournalsForMessage','StudentWork','Exercise') and user_id =?", @user.id).order("created_at desc") @message_alls = CourseMessage.where("course_message_type in ('HomeworkCommon','StudentWorksScore','JournalsForMessage','StudentWork','Exercise') and user_id =? and course_id NOT IN #{course_ids}", @user.id).order("created_at desc")
when 'course_message' when 'course_message'
@message_alls = CourseMessage.where("course_message_type =? and user_id =?", "Message", @user.id).order("created_at desc") @message_alls = CourseMessage.where("course_message_type =? and user_id =? and course_id NOT IN #{course_ids}", "Message", @user.id).order("created_at desc")
when 'course_news' when 'course_news'
# 课程通知包含发布的通知和回复的通知 # 课程通知包含发布的通知和回复的通知
@message_alls = CourseMessage.where("course_message_type in ('News', 'Comment') and user_id =?", @user.id).order("created_at desc") @message_alls = CourseMessage.where("course_message_type in ('News', 'Comment') and user_id =? and course_id NOT IN #{course_ids}", @user.id).order("created_at desc")
when 'poll' when 'poll'
@message_alls = CourseMessage.where("course_message_type =? and user_id =?", "Poll", @user.id).order("created_at desc") @message_alls = CourseMessage.where("course_message_type =? and user_id =? and course_id NOT IN #{course_ids}", "Poll", @user.id).order("created_at desc")
#项目相关消息 #项目相关消息
when 'issue' when 'issue'
@message_alls = ForgeMessage.where("forge_message_type in ('Issue', 'Journal') and user_id =?" , @user.id).order("created_at desc") @message_alls = ForgeMessage.where("forge_message_type in ('Issue', 'Journal') and user_id =?" , @user.id).order("created_at desc")
@ -311,6 +354,28 @@ class UsersController < ApplicationController
end end
end end
# 处理资源引用请求
# status
def deal_with_apply_resource
@msg = CourseMessage.find(params[:msg_id])
ar = ApplyResource.where("id = ?", @msg.course_message_id).first
unless ar.nil?
case params[:agree]
when 'Y'
ar.update_column('status', 2)
@msg.update_attributes(:apply_result => 1, :viewed => 1)
ar.course_messages << CourseMessage.new(:user_id => ar.user_id, :course_id => -1, :viewed => false, :apply_result => 2, :status => 1)
when 'N'
ar.update_column('status', 3)
@msg.update_attributes(:apply_result => 2, :viewed => 1)
ar.course_messages << CourseMessage.new(:user_id => ar.user_id, :course_id => -1, :viewed => false, :apply_result => 3, :status => 1)
end
end
respond_to do |format|
format.js
end
end
#处理引用作业的请求 #处理引用作业的请求
#status 1 同意 2 拒绝 #status 1 同意 2 拒绝
def dealwith_apply_homework def dealwith_apply_homework
@ -419,6 +484,14 @@ class UsersController < ApplicationController
end end
# end # end
# 资源分享请求弹框
def apply_resource
@attachment = Attachment.find params[:attachment_id]
respond_to do |format|
format.js
end
end
#引用作业请求弹框 #引用作业请求弹框
def apply_homework def apply_homework
if User.current.logged? if User.current.logged?
@ -432,6 +505,27 @@ class UsersController < ApplicationController
end end
end end
# 申请引用资源
def apply_for_resource
if User.current.logged?
@attachment = Attachment.where("id =?", params[:attachment_id].to_i).first
unless @attachment.nil?
ar = ApplyResource.where("user_id = ? and attachment_id = ?", User.current.id, params[:attacment_id].to_i)
if ar.empty?
ApplyResource.create(:user_id => params[:id].to_i, :attachment_id => params[:attachment_id].to_i, :status => true, :container_id => @attachment.container_id, :container_type => @attachment.container_type, :content => params[:content], :apply_user_id => @attachment.author_id)
@state = 2
else
@state = 3
end
end
else
@state = 1
end
respond_to do |format|
format.js
end
end
#申请引用非公开作业 #申请引用非公开作业
def apply_for_homework def apply_for_homework
if User.current.logged? if User.current.logged?
@ -483,28 +577,28 @@ class UsersController < ApplicationController
end end
def student_homeworks def student_homeworks
if User.current == @user if User.current == @user
@page = params[:page] ? params[:page].to_i + 1 : 0 @page = params[:page] ? params[:page].to_i + 1 : 0
user_course_ids = @user.courses.empty? ? "(-1)" :"(" + @user.courses.visible.map{|course| course.id}.join(",") + ")" user_course_ids = @user.courses.empty? ? "(-1)" :"(" + @user.courses.visible.map{|course| course.id}.join(",") + ")"
#判断当前用户在当前课程的身份 #判断当前用户在当前课程的身份
visibleCourse = @user.courses.empty? ? [] : @user.courses.where("is_delete = 0").visible visibleCourse = @user.courses.empty? ? [] : @user.courses.where("is_delete = 0").visible
homework_ids = [] homework_ids = []
visibleCourse.each do |course| visibleCourse.each do |course|
homeworks = HomeworkCommon.where("course_id = #{course.id} and publish_time <= '#{Date.today}'") homeworks = HomeworkCommon.where("course_id = #{course.id} and publish_time <= '#{Date.today}'")
homework_ids << homeworks.pluck(:id) unless homeworks.empty? homework_ids << homeworks.pluck(:id) unless homeworks.empty?
end end
visible_homework_ids = homework_ids.size == 0 ? "(-1)" :"(" + homework_ids.join(",") + ")" visible_homework_ids = homework_ids.size == 0 ? "(-1)" :"(" + homework_ids.join(",") + ")"
@homework_commons = HomeworkCommon.where("id in #{visible_homework_ids}").order("created_at desc").limit(10).offset(@page * 10) @homework_commons = HomeworkCommon.where("id in #{visible_homework_ids}").order("created_at desc").limit(10).offset(@page * 10)
@is_teacher = User.current.user_extensions && User.current.user_extensions.identity == 0 && User.current.allowed_to?(:add_course, nil, :global => true) @is_teacher = User.current.user_extensions && User.current.user_extensions.identity == 0 && User.current.allowed_to?(:add_course, nil, :global => true)
@is_in_course = params[:is_in_course].to_i || 0 @is_in_course = params[:is_in_course].to_i || 0
respond_to do |format| respond_to do |format|
format.js format.js
format.html {render :layout => 'new_base_user'} format.html {render :layout => 'new_base_user'}
end
else
render_403
end end
else
render_403
end
end end
def choose_user_course def choose_user_course
@ -519,7 +613,7 @@ class UsersController < ApplicationController
end end
if !params[:search].nil? if !params[:search].nil?
search = "%#{params[:search].to_s.strip.downcase}%" search = "%#{params[:search].to_s.strip.downcase}%"
@course = @user.courses.where("is_delete = 0 and #{Course.table_name}.id != #{homework.course_id} and #{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like :p",:p=>search).select { |course| @user.allowed_to?(:as_teacher,course)} @course = @user.courses.where("is_delete = 0 and #{Course.table_name}.id != #{homework.course_id} and (#{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like :p)",:p=>search).select { |course| @user.allowed_to?(:as_teacher,course)}
else else
@course = @user.courses.where("is_delete = 0 and #{Course.table_name}.id != #{homework.course_id}").select { |course| @user.allowed_to?(:as_teacher,course)} @course = @user.courses.where("is_delete = 0 and #{Course.table_name}.id != #{homework.course_id}").select { |course| @user.allowed_to?(:as_teacher,course)}
end end
@ -589,7 +683,7 @@ class UsersController < ApplicationController
new_homework.homework_detail_programing.save if new_homework.homework_detail_programing new_homework.homework_detail_programing.save if new_homework.homework_detail_programing
new_homework.homework_detail_group.save if new_homework.homework_detail_group new_homework.homework_detail_group.save if new_homework.homework_detail_group
end end
homework.update_attribute(:quotes, homework.quotes+1) homework.update_column(:quotes, homework.quotes+1)
end end
@homework = homework @homework = homework
respond_to do |format| respond_to do |format|
@ -671,21 +765,21 @@ class UsersController < ApplicationController
end end
def show_homework_detail def show_homework_detail
homework = HomeworkCommon.find params[:homework].to_i @homework = HomeworkCommon.find params[:homework].to_i
if homework.course.is_public == 0 && !User.current.allowed_to?(:as_teacher,homework.course) && User.current != homework.user # if homework.course.is_public == 0 && !User.current.allowed_to?(:as_teacher,homework.course) && User.current != homework.user
ah = ApplyHomework.where("user_id = ? and homework_common_id = ?", User.current.id, params[:homework].to_i) # ah = ApplyHomework.where("user_id = ? and homework_common_id = ?", User.current.id, params[:homework].to_i)
if ah.empty? # if ah.empty?
@status = 2 # @status = 2
@homework = nil # @homework = nil
elsif ah.first.status != 2 # elsif ah.first.status != 2
@status = ah.first.status # @status = ah.first.status
@homework = nil # @homework = nil
elsif ah.first.status == 2 # elsif ah.first.status == 2
@homework = homework # @homework = homework
end # end
else # else
@homework = homework # @homework = homework
end # end
@is_import = params[:is_import] @is_import = params[:is_import]
respond_to do |format| respond_to do |format|
format.js format.js
@ -862,7 +956,7 @@ class UsersController < ApplicationController
student_work.save student_work.save
send_message_to_teacher(student_work) send_message_to_teacher(student_work)
homework.update_attributes(:updated_at => Time.now) homework.update_column(:updated_at, Time.now)
update_course_activity(homework.class,homework.id) update_course_activity(homework.class,homework.id)
update_user_activity(homework.class,homework.id) update_user_activity(homework.class,homework.id)
update_org_activity(homework.class,homework.id) update_org_activity(homework.class,homework.id)
@ -950,7 +1044,7 @@ class UsersController < ApplicationController
homework_detail_group.save if homework_detail_group homework_detail_group.save if homework_detail_group
if params[:quotes] && !params[:quotes].blank? if params[:quotes] && !params[:quotes].blank?
quotes_homework = HomeworkCommon.find params[:quotes].to_i quotes_homework = HomeworkCommon.find params[:quotes].to_i
quotes_homework.update_attribute(:quotes, quotes_homework.quotes+1) quotes_homework.update_column(:quotes, quotes_homework.quotes+1)
end end
if params[:is_in_course] == "1" if params[:is_in_course] == "1"
redirect_to homework_common_index_path(:course => homework.course_id) redirect_to homework_common_index_path(:course => homework.course_id)
@ -1039,22 +1133,27 @@ class UsersController < ApplicationController
#引入资源列表根据关键词过滤 #引入资源列表根据关键词过滤
def user_ref_resource_search def user_ref_resource_search
search = params[:search].to_s.strip.downcase if User.current.id.to_i != params[:id].to_i
if(params[:type].blank? || params[:type] == "1") #全部 render_403
user_course_ids = User.current.courses.map { |c| c.is_delete == 0 && c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 取交集并查询 return
@attachments = Attachment.where("((author_id = #{params[:id]} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) "+ end
" or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}))) and (filename like '%#{search}%') ").order("created_on desc") @resource_id = params[:mul_id]
elsif params[:type] == "2" #课程资源 @resource_type = params[:mul_type]
@order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
@score = @b_sort == "desc" ? "asc" : "desc"
@user = User.current
@switch_search = params[:search].nil? ? " " : params[:search]
search = "%#{@switch_search.strip.downcase}%"
# 别人的资源库是没有权限去看的
if(params[:type] == "1") # 我的资源
# 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
user_course_ids = User.current.courses.map { |c| c.is_delete == 0 && c.id} user_course_ids = User.current.courses.map { |c| c.is_delete == 0 && c.id}
@attachments = Attachment.where("(author_id = #{params[:id]} and container_type = 'Course') or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')})) and (filename like '%#{search}%') ").order("created_on desc") user_project_ids = User.current.projects.map {|p| p.status != 9 && p.id }
elsif params[:type] == "3" #项目资源 # user_org_ids = User.current.organizations.map {|o| o.id}
@attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Project' and (filename like '%#{search}%')").order("created_on desc") @attachments = get_my_resources_search(params[:id], user_course_ids, user_project_ids, @order, @score, search)
elsif params[:type] == "4" #附件 elsif (params[:type].blank? || params[:type] == "6") # 公共资源
@attachments = Attachment.where("author_id = #{params[:id]} and container_type in('Project','Issue','Document','Message','News','StudentWorkScore','HomewCommon') and (filename like '%#{search}%')").order("created_on desc") # 公共资源库:所有公开资源或者我上传的私有资源
elsif params[:type] == "5" #用户资源 @attachments = get_public_resources_search(user_course_ids, user_project_ids, @order, @score, search)
@attachments = Attachment.where("author_id = #{params[:id]} and container_type = 'Principal' and (filename like '%#{search}%')").order("created_on desc")
elsif params[:type] == "6" #公共资源
@attachments = Attachment.where("(is_public =1 and is_publish = 1 and container_id is not null)" + "or (author_id = #{params[:id]} and is_publish = 0)").order("created_on desc")
end end
@type = params[:type] @type = params[:type]
@limit = 7 @limit = 7
@ -1158,6 +1257,12 @@ class UsersController < ApplicationController
render :layout=>'new_base_user' render :layout=>'new_base_user'
end end
#给某人留言
def feedBackTo
end
def user_comments def user_comments
end end
@ -1277,7 +1382,15 @@ class UsersController < ApplicationController
#显示更多用户课程 #显示更多用户课程
def user_courses4show def user_courses4show
@page = params[:page].to_i + 1 @page = params[:page].to_i + 1
@courses = @user.courses.visible.where("is_delete =?", 0).select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc").limit(5).offset(@page * 5) @type = params[:type]
if @type == 'User'
@courses = @user.courses.visible.where("is_delete =?", 0).select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc").limit(5).offset(@page * 5)
@all_count = @user.courses.visible.where("is_delete =?", 0).count
elsif @type == 'Syllabus'
@syllabus = Syllabus.where("id = #{params[:syllabus]}").first
@courses = User.current.courses.visible.where("is_delete =? and syllabus_id =?", 0, @syllabus.id).select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc").limit(5).offset(@page * 5)
@all_count = User.current.courses.visible.where("is_delete =? and syllabus_id =?", 0, @syllabus.id).count
end
end end
#显示更多用户项目 #显示更多用户项目
@ -1373,7 +1486,7 @@ class UsersController < ApplicationController
user_project_ids = (@user.projects.visible.map{|project| project.id}-shield_project_ids).empty? ? "(-1)" : "(" + (@user.projects.visible.map{|project| project.id}-shield_project_ids).join(",") + ")" user_project_ids = (@user.projects.visible.map{|project| project.id}-shield_project_ids).empty? ? "(-1)" : "(" + (@user.projects.visible.map{|project| project.id}-shield_project_ids).join(",") + ")"
user_course_ids = (@user.courses.visible.where("is_delete = 0").map{|course| course.id}-shield_course_ids).empty? ? "(-1)" : "(" + (@user.courses.visible.where("is_delete = 0").map{|course| course.id}-shield_course_ids).join(",") + ")" user_course_ids = (@user.courses.visible.where("is_delete = 0").map{|course| course.id}-shield_course_ids).empty? ? "(-1)" : "(" + (@user.courses.visible.where("is_delete = 0").map{|course| course.id}-shield_course_ids).join(",") + ")"
course_types = "('Message','News','HomeworkCommon','Poll','Course','JournalsForMessage')" course_types = "('Message','News','HomeworkCommon','Poll','Course','JournalsForMessage')"
project_types = "('Message','Issue','ProjectCreateInfo')" project_types = "('Message','Issue','Project')"
principal_types = "JournalsForMessage" principal_types = "JournalsForMessage"
if params[:type].present? if params[:type].present?
case params[:type] case params[:type]
@ -1408,8 +1521,8 @@ class UsersController < ApplicationController
# 减少数据库交互 # 减少数据库交互
watched_user_ids = User.watched_by(@user.id).count == 0 ? " " : ("," + User.watched_by(@user.id).map{|u| u.id.to_s }.join(',')) watched_user_ids = User.watched_by(@user.id).count == 0 ? " " : ("," + User.watched_by(@user.id).map{|u| u.id.to_s }.join(','))
user_ids = "(" + @user.id.to_s + watched_user_ids + ")" user_ids = "(" + @user.id.to_s + watched_user_ids + ")"
watched_user_blog_ids = Blog.select("id").where("author_id in #{user_ids}").map { |blog| blog.id}.join(",") watched_user_blog_ids = Blog.select("id").where("author_id in #{user_ids}")
blog_ids = "(" + watched_user_blog_ids + ")" blog_ids = watched_user_blog_ids.empty? ? "(-1)" : "(" + watched_user_blog_ids.map { |blog| blog.id}.join(",") + ")"
@user_activities = UserActivity.where("(container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types})" + @user_activities = UserActivity.where("(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 = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types}) "+
@ -1886,7 +1999,7 @@ class UsersController < ApplicationController
# 将资源发送到对应的课程,分为发送单个,或者批量发送 # 将资源发送到对应的课程,分为发送单个,或者批量发送
def add_exist_file_to_course def add_exist_file_to_course
@flag = true @flag = true
if params[:send_id].present? if params[:send_id].present?
send_id = params[:send_id] send_id = params[:send_id]
@ori = Attachment.find_by_id(send_id) @ori = Attachment.find_by_id(send_id)
course_ids = params[:course_ids] course_ids = params[:course_ids]
@ -1926,21 +2039,21 @@ class UsersController < ApplicationController
end end
end end
elsif params[:send_ids].present? elsif params[:send_ids].present?
send_ids = params[:send_ids].split(" ") send_ids = params[:send_ids].split(",")
course_ids = params[:course_ids] course_ids = params[:course_ids]
if course_ids.nil? if course_ids.nil?
@flag = false @flag = false
end end
send_ids.each do |send_id| send_ids.each do |send_id|
quotes = 0 quotes = 0
ori = Attachment.find_by_id(send_id) @ori = Attachment.find_by_id(send_id)
unless course_ids.nil? unless course_ids.nil?
course_ids.each do |id| course_ids.each do |id|
quotes = 0 quotes = 0
next if ori.blank? next if @ori.blank?
@exist = false @exist = false
Course.find(id).attachments.each do |att| #如果课程中包含该资源 Course.find(id).attachments.each do |att| #如果课程中包含该资源
if att.id == ori.id || (!att.copy_from.nil? && !ori.copy_from.nil? && att.copy_from == ori.copy_from) || att.copy_from == ori.id || att.id == ori.copy_from if att.id == @ori.id || (!att.copy_from.nil? && !@ori.copy_from.nil? && att.copy_from == @ori.copy_from) || att.copy_from == @ori.id || att.id == @ori.copy_from
att.created_on = Time.now att.created_on = Time.now
att.save att.save
@exist = true @exist = true
@ -1948,21 +2061,21 @@ class UsersController < ApplicationController
end end
end end
next if @exist next if @exist
attach_copied_obj = ori.copy attach_copied_obj = @ori.copy
attach_copied_obj.tag_list.add(ori.tag_list) # tag关联 attach_copied_obj.tag_list.add(@ori.tag_list) # tag关联
attach_copied_obj.container = Course.find(id) attach_copied_obj.container = Course.find(id)
attach_copied_obj.created_on = Time.now attach_copied_obj.created_on = Time.now
attach_copied_obj.author_id = User.current.id attach_copied_obj.author_id = User.current.id
attach_copied_obj.is_public = 0 attach_copied_obj.is_public = 0
attach_copied_obj.copy_from = ori.copy_from.nil? ? ori.id : ori.copy_from #发送要添加copy_from attach_copied_obj.copy_from = @ori.copy_from.nil? ? @ori.id : @ori.copy_from #发送要添加copy_from
if attach_copied_obj.attachtype == nil if attach_copied_obj.attachtype == nil
attach_copied_obj.attachtype = 4 attach_copied_obj.attachtype = 4
end end
if attach_copied_obj.save if attach_copied_obj.save
# 更新引用次数 # 更新引用次数
quotes = ori.quotes.to_i + 1 quotes = @ori.quotes.to_i + 1
ori.update_attribute(:quotes, quotes) unless ori.nil? @ori.update_attribute(:quotes, quotes) unless @ori.nil?
ori.forwards << Forward.new(:to_type => attach_copied_obj.class.name, :to_id => attach_copied_obj.id,:created_at => Time.now) @ori.forwards << Forward.new(:to_type => attach_copied_obj.class.name, :to_id => attach_copied_obj.id,:created_at => Time.now)
end end
@save_message = attach_copied_obj.errors.full_messages @save_message = attach_copied_obj.errors.full_messages
end end
@ -1975,7 +2088,7 @@ class UsersController < ApplicationController
@score = @b_sort == "desc" ? "asc" : "desc" @score = @b_sort == "desc" ? "asc" : "desc"
user_project_ids = User.current.projects.map {|p| p.id} user_project_ids = User.current.projects.map {|p| p.id}
user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源
if(params[:type].blank? || params[:type] == "1") # 我的资源 if(params[:type] == "1") # 我的资源
# 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源 # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
if params[:status] == "2" if params[:status] == "2"
@attachments = get_course_resources(params[:id], user_course_ids, @order, @score) @attachments = get_course_resources(params[:id], user_course_ids, @order, @score)
@ -1989,7 +2102,7 @@ class UsersController < ApplicationController
# 公共资源库:所有公开资源或者我上传的私有资源 # 公共资源库:所有公开资源或者我上传的私有资源
@attachments = get_my_resources(params[:id], user_course_ids, user_project_ids, @order, @score) @attachments = get_my_resources(params[:id], user_course_ids, user_project_ids, @order, @score)
end end
elsif params[:type] == "6" # 公共资源 elsif (params[:type].blank? || params[:type] == "6") # 公共资源
if params[:status] == "2" if params[:status] == "2"
@attachments = get_course_resources_public( user_course_ids, @order, @score) @attachments = get_course_resources_public( user_course_ids, @order, @score)
elsif params[:status] == "3" elsif params[:status] == "3"
@ -2002,6 +2115,18 @@ class UsersController < ApplicationController
# 公共资源库:所有公开资源或者我上传的私有资源 # 公共资源库:所有公开资源或者我上传的私有资源
@attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score) @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
end 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 end
@type = params[:type] @type = params[:type]
@limit = 25 @limit = 25
@ -2032,7 +2157,8 @@ class UsersController < ApplicationController
project_ids.each do |project_id| project_ids.each do |project_id|
next if ori.blank? next if ori.blank?
@exist = false @exist = false
Project.find(project_id).attachments.each do |att| #如果课程中包含该资源 # 如果对象中包含该资源
Project.find(project_id).attachments.each do |att|
if att.id == ori.id || (!att.copy_from.nil? && !ori.copy_from.nil? && att.copy_from == ori.copy_from) || att.copy_from == ori.id || att.id == ori.copy_from if att.id == ori.id || (!att.copy_from.nil? && !ori.copy_from.nil? && att.copy_from == ori.copy_from) || att.copy_from == ori.id || att.id == ori.copy_from
att.created_on = Time.now att.created_on = Time.now
att.save att.save
@ -2065,7 +2191,7 @@ class UsersController < ApplicationController
@ori = ori @ori = ori
end end
elsif params[:send_ids].present? elsif params[:send_ids].present?
send_ids = params[:send_ids].split(" ") send_ids = params[:send_ids].split(",")
project_ids = params[:projects_ids] project_ids = params[:projects_ids]
if project_ids.nil? if project_ids.nil?
@flag = false @flag = false
@ -2116,7 +2242,7 @@ class UsersController < ApplicationController
@score = @b_sort == "desc" ? "asc" : "desc" @score = @b_sort == "desc" ? "asc" : "desc"
user_project_ids = User.current.projects.map {|p| p.id} user_project_ids = User.current.projects.map {|p| p.id}
user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源
if(params[:type].blank? || params[:type] == "1") # 我的资源 if(params[:type] == "1") # 我的资源
# 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源 # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
if params[:status] == "2" if params[:status] == "2"
@attachments = get_course_resources(params[:id], user_course_ids, @order, @score) @attachments = get_course_resources(params[:id], user_course_ids, @order, @score)
@ -2130,7 +2256,7 @@ class UsersController < ApplicationController
# 公共资源库:所有公开资源或者我上传的私有资源 # 公共资源库:所有公开资源或者我上传的私有资源
@attachments = get_my_resources(params[:id], user_course_ids, user_project_ids, @order, @score) @attachments = get_my_resources(params[:id], user_course_ids, user_project_ids, @order, @score)
end end
elsif params[:type] == "6" # 公共资源 elsif (params[:type].blank? || params[:type] == "6") # 公共资源
if params[:status] == "2" if params[:status] == "2"
@attachments = get_course_resources_public( user_course_ids, @order, @score) @attachments = get_course_resources_public( user_course_ids, @order, @score)
elsif params[:status] == "3" elsif params[:status] == "3"
@ -2143,6 +2269,18 @@ class UsersController < ApplicationController
# 公共资源库:所有公开资源或者我上传的私有资源 # 公共资源库:所有公开资源或者我上传的私有资源
@attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score) @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
end 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 end
@status = params[:status] @status = params[:status]
@type = params[:type] @type = params[:type]
@ -2200,7 +2338,7 @@ class UsersController < ApplicationController
end end
@ori = ori @ori = ori
elsif params[:send_ids].present? elsif params[:send_ids].present?
send_ids = params[:send_ids].split(" ") send_ids = params[:send_ids].split(",")
subfield_id = params[:subfield] subfield_id = params[:subfield]
if subfield_id.nil? if subfield_id.nil?
@flag = false @flag = false
@ -2245,7 +2383,7 @@ class UsersController < ApplicationController
@score = @b_sort == "desc" ? "asc" : "desc" @score = @b_sort == "desc" ? "asc" : "desc"
user_project_ids = User.current.projects.map {|p| p.id} user_project_ids = User.current.projects.map {|p| p.id}
user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源 user_course_ids = User.current.courses.map { |c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源
if(params[:type].blank? || params[:type] == "1") # 我的资源 if(params[:type] == "1") # 我的资源
# 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源 # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
if params[:status] == "2" if params[:status] == "2"
@attachments = get_course_resources(params[:id], user_course_ids, @order, @score) @attachments = get_course_resources(params[:id], user_course_ids, @order, @score)
@ -2259,7 +2397,7 @@ class UsersController < ApplicationController
# 公共资源库:所有公开资源或者我上传的私有资源 # 公共资源库:所有公开资源或者我上传的私有资源
@attachments = get_my_resources(params[:id], user_course_ids, user_project_ids, @order, @score) @attachments = get_my_resources(params[:id], user_course_ids, user_project_ids, @order, @score)
end end
elsif params[:type] == "6" # 公共资源 elsif (params[:type].blank? || params[:type] == "6") # 公共资源
if params[:status] == "2" if params[:status] == "2"
@attachments = get_course_resources_public( user_course_ids, @order, @score) @attachments = get_course_resources_public( user_course_ids, @order, @score)
elsif params[:status] == "3" elsif params[:status] == "3"
@ -2272,6 +2410,18 @@ class UsersController < ApplicationController
# 公共资源库:所有公开资源或者我上传的私有资源 # 公共资源库:所有公开资源或者我上传的私有资源
@attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score) @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
end 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 end
@type = params[:type] @type = params[:type]
@limit = 25 @limit = 25
@ -2608,12 +2758,12 @@ class UsersController < ApplicationController
# 获取公共资源 # 获取公共资源
def get_public_resources user_course_ids, user_project_ids, order, score def get_public_resources user_course_ids, user_project_ids, order, score
attachments = Attachment.where("(is_publish = 1 and is_public =1 and container_id is not null and container_type in('Project','OrgSubfield','Principal','Course')) ").order("#{order.nil? ? 'created_on' : order} #{score}") attachments = Attachment.where("(is_publish = 1 and is_public = 1 and container_id is not null and container_type in('Project','OrgSubfield','Principal','Course')) ").order("#{order.nil? ? 'created_on' : order} #{score}")
end end
# 获取公共资源搜索 # 获取公共资源搜索
def get_public_resources_search user_course_ids, user_project_ids, order, score, search def get_public_resources_search user_course_ids, user_project_ids, order, score, search
attachments = Attachment.where("is_publish = 1 and is_public = 1 and container_id is not null and container_type in('Project','OrgSubfield','Principal','Course') and (filename like :p)" ,:p => search).order("#{order.nil? ? 'created_on' : order} #{score}") attachments = Attachment.where("is_publish = 1 and is_public = 1 and container_id is not null and container_type in('Project','OrgSubfield','Principal','Course') and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
end end
# 获取我的资源 # 获取我的资源
@ -2633,10 +2783,20 @@ class UsersController < ApplicationController
# 获取我的课程资源 # 获取我的课程资源
def get_course_resources author_id, user_course_ids, order, score def get_course_resources author_id, user_course_ids, order, score
attchments = Attachment.where("(author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Course')"+ attchments = Attachment.where("(author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Course')"+
"or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')}) "or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0': user_course_ids.join(',')})
and is_publish = 1 and container_id is not null)" ).order("#{order.nil? ? 'created_on' : order} #{score}") and is_publish = 1 and container_id is not null)" ).order("#{order.nil? ? 'created_on' : order} #{score}")
end end
# # 获取我的私有资源分享结果
# def get_my_private_resources apply_ids, resource_type, order, score
# attachments = Attachment.where("id in (#{apply_ids.empty? ? '0': apply_ids.join(',')}) and container_type in(#{resource_type})").order("#{order.nil? ? 'created_on' : order} #{score}")
# end
#
# # 获取我的私有资源分享搜索结果
# def get_my_private_resources_search apply_ids, resource_type, order, score, search
# attachments = Attachment.where("id in (#{apply_ids.empty? ? '0': apply_ids.join(',')}) and container_type in(#{resource_type}) and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
# end
# 获取我的课程资源中搜索结果 # 获取我的课程资源中搜索结果
def get_course_resources_search author_id, user_course_ids, order, score, search def get_course_resources_search author_id, user_course_ids, order, score, search
attchments = Attachment.where("((author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Course')"+ attchments = Attachment.where("((author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Course')"+
@ -2657,7 +2817,7 @@ class UsersController < ApplicationController
# 获取我的项目资源 # 获取我的项目资源
def get_project_resources author_id, user_project_ids, order, score def get_project_resources author_id, user_project_ids, order, score
attchments = Attachment.where("(author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Project') "+ attchments = Attachment.where("(author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Project') "+
"or (container_type = 'Project' and container_id in (#{user_project_ids.empty? ? '0': user_project_ids.join(',')}) "or (container_type = 'Project' and container_id in (#{user_project_ids.empty? ? '0': user_project_ids.join(',')})
and is_publish = 1 and container_id is not null)").order("#{order.nil? ? 'created_on' : order} #{score}") and is_publish = 1 and container_id is not null)").order("#{order.nil? ? 'created_on' : order} #{score}")
end end
@ -2714,7 +2874,7 @@ class UsersController < ApplicationController
# 获取我的用户类型资源 # 获取我的用户类型资源
def get_principal_resources_public order, score def get_principal_resources_public order, score
attchments = Attachment.where("container_type = 'Principal'and container_id is not null and is_public =1").order("#{order.nil? ? 'created_on' : order} #{score}") attchments = Attachment.where("container_type = 'Principal' and is_public =1 and container_id is not null").order("#{order.nil? ? 'created_on' : order} #{score}")
end end
# 获取我的用户类型资源 # 获取我的用户类型资源
@ -2734,7 +2894,7 @@ class UsersController < ApplicationController
user_course_ids = User.current.courses.map { |c| c.is_delete == 0 && c.id} user_course_ids = User.current.courses.map { |c| c.is_delete == 0 && c.id}
user_project_ids = User.current.projects.map {|p| p.status != 9 && p.id } user_project_ids = User.current.projects.map {|p| p.status != 9 && p.id }
# user_org_ids = User.current.organizations.map {|o| o.id} # user_org_ids = User.current.organizations.map {|o| o.id}
if(params[:type].blank? || params[:type] == "1") # 我的资源 if( params[:type] == "1") # 我的资源
# 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源 # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
if params[:status] == "2" if params[:status] == "2"
@attachments = get_course_resources(params[:id], user_course_ids, @order, @score) @attachments = get_course_resources(params[:id], user_course_ids, @order, @score)
@ -2748,7 +2908,7 @@ class UsersController < ApplicationController
# 公共资源库:所有公开资源或者我上传的私有资源 # 公共资源库:所有公开资源或者我上传的私有资源
@attachments = get_my_resources(params[:id], user_course_ids, user_project_ids, @order, @score) @attachments = get_my_resources(params[:id], user_course_ids, user_project_ids, @order, @score)
end end
elsif params[:type] == "6" # 公共资源 elsif (params[:type].blank? || params[:type] == "6") # 公共资源
if params[:status] == "2" if params[:status] == "2"
@attachments = get_course_resources_public( user_course_ids, @order, @score) @attachments = get_course_resources_public( user_course_ids, @order, @score)
elsif params[:status] == "3" elsif params[:status] == "3"
@ -2761,6 +2921,18 @@ class UsersController < ApplicationController
# 公共资源库:所有公开资源或者我上传的私有资源 # 公共资源库:所有公开资源或者我上传的私有资源
@attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score) @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
end 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 end
@status = params[:status] @status = params[:status]
@type = params[:type] @type = params[:type]
@ -2780,8 +2952,7 @@ class UsersController < ApplicationController
# 导入资源 # 导入资源
def import_resources def import_resources
# 别人的资源库是没有权限去看的 # 别人的资源库是没有权限去看的
@user = User.find_by_login(params[:id]) if User.current.id != params[:id].to_i
if User.current != @user
render_403 render_403
return return
end end
@ -2939,8 +3110,21 @@ class UsersController < ApplicationController
@attachments = get_principal_resources_public_search(@order, @score, search) @attachments = get_principal_resources_public_search(@order, @score, search)
else else
# 公共资源库:所有公开资源或者我上传的私有资源 # 公共资源库:所有公开资源或者我上传的私有资源
@attachments = get_public_resources_search(user_course_ids, user_project_ids, @order, @score, search) @attachments = get_public_resources_search(user_course_ids, user_project_ids, @order, @score, search)
end 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_search(apply_ids, resource_type, @order, @score, search)
# @attachments
end end
@status = params[:status] @status = params[:status]
@type = params[:type] @type = params[:type]
@ -2995,6 +3179,7 @@ class UsersController < ApplicationController
@orgs = @user.organizations.select{|org| OrgSubfield.where("organization_id = #{org.id} and field_type='Resource'").count > 0} @orgs = @user.organizations.select{|org| OrgSubfield.where("organization_id = #{org.id} and field_type='Resource'").count > 0}
end end
end end
@type = params[:type]
@search = params[:search] @search = params[:search]
#这里仅仅是传递需要发送的资源id #这里仅仅是传递需要发送的资源id
@send_id = params[:send_id] @send_id = params[:send_id]
@ -3014,23 +3199,26 @@ class UsersController < ApplicationController
@c_sort = 2 @c_sort = 2
end end
sort_name = "updated_on" sort_name = "updated_at"
sort_type = @c_sort == 1 ? "asc" : "desc" sort_type = @c_sort == 1 ? "asc" : "desc"
# @courses = @user.courses.visible.where("is_delete =?", 0).order("#{sort_name} #{sort_type}") @courses = @user.courses.visible.where("is_delete =?", 0)
@courses = @user.courses.visible.where("is_delete =?", 0).select("courses.*,(SELECT MAX(updated_at) FROM `course_activities` WHERE course_activities.course_id = courses.id) AS #{sort_name}").order("#{sort_name} #{sort_type}") syllabus_ids = @courses.empty? ? '(-1)' : "(" + @courses.map{|course| !course.syllabus_id.nil? && course.syllabus_id}.join(",") + ")"
@syllabus = Syllabus.where("id in #{syllabus_ids} or user_id = #{User.current.id}").order("#{sort_name} #{sort_type}")
#根据 作业+资源数排序 #根据 作业+资源数排序
if @order.to_i == 2 if @order.to_i == 2
@type = 2 @type = 2
@courses.each do |course| @syllabus.each do |syllabus|
course[:infocount] = (User.current.admin? || User.current.allowed_to?(:as_teacher,course)) ? (course.homework_commons.count + visable_attachemnts_incourse(course).count) : (course.homework_commons.where("publish_time <= '#{Date.today}'").count + visable_attachemnts_incourse(course).count) count = 0
if course[:infocount] < 0 courses = @courses.where("syllabus_id = #{syllabus.id}")
course[:infocount] = 0 courses.each do |c|
count += (User.current.admin? || User.current.allowed_to?(:as_teacher,c)) ? (c.homework_commons.count + visable_attachemnts_incourse(c).count) : (c.homework_commons.where("publish_time <= '#{Date.today}'").count + visable_attachemnts_incourse(c).count)
end end
syllabus[:infocount] = count
end end
@c_sort == 1 ? (@courses = @courses.sort{|x,y| x[:infocount] <=> y[:infocount] }) : (@courses = @courses.sort{|x,y| y[:infocount] <=> x[:infocount]}) @c_sort == 1 ? (@syllabus = @syllabus.sort{|x,y| x[:infocount] <=> y[:infocount] }) : (@syllabus = @syllabus.sort{|x,y| y[:infocount] <=> x[:infocount]})
@courses = sortby_time_countcommon_nosticky @courses,sort_name @syllabus = sortby_time_countcommon_nosticky @syllabus,sort_name
else else
@type = 1 @type = 1
end end
@ -3038,10 +3226,10 @@ class UsersController < ApplicationController
#分页 #分页
@limit = 10 @limit = 10
@is_remote = true @is_remote = true
@atta_count = @courses.count @atta_count = @syllabus.count
@atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1 @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
@offset ||= @atta_pages.offset @offset ||= @atta_pages.offset
@courses = paginateHelper @courses,@limit @syllabus = paginateHelper @syllabus,@limit
respond_to do |format| respond_to do |format|
format.js format.js
@ -3094,6 +3282,50 @@ class UsersController < ApplicationController
end end
end end
def all_journals
if params[:type].present?
case params[:type]
when 'OrgDocumentComment'
obj = OrgDocumentComment.where('id = ?', params[:id].to_i).first
@journals = obj.children.reorder("created_at desc")
when 'Message'
obj = Message.where('id = ?', params[:id].to_i).first
@type = 'Message'
@is_course = params[:is_course]
@is_board = params[:is_board]
@user_activity_id = params[:div_id].to_i if params[:div_id]
comments = []
@journals = get_all_children(comments, obj)
when 'News'
obj = News.where('id = ?', params[:id].to_i).first
@journals = obj.comments.reorder("created_on desc")
when 'Syllabus'
obj = Syllabus.where('id = ?', params[:id].to_i).first
@journals = obj.comments.reorder("created_on desc")
when 'JournalsForMessage'
obj = JournalsForMessage.where('id = ?', params[:id].to_i).first
journals = []
@journals = get_all_children(journals, obj)
@type = 'JournalsForMessage'
@user_activity_id = params[:div_id].to_i if params[:div_id]
@allow_delete = params[:allow_delete]
when 'Issue'
obj = Issue.where('id = ?', params[:id].to_i).first
@journals = obj.journals.reorder("created_on desc")
when 'BlogComment'
obj = BlogComment.where('id = ?', params[:id].to_i).first
@journals = obj.children.reorder("created_on desc")
when 'HomeworkCommon'
obj = HomeworkCommon.where('id = ?', params[:id].to_i).first
@journals = obj.journals_for_messages.reorder("created_on desc")
@is_in_course = params[:is_in_course].to_i if params[:is_in_course]
@course_activity = params[:course_activity].to_i if params[:course_activity]
@is_teacher = User.current.allowed_to?(:as_teacher,obj.course)
@user_activity_id = params[:user_activity_id].to_i if params[:user_activity_id]
end
end
end
private private
def find_user def find_user

@ -3,10 +3,12 @@ class WechatsController < ActionController::Base
wechat_responder wechat_responder
include ApplicationHelper include ApplicationHelper
ROOT_URL = ENV["wechat_url"] || "#{Setting.protocol}://#{Setting.host_name}"
#ROOT_URL = "http://www.trustie.net"
# default text responder when no other match # default text responder when no other match
on :text do |request, content| on :text do |request, content|
request.reply.text "您的意见已收到" # Just echo #邀请码
sendBindClass(request, {invite_code: content})
end end
# When receive 'help', will trigger this responder # When receive 'help', will trigger this responder
@ -35,13 +37,13 @@ class WechatsController < ActionController::Base
# When subscribe user scan scene_id in public account # When subscribe user scan scene_id in public account
on :scan, with: 'scene_id' do |request, ticket| on :scan, with: 'scene_id' do |request, ticket|
request.reply.text "Subscribe user #{request[:FromUserName]} Ticket #{ticket}" sendBindClass(request, {ticket: ticket})
end end
# When no any on :scan responder can match subscribe user scaned scene_id # When no any on :scan responder can match subscribe user scaned scene_id
on :event, with: 'scan' do |request| on :event, with: 'scan' do |request|
if request[:EventKey].present? if request[:EventKey].present?
request.reply.text "event scan got EventKey #{request[:EventKey]} Ticket #{request[:Ticket]}" sendBindClass(request, {ticket: request[:Ticket]})
end end
end end
@ -62,6 +64,9 @@ class WechatsController < ActionController::Base
request.reply.text "User: #{request[:FromUserName]} click #{key}" request.reply.text "User: #{request[:FromUserName]} click #{key}"
end end
on :click, with: 'DEV' do |request, key|
request.reply.text "此功能正在开发中,很快就会上线,谢谢!"
end
# When user view URL in the menu button # When user view URL in the menu button
on :view, with: 'http://wechat.somewhere.com/view_url' do |request, view| on :view, with: 'http://wechat.somewhere.com/view_url' do |request, view|
request.reply.text "#{request[:FromUserName]} view #{view}" request.reply.text "#{request[:FromUserName]} view #{view}"
@ -121,117 +126,193 @@ class WechatsController < ActionController::Base
on :fallback, respond: 'fallback message' on :fallback, respond: 'fallback message'
on :click, with: 'FEEDBACK' do |request, key| on :click, with: 'FEEDBACK' do |request, key|
request.reply.text "如有反馈问题,请直接切入至输入框,发微信给我们即可" request.reply.text "如有反馈问题,请直接切换至输入框,发微信给我们即可"
end end
on :click, with: 'MY_NEWS' do |request, key| on :click, with: 'MY_NEWS' do |request, key|
default_msg(request) default_msg(request)
end end
on :click, with: 'JOIN_CLASS' do |request, key|
uw = user_binded?(request[:FromUserName])
unless uw
sendBind(request)
else
request.reply.text "请直接回复5位班级邀请码\n(不区分大小写):"
end
end
def sendBindClass(request, params)
begin
uw = user_binded?(request[:FromUserName])
if !uw
return sendBind(request)
else
return join_class(params, uw.user, request)
end
rescue => e
logger.error e.inspect
logger.error e.backtrace.join("\n")
return request.reply.text e
end
end
def default_msg(request) def default_msg(request)
uw = user_binded?(request[:FromUserName]) uw = user_binded?(request[:FromUserName])
if uw && uw.user if uw && uw.user
request.reply.text "欢迎回来, #{uw.user.show_name}" request.reply.text "欢迎回来, #{uw.user.show_name}"
else else
request.reply.text "欢迎关注Trustie创新实践社区"
sendBind(request) sendBind(request)
end end
end end
def sendBind(request) def sendBind(request)
news = (1..1).each_with_object([]) { |n, memo| memo << { title: '绑定登录', content: "您还未绑定确实的用户,请先绑定." } } news = (1..1).each_with_object([]) { |n, memo| memo << { title: '绑定登录', content: "欢迎使用Trustie创新实践服务平台
" } }
request.reply.news(news) do |article, n, index| # article is return object request.reply.news(news) do |article, n, index| # article is return object
url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{Wechat.config.appid}&redirect_uri=#{login_wechat_url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect" url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{Wechat.config.appid}&redirect_uri=#{ROOT_URL+'/wechat/user_activities'}&response_type=code&scope=snsapi_base&state=login#wechat_redirect"
pic_url = "#{ROOT_URL}/images/weixin_pic.jpg"
article.item title: "#{n[:title]}", article.item title: "#{n[:title]}",
description: n[:content], description: n[:content],
pic_url: 'https://www.trustie.net/images/trustie_logo2.png', pic_url: pic_url,
url: url url: url
end end
end end
def join_class(params, user, request)
course = nil
course = Course.where(qrcode: params[:ticket]).first if params[:ticket]
course = Course.where(invite_code: params[:invite_code]).first if params[:invite_code]
raise "班级不存在,请确认您的邀请码是否输入正确,谢谢!" unless course
def get_open_id cs = CoursesService.new
begin status = cs.join_course({invite_code: course.invite_code}, user)
raise "非法操作, code不存在" unless params[:code] logger.info status
openid = get_openid_from_code(params[:code]) if status[:state] != 0
raise "无法获取到openid" unless openid raise CoursesService::JoinCourseError.message(status[:state])
render :json => {status:0, openid: openid}
rescue Exception=>e
render :json => {status: -1, msg: e.message}
end end
end
def bind news = (1..1).each_with_object([]) { |n, memo| memo << { title: '恭喜您成功加入班级,开始学习吧!',
begin content: "课程名称: #{course.name}\n班级名称: #{course.name}\n任课老师: #{course.teacher.show_name}\n进入班级,和小伙伴愉快的学习吧!"} }
raise "非法操作, code不存在" unless params[:code] return request.reply.news(news) do |article, n, index| # article is return object
openid = get_openid_from_code(params[:code]) url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{Wechat.config.appid}&redirect_uri=#{ROOT_URL+'/wechat/user_activities?id='+course.id.to_s}&response_type=code&scope=snsapi_base&state=myclass#wechat_redirect"
raise "无法获取到openid" unless openid pic_url = "#{ROOT_URL}/images/wechat/class.jpg"
raise "此微信号已绑定用户, 不能重复绑定" if user_binded?(openid) article.item title: "#{n[:title]}",
description: n[:content],
user, last_login_on = User.try_to_login(params[:username], params[:password]) pic_url: pic_url,
raise "用户名或密码错误,请重新登录" unless user url: url
#补全用户信息
raise "此用户已经绑定了公众号" if user.user_wechat
UserWechat.create!(
openid: openid,
user: user
)
request.reply.text "欢迎加入Trustie创新实践社区"
render :json => {status:0, msg: "绑定成功"}
rescue Exception=>e
render :json => {status: -1, msg: e.message}
end end
end
def login
@code = params[:code] #TODO 安全性
render 'wechats/login', layout: 'base_wechat'
end end
private ### controller method
def get_openid_from_code(code) module Controllers
url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=#{Wechat.config.appid}&secret=#{Wechat.config.secret}&code=#{code}&grant_type=authorization_code" def get_bind
logger.debug url begin
body = URI.parse(url).read code = params[:code] || session[:wechat_code]
logger.debug body openid = get_openid_from_code(code)
JSON.parse(body)["openid"]
end
def user_binded?(openid) raise "无法获取到微信openid" unless openid
uw = UserWechat.where(openid: openid).first
end uw = UserWechat.where(openid: openid).first
raise "还未绑定trustie帐户" unless uw
logger.debug "get_bind ============= #{uw}"
def user_activity(user) user = uw.user
@user = user ::ApiKey.delete_all(user_id: user.id)
shield_project_ids = ShieldActivity.where("container_type='User' and container_id=#{@user.id} and shield_type='Project'").map(&:shield_id) key = ::ApiKey.create!(user_id: user.id)
shield_course_ids = ShieldActivity.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.projects.visible.map{|project| project.id}-shield_project_ids).empty? ? "(-1)" : "(" + (@user.projects.visible.map{|project| project.id}-shield_project_ids).join(",") + ")"
user_course_ids = (@user.courses.visible.map{|course| course.id}-shield_course_ids).empty? ? "(-1)" : "(" + (@user.courses.visible.map{|course| course.id}-shield_course_ids).join(",") + ")"
course_types = "('Message','News','HomeworkCommon','Poll','Course')"
project_types = "('Message','Issue','ProjectCreateInfo')"
principal_types = "JournalsForMessage"
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(','))+")" render :json =>{status: 0, token: key.access_token}
@user_activities = UserActivity.where("(container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types})" + rescue Exception=>e
"or (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types}) "+ render :json => {status: -1, message: e.message}
"or (container_type = 'Principal' and act_type= '#{principal_types}' and container_id = #{@user.id}) " + end
"or (container_type = 'Blog' and act_type= 'BlogComment' and container_id in #{blog_ids})").order('updated_at desc').limit(10).offset(@page * 10) end
def bind
begin
end code = params[:code] || session[:wechat_code]
openid = get_openid_from_code(code)
raise "无法获取到openid请在微信中打开本页面" unless openid
raise "此微信号已绑定用户,不能重复绑定" if user_binded?(openid)
user, last_login_on = User.try_to_login(params[:username], params[:password])
raise "用户名或密码错误,请重新输入" unless user
#补全用户信息
raise "此用户已经绑定过公众号,请换一个帐户试试" if user.user_wechat
UserWechat.create!(
openid: openid,
user: user
)
ws = WechatService.new
ws.binding_succ_notice(user.id, "您已成功绑定Trustie平台", user.login, format_time(Time.now))
render :json => {status:0, msg: "绑定成功"}
rescue Exception=>e
render :json => {status: -1, msg: e.message}
end
end
def login
session[:wechat_code] = params[:code] if params[:code]
openid = get_openid_from_code(params[:code])
@wechat_user = user_binded?(openid)
render 'wechats/login', layout: 'base_wechat'
end
def user_activities
session[:wechat_code] = params[:code] if params[:code]
@path = '/'+(params[:state] || '')
open_id = get_openid_from_code(params[:code]) rescue
unless open_id
render 'wechats/open_wechat', layout: nil and return
end
if params[:state] == 'myclass'
@course_id = params[:id];
end
session[:wechat_openid] = open_id
if params[:code]
redirect_to "/wechat/user_activities##{@path}?id=#{params[:id]}" and return
end
render 'wechats/user_activities', layout: nil
end
def process_activity(user_activity)
act= user_activity.act private
case user_activity.container_type.to_s def get_openid_from_code(code)
when 'Course' return 'oCnvgvz8R7QheXE-R9Kkr39j8Ndg' if code =='only-for-test'
when 'Project' openid = session[:wechat_openid]
case user_activity.act_type.to_s
when 'Issue' unless openid
[act.project.name.to_s+" | 项目问题", act.subject.to_s, url_to_avatar(act.author),"http://wechat.trustie.net/app.html#/issue/#{act.id}"] if code
openid = wechat.web_access_token(code)["openid"]
end end
end
if openid
session[:wechat_openid] = openid
end
return openid
end
def user_binded?(openid)
uw = UserWechat.where(openid: openid).first
end end
end end
include Controllers
end end

@ -54,15 +54,16 @@ class WordsController < ApplicationController
:reply_id => reply_user_id, :reply_id => reply_user_id,
:notes => content, :notes => content,
:is_readed => false} :is_readed => false}
@jfm = add_reply_adapter options @activity = params[:activity_id].nil? ? JournalsForMessage.find(parent_id) : JournalsForMessage.find(params[:activity_id].to_i)
@jfm = add_reply_adapter(@activity, options)
@save_succ = true if @jfm.errors.empty? @save_succ = true if @jfm.errors.empty?
if @save_succ if @save_succ
update_course_activity('JournalsForMessage',parent_id) update_course_activity('JournalsForMessage',@activity.id)
update_user_activity('JournalsForMessage',parent_id) update_user_activity('JournalsForMessage',@activity.id)
update_forge_activity('JournalsForMessage',parent_id) update_forge_activity('JournalsForMessage',@activity.id)
update_org_activity('JournalsForMessage',parent_id) update_org_activity('JournalsForMessage',@activity.id)
update_principal_activity('JournalsForMessage',parent_id) update_principal_activity('JournalsForMessage',@activity.id)
(JournalsForMessage.find parent_id).update_attribute(:updated_on,Time.now) @activity.update_attribute(:updated_on,Time.now)
end end
respond_to do |format| respond_to do |format|
# format.html { # format.html {
@ -76,8 +77,6 @@ class WordsController < ApplicationController
format.js { format.js {
#@reply_type = params[:reply_type] #@reply_type = params[:reply_type]
@user_activity_id = params[:user_activity_id] @user_activity_id = params[:user_activity_id]
@activity = JournalsForMessage.find(parent_id)
@is_activity = params[:is_activity] if params[:is_activity]
} }
end end
@ -92,13 +91,14 @@ class WordsController < ApplicationController
elsif @journal_destroyed.jour_type == "Course" elsif @journal_destroyed.jour_type == "Course"
@course = Course.find @journal_destroyed.jour_id @course = Course.find @journal_destroyed.jour_id
@jours_count = @course.journals_for_messages.where('m_parent_id IS NULL').count @jours_count = @course.journals_for_messages.where('m_parent_id IS NULL').count
@user_activity_id = params[:user_activity_id] if params[:user_activity_id]
@activity = JournalsForMessage.where("id = #{params[:activity_id].to_i}").first if params[:activity_id]
elsif @journal_destroyed.jour_type == "Principal" elsif @journal_destroyed.jour_type == "Principal"
@user = User.find(@journal_destroyed.jour_id) @user = User.find(@journal_destroyed.jour_id)
@jours_count = @user.journals_for_messages.where('m_parent_id IS NULL').count @jours_count = @user.journals_for_messages.where('m_parent_id IS NULL').count
@is_user = true @is_user = true
@user_activity_id = params[:user_activity_id] if params[:user_activity_id] @user_activity_id = params[:user_activity_id] if params[:user_activity_id]
@is_activity = params[:is_activity].to_i if params[:is_activity] @activity = JournalsForMessage.where("id = #{params[:activity_id].to_i}").first if params[:activity_id]
@activity = @journal_destroyed.parent if @journal_destroyed.parent
unless @activity unless @activity
redirect_to feedback_path(@user) redirect_to feedback_path(@user)
return return
@ -106,7 +106,7 @@ class WordsController < ApplicationController
elsif @journal_destroyed.jour_type == 'HomeworkCommon' elsif @journal_destroyed.jour_type == 'HomeworkCommon'
@homework = HomeworkCommon.find @journal_destroyed.jour_id @homework = HomeworkCommon.find @journal_destroyed.jour_id
if params[:user_activity_id] if params[:user_activity_id]
@user_activity_id = params[:user_activity_id] @user_activity_id = params[:user_activity_id].to_i
else else
@user_activity_id = -1 @user_activity_id = -1
end end
@ -264,6 +264,28 @@ class WordsController < ApplicationController
end end
end end
#课程大纲的回复
def leave_syllabus_message
if User.current.logged?
@user = User.current
@syllabus = Syllabus.find(params[:id]);
if params[:comment].size>0 && User.current.logged? && @user
feedback = Syllabus.add_syllabus_jour(@user, params[:comment], params[:id])
if (feedback.errors.empty?)
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,feedback[:id],OwnerTypeHelper::JOURNALSFORMESSAGE
end
redirect_to syllabus_path(@syllabus)
else
flash[:error] = feedback.errors.full_messages[0]
end
end
else
render_403
end
end
#作业的回复 #作业的回复
def leave_homework_message def leave_homework_message
if User.current.logged? if User.current.logged?
@ -337,6 +359,27 @@ class WordsController < ApplicationController
UserExtensions.introduction(user, message) UserExtensions.introduction(user, message)
redirect_to user_url(user.id) redirect_to user_url(user.id)
end end
#邮箱激活问题留言 留言成功给出提示框
def leave_email_activation_message
status = 1 #成功
me = User.find(params[:user])
if me
#课程使者id=1
@user = User.find(1)
if params[:text].size>0 && @user
# @user.add_jour(me, params[:text])
#私信
message = "<span style='color:red;'>【未收到激活邮件的用户反馈,用户邮箱:"+me.mail+"】</span><br>"+params[:text]
@user.journals_for_messages << JournalsForMessage.new(:user_id => me.id, :notes => message, :reply_id => 0, :status => true, :is_readed => false, :private => 1)
else
status = 0
end
render :json => status
else
render_403
end
end
private private
@ -374,28 +417,44 @@ class WordsController < ApplicationController
obj obj
end end
def add_reply_adapter options def add_reply_adapter obj, options
#modify by nwb #modify by nwb
#添加对课程留言的支持 #添加对课程留言的支持
#留言回复应该不关系其所属的Class而关心的是其所属的父留言 #留言回复应该不关系其所属的Class而关心的是其所属的父留言
obj = obj_distinguish_url_origin || User.find_by_id(2) case obj.jour_type
if obj.kind_of? User when 'Principal'
obj.add_jour(nil, nil, nil, options) obj.jour.add_jour(nil, nil, nil, options)
elsif obj.kind_of? Project when 'Project'
Project.add_new_jour(nil, nil, obj.id, options) Project.add_new_jour(nil, nil, obj.jour_id, options)
elsif obj.kind_of? Course when 'Course'
Course.add_new_jour(nil, nil, obj.id, options) Course.add_new_jour(nil, nil, obj.jour_id, options)
elsif obj.kind_of? Bid when 'Bid'
obj.add_jour(nil, nil, nil, options) obj.jour.add_jour(nil, nil, nil, options)
elsif obj.kind_of? Contest when 'Contest'
obj.add_jour(nil, nil, obj.id, options) #new added obj.jour.add_jour(nil, nil, obj.jour_id, options)
elsif obj.kind_of? Softapplication when 'Softapplication'
obj.add_jour(nil, nil, obj.id, options) #new added obj.jour.add_jour(nil, nil, obj.jour_id, options)
elsif obj.kind_of? HomeworkAttach when 'HomeworkAttach'
obj.add_jour(nil, nil, obj.id, options) #new added obj.jour.add_jour(nil, nil, obj.jour_id, options)
else
raise "create reply obj unknow type.#{obj.class}"
end end
# obj = obj_distinguish_url_origin || User.find_by_id(2)
# if obj.kind_of? User
# obj.add_jour(nil, nil, nil, options)
# elsif obj.kind_of? Project
# Project.add_new_jour(nil, nil, obj.id, options)
# elsif obj.kind_of? Course
# Course.add_new_jour(nil, nil, obj.id, options)
# elsif obj.kind_of? Bid
# obj.add_jour(nil, nil, nil, options)
# elsif obj.kind_of? Contest
# obj.add_jour(nil, nil, obj.id, options) #new added
# elsif obj.kind_of? Softapplication
# obj.add_jour(nil, nil, obj.id, options) #new added
# elsif obj.kind_of? HomeworkAttach
# obj.add_jour(nil, nil, obj.id, options) #new added
# else
# raise "create reply obj unknow type.#{obj.class}"
# end
end end
#######end of message #######end of message
end end

@ -10,14 +10,14 @@ class ZipdownController < ApplicationController
#勿删 before_filter :authorize, :only => [:assort,:download_user_homework] #勿删 before_filter :authorize, :only => [:assort,:download_user_homework]
SAVE_FOLDER = "#{Rails.root}/files" SAVE_FOLDER = "#{Rails.root}/files"
OUTPUT_FOLDER = "#{Rails.root}/files/archiveZip" OUTPUT_FOLDER = "#{Rails.root}/files/archiveZip"
MAX_PATH = 50
#统一下载功能 #统一下载功能
def download def download
if User.current.logged? if User.current.logged?
begin begin
if params[:base64file] if params[:base64file]
file = Base64.decode64(params[:base64file]) file = decode64(params[:base64file])
file = file.sub('*', '+')
send_file "#{OUTPUT_FOLDER}/#{file}", :filename => filename_for_content_disposition(file), :type => detect_content_type(file) send_file "#{OUTPUT_FOLDER}/#{file}", :filename => filename_for_content_disposition(file), :type => detect_content_type(file)
else else
send_file "#{OUTPUT_FOLDER}/#{params[:file]}", :filename => filename_for_content_disposition(params[:filename]), :type => detect_content_type(params[:file]) send_file "#{OUTPUT_FOLDER}/#{params[:file]}", :filename => filename_for_content_disposition(params[:filename]), :type => detect_content_type(params[:file])
@ -125,7 +125,11 @@ class ZipdownController < ApplicationController
end end
def encode64(str) def encode64(str)
Base64.encode64(str).sub('+', '*') Base64.urlsafe_encode64(str)
end
def decode64(str)
Base64.urlsafe_decode64(str)
end end
def zip_homework_common homework_common def zip_homework_common homework_common
@ -242,6 +246,12 @@ class ZipdownController < ApplicationController
def zipping(zip_name_refer, files_paths, output_path, is_attachment=false, not_exist_file=[]) def zipping(zip_name_refer, files_paths, output_path, is_attachment=false, not_exist_file=[])
rename_zipfile = zip_name_refer ||= "#{Time.now.to_i.to_s}.zip" rename_zipfile = zip_name_refer ||= "#{Time.now.to_i.to_s}.zip"
# 文件名过长
if rename_zipfile.size > MAX_PATH
rename_zipfile = rename_zipfile[0,rename_zipfile.size-4][0,MAX_PATH-4] + rename_zipfile[-4,4]
end
zipfile_name = "#{output_path}/#{rename_zipfile}" zipfile_name = "#{output_path}/#{rename_zipfile}"
Dir.mkdir(File.dirname(zipfile_name)) unless File.exist?(File.dirname(zipfile_name)) Dir.mkdir(File.dirname(zipfile_name)) unless File.exist?(File.dirname(zipfile_name))

@ -182,7 +182,7 @@ module ApiHelper
timeIntoFormat = 0 timeIntoFormat = 0
updateAtValue = "" updateAtValue = ""
if timePassed < 0 if timePassed < 0
updateAtValue = "时间有问题" updateAtValue = "刚刚"
elsif timePassed < ONE_MINUTE elsif timePassed < ONE_MINUTE
updateAtValue = "1分钟前" updateAtValue = "1分钟前"
elsif timePassed < ONE_HOUR elsif timePassed < ONE_HOUR
@ -489,4 +489,26 @@ module ApiHelper
self.update_attribute(:praise_num, self.praise_num.to_i - num) self.update_attribute(:praise_num, self.praise_num.to_i - num)
end end
class Errors
def self.define_error(arr)
@errors = {}
arr.each_with_index { |item, index|
if index %2 == 1
@errors[arr[index-1]] = item
end
}
if arr.count % 2== 1
@default_error = arr.last
else
@default_error = "未知错误"
end
end
def self.message(msg_id)
@errors[msg_id] || @default_error
end
end
end end

@ -49,6 +49,29 @@ module ApplicationHelper
return result return result
end end
# 判断某个资源是否可以申请
def attach_show_allow attach_id
attachment = Attachment.find(attach_id)
case attachment.container_type
when "Project"
User.current.member_of?(attachment.container) ? true : false
when "Course"
User.current.member_of_course?(attachment.container) ? true : false
when "OrgSubfield"
User.current.member_of_org?(attachment.container.organization) ? true : false
when "Principal"
User.current.id == attachment.author_id ? true : false
end
end
# 判断某个私有资源是否可以发送下载权限
# 结果为true不能下载false可以下载
def private_attachment_allow attachment_id
attach = Attachment.find(attachment_id)
# 条件取否result结果为true则不能下载
result = attach.is_public == 0 && attach.author != User.current && !attach.get_apply_resource_status(attach.id, User.current.id) && !attach_show_allow(attach)
end
# Time 2015-03-24 15:27:29 # Time 2015-03-24 15:27:29
# Author lizanle # Author lizanle
# Description 从硬盘上删除对应的资源文件 # Description 从硬盘上删除对应的资源文件
@ -780,22 +803,22 @@ module ApplicationHelper
end end
# 获取Gitlab版本库提交总数 # 获取Gitlab版本库提交总数
def commit_count(project) def commit_count(project, branch)
g = Gitlab.client g = Gitlab.client
#add by hx #add by hx
if g.commits(project.gpid , :page=>200).count > 0 if g.commits(project.gpid, :ref_name => @rev , :page=>200).count > 0
count = 4020 count = 4020
elsif g.commits(project.gpid , :page=>25).count==0 elsif g.commits(project.gpid , :page=>25, :ref_name => branch).count==0
count = count_commits(project.gpid , 0 , 25) count = count_commits(project.gpid , 0 , 25)
elsif g.commits(project.gpid , :page=>50).count ==0 elsif g.commits(project.gpid , :page=>50, :ref_name => branch).count ==0
count = count_commits(project.gpid , 25 , 50)+ 25 * 20 count = count_commits(project.gpid , 25 , 50)+ 25 * 20
elsif g.commits(project.gpid , :page=>75).count ==0 elsif g.commits(project.gpid , :page=>75, :ref_name => branch).count ==0
count = count_commits(project.gpid , 50 , 75)+ 50 * 20 count = count_commits(project.gpid , 50 , 75)+ 50 * 20
elsif g.commits(project.gpid , :page=>100).count== 0 elsif g.commits(project.gpid , :page=>100, :ref_name => branch).count== 0
count = count_commits(project.gpid , 75 , 100) + 75 * 20 count = count_commits(project.gpid , 75 , 100) + 75 * 20
elsif g.commits(project.gpid , :page=>125).count==0 elsif g.commits(project.gpid , :page=>125, :ref_name => branch).count==0
count = count_commits(project.gpid , 100 , 125) + 100 * 20 count = count_commits(project.gpid , 100 , 125) + 100 * 20
elsif g.commits(project.gpid , :page=>150).count==0 elsif g.commits(project.gpid , :page=>150, :ref_name => branch).count==0
count = count_commits(project.gpid , 125 , 150) + 125 * 20 count = count_commits(project.gpid , 125 , 150) + 125 * 20
else else
count = count_commits(project.gpid , 150 ,200) + 150 * 20 count = count_commits(project.gpid , 150 ,200) + 150 * 20
@ -809,7 +832,7 @@ module ApplicationHelper
if $g.commits(project_id,:page => page).count == 0 if $g.commits(project_id,:page => page).count == 0
break break
else else
count = count + $g.commits(project_id,:page => page).count count = count + $g.commits(project_id, :ref_name => @rev, :page => page).count
end end
end end
return count return count
@ -1056,8 +1079,10 @@ module ApplicationHelper
title << @organization.name title << @organization.name
elsif @user elsif @user
title << @user.try(:realname) title << @user.try(:realname)
elsif @syllabus
title << @syllabus.title
else else
title << User.current.try(:realname) title << (User.current.id == 2 ? "未登录" : User.current.try(:realname))
end end
if first_page.nil? || first_page.web_title.nil? if first_page.nil? || first_page.web_title.nil?
title << Setting.app_title unless Setting.app_title == title.last title << Setting.app_title unless Setting.app_title == title.last
@ -2074,12 +2099,12 @@ module ApplicationHelper
def attachment_history_candown attachment_history def attachment_history_candown attachment_history
if attachment_history.container_type == "Course" if attachment_history.container_type == "Course"
course = Course.find(attachment_history.container_id) course = Course.find(attachment_history.container_id)
candown = User.current.member_of?(course) || (course.is_public && attachment_history.is_public == 1) candown = User.current.member_of_course?(course) || (course.is_public && attachment_history.is_public == 1)
elsif attachment_history.container_type == "Project" elsif attachment_history.container_type == "Project"
project = Project.find(attachment_history.container_id) project = Project.find(attachment_history.container_id)
candown = User.current.member_of?(project) || (project.is_public && attachment_history.is_public == 1) candown = User.current.member_of?(project) || (project.is_public && attachment_history.is_public == 1)
elsif attachment_history.container_type == "OrgSubfield" elsif attachment_history.container_type == "OrgSubfield"
org = OrgSubfield.find(attachment_history.container_id) org = OrgSubfield.find(attachment_history.container_id).organization
candown = User.current.member_of_org?(org) || (org.organization.is_public && attachment_history.is_public == 1 && (User.current.logged? || org.organization.allow_guest_download?)) candown = User.current.member_of_org?(org) || (org.organization.is_public && attachment_history.is_public == 1 && (User.current.logged? || org.organization.allow_guest_download?))
end end
end end
@ -2094,20 +2119,20 @@ module ApplicationHelper
candown= User.current.member_of?(project) || (project.is_public && attachment.is_public == 1) candown= User.current.member_of?(project) || (project.is_public && attachment.is_public == 1)
elsif attachment.container.is_a?(Project) elsif attachment.container.is_a?(Project)
project = attachment.container project = attachment.container
candown= User.current.member_of?(project) || (project.is_public && attachment.is_public == 1) candown = User.current.member_of?(project) || (attachment.is_public == 1) || attachment.get_status_by_attach(User.current.id) == 2
elsif (attachment.container.has_attribute?(:board) || attachment.container.has_attribute?(:board_id)) && attachment.container.board && elsif (attachment.container.has_attribute?(:board) || attachment.container.has_attribute?(:board_id)) && attachment.container.board &&
attachment.container.board.project attachment.container.board.project
project = attachment.container.board.project project = attachment.container.board.project
candown = User.current.member_of?(project) || (project.is_public && attachment.is_public == 1) candown = User.current.member_of?(project) || (project.is_public && attachment.is_public == 1)
elsif (attachment.container.has_attribute?(:course) ||attachment.container.has_attribute?(:course_id) ) && attachment.container.course elsif (attachment.container.has_attribute?(:course) ||attachment.container.has_attribute?(:course_id) ) && attachment.container.course
course = attachment.container.course course = attachment.container.course
candown = User.current.member_of_course?(course) || (course.is_public==1 && attachment.is_public == 1) candown = User.current.member_of_course?(course) || (attachment.is_public == 1) || attachment.get_status_by_attach(User.current.id) == 2
elsif attachment.container.is_a?(Course) elsif attachment.container.is_a?(Course)
course = attachment.container course = attachment.container
candown= User.current.member_of_course?(course) || (course.is_public==1 && attachment.is_public == 1) candown= User.current.member_of_course?(course) || (attachment.is_public == 1) || attachment.get_status_by_attach(User.current.id) == 2
elsif attachment.container.is_a?(OrgSubfield) elsif attachment.container.is_a?(OrgSubfield)
org = attachment.container.organization org = attachment.container.organization
candown = User.current.member_of_org?(org) || (org.is_public && attachment.is_public == 1) candown = User.current.member_of_org?(org) || (attachment.is_public == 1) || attachment.get_status_by_attach(User.current.id) == 2
elsif attachment.container.is_a?(OrgDocumentComment) elsif attachment.container.is_a?(OrgDocumentComment)
org = attachment.container.organization org = attachment.container.organization
candown = User.current.member_of_org?(org) || (org.is_public && attachment.is_public == 1) candown = User.current.member_of_org?(org) || (org.is_public && attachment.is_public == 1)
@ -3080,9 +3105,10 @@ def named_attachment_url_without_domain(id, filename, option={})
attachment_id = (Attachment === id ? id.id : id) attachment_id = (Attachment === id ? id.id : id)
Setting.protocol + "://" + Setting.host_name + "/attachments/" + attachment_id.to_s + "/" + filename Setting.protocol + "://" + Setting.host_name + "/attachments/" + attachment_id.to_s + "/" + filename
end end
#判断是否为默认的组织栏目 #判断是否为默认的组织栏目
def is_default_field? field def is_default_field? field
(field.name == 'activity' || field.name == 'course' || field.name == 'project') && field.field_type == 'default' (field.name == 'activity' || field.name == 'course' || field.name == 'project' ) && field.field_type == 'default'
end end
def host_with_protocol def host_with_protocol
@ -3103,6 +3129,26 @@ def get_reply_parents parents_rely, comment
parents_rely parents_rely
end end
#获取回复的所有父节点(不包括根节点)
def get_reply_parents_no_root parents_rely, comment
if !comment.parent.nil? && !comment.parent.parent.nil?
parents_rely << comment.parent
get_reply_parents_no_root parents_rely, comment.parent
end
parents_rely
end
#获取所有子节点
def get_all_children result, jour
if (jour.kind_of? JournalsForMessage) || (jour.kind_of? Message)
jour.children.each do |jour_child|
result << jour_child
get_all_children result, jour_child
end
end
result.sort! { |a,b| b.created_on <=> a.created_on }
end
#将有置顶属性的提到数组前面 #将有置顶属性的提到数组前面
def sort_by_sticky topics def sort_by_sticky topics
tmpTopics = [] tmpTopics = []
@ -3237,6 +3283,7 @@ def strip_html(text,len=0,endss="...")
ss = "" ss = ""
if text.length>0 if text.length>0
ss=text.gsub(/<\/?.*?>/, '').strip ss=text.gsub(/<\/?.*?>/, '').strip
ss = ss.gsub(/&nbsp;/, ' ')
if len > 0 && ss.length > len if len > 0 && ss.length > len
ss = ss[0, len] + endss ss = ss[0, len] + endss
@ -3247,3 +3294,31 @@ def strip_html(text,len=0,endss="...")
end end
return ss return ss
end end
def get_hw_index(hw,is_teacher)
if is_teacher
homeworks = hw.course.homework_commons.order("created_at asc")
else
homeworks = hw.course.homework_commons.where("publish_time <= '#{Date.today}'").order("created_at asc")
end
hw_ids = homeworks.map{|hw| hw.id} if !homeworks.empty?
index = hw_ids.index(hw.id)
return index
end
def get_group_member_names work
result = ""
unless work.nil?
work.student_work_projects.each do |member|
user = User.where(:id => member.user_id).first
unless user.nil?
if result != ""
result += "#{user.show_name}"
else
result += user.show_name
end
end
end
end
result
end

@ -44,9 +44,9 @@ module CoursesHelper
def visible_excellent_course obj def visible_excellent_course obj
# if course.is_pu # if course.is_pu
end end
# 返回x项目成员数量即roles表中定义的所有成员 # 返回x项目成员数量即roles表中定义的所有成员
def projectCount project def projectCount project
#searchCountByRoles project, AllPeople #searchCountByRoles project, AllPeople
project.members.count project.members.count
end end
@ -147,10 +147,10 @@ module CoursesHelper
# 返回学生数量即roles表中定义的Reporter # 返回学生数量即roles表中定义的Reporter
#def studentCount project #def studentCount project
# searchStudent(project).count # searchStudent(project).count
# or # or
# searchStudent(project).count # searchStudent(project).count
# end # end
# 判断用户是否是课程的管理员 # 判断用户是否是课程的管理员
# add by nwb # add by nwb
@ -225,11 +225,11 @@ module CoursesHelper
#end #end
# 注意:此方法有问题,速度慢且结果不准 # 注意:此方法有问题,速度慢且结果不准
# alias studentCountOrigin studentCount # alias studentCountOrigin studentCount
#def studentCount course #def studentCount course
# count = studentCountOrigin course # count = studentCountOrigin course
#garble count #garble count
# end # end
#获取课程所有成员 #获取课程所有成员
def course_all_member course def course_all_member course
@ -265,7 +265,7 @@ module CoursesHelper
def garble count def garble count
count = count.round( 1-count.to_s.size ).to_i count = count.round( 1-count.to_s.size ).to_i
return count.to_s if count.to_s.size.eql?(1) return count.to_s if count.to_s.size.eql?(1)
count.to_s << '+' count.to_s << '+'
end end
# ===================================================================================== # =====================================================================================
@ -274,7 +274,7 @@ module CoursesHelper
#searchPeopleByRoles(project, TeacherRoles) #searchPeopleByRoles(project, TeacherRoles)
members = [] members = []
project.members.includes(:user).each do |m| project.members.includes(:user).each do |m|
members << m if m && m.user && m.user.allowed_to?(:as_teacher,project) members << m if m && m.user && m.user.allowed_to?(:as_teacher,project)
end end
members members
end end
@ -304,8 +304,8 @@ module CoursesHelper
members members
end end
def searchStudent_by_name project, name def searchStudent_by_name project, name
#searchPeopleByRoles(project, StudentRoles) #searchPeopleByRoles(project, StudentRoles)
members = [] members = []
@ -324,29 +324,29 @@ module CoursesHelper
mems = [] mems = []
if name != "" if name != ""
name = name.to_s.downcase name = name.to_s.downcase
members.each do |m| members.each do |m|
username = m.user[:lastname].to_s.downcase + m.user[:firstname].to_s.downcase username = m.user[:lastname].to_s.downcase + m.user[:firstname].to_s.downcase
if(m.user[:login].to_s.downcase.include?(name) || m.user.user_extensions[:student_id].to_s.downcase.include?(name) || username.include?(name)) if(m.user[:login].to_s.downcase.include?(name) || m.user.user_extensions[:student_id].to_s.downcase.include?(name) || username.include?(name))
mems << m mems << m
end end
end end
else else
mems = members mems = members
end end
mems mems
end end
def searchgroupmember_by_name members, name, group def searchgroupmember_by_name members, name, group
#searchPeopleByRoles(project, StudentRoles) #searchPeopleByRoles(project, StudentRoles)
mems = [] mems = []
if name != "" if name != ""
members.each do |m| members.each do |m|
if m.course_group_id == group.id if m.course_group_id == group.id
username = m.user[:lastname].to_s + m.user[:firstname].to_s username = m.user[:lastname].to_s + m.user[:firstname].to_s
if(m.user[:login].to_s.include?(name) || m.user.user_extensions[:student_id].to_s.include?(name) || username.include?(name)) if(m.user[:login].to_s.include?(name) || m.user.user_extensions[:student_id].to_s.include?(name) || username.include?(name))
mems << m mems << m
end
end
end end
end
end
else else
mems = members mems = members
end end
@ -458,7 +458,7 @@ module CoursesHelper
content = content_tag('ul', content) content = content_tag('ul', content)
content_tag('div', content, :class => "tabs") content_tag('div', content, :class => "tabs")
end end
def findCourseTime project def findCourseTime project
str = "" str = ""
begin begin
@ -671,6 +671,22 @@ module CoursesHelper
is_current_term || is_next_term is_current_term || is_next_term
end end
#课程大纲下拉框
def syllabus_option
type = []
option1 = []
option1 << "请选择课程"
option1 << 0
type << option1
Syllabus.all.each do |syllabus|
option = []
option << syllabus.title
option << syllabus.id
type << option
end
type
end
#获取课程动态 #获取课程动态
def get_course_activity courses, activities def get_course_activity courses, activities
@course_ids=activities.keys() @course_ids=activities.keys()
@ -683,9 +699,9 @@ module CoursesHelper
#file_count #file_count
Attachment.where(container_id: @course_ids, container_type: Course).where("created_on>?", date_from).each do |attachment| Attachment.where(container_id: @course_ids, container_type: Course).where("created_on>?", date_from).each do |attachment|
if attachment.is_public? || User.current.member_of_course?(@course) || User.current.admin? if attachment.is_public? || User.current.member_of_course?(@course) || User.current.admin?
activities[attachment.container_id]+=1 activities[attachment.container_id]+=1
else else
activities[attachment.container_id] activities[attachment.container_id]
end end
end end
@ -704,8 +720,8 @@ module CoursesHelper
#news #news
News.where(course_id: @course_ids).where("created_on>?",date_from).each do |news| News.where(course_id: @course_ids).where("created_on>?",date_from).each do |news|
if news.author.member_of_course?(@course) if news.author.member_of_course?(@course)
activities[news.course_id]+=1 activities[news.course_id]+=1
end end
end end
#homework_count #homework_count
@ -777,6 +793,15 @@ module CoursesHelper
result result
end 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 <= '#{Date.today}'").count
end
homework_num
end
def zh_course_role role def zh_course_role role
if role == "TeachingAsistant" if role == "TeachingAsistant"
result = l(:label_TA) result = l(:label_TA)

@ -23,7 +23,7 @@ module OrganizationsHelper
when 'activity' then when 'activity' then
return '动态' return '动态'
when 'course' then when 'course' then
return '课程' return '班级'
when 'project' then when 'project' then
return '项目' return '项目'
end end
@ -42,11 +42,15 @@ module OrganizationsHelper
Attachment.find_by_sql("SELECT * FROM `attachments` where container_id =#{field_id} and container_type = 'OrgSubfield' and is_public =1 order by created_on limit 6;") Attachment.find_by_sql("SELECT * FROM `attachments` where container_id =#{field_id} and container_type = 'OrgSubfield' and is_public =1 order by created_on limit 6;")
end end
# 获取两种类型的隐藏状态数量大于0说明是可见
def double_field_show org
OrgSubfield.find_by_sql("SELECT * FROM `org_subfields` where organization_id = #{org.id} and (field_type = 'Compstu' or field_type = 'Comptec') and hide = 0;").count
end
def get_attach_org2(field) def get_attach_org2(field)
org_attachments = field.attachments org_attachments = field.attachments
attachments = User.current.admin? ? org_attachments : visable_attachemnts(org_attachments) attachments = User.current.admin? ? org_attachments.first(5) : visable_attachemnts(org_attachments).first(5)
return attachments.sort_by{|x| x.created_on}.reverse.first(6) attachments.sort_by{|x| x.created_on}.reverse
# Attachment.find_by_sql("SELECT * FROM `attachments` where container_id =#{field_id} and container_type = 'OrgSubfield' and is_public =1 order by created_on limit 6;")
end end
# 从内容中获取路径 # 从内容中获取路径
@ -59,6 +63,108 @@ module OrganizationsHelper
end end
end end
def org_user_by_type obj
case obj.act_type
when "Message"
obj.act.author
when "News"
obj.act.author
when "HomeworkCommon"
obj.act.user
when "Issue"
obj.act.author
end
end
def org_title_by_type obj
case obj.act_type
when "Message"
obj.act.parent_id.nil? ? obj.act.subject : obj.act.parent.subject
when "News"
obj.act.title
when "HomeworkCommon"
obj.act.name
when "Issue"
obj.act.subject
end
end
def org_content_by_type obj
case obj.act_type
when "Message"
obj.act.parent_id.nil? ? obj.act.content : obj.act.parent.content
when "News"
obj.act.description
when "HomeworkCommon"
obj.act.description
when "Issue"
obj.act.description
end
end
def org_time_by_type obj
case obj.act_type
when "Message"
obj.act.created_on
when "News"
obj.act.created_on
when "HomeworkCommon"
obj.act.created_at
when "Issue"
obj.act.created_on
end
end
def org_reply_count_type obj
case obj.act_type
when "HomeworkCommon"
obj.act.journals_for_messages.count
when "Issue"
obj.act.journals.count
when "Message"
obj.act.children.count
when "News"
obj.act.comments_count
end
end
# 组织的栏目类型标题
def subfield_title_type obj
case obj.org_act_type
when "OrgDocumentComment"
obj.org_act.title
when "Message"
obj.org_act.parent_id.nil? ? obj.org_act.subject : obj.org_act.parent.subject
when "News"
obj.org_act.title
when "Issue"
obj.org_act.subject
end
end
# 组织的栏目类型时间
def subfield_time_type obj
case obj.org_act_type
when "OrgDocumentComment"
obj.org_act.updated_at
when "Message"
obj.org_act.updated_on
when "News"
obj.org_act.created_on
end
end
def subfield_reply_count_type obj
case obj.org_act_type
when "OrgDocumentComment"
obj.org_act.children.count
when "Message"
obj.org_act.children.count
when "News"
obj.org_act.comments_count
end
end
#排列下拉框 #排列下拉框
def subfield_status_option def subfield_status_option
type = [] type = []
@ -66,34 +172,14 @@ module OrganizationsHelper
option1 << "左一" option1 << "左一"
option1 << "1" option1 << "1"
type << option1 type << option1
# option2 = [] option2 = []
# option2 << "中一" option2 << "左二"
# option2 << "2" option2 << "2"
# type << option2 type << option2
option3 = [] option3 = []
option3 << "" option3 << ""
option3 << "3" option3 << "3"
type << option3 type << option3
option4 = []
option4 << "左三"
option4 << "4"
type << option4
option5 = []
option5 << "左四"
option5 << "5"
type << option5
option6 = []
option6 << "右一"
option6 << "6"
type << option6
option7 = []
option7 << "右二"
option7 << "7"
type << option7
option8 = []
option8 << "右三"
option8 << "8"
type << option8
type type
end end
@ -104,18 +190,22 @@ module OrganizationsHelper
option1 << "左一" option1 << "左一"
option1 << "1" option1 << "1"
type << option1 type << option1
option2 = []
option2 << "左二"
option2 << "2"
type << option2
option3 = [] option3 = []
option3 << "左二" option3 << ""
option3 << "3" option3 << "2"
type << option3 type << option3
option4 = [] option4 = []
option4 << "左三" option4 << "右一"
option4 << "4" option4 << "3"
type << option4 type << option4
option6 = [] option5 = []
option6 << "右一" option5 << "右二"
option6 << "6" option5 << "5"
type << option6 type << option5
type type
end end
@ -128,30 +218,38 @@ module OrganizationsHelper
when 3 when 3
resulet = "左二" resulet = "左二"
when 4 when 4
resulet = "左三"
when 5
resulet = "左四"
when 6
resulet = "右一" resulet = "右一"
when 7 when 5
resulet = "右二" resulet = "右二"
when 8 when 6
resulet = "右三" resulet = "右三"
end end
end end
# 系统栏目只有管理员才能看到
def subfield_to_addmin?(org)
# if User.current.admin?
@organization.org_subfields.order("priority")
# else
# @organization.org_subfields.select { |os| (os.field_type != "Comptec" && os.field_type != "Compstu" && os.field_type != "Comppro" && os.field_type != "Compcou" && os.field_type != "Compact") }.sort_by {|os| os.priority}
# end
end
def get_subfield_acts field def get_subfield_acts field
org_subfield = OrgSubfield.find(field.id) unless field.nil?
org_subfield_ids = org_subfield.org_document_comments.map(&:id) << 0 org_subfield = OrgSubfield.find(field.id)
org_acts = OrgActivity.where("(org_act_type='OrgDocumentComment'and org_act_id in (#{org_subfield_ids.join(",")})) || (container_type='OrgSubfield' and container_id=#{org_subfield.id})").order('updated_at desc') org_subfield_ids = org_subfield.org_document_comments.map(&:id) << 0
org_acts org_acts = OrgActivity.where("(org_act_type='OrgDocumentComment'and org_act_id in (#{org_subfield_ids.join(",")})) || (container_type='OrgSubfield' and container_id=#{org_subfield.id})").order('updated_at desc')
end
end
def allow_to_create?(org, type)
!org_subfield_had_created?(org, type) && User.current.admin?
end end
def org_subfield_had_created?(org, type) def org_subfield_had_created?(org, type)
sub_field = org.org_subfields.select{|subfield| subfield.field_type == type} sub_field = org.org_subfields.select{|subfield| subfield.field_type == type}
result = sub_field.length > 0 ? true : false result = sub_field.length > 0 ? true : false
result
end end
def org_subfield_type(field) def org_subfield_type(field)
@ -166,9 +264,20 @@ module OrganizationsHelper
result = "教师" result = "教师"
when "Complex" when "Complex"
result = "综合" result = "综合"
when "Compcou"
result = "课程"
when "Comppro"
result = "项目"
when "Compact"
result = "动态"
end end
end end
# 获取最新动态
# def get_latest_acts
# acts = UserActivity.find_by_sql("SELECT * FROM `user_activities` where act_type in ('HomeworkCommon', 'news', 'message', 'Issue') and (container_type = 'Course' or container_type = 'Project') order by created_at limit 10;")
# end
def org_teacher_resource_count user def org_teacher_resource_count user
results = Attachment.find_by_sql("SELECT * FROM attachments where author_id = #{user.id};").count results = Attachment.find_by_sql("SELECT * FROM attachments where author_id = #{user.id};").count
end end
@ -187,4 +296,33 @@ module OrganizationsHelper
from users u, user_extensions ue where u.id = ue.user_id and ue.identity=0 and u.excellent_teacher =1 order by course_count desc").first(5) from users u, user_extensions ue where u.id = ue.user_id and ue.identity=0 and u.excellent_teacher =1 order by course_count desc").first(5)
end end
def excellent_students
User.find_by_sql("select u.*, ue.technical_title, ue.school_id,(select count(*) from courses where courses.tea_id = u.id) as course_count
from users u, user_extensions ue where u.id = ue.user_id and ue.identity = 1 and u.excellent_student = 1 order by course_count desc").first(5)
end
def excellent_teachers_hide? org
org.org_subfields.where(:field_type => "Comptec").first.hide
end
def excellent_students_hide? org
org.org_subfields.where(:field_type => "Compstu").first.hide
end
#当前学期(2015春季学期)
def current_time_and_term course
str = ""
term = cur_course_term
if (course.time == course.end_time && course.term == course.end_term) || (course.end_term.nil? && course.end_time.nil?) || course.time > Time.now.year
str = course.time.to_s + course.term.to_s
elsif course.time == Time.now.year && set_term_value(cur_course_term) <= set_term_value(course.term)
str = course.time.to_s + course.term.to_s
elsif course.end_time < Time.now.year || (course.end_time == Time.now.year && set_term_value(cur_course_term) >= set_term_value(course.term))
str = course.end_time.to_s + course.end_term.to_s
else
str = Time.now.year.to_s + cur_course_term.to_s
end
str
end
end end

@ -7,5 +7,6 @@ module OwnerTypeHelper
BID = 6 BID = 6
JOURNALSFORMESSAGE = 7 JOURNALSFORMESSAGE = 7
HOMEWORKCOMMON = 8 HOMEWORKCOMMON = 8
BLOGCOMMENT=9 BLOGCOMMENT = 9
SYLLABUS = 10
end end

@ -0,0 +1,97 @@
# encoding: utf-8
module QualityAnalysisHelper
def sqale_rating_status val
arr = []
if val < 5
arr << "很好"
arr << "b_green2"
elsif val. > 5 && val < 10
arr << "较好"
arr << "b_slow_yellow"
elsif val > 10 && val < 20
arr << "中等"
arr << "b_yellow"
elsif val > 20 && val < 50
arr << "较差"
arr << "b_slow_red"
elsif val > 20
arr << "很差"
arr << "b_red"
end
end
def complexity_status val
arr = []
if val < 10
arr << "良好"
arr << "b_green2"
elsif val > 10 && val < 15
arr << "较高"
arr << "b_yellow"
elsif val > 15
arr << "很高"
arr << "b_red"
end
end
def duplicated_lines_density_status val
arr = []
if val < 30
arr << "良好"
arr << "b_green2"
elsif val > 30 && val < 50
arr << "较高"
arr << "b_yellow"
elsif val > 50
arr << "很高"
arr << "b_red"
end
end
def comment_lines_density_status val
arr = []
if val < 20
arr << "较低"
arr << "b_yellow"
elsif val > 20 && val < 50
arr << "正常"
arr << "b_green2"
elsif val > 50
arr << "较高"
arr << "b_red"
end
end
def score_sqale_rating val
if val > 0 && val < 5
"5"
elsif val > 5 && val < 10
"4"
elsif val > 10 && val < 20
"3"
elsif val > 20 && val < 50
"2"
elsif val > 20
"1"
end
end
def lines_scale val
if val.to_i < 5000
"小型"
elsif val.to_i >5000 && val.to_i < 50000
"中型"
else
"大型"
end
end
#统计答题百分比,统计结果保留两位小数
def statistics_result_percentage(e, t)
e = e.to_f
t = t.to_f
t == 0 ? 0 : format("%.2f", e*100/t)
end
end

@ -41,6 +41,11 @@ module RepositoriesHelper
identifiers.include?(iden) ? false :true identifiers.include?(iden) ? false :true
end end
def quality_analysis login, rep_id
long_rep_id = "#{login}:#{rep_id}"
QualityAnalysis.where(:sonar_name => long_rep_id).first
end
# 获取文件目录的最新动态 # 获取文件目录的最新动态
def get_trees_last_changes(project_id, rev, ent_name) def get_trees_last_changes(project_id, rev, ent_name)
g = Gitlab.client g = Gitlab.client

@ -0,0 +1,72 @@
# encoding: utf-8
module SyllabusesHelper
def get_syllabuses_by_tag(tag_name)
Syllabus.tagged_with(tag_name).order('updated_at desc')
end
def teacher_count syllabus
count = 0
courses = syllabus.courses
unless courses.empty?
courses.each do |c|
count += TeacherAndAssistantCount c
end
end
count
end
def student_count syllabus
count = 0
courses = syllabus.courses
unless courses.empty?
courses.each do |c|
count += studentCount c
end
end
count
end
def file_count syllabus
count = 0
courses = syllabus.courses
unless courses.empty?
courses.each do |c|
count += visable_attachemnts_incourse(c).count
end
end
count
end
#课程性质下拉框
def syllabus_type
type = []
option1 = []
option2 = []
option3 = []
option4 = []
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
end
end

@ -23,6 +23,8 @@ module TagsHelper
@obj= Course.find_by_id(obj_id) @obj= Course.find_by_id(obj_id)
when '10' when '10'
@obj = Attachment.find_by_id(obj_id) @obj = Attachment.find_by_id(obj_id)
when '11'
@obj = Syllabus.find_by_id(obj_id)
else else
raise Exception, '[TagsHelper] ===> tag type unknow.' raise Exception, '[TagsHelper] ===> tag type unknow.'
end end

@ -32,7 +32,7 @@ module UsersHelper
def get_resource_type type def get_resource_type type
case type case type
when 'Course' when 'Course'
'课程资源' '班级资源'
when 'Project' when 'Project'
'项目资源' '项目资源'
when 'Issue' when 'Issue'
@ -122,11 +122,11 @@ module UsersHelper
when 'homework' when 'homework'
'作业消息' '作业消息'
when 'course_message' when 'course_message'
'课程讨论' '班级讨论'
when 'course_news' when 'course_news'
'课程通知' '班级通知'
when 'poll' when 'poll'
'课程问卷' '班级问卷'
when 'issue' when 'issue'
'项目任务' '项目任务'
when 'forge_message' when 'forge_message'
@ -147,7 +147,9 @@ module UsersHelper
# 统计未读消息数 # 统计未读消息数
def unviewed_message(user) def unviewed_message(user)
course_count = CourseMessage.where("user_id =? and viewed =?", user, 0).count courses = user.courses.where("is_delete = 1")
course_ids = courses.empty? ? "(-1)" : "(" + courses.map{|course| course.id}.join(",") + ")"
course_count = CourseMessage.where("user_id =? and viewed =? and course_id not in #{course_ids}", user, 0).count
forge_count = ForgeMessage.where("user_id =? and viewed =?", user, 0).count forge_count = ForgeMessage.where("user_id =? and viewed =?", user, 0).count
org_count = OrgMessage.where("user_id =? and viewed =?", user, 0).count org_count = OrgMessage.where("user_id =? and viewed =?", user, 0).count
user_feedback_count = UserFeedbackMessage.where("user_id =? and viewed =?", user, 0).count user_feedback_count = UserFeedbackMessage.where("user_id =? and viewed =?", user, 0).count

@ -0,0 +1,3 @@
class ApplyAddSchools < ActiveRecord::Base
attr_accessible :address, :city, :name, :province, :remarks, :school_id, :status
end

@ -0,0 +1,19 @@
class ApplyResource < ActiveRecord::Base
# status1. 等待回复 2.审核通过 3.已拒绝
attr_accessible :attachment_id, :status, :user_id, :container_type, :container_id, :apply_user_id, :content
belongs_to :user
belongs_to :attachment
has_many :course_messages, :class_name => 'CourseMessage', :as => :course_message, :dependent => :destroy
after_create :act_as_apply_resource_message
def act_as_apply_resource_message
self.course_messages << CourseMessage.new(:user_id => self.apply_user_id, :course_id => -1, :viewed => false, :status => 0, )
# REDO:发送邮件
# Mailer.run.apply_for_resource_request(self.container_id, User.current)
end
def find_attachment attachment_id
Attachment.find(attachment_id)
end
end

@ -24,6 +24,7 @@ class Attachment < ActiveRecord::Base
belongs_to :course, foreign_key: 'container_id', conditions: "attachments.container_type = 'Course'" 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 :org_subfield, foreign_key: 'container_id', conditions: "attachements.container_type = 'OrgSubfield'"
belongs_to :organization, foreign_key: 'container_id', conditions: "attachements.container_type = 'Organization'" belongs_to :organization, foreign_key: 'container_id', conditions: "attachements.container_type = 'Organization'"
belongs_to :syllabus, foreign_key: 'container_id', conditions: "attachements.container_type = 'Syllabus'"
belongs_to :softapplication, foreign_key: 'container_id', conditions: "attachments.container_type = 'Softapplication'" belongs_to :softapplication, foreign_key: 'container_id', conditions: "attachments.container_type = 'Softapplication'"
belongs_to :author, :class_name => "User", :foreign_key => "author_id" belongs_to :author, :class_name => "User", :foreign_key => "author_id"
belongs_to :attachmentstype, :foreign_key => "attachtype",:primary_key => "id" belongs_to :attachmentstype, :foreign_key => "attachtype",:primary_key => "id"
@ -35,6 +36,7 @@ class Attachment < ActiveRecord::Base
# end # end
include UserScoreHelper include UserScoreHelper
has_many :attachment_histories has_many :attachment_histories
has_many :apply_resources, :dependent => :destroy
validates :filename, presence: true, length: {maximum: 254} validates :filename, presence: true, length: {maximum: 254}
validates :author, presence: true validates :author, presence: true
@ -139,6 +141,12 @@ class Attachment < ActiveRecord::Base
} }
) )
end end
def get_apply_resource_status attachment_id, author_id
status = ApplyResource.where("attachment_id =? and user_id =?", attachment_id, author_id).first.try(:status)
status == 2
end
# add by nwb # add by nwb
# 公开的项目id列表 # 公开的项目id列表
def self.public_project_id def self.public_project_id
@ -536,6 +544,11 @@ class Attachment < ActiveRecord::Base
end end
end end
# 获取资源申请状态
def get_status_by_attach user_id
ApplyResource.where("user_id =? and attachment_id =?", user_id, self.id).first.try(:status)
end
private private
# Physically deletes the file from the file system # Physically deletes the file from the file system

@ -21,7 +21,7 @@ class BlogComment < ActiveRecord::Base
after_save :add_user_activity after_save :add_user_activity
after_update :update_activity after_update :update_activity
after_create :update_parent_time, :blog_wechat_message after_create :update_parent_time
before_destroy :destroy_user_activity before_destroy :destroy_user_activity
scope :like, lambda {|arg| scope :like, lambda {|arg|
@ -76,17 +76,29 @@ class BlogComment < ActiveRecord::Base
def project def project
end end
#博客回复微信模板消息 def creator_user
def blog_wechat_message self.author
ws = WechatService.new end
if self.parent_id.nil?
self.author.watcher_users.each do |watcher| def created_time
content = strip_html self.author.try(:realname) + " 发表了博客:" + self.title.html_safe, 200 self.created_at
ws.message_update_template watcher.id, "blog_comment", self.id, "#{l(:label_new_blog_template)}", content, format_time(self.created_at)
end
else
content = strip_html self.content.html_safe, 200
ws.comment_template self.parent.author_id, "blog_comment", self.parent_id, "#{l(:label_blog_comment_template)}", self.author.try(:realname), format_time(self.created_at), content
end
end end
def content_detail
self.content
end
#博客回复微信模板消息
# def blog_wechat_message
# ws = WechatService.new
# if self.parent_id.nil?
# self.author.watcher_users.each do |watcher|
# content = strip_html self.author.try(:realname) + " 发表了博客:" + self.title.html_safe, 200
# ws.message_update_template watcher.id, "blog_comment", self.id, "#{l(:label_new_blog_template)}", content, format_time(self.created_at)
# end
# else
# content = strip_html self.content.html_safe, 200
# ws.comment_template self.parent.author_id, "blog_comment", self.parent_id, "#{l(:label_blog_comment_template)}", self.author.try(:realname), format_time(self.created_at), content
# end
# end
end end

@ -41,15 +41,15 @@ class Comment < ActiveRecord::Base
after_destroy :down_course_score after_destroy :down_course_score
def act_as_system_message def act_as_system_message
ws = WechatService.new #ws = WechatService.new
if self.commented.course if self.commented.course
if self.author_id != self.commented.author_id if self.author_id != self.commented.author_id
self.course_messages << CourseMessage.new(:user_id => self.commented.author_id, :course_id => self.commented.course.id, :viewed => false) self.course_messages << CourseMessage.new(:user_id => self.commented.author_id, :course_id => self.commented.course.id, :viewed => false)
count = ShieldWechatMessage.where("container_type='User' and container_id=#{self.commented.author_id} and shield_type='Course' and shield_id=#{self.commented.course.id}").count # count = ShieldWechatMessage.where("container_type='User' and container_id=#{self.commented.author_id} and shield_type='Course' and shield_id=#{self.commented.course.id}").count
if count == 0 # if count == 0
content = strip_html self.comments.html_safe, 200 # content = strip_html self.comments.html_safe, 200
ws.comment_template self.commented.author_id, "course_notice", self.id, "#{l(:label_notice_comment_template)}", self.author.try(:realname), format_time(self.created_on), content # ws.comment_template self.commented.author_id, "course_notice", self.id, "#{l(:label_notice_comment_template)}", self.author.try(:realname), format_time(self.created_on), content
end # end
end end
else # 项目相关 else # 项目相关
if self.author_id != self.commented.author_id if self.author_id != self.commented.author_id
@ -104,4 +104,16 @@ class Comment < ActiveRecord::Base
end end
end end
def creator_user
self.author
end
def created_time
self.created_on
end
def content_detail
self.comments
end
end end

@ -1,3 +1,5 @@
#coding=utf-8
require 'elasticsearch/model' require 'elasticsearch/model'
class Course < ActiveRecord::Base class Course < ActiveRecord::Base
include Redmine::SafeAttributes include Redmine::SafeAttributes
@ -24,6 +26,7 @@ class Course < ActiveRecord::Base
#belongs_to :project, :class_name => 'Course', :foreign_key => :extra, primary_key: :identifier #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 :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 :school, :class_name => 'School', :foreign_key => :school_id #定义一个方法school该方法通过school_id来调用School表
belongs_to :syllabus
# has_many :bid # 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 :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 :memberships, :class_name => 'Member'
@ -64,7 +67,7 @@ class Course < ActiveRecord::Base
acts_as_attachable :view_permission => :view_course_files, acts_as_attachable :view_permission => :view_course_files,
:delete_permission => :manage_files :delete_permission => :manage_files
validates_presence_of :password, :term,:name validates_presence_of :term,:name
validates_format_of :class_period, :with =>/^[1-9]\d*$/ validates_format_of :class_period, :with =>/^[1-9]\d*$/
validates_format_of :name,:with =>/^[^ ]+[a-zA-Z0-9_\u4e00-\u9fa5\s\S]+$/ validates_format_of :name,:with =>/^[^ ]+[a-zA-Z0-9_\u4e00-\u9fa5\s\S]+$/
validates_length_of :description, :maximum => 10000 validates_length_of :description, :maximum => 10000
@ -87,10 +90,12 @@ class Course < ActiveRecord::Base
'description', 'description',
'class_period', 'class_period',
'open_student', 'open_student',
'is_delete' 'is_delete',
'syllabus_id'
acts_as_customizable acts_as_customizable
scope :not_deleted, lambda{where(is_delete: 0)}
scope :all_course scope :all_course
scope :active, lambda { where(:status => STATUS_ACTIVE) } scope :active, lambda { where(:status => STATUS_ACTIVE) }
scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) } scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) }
@ -404,6 +409,7 @@ class Course < ActiveRecord::Base
self.course_messages << CourseMessage.new(:user_id => self.tea_id, :course_id => self.id, :viewed => false) self.course_messages << CourseMessage.new(:user_id => self.tea_id, :course_id => self.id, :viewed => false)
end end
#项目与课程分离后,很多课程的名称等信息为空,这些数据信息存储在项目表中!!就是数据兼容的问题 #项目与课程分离后,很多课程的名称等信息为空,这些数据信息存储在项目表中!!就是数据兼容的问题
#def name #def name
# read_attribute('name') || Project.find_by_identifier(self.extra).try(:name) # read_attribute('name') || Project.find_by_identifier(self.extra).try(:name)
@ -421,12 +427,14 @@ class Course < ActiveRecord::Base
# __elasticsearch__.delete_document # __elasticsearch__.delete_document
# end # end
def create_course_ealasticsearch_index def create_course_ealasticsearch_index
return if Rails.env.development?
if self.is_public == 1 and self.is_delete == 0 #公开 和 没有被删除的课程才被索引 if self.is_public == 1 and self.is_delete == 0 #公开 和 没有被删除的课程才被索引
self.__elasticsearch__.index_document self.__elasticsearch__.index_document
end end
end end
def update_course_ealasticsearch_index def update_course_ealasticsearch_index
return if Rails.env.development?
if self.is_public == 1 and self.is_delete == 0 #如果是初次更新成为公开或者恢复被删除的情况,会报错,那么这条记录尚未被索引过。没有报错就是更新的其他属性 if self.is_public == 1 and self.is_delete == 0 #如果是初次更新成为公开或者恢复被删除的情况,会报错,那么这条记录尚未被索引过。没有报错就是更新的其他属性
begin begin
self.__elasticsearch__.update_document self.__elasticsearch__.update_document
@ -443,6 +451,7 @@ class Course < ActiveRecord::Base
end end
def delete_course_ealasticsearch_index def delete_course_ealasticsearch_index
return if Rails.env.development?
begin begin
self.__elasticsearch__.delete_document self.__elasticsearch__.delete_document
rescue => e rescue => e
@ -450,6 +459,35 @@ class Course < ActiveRecord::Base
end end
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
response = Wechat.api.qrcode_create_scene(invite_code)
logger.debug "response = #{response}"
self.qrcode = response['ticket']
save! && reload
ticket = qrcode
end
ticket
end
end end

@ -5,8 +5,7 @@ class CourseActivity < ActiveRecord::Base
belongs_to :course belongs_to :course
belongs_to :user belongs_to :user
has_many :user_acts, :class_name => 'UserAcivity',:as =>:act has_many :user_acts, :class_name => 'UserAcivity',:as =>:act
after_save :add_user_activity, :add_org_activity after_create :add_course_lead,:add_user_activity, :add_org_activity
after_create :add_course_lead
before_destroy :destroy_user_activity, :destroy_org_activity before_destroy :destroy_user_activity, :destroy_org_activity
#在个人动态里面增加当前动态 #在个人动态里面增加当前动态

@ -1,5 +1,7 @@
class CourseMessage < ActiveRecord::Base class CourseMessage < ActiveRecord::Base
# status说明 status在课程不同的类型区分不同的功能 status = 9 作品的提交记录 # status说明 status在课程不同的类型区分不同的功能 status = 9 作品的提交记录
# ApplyResource status:
# 0: 发送申请 1回复允许申请 2拒绝申请消息
# HomeworkCommonstatus # HomeworkCommonstatus
# nil发布了作业 1作业截止时间到了提醒2:开启匿评; 3关闭匿评 4匿评开始失败 5申请引用作业, 6:申请结果 # nil发布了作业 1作业截止时间到了提醒2:开启匿评; 3关闭匿评 4匿评开始失败 5申请引用作业, 6:申请结果
# apply_user_id: 申请者的用户id # apply_user_id: 申请者的用户id

@ -20,7 +20,7 @@ class ForgeActivity < ActiveRecord::Base
validates :forge_act_id,presence: true validates :forge_act_id,presence: true
validates :forge_act_type, presence: true validates :forge_act_type, presence: true
has_many :user_acts, :class_name => 'UserAcivity',:as =>:act has_many :user_acts, :class_name => 'UserAcivity',:as =>:act
after_save :add_user_activity, :add_org_activity after_create :add_user_activity, :add_org_activity
before_destroy :destroy_user_activity, :destroy_org_activity before_destroy :destroy_user_activity, :destroy_org_activity
#在个人动态里面增加当前动态 #在个人动态里面增加当前动态

@ -29,7 +29,7 @@ class HomeworkCommon < ActiveRecord::Base
:description => :description, :description => :description,
:author => :author, :author => :author,
:url => Proc.new {|o| {:controller => 'student_work', :action => 'index', :homework => o.id}} :url => Proc.new {|o| {:controller => 'student_work', :action => 'index', :homework => o.id}}
after_create :act_as_activity, :send_mail after_create :act_as_activity, :send_mail,:act_as_course_message
after_update :update_activity after_update :update_activity
after_save :act_as_course_activity after_save :act_as_course_activity
after_destroy :delete_kindeditor_assets after_destroy :delete_kindeditor_assets
@ -59,12 +59,12 @@ class HomeworkCommon < ActiveRecord::Base
else else
self.course.members.each do |m| self.course.members.each do |m|
# if m.user_id != self.user_id # if m.user_id != self.user_id
self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.course_id, :viewed => false) #self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.course_id, :viewed => false)
#count = ShieldWechatMessage.where("container_type='User' and container_id=#{m.user_id} and shield_type='Course' and shield_id=#{self.course_id}").count 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 if count == 0
# ws = WechatService.new ws = WechatService.new
# ws.homework_template(m.user_id, "homework", self.id, "#{l(:label_new_homework_template)}", self.course.name, self.name.html_safe, self.end_time.to_s + " 23:59:59") ws.homework_message_notice(m.user_id, "homework", self.id, "#{m.user.show_name}#{l(:label_new_homework_template)}", self.course.name, "新作业:"+ self.name.html_safe, "作业内容请点击“详情”查看。")
#end end
# end # end
end end
end end
@ -108,15 +108,15 @@ class HomeworkCommon < ActiveRecord::Base
end end
#修改作业后发送微信模板消息 #修改作业后发送微信模板消息
def wechat_message # def wechat_message
self.course.members.each do |member| # self.course.members.each do |member|
count = ShieldWechatMessage.where("container_type='User' and container_id=#{member.user_id} and shield_type='Course' and shield_id=#{self.course_id}").count # count = ShieldWechatMessage.where("container_type='User' and container_id=#{member.user_id} and shield_type='Course' and shield_id=#{self.course_id}").count
if count == 0 # if count == 0
ws = WechatService.new # ws = WechatService.new
ws.homework_template(member.user_id, "homework", self.id, "#{l(:label_update_homework_template)}", self.course.name, self.name.html_safe, self.end_time.to_s + " 23:59:59") # ws.homework_template(member.user_id, "homework", self.id, "#{l(:label_update_homework_template)}", self.course.name, self.name.html_safe, self.end_time.to_s + " 23:59:59")
end # end
end # end
end # end
delegate :language_name, :language, :to => :homework_detail_programing delegate :language_name, :language, :to => :homework_detail_programing

@ -160,14 +160,27 @@ class Issue < ActiveRecord::Base
unless self.author_id == self.assigned_to_id unless self.author_id == self.assigned_to_id
self.forge_messages << ForgeMessage.new(:user_id => self.assigned_to_id, :project_id => self.project_id, :viewed => false) self.forge_messages << ForgeMessage.new(:user_id => self.assigned_to_id, :project_id => self.project_id, :viewed => false)
end end
self.project.members.each do |m| # self.project.members.each do |m|
count = ShieldWechatMessage.where("container_type='User' and container_id=#{m.user_id} and shield_type='Project' and shield_id=#{self.project_id}").count # count = ShieldWechatMessage.where("container_type='User' and container_id=#{m.user_id} and shield_type='Project' and shield_id=#{self.project_id}").count
if m.user_id != self.author_id && count == 0 # if m.user_id != self.author_id && count == 0
ws = WechatService.new # ws = WechatService.new
content = strip_html self.project.name + " 有新缺陷了:" + self.subject.html_safe, 200 # str = " 有新缺陷了: "
ws.message_update_template m.user_id, "issues", self.id, "#{l(:label_new_issue_template)}", content, format_time(self.created_on) # case self.tracker_id
end # when 1
end # str = " 有新缺陷了: "
# when 2
# str = " 有新功能了: "
# when 3
# str = " 有新支持了: "
# when 4
# str = " 有新任务了: "
# when 5
# str = " 有新周报了: "
# end
# content = strip_html self.project.name + str + self.subject.html_safe, 200
# ws.message_update_template m.user_id, "issues", self.id, "#{l(:label_new_issue_template)}", content, format_time(self.created_on)
# end
# end
if self.tracker_id == 5 if self.tracker_id == 5
self.project.members.each do |m| self.project.members.each do |m|
if m.roles.first.to_s.include?("Manager") && m.user_id != self.author_id && m.user_id != self.assigned_to_id if m.roles.first.to_s.include?("Manager") && m.user_id != self.author_id && m.user_id != self.assigned_to_id

@ -55,7 +55,6 @@ class Journal < ActiveRecord::Base
# fq # fq
after_save :act_as_activity,:be_user_score, :act_as_forge_message, act_as_at_message(:notes, :user_id) after_save :act_as_activity,:be_user_score, :act_as_forge_message, act_as_at_message(:notes, :user_id)
after_create :issue_wechat_message
# end # end
#after_destroy :down_user_score #after_destroy :down_user_score
#before_save :be_user_score #before_save :be_user_score
@ -138,6 +137,18 @@ class Journal < ActiveRecord::Base
end end
## ##
def creator_user
self.user
end
def created_time
self.created_on
end
def content_detail
self.notes
end
private private
def split_private_notes def split_private_notes
@ -238,9 +249,11 @@ class Journal < ActiveRecord::Base
end end
#缺陷回复微信模板消息 #缺陷回复微信模板消息
def issue_wechat_message # def issue_wechat_message
ws = WechatService.new # if !self.notes.nil? && self.notes.gsub(' ','') != ''
content = strip_html self.notes.html_safe, 200 # ws = WechatService.new
ws.comment_template self.issue.author_id, "issues", self.journalized_id, "#{l(:label_issue_comment_template)}", self.user.try(:realname), format_time(self.created_on), content # content = strip_html self.notes.html_safe, 200
end # ws.comment_template self.issue.author_id, "issues", self.journalized_id, "#{l(:label_issue_comment_template)}", self.user.try(:realname), format_time(self.created_on), content
# end
# end
end end

@ -259,14 +259,25 @@ class JournalsForMessage < ActiveRecord::Base
if self.m_parent_id.nil? if self.m_parent_id.nil?
if self.user_id != self.jour.user_id if self.user_id != self.jour.user_id
self.course_messages << CourseMessage.new(:user_id => self.jour.user_id,:course_id => self.jour.course.id, :viewed => false) self.course_messages << CourseMessage.new(:user_id => self.jour.user_id,:course_id => self.jour.course.id, :viewed => false)
# count = ShieldWechatMessage.where("container_type='User' and container_id=#{self.jour.user_id} and shield_type='Course' and shield_id=#{self.jour.course_id}").count
# if count == 0
# ws = WechatService.new
# #content = truncate(strip_tags(self.notes.to_s), length: 200)
# content = strip_html self.notes.html_safe, 200
# ws.comment_template self.jour.user_id, "homework", self.jour_id, "#{l(:label_homework_comment_template)}", self.user.try(:realname), format_time(self.created_on), content
# end
end
else
if self.user_id != self.parent.user_id
self.course_messages << CourseMessage.new(:user_id => self.parent.user_id,:course_id => self.jour.course.id, :viewed => false)
# count = ShieldWechatMessage.where("container_type='User' and container_id=#{self.parent.user_id} and shield_type='Course' and shield_id=#{self.jour.course_id}").count
# if count == 0
# ws = WechatService.new
# #content = truncate(strip_tags(self.notes.to_s), length: 200)
# content = strip_html self.notes.html_safe, 200
# ws.comment_template self.parent.user_id, "homework", self.jour_id, "#{l(:label_new_second_comment_template)}", self.user.try(:realname), format_time(self.created_on), content
# end
end end
end
count = ShieldWechatMessage.where("container_type='User' and container_id=#{self.jour.user_id} and shield_type='Course' and shield_id=#{self.jour.course_id}").count
if count == 0
ws = WechatService.new
#content = truncate(strip_tags(self.notes.to_s), length: 200)
content = strip_html self.notes.html_safe, 200
ws.comment_template self.jour.user_id, "homework", self.jour_id, "#{l(:label_homework_comment_template)}", self.user.try(:realname), format_time(self.created_on), content
end end
end end
end end
@ -282,7 +293,7 @@ class JournalsForMessage < ActiveRecord::Base
if self.user_id != self.jour_id # 过滤自己给自己的留言消息 if self.user_id != self.jour_id # 过滤自己给自己的留言消息
receivers << self.jour receivers << self.jour
content = strip_html self.notes, 200 content = strip_html self.notes, 200
ws.message_update_template self.jour_id, "journal_for_message", self.id, "#{l(:label_new_journals_template)}", content, format_time(self.created_on) ws.journal_notice self.jour_id, "journal_for_message", self.id, "#{l(:label_new_journals_template)}", self.user.show_name, format_time(self.created_on),content
end end
else # 留言回复 else # 留言回复
reply_to = User.find(self.reply_id) reply_to = User.find(self.reply_id)
@ -292,8 +303,8 @@ class JournalsForMessage < ActiveRecord::Base
if self.user_id != self.parent.jour_id && self.reply_id != self.parent.jour_id # 给东家发信息,如果回复的对象是东家则不发 if self.user_id != self.parent.jour_id && self.reply_id != self.parent.jour_id # 给东家发信息,如果回复的对象是东家则不发
receivers << self.parent.jour receivers << self.parent.jour
end end
content = strip_html self.notes, 200 #content = strip_html self.notes, 200
ws.comment_template self.reply_id, "journal_for_message", self.parent.id, "#{l(:label_journals_comment_template)}", self.user.try(:realname), format_time(self.created_on), content #ws.comment_template self.reply_id, "journal_for_message", self.parent.id, "#{l(:label_journals_comment_template)}", self.user.try(:realname), format_time(self.created_on), content
end end
receivers.each do |r| 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) self.user_feedback_messages << UserFeedbackMessage.new(:user_id => r.id, :journals_for_message_id => self.id, :journals_for_message_type => "Principal", :viewed => false)
@ -318,4 +329,16 @@ class JournalsForMessage < ActiveRecord::Base
down_course_score_num(self.jour.course_id, self.user_id, "HomeworkCommon") down_course_score_num(self.jour.course_id, self.user_id, "HomeworkCommon")
end end
end end
def creator_user
self.user
end
def created_time
self.created_on
end
def content_detail
self.notes
end
end end

@ -83,7 +83,7 @@ class Message < ActiveRecord::Base
# after_create :add_author_as_watcher, :reset_counters!, :add_boards_count # after_create :add_author_as_watcher, :reset_counters!, :add_boards_count
after_update :update_messages_board, :update_activity after_update :update_messages_board, :update_activity
after_destroy :reset_counters!,:down_user_score,:delete_kindeditor_assets, :decrease_boards_count, :down_course_score after_destroy :reset_counters!,:down_user_score,:delete_kindeditor_assets, :decrease_boards_count, :down_course_score
after_create :act_as_course_activity, :act_as_forge_activity, :act_as_student_score, act_as_at_message(:content, :author_id), :add_author_as_watcher, :reset_counters!, :add_boards_count, :act_as_system_message after_create :act_as_course_activity, :act_as_forge_activity, :act_as_student_score, act_as_at_message(:content, :author_id), :add_author_as_watcher, :reset_counters!, :add_boards_count, :act_as_system_message, :delay_message_send
#before_save :be_user_score #before_save :be_user_score
scope :visible, lambda {|*args| scope :visible, lambda {|*args|
@ -221,6 +221,18 @@ class Message < ActiveRecord::Base
update_org_activity(self.class, self.id) update_org_activity(self.class, self.id)
end end
def creator_user
self.author
end
def created_time
self.created_on
end
def content_detail
self.content
end
private private
def add_author_as_watcher def add_author_as_watcher
@ -258,28 +270,28 @@ class Message < ActiveRecord::Base
# 主贴项目成员都能收到 # 主贴项目成员都能收到
# 回帖:帖子的发布人收到 # 回帖:帖子的发布人收到
def act_as_system_message def act_as_system_message
ws = WechatService.new #ws = WechatService.new
if self.course if self.course
if self.parent_id.nil? # 主贴 if self.parent_id.nil? # 主贴
self.course.members.includes(:user).each do |m| self.course.members.includes(:user).each do |m|
if self.author.allowed_to?(:as_teacher, self.course) && m.user_id != self.author_id # 老师 自己的帖子不给自己发送消息 if self.author.allowed_to?(:as_teacher, self.course) && m.user_id != self.author_id # 老师 自己的帖子不给自己发送消息
#self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.board.course_id, :viewed => false) #self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.board.course_id, :viewed => false)
count = ShieldWechatMessage.where("container_type='User' and container_id=#{m.user_id} and shield_type='Course' and shield_id=#{self.course.id}").count # 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 # if count == 0
content = strip_html self.subject, 200 # content = strip_html self.subject, 200
ws.topic_publish_template m.user_id, "course_discussion", self.id, "#{l(:label_course_topic_template)}", content, self.author.try(:realname), format_time(self.created_on) # ws.topic_publish_template m.user_id, "course_discussion", self.id, "#{l(:label_course_topic_template)}", content, self.author.try(:realname), format_time(self.created_on)
end # end
end end
end end
else # 回帖 else # 回帖
parent_author_id = Message.find(self.parent_id).author_id parent_author_id = Message.find(self.parent_id).author_id
if parent_author_id != self.author_id # 只针对主贴回复,回复自己的帖子不发消息 if parent_author_id != self.author_id # 只针对主贴回复,回复自己的帖子不发消息
#self.course_messages << CourseMessage.new(:user_id => parent_author_id, :course_id => self.board.course_id, :viewed => false) self.course_messages << CourseMessage.new(:user_id => parent_author_id, :course_id => self.board.course_id, :viewed => false)
count = ShieldWechatMessage.where("container_type='User' and container_id=#{parent_author_id} and shield_type='Course' and shield_id=#{self.board.course_id}").count # count = ShieldWechatMessage.where("container_type='User' and container_id=#{parent_author_id} and shield_type='Course' and shield_id=#{self.board.course_id}").count
if count == 0 # if count == 0
content = strip_html self.content.html_safe, 200 # content = strip_html self.content.html_safe, 200
ws.comment_template parent_author_id, "course_discussion", self.parent_id, "#{l(:label_topic_comment_template)}", self.author.try(:realname), format_time(self.created_on), content # ws.comment_template parent_author_id, "course_discussion", self.parent_id, "#{l(:label_topic_comment_template)}", self.author.try(:realname), format_time(self.created_on), content
end # end
end end
end end
elsif self.project # 项目相关 elsif self.project # 项目相关
@ -287,27 +299,43 @@ class Message < ActiveRecord::Base
self.project.members.includes(:user).each do |m| self.project.members.includes(:user).each do |m|
if m.user_id != self.author_id if m.user_id != self.author_id
#self.forge_messages << ForgeMessage.new(:user_id => m.user_id, :project_id => self.board.project_id, :viewed => false) #self.forge_messages << ForgeMessage.new(:user_id => m.user_id, :project_id => self.board.project_id, :viewed => false)
count = ShieldWechatMessage.where("container_type='User' and container_id=#{m.user_id} and shield_type='Project' and shield_id=#{self.project.id}").count # count = ShieldWechatMessage.where("container_type='User' and container_id=#{m.user_id} and shield_type='Project' and shield_id=#{self.project.id}").count
if count == 0 # if count == 0
content = strip_html self.subject, 200 # content = strip_html self.subject, 200
ws.topic_publish_template m.user_id, "project_discussion", self.id, "#{l(:label_project_topic_template)}", content, self.author.try(:realname), format_time(self.created_on) # ws.topic_publish_template m.user_id, "project_discussion", self.id, "#{l(:label_project_topic_template)}", content, self.author.try(:realname), format_time(self.created_on)
end # end
end end
end end
else # 回帖 else # 回帖
parent_author_id = Message.find(self.parent_id).author_id parent_author_id = Message.find(self.parent_id).author_id
if parent_author_id != self.author_id # 只针对主贴回复,回复自己的帖子不发消息 if parent_author_id != self.author_id # 只针对主贴回复,回复自己的帖子不发消息
#self.forge_messages << ForgeMessage.new(:user_id => parent_author_id, :project_id => self.board.project_id, :viewed => false) self.forge_messages << ForgeMessage.new(:user_id => parent_author_id, :project_id => self.board.project_id, :viewed => false)
count = ShieldWechatMessage.where("container_type='User' and container_id=#{parent_author_id} and shield_type='Project' and shield_id=#{self.board.project_id}").count # count = ShieldWechatMessage.where("container_type='User' and container_id=#{parent_author_id} and shield_type='Project' and shield_id=#{self.board.project_id}").count
if count == 0 # if count == 0
content = strip_html self.content.html_safe, 200 # content = strip_html self.content.html_safe, 200
ws.comment_template parent_author_id, "project_discussion", self.parent_id, "#{l(:label_topic_comment_template)}", self.author.try(:realname), format_time(self.created_on), content # ws.comment_template parent_author_id, "project_discussion", self.parent_id, "#{l(:label_topic_comment_template)}", self.author.try(:realname), format_time(self.created_on), content
end # end
end end
end end
end end
end end
def delay_message_send
if self.course
if self.parent_id.nil? # 发帖
self.delay.contain_messages_message
end
end
end
def contain_messages_message
self.course.members.includes(:user).each do |m|
if self.author.allowed_to?(:as_teacher, self.course) && m.user_id != self.author_id # 老师 自己的帖子不给自己发送消息
self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.board.course_id, :viewed => false)
end
end
end
#更新用户分数 -by zjc #更新用户分数 -by zjc
def be_user_score def be_user_score
#新建message且无parent的为发帖 #新建message且无parent的为发帖

@ -62,7 +62,7 @@ class News < ActiveRecord::Base
:author_key => :author_id :author_key => :author_id
acts_as_watchable acts_as_watchable
after_create :act_as_activity,:act_as_forge_activity, :act_as_course_activity, :add_author_as_watcher, :send_mail, :add_news_count, :act_as_student_score after_create :act_as_activity,:act_as_forge_activity, :act_as_course_activity, :add_author_as_watcher, :send_mail, :add_news_count, :act_as_student_score, :act_as_system_message, :delay_news_send
after_update :update_activity after_update :update_activity
after_destroy :delete_kindeditor_assets, :decrease_news_count, :delete_org_activities, :down_course_score after_destroy :delete_kindeditor_assets, :decrease_news_count, :delete_org_activities, :down_course_score
@ -163,18 +163,18 @@ class News < ActiveRecord::Base
end end
end end
#课程/项目通知 消息发送 # 课程/项目通知 消息发送
#消息发送原则:除了消息的发布者,课程的其它成员都能收到消息提醒 # 消息发送原则:除了消息的发布者,课程的其它成员都能收到消息提醒
def act_as_system_message def act_as_system_message
if self.course if self.course
self.course.members.each do |m| self.course.members.each do |m|
if m.user_id != self.author_id if m.user_id != self.author_id
self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.course_id, :viewed => false) #self.course_messages << CourseMessage.new(:user_id => m.user_id, :course_id => self.course_id, :viewed => false)
count = ShieldWechatMessage.where("container_type='User' and container_id=#{m.user_id} and shield_type='Course' and shield_id=#{self.course_id}").count 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 if count == 0
ws = WechatService.new ws = WechatService.new
content = strip_html self.author.try(:realname) + " 发布了通知:" + self.title.html_safe, 200 content = strip_html self.author.try(:realname) + " 发布了通知:" + self.title.html_safe, 200
ws.message_update_template m.user_id, "course_notice", self.id, "#{l(:label_new_notice_template)}", self.author.try(:realname) + " 发布了通知:" + content, format_time(self.created_on) ws.class_notice m.user_id, "course_notice", self.id, "#{l(:label_new_notice_template)}", self.course.name, self.author.show_name, format_time(self.created_on), content, "点击查看通知详情"
end end
end end
end end
@ -189,6 +189,20 @@ class News < ActiveRecord::Base
end end
end end
def delay_news_send
if self.course
self.delay.contain_news_message
end
end
def contain_news_message
self.course.members.each do |m|
if m.user_id != self.author_id
self.course_messages << CourseMessage.new(:user_id => user_id, :course_id => container_id, :viewed => false)
end
end
end
# Time 2015-03-31 13:50:54 # Time 2015-03-31 13:50:54
# Author lizanle # Author lizanle
# Description 删除news后删除对应的资源 # Description 删除news后删除对应的资源

@ -1,5 +1,6 @@
class OrgDocumentComment < ActiveRecord::Base class OrgDocumentComment < ActiveRecord::Base
attr_accessible :content, :creator_id, :organization_id, :parent_id, :reply_id, :title,:sticky,:locked # status: 1 模式二中置顶 0模式二中正常显示
attr_accessible :content, :creator_id, :organization_id, :parent_id, :reply_id, :title, :sticky, :locked, :status
include Redmine::SafeAttributes include Redmine::SafeAttributes
include ApplicationHelper include ApplicationHelper
belongs_to :organization belongs_to :organization
@ -34,4 +35,15 @@ class OrgDocumentComment < ActiveRecord::Base
end end
def creator_user
self.creator
end
def created_time
self.created_at
end
def content_detail
self.content
end
end end

@ -11,6 +11,8 @@ class OrgSubfield < ActiveRecord::Base
acts_as_attachable acts_as_attachable
after_create :create_board_sync after_create :create_board_sync
after_destroy :update_priority after_destroy :update_priority
# status 为栏目定制决定参数1 左一 2 左二 3 左三 4 右一 5 右二 6 右三 默认的 7 学霸 8 热门项目 9 精品课程 10 最新动态
# 创建资源栏目讨论区 # 创建资源栏目讨论区
def create_board_sync def create_board_sync
@board = self.boards.build @board = self.boards.build

@ -18,17 +18,17 @@ class Organization < ActiveRecord::Base
end end
def add_default_subfields def add_default_subfields
OrgSubfield.create(:organization_id => self.id, :name => 'activity', :field_type => 'default', :priority => 1) OrgSubfield.create(:organization_id => self.id, :name => 'activity', :field_type => 'default', :priority => 1, :status => 0)
OrgSubfield.create(:organization_id => self.id, :name => 'course', :field_type => 'default', :priority => 2) OrgSubfield.create(:organization_id => self.id, :name => 'course', :field_type => 'default', :priority => 2, :status => 2)
OrgSubfield.create(:organization_id => self.id, :name => 'project', :field_type => 'default', :priority => 3) OrgSubfield.create(:organization_id => self.id, :name => 'project', :field_type => 'default', :priority => 3, :status => 2)
end end
def switch_type def switch_type
self.show_mode.to_i == 1 ? true : false self.show_mode.to_i == 1
end end
def allow_set_teachers def allow_set_teachers
self.allow_teacher.to_i == 1 ? true : false self.allow_teacher.to_i == 1
end end
def secdomain_name def secdomain_name

@ -155,7 +155,7 @@ class Project < ActiveRecord::Base
#ActiveModel::Dirty 这里有一个changed方法。对任何对象都可以用 #ActiveModel::Dirty 这里有一个changed方法。对任何对象都可以用
after_save :update_inherited_members, :if => Proc.new {|project| project.inherit_members_changed?} after_save :update_inherited_members, :if => Proc.new {|project| project.inherit_members_changed?}
# 创建project之后默认创建一个board之后的board去掉了board的概念 # 创建project之后默认创建一个board之后的board去掉了board的概念
after_create :create_board_sync,:acts_as_forge_activities,:create_project_ealasticsearch_index after_create :create_board_sync,:acts_as_forge_activities, :create_project_ealasticsearch_index
before_destroy :delete_all_members,:delete_project_ealasticsearch_index before_destroy :delete_all_members,:delete_project_ealasticsearch_index
after_update :update_project_ealasticsearch_index after_update :update_project_ealasticsearch_index
def remove_references_before_destroy def remove_references_before_destroy

@ -0,0 +1,7 @@
class QualityAnalysis < ActiveRecord::Base
attr_accessible :author_login, :project_id, :rep_identifier, :sonar_version, :branch, :path, :rep_identifier, :language, :sonar_name
def user_rep_name
self.author_login+":"+self.rep_identifier
end
end

@ -0,0 +1,3 @@
class SonarAnalysis < ActiveRecord::Base
attr_accessible :author_login, :project_id, :rep_identifier
end

@ -17,7 +17,7 @@ class Sso < ActiveRecord::Base
sso.openid = opt["openid"] sso.openid = opt["openid"]
sso.email = opt["email"] sso.email = opt["email"]
sso.password = opt["password"] sso.password = opt["password"]
sso.school = Base64.decode64(opt["school"]).force_encoding('utf-8') sso.school = opt["school"]
sso.sex = opt["sex"] sso.sex = opt["sex"]

@ -0,0 +1,46 @@
# encoding: utf-8
class Syllabus < ActiveRecord::Base
include Redmine::SafeAttributes
include ApplicationHelper
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
attr_accessible :description, :title, :eng_name, :syllabus_type, :credit, :hours, :theory_hours, :practice_hours, :applicable_major, :pre_course
safe_attributes 'title', 'description', 'eng_name', 'syllabus_type', 'credit', 'hours', 'theory_hours', 'practice_hours', 'credit', 'applicable_major', 'pre_course'
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 , options = {})
syllabus = Syllabus.find(id)
if options.count == 0
jfm = syllabus.journals_for_messages.build(:user_id => user.id, :notes => notes, :reply_id => 0)
else
jfm = syllabus.journals_for_messages.build(options)
end
jfm.save
jfm
end
end

@ -90,6 +90,7 @@ class User < Principal
has_many :homework_users has_many :homework_users
has_many :homework_attaches, :through => :homework_users has_many :homework_attaches, :through => :homework_users
has_many :homework_evaluations has_many :homework_evaluations
has_many :syllabuses, :dependent => :destroy
#问卷相关关关系 #问卷相关关关系
has_many :poll_users, :dependent => :destroy has_many :poll_users, :dependent => :destroy
has_many :poll_votes, :dependent => :destroy has_many :poll_votes, :dependent => :destroy
@ -109,6 +110,7 @@ class User < Principal
has_many :student_works_scores, :dependent => :destroy has_many :student_works_scores, :dependent => :destroy
has_many :student_work_projects, :dependent => :destroy has_many :student_work_projects, :dependent => :destroy
has_many :apply_homeworks, :dependent => :destroy has_many :apply_homeworks, :dependent => :destroy
has_many :apply_resources, :dependent => :destroy
#end #end
has_and_belongs_to_many :groups, :after_add => Proc.new {|user, group| group.user_added(user)}, has_and_belongs_to_many :groups, :after_add => Proc.new {|user, group| group.user_added(user)},
@ -143,6 +145,7 @@ class User < Principal
has_many :acts, :class_name => 'Activity', :as => :act, :dependent => :destroy has_many :acts, :class_name => 'Activity', :as => :act, :dependent => :destroy
has_many :principal_acts, :class_name => 'PrincipalActivity',:as =>:principal_act ,:dependent => :destroy has_many :principal_acts, :class_name => 'PrincipalActivity',:as =>:principal_act ,:dependent => :destroy
has_many :file_commit, :class_name => 'Attachment', :foreign_key => 'author_id', :conditions => "container_type = 'Project' or container_type = 'Version'" has_many :file_commit, :class_name => 'Attachment', :foreign_key => 'author_id', :conditions => "container_type = 'Project' or container_type = 'Version'"
has_many :course_attachments , :class_name => 'Attachment', :foreign_key => 'author_id', :conditions => "container_type = 'Course'"
#### ####
# added by bai # added by bai
has_many :join_in_contests, :dependent => :destroy has_many :join_in_contests, :dependent => :destroy
@ -246,7 +249,7 @@ class User < Principal
before_save :update_hashed_password before_save :update_hashed_password
before_destroy :remove_references_before_destroy,:delete_user_ealasticsearch_index before_destroy :remove_references_before_destroy,:delete_user_ealasticsearch_index
# added by fq # added by fq
after_create :act_as_activity, :add_onclick_time, :act_as_principal_activity,:create_user_ealasticsearch_index after_create :act_as_activity, :add_onclick_time, :act_as_principal_activity,:create_user_ealasticsearch_index,:add_new_jour
# end # end
# 更新邮箱用户或用户名的同事,同步更新邀请信息 # 更新邮箱用户或用户名的同事,同步更新邀请信息
after_update :update_invite_list,:update_user_ealasticsearch_index after_update :update_invite_list,:update_user_ealasticsearch_index
@ -1143,6 +1146,22 @@ class User < Principal
end end
end end
#为新注册用户发送留言
def add_new_jour
if Message.where("id=19278").any? and Message.where("id=19291").any? and Message.where("id=19292").any?
lead_message1 = Message.find(19278)
notes1 = lead_message1.content
# lead_message2 = Message.find(19292)
# notes2 = lead_message2.content
# lead_message3 = Message.find(19291)
# 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
# 更新邮箱的同事更新invite_lists表中的邮箱信息 # 更新邮箱的同事更新invite_lists表中的邮箱信息
def update_invite_list def update_invite_list
invite_lists = InviteList.where("user_id =?",self.id).all invite_lists = InviteList.where("user_id =?",self.id).all

@ -32,6 +32,18 @@ class CoursesService
course_list course_list
end end
def user_courses_list(current_user)
courses = current_user.courses.not_deleted
courses.inject([]) {|course_list, course|
course_list << {: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),
course_student_num: searchStudent(course).count
}
}
end
#搜索课程 #搜索课程
def search_course params,current_user def search_course params,current_user
courses_all = Course.all_course courses_all = Course.all_course
@ -68,7 +80,6 @@ class CoursesService
if current_user.nil? || !(current_user.admin? || c.is_public == 1 || (c.is_public == 0 && current_user.member_of_course?(c))) if current_user.nil? || !(current_user.admin? || c.is_public == 1 || (c.is_public == 0 && current_user.member_of_course?(c)))
raise '403' raise '403'
end end
@teachers= searchTeacherAndAssistant(c)
#@canShowCode = isCourseTeacher(User.current.id,course) && params[:role] != '1' #@canShowCode = isCourseTeacher(User.current.id,course) && params[:role] != '1'
case params[:role] case params[:role]
when '1' when '1'
@ -87,7 +98,11 @@ class CoursesService
gender = m.user.user_extensions.gender.nil? ? 0 : m.user.user_extensions.gender gender = m.user.user_extensions.gender.nil? ? 0 : m.user.user_extensions.gender
work_unit = get_user_work_unit m.user work_unit = get_user_work_unit m.user
location = get_user_location m.user location = get_user_location m.user
users << {:id => m.user.id, :img_url => img_url, :nickname => m.user.login, :gender => gender, :work_unit => work_unit, :mail => m.user.mail, :location => location, :brief_introduction => m.user.user_extensions.brief_introduction,:realname=>m.user.realname} users << {:id => m.user.id, :img_url => img_url, :nickname => m.user.login, :gender => gender,
:work_unit => work_unit, :mail => m.user.mail, :location => location,
role_name: m.roles.first.name,
name: m.user.show_name,
:brief_introduction => m.user.user_extensions.brief_introduction,:realname=>m.user.realname}
end end
users users
end end
@ -162,6 +177,9 @@ class CoursesService
#显示课程 #显示课程
def show_course(params,current_user) def show_course(params,current_user)
course = Course.find(params[:id]) course = Course.find(params[:id])
course.generate_invite_code
course.generate_qrcode
if course.school if course.school
work_unit = course.school.name work_unit = course.school.name
else else
@ -193,8 +211,9 @@ class CoursesService
@course.extra = 'course' + DateTime.parse(Time.now.to_s).strftime('%Y-%m-%d_%H-%M-%S').to_s @course.extra = 'course' + DateTime.parse(Time.now.to_s).strftime('%Y-%m-%d_%H-%M-%S').to_s
@course.send(:safe_attributes=, params[:course], current_user) @course.send(:safe_attributes=, params[:course], current_user)
#@course.safe_attributes(current_user,params[:course]) #@course.safe_attributes(current_user,params[:course])
@course.password = params[:course][:password] #@course.password = params[:course][:password]
@course.tea_id = current_user.id @course.tea_id = current_user.id
@course.syllabus_id = params[:syllabus_id].to_i
@course.term = params[:term] @course.term = params[:term]
@course.time = params[:time] @course.time = params[:time]
@course.end_term = params[:end_term] @course.end_term = params[:end_term]
@ -252,7 +271,8 @@ class CoursesService
def edit_course(params,course,current_user) def edit_course(params,course,current_user)
course.send(:safe_attributes=, params[:course], current_user) course.send(:safe_attributes=, params[:course], current_user)
#course.safe_attributes = params[:course] #course.safe_attributes = params[:course]
course.password = params[:course][:password] #course.password = params[:course][:password]
course.syllabus_id = params[:syllabus_id].to_i
course.time = params[:time] course.time = params[:time]
course.term = params[:term] course.term = params[:term]
course.end_time = params[:end_time] course.end_time = params[:end_time]
@ -300,23 +320,27 @@ class CoursesService
@state @state
end end
class JoinCourseError < Errors
define_error [
0, '加入成功',
1, '密码错误',
2, '班级已过期 请联系班级管理员重启班级。',
3, '您已经加入了班级',
4, '您加入的班级不存在',
5, '您还未登录',
6, '申请成功,请等待审核完毕',
7, '您已经发送过申请了,请耐心等待',
8, '您已经是该班级的教师了',
9, '您已经是该班级的教辅了',
10, '您已经是该班级的管理员了',
'未知错误,请稍后再试'
]
end
#加入课程 #加入课程
#object_id课程id #object_id课程id
#course_password :加入课程的密码 #course_password :加入课程的密码
#@state == 0 加入成功
#@state == 1 密码错误
#@state == 2 课程已过期 请联系课程管理员重启课程。(在配置课程处)
#@state == 3 您已经加入了课程
#@state == 4 您加入的课程不存在
#@state == 5 您还未登录
#@state == 6 申请成功,请等待审核完毕
#@state == 7 您已经发送过申请了,请耐心等待
#@state == 8 您已经是该课程的教师了
#@state == 9 您已经是该课程的教辅了
#@state == 10 您已经是该课程的管理员了
#@state 其他 未知错误,请稍后再试
def join_course params,current_user def join_course params,current_user
course = Course.find_by_id params[:object_id] course = Course.find_by_invite_code(params[:invite_code]) if params[:invite_code]
@state = 10 @state = 10
if course if course
@ -326,7 +350,7 @@ class CoursesService
if current_user.member_of_course?(course) #如果已经是成员 if current_user.member_of_course?(course) #如果已经是成员
member = course.members.where("user_id=#{current_user.id} and course_id=#{course.id}")[0] member = course.members.where("user_id=#{current_user.id} and course_id=#{course.id}")[0]
roleName = member.roles[0].name if member roleName = member.roles[0].name if member
if params[:course_password] == course.password if params[:invite_code].present?
#如果加入角色为学生 并且当前是学生 #如果加入角色为学生 并且当前是学生
if params[:role] == "10" && roleName == "Student" if params[:role] == "10" && roleName == "Student"
@state = 3 @state = 3
@ -341,7 +365,7 @@ class CoursesService
#如果加入角色为教师或者教辅,并且当前是学生,或者是要成为教辅,当前不是教辅,或者要成为教师,当前不是教师。那么要发送请求 #如果加入角色为教师或者教辅,并且当前是学生,或者是要成为教辅,当前不是教辅,或者要成为教师,当前不是教师。那么要发送请求
elsif (params[:role] != "10" && roleName == "Student") || (params[:role] == "7" && roleName != "TeachingAsistant" ) || (params[:role] == "9" && roleName != "Teacher" ) elsif (params[:role] != "10" && roleName == "Student") || (params[:role] == "7" && roleName != "TeachingAsistant" ) || (params[:role] == "9" && roleName != "Teacher" )
#如果已经发送过消息了,那么就要给个提示 #如果已经发送过消息了,那么就要给个提示
if CourseMessage.where("course_message_type = 'JoinCourseRequest' and user_id = #{course.tea_id} and content = #{params[:role]} and course_message_id = #{User.current.id} and course_id = #{course.id} and status = 0 ").count != 0 if CourseMessage.where("course_message_type = 'JoinCourseRequest' and user_id = #{course.tea_id} and course_message_id = #{User.current.id} and course_id = #{course.id} and status = 0 ").count != 0
@state = 7 @state = 7
else else
Mailer.run.join_course_request(course, User.current, params[:role]) Mailer.run.join_course_request(course, User.current, params[:role])
@ -352,19 +376,19 @@ class CoursesService
elsif params[:role] == "10" && roleName != "Student" elsif params[:role] == "10" && roleName != "Student"
member.role_ids = [params[:role]] member.role_ids = [params[:role]]
member.save member.save
StudentsForCourse.create(:student_id => current_user.id, :course_id => params[:object_id]) StudentsForCourse.create(:student_id => current_user.id, :course_id => course.id)
@state = 0 @state = 0
end end
else else
@state = 1 @state = 1
end end
else else
if params[:course_password] == course.password if params[:invite_code].present?
if params[:role] == "10" || params[:role] == nil if params[:role] == "10" || params[:role] == nil
members = [] members = []
members << Member.new(:role_ids => [10], :user_id => current_user.id) members << Member.new(:role_ids => [10], :user_id => current_user.id)
course.members << members course.members << members
StudentsForCourse.create(:student_id => current_user.id, :course_id => params[:object_id]) StudentsForCourse.create(:student_id => current_user.id, :course_id => course.id)
@state = 0 @state = 0
else else
#如果已经发送过消息了,那么就要给个提示 #如果已经发送过消息了,那么就要给个提示

@ -5,7 +5,7 @@ class WechatService
data = { data = {
touser:openid, touser:openid,
template_id:template_id, template_id:template_id,
url:"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc09454f171153c2d&redirect_uri=https://www.trustie.net/assets/wechat/app.html#/#{type}/#{id}?response_type=code&scope=snsapi_base&state=123#wechat_redirect", url:"https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{Wechat.config.appid}&redirect_uri=#{Setting.protocol}://#{Setting.host_name}/assets/wechat/app.html#/#{type}/#{id}?response_type=code&scope=snsapi_base&state=123#wechat_redirect",
topcolor:"#FF0000", topcolor:"#FF0000",
data:{ data:{
first: { first: {
@ -44,7 +44,6 @@ class WechatService
end end
Rails.logger.info "send over. #{req}" Rails.logger.info "send over. #{req}"
end end
Rails.logger.info "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc09454f171153c2d&redirect_uri=https://www.trustie.net/assets/wechat/app.html#/#{type}/#{id}?response_type=code&scope=snsapi_base&state=123#wechat_redirect"
end end
def topic_publish_template(user_id, type, id, first, key1, key2, key3, remark="") def topic_publish_template(user_id, type, id, first, key1, key2, key3, remark="")
@ -59,7 +58,6 @@ class WechatService
end end
Rails.logger.info "send over. #{req}" Rails.logger.info "send over. #{req}"
end end
Rails.logger.info "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc09454f171153c2d&redirect_uri=https://www.trustie.net/assets/wechat/app.html#/#{type}/#{id}?response_type=code&scope=snsapi_base&state=123#wechat_redirect"
end end
def comment_template(user_id,type, id, first, key1, key2, key3, remark="") def comment_template(user_id,type, id, first, key1, key2, key3, remark="")
@ -74,7 +72,6 @@ class WechatService
end end
Rails.logger.info "send over. #{req}" Rails.logger.info "send over. #{req}"
end end
Rails.logger.info "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc09454f171153c2d&redirect_uri=https://www.trustie.net/assets/wechat/app.html#/#{type}/#{id}?response_type=code&scope=snsapi_base&state=123#wechat_redirect"
end end
def message_update_template(user_id, type, id, first, key1, key2, remark="") def message_update_template(user_id, type, id, first, key1, key2, remark="")
@ -83,7 +80,7 @@ class WechatService
data = { data = {
touser:uw.openid, touser:uw.openid,
template_id:"YTyNPZnQD8uZFBFq-Q6cCOWaq5LA9vL6RFlF2JuD5Cg", template_id:"YTyNPZnQD8uZFBFq-Q6cCOWaq5LA9vL6RFlF2JuD5Cg",
url:"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc09454f171153c2d&redirect_uri=https://www.trustie.net/assets/wechat/app.html#/#{type}/#{id}?response_type=code&scope=snsapi_base&state=123#wechat_redirect", url:"https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{Wechat.config.appid}&redirect_uri=#{Setting.protocol}://#{Setting.host_name}/assets/wechat/app.html#/#{type}/#{id}?response_type=code&scope=snsapi_base&state=123#wechat_redirect",
topcolor:"#FF0000", topcolor:"#FF0000",
data:{ data:{
first: { first: {
@ -112,6 +109,145 @@ class WechatService
end end
Rails.logger.info "send over. #{req}" Rails.logger.info "send over. #{req}"
end end
Rails.logger.info "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc09454f171153c2d&redirect_uri=https://www.trustie.net/assets/wechat/app.html#/#{type}/#{id}?response_type=code&scope=snsapi_base&state=123#wechat_redirect"
end end
def two_keys_template(openid, template_id, type, id, first, key1, key2, remark="")
data = {
touser:openid,
template_id:template_id,
url:"#{Setting.protocol}://#{Setting.host_name}/assets/wechat/app.html#/#{type}/#{id}",
topcolor:"#FF0000",
data:{
first: {
value:first,
color:"#707070"
},
keyword1:{
value:key1,
color:"#707070"
},
keyword2:{
value:key2,
color:"#707070"
},
remark:{
value:remark,
color:"#707070"
}
}
}
data
end
def four_keys_template(openid, template_id, type, id, first, key1, key2, key3, key4, remark="")
data = {
touser:openid,
template_id:template_id,
url:"#{Setting.protocol}://#{Setting.host_name}/assets/wechat/app.html#/#{type}/#{id}",
topcolor:"#FF0000",
data:{
first: {
value:first,
color:"#707070"
},
keyword1:{
value:key1,
color:"#707070"
},
keyword2:{
value:key2,
color:"#707070"
},
keyword3:{
value:key3,
color:"#707070"
},
keyword4:{
value:key4,
color:"#707070"
},
remark:{
value:remark,
color:"#707070"
}
}
}
data
end
def binding_succ_notice(user_id, first, key1, key2)
uw = UserWechat.where(user_id: user_id).first
unless uw.nil?
data = {
touser:uw.openid,
template_id:Wechat.config.binding_succ_notice,
url:"#{Setting.protocol}://#{Setting.host_name}/wechat/user_activities",
topcolor:"#FF0000",
data:{
first: {
value:first,
color:"#707070"
},
keyword1:{
value:key1,
color:"#707070"
},
keyword2:{
value:key2,
color:"#707070"
},
remark:{
value:"绑定成功后可使用微信查看Trustie平台最新动态",
color:"#707070"
}
}
}
begin
req = Wechat.api.template_message_send Wechat::Message.to(uw.openid).template(data)
rescue Exception => e
Rails.logger.error "[homework] ===> #{e}"
end
Rails.logger.info "send over. #{req}"
end
end
def journal_notice(user_id, type, id, first, key1, key2, remark="")
uw = UserWechat.where(user_id: user_id).first
unless uw.nil?
data = two_keys_template uw.openid,Wechat.config.journal_notice, type, id, first, key1, key2, remark
begin
req = Wechat.api.template_message_send Wechat::Message.to(uw.openid).template(data)
rescue Exception => e
Rails.logger.error "[homework] ===> #{e}"
end
Rails.logger.info "send over. #{req}"
end
end
def homework_message_notice(user_id, type, id, first, key1, key2, remark="")
uw = UserWechat.where(user_id: user_id).first
unless uw.nil?
data = two_keys_template uw.openid,Wechat.config.homework_message_notice, type, id, first, key1, key2, remark
begin
req = Wechat.api.template_message_send Wechat::Message.to(uw.openid).template(data)
rescue Exception => e
Rails.logger.error "[homework] ===> #{e}"
end
Rails.logger.info "send over. #{req}"
end
end
def class_notice(user_id, type, id, first, key1, key2, key3, key4, remark="")
uw = UserWechat.where(user_id: user_id).first
unless uw.nil?
data = four_keys_template uw.openid,Wechat.config.class_notice, type, id, first, key1, key2, key3, key4, remark
begin
req = Wechat.api.template_message_send Wechat::Message.to(uw.openid).template(data)
rescue Exception => e
Rails.logger.error "[homework] ===> #{e}"
end
Rails.logger.info "send over. #{req}"
end
end
end end

@ -0,0 +1,58 @@
<div class="new_content">
<div class="email_verify">
<p class="email_verify_prompt"><span class="icons_email_prompt"></span>您的账号尚未激活,请先进入您的注册邮箱,激活您的账号。</p>
<button class="email_verify_btn mt30 ml30" onclick = "resendMail('<%= resendmail_path(@user) %>','<%= @user.id %>');">重新发送激活邮件</button>
<%#= link_to l(:label_mail_resend), { :controller => 'account', :action => 'resendmail',:user => @user}, :class=>"email_verify_btn mt30 ml30", :remote => true, :method => 'get' %>
<ul class="email_prompt_txt ml30 mt30">
<p class="email_prompt_p">如果您尚未收到激活邮件,请按照以下步骤操作:</p>
<li>检查邮箱的“订阅邮件”、“垃圾邮件”,可能会发现激活邮件。 </li>
<li>如果激活邮件已无效,请点击重新发送激活邮件按钮。</li>
<li>如果您无法收到激活邮件,请您直接给我们管理员留言:</li>
<div class=" mt10">
<textarea style="resize: none;" class="email_prompt_mes" placeholder="请管理员尽快帮我解决邮箱激活问题"></textarea>
<button class="email_sub_btn fr" onclick="leave_email_activation_message('<%= leave_email_activation_message_path(1)%>','<%= @user.id %>');">确定</button>
<div class="cl"></div>
</div>
</ul>
</div>
</div>
<script type="text/javascript">
function resendMail(url,id)
{
$.get(
url,
{user: id },
function (data) {
//邮箱@之前用a**b格式显示
var mail = data.email;
var pos = mail.indexOf("@");
var restr = mail.substring(1,pos-1);
if( mail.split("@")[0].length > 2 ){
mail = mail.replace(restr,"***");
}
$(".email_verify_btn").replaceWith("<p class='email_verify_p mt30 ml30'>激活邮件已发送至您的注册邮箱("+mail+"),请及时登录邮箱进行验证。</p>");
}
);
}
function leave_email_activation_message(url,user)
{
if ($(".email_prompt_mes").val().length == 0){
//弹框请他输入文字
var htmlvalue = "</br><div style='width:550px;text-align:center'>您的留言不能为空</div></br><div style='width:67px; margin:0 auto; text-align:center'><a href='javascript:void(0);' class='Blue-btn' onclick='hideModal()'>确定</a></div>";
pop_up_box(htmlvalue,580,30,50);
return;
}
$.ajax({
url: url,
data: {user: user, text: $(".email_prompt_mes").val() },
type: "POST",
success: function (data) {
var htmlvalue = "<div class='email_tancon'><h2 class='email_tan_title'>您的留言已发送</h2><p class='email_tan_p'>我们将尽快处理好,并通过邮件通知您。感谢您的反馈!</p></div>"
pop_up_box(htmlvalue, 580, 30, 45);
$(".email_prompt_mes").val("");
}
});
}
</script>

@ -2,32 +2,6 @@
<%= stylesheet_link_tag 'css/public'%> <%= stylesheet_link_tag 'css/public'%>
<script type="text/javascript"> <script type="text/javascript">
// $(document).ready(function(){
// $("#loginSignButton").click(function(){
// $("#signUpBox").css({display:"block"});
// $("#loginInBox").css({display:"none"});
// });
// $("#loginInButton").click(function(){
// $("#signUpBox").css({display:"none"});
// $("#loginInBox").css({display:"block"});
// });
// });
// $(function(){
// $("#username").keypress(function(e){
// alert(11);
// if (e.keyCode == '13') {
// $('#main_login_form').submit();
// }
// });
//
// $("#password").keypress(function(e){
// if (e.keyCode == '13') {
// $('#main_login_form').submit();
// }
// });
// });
$(document).ready(function(){ $(document).ready(function(){
$(".homepageSearchIcon").click(function(){ $(".homepageSearchIcon").click(function(){
var val=$('input:radio[name="search_type"]:checked').val(); var val=$('input:radio[name="search_type"]:checked').val();
@ -38,10 +12,6 @@
$("#navSearchAlert").css({display:"none"}); $("#navSearchAlert").css({display:"none"});
} }
}); });
// $("#loginInButton").click(function(){
// $("#signUpBox").css({display:"none"});
// $("#loginInBox").css({display:"block"});
// });
}); });
$(document).ready(function(){ $(document).ready(function(){
@ -62,42 +32,6 @@
} }
}); });
// $('#regist_btn').bind('keyup', function(event) {
// if (event.keyCode == "13" && $("#signUpBox").css('display') == 'block')) {
// register();
// }
//});
function clearInfo(id, content) {
var text = $('#' + id);
if (text.val() == content) {
$('#' + id).val('');
}
}
function showInfo(id, content) {
var text = $('#' + id);
if (text.val() == '') {
$('#' + id).val(content);
}
}
function login(){
$('#main_login_form').submit(); //表单提交没有任何反应的原因js冲突
}
function register(){
if($("#loginUpButton").hasClass('loginUpDisableButton')){
return;
}
if($login_correct && $mail_correct && $passwd_correct && $passwd_comfirm_correct && $("#read_and_confirm").attr("checked") == 'checked'){
$("#main_reg_form").submit();
}else{
$('#user_login').blur();
$('#user_mail').blur();
$('#user_password').blur();
$('#user_password_confirmation').blur();
}
}
var $login_correct = false; var $login_correct = false;
var $mail_correct = false; var $mail_correct = false;
var $passwd_correct = false; var $passwd_correct = false;
@ -118,7 +52,7 @@
$('#login_req').html('<span style="color: green">'+data.message+'</span>'); $('#login_req').html('<span style="color: green">'+data.message+'</span>');
$login_correct = true; $login_correct = true;
} else { } else {
$('#login_req').html( '<span style="color: red">'+data.message+'</span>'); $('#login_req').html( '<span style="color: #c00202">'+data.message+'</span>');
$login_correct = false; $login_correct = false;
} }
$('#login_req').css('display','block'); $('#login_req').css('display','block');
@ -129,7 +63,7 @@
$mail.blur(function (event) { $mail.blur(function (event) {
if (/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(this.value) == false){ if (/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(this.value) == false){
$('#mail_req').html( '<span style="color: red">邮件格式不对</span>').show(); $('#mail_req').html( '<span style="color: #c00202">邮件格式不对</span>').show();
$mail_correct = false; $mail_correct = false;
return ; return ;
} }
@ -142,7 +76,7 @@
$('#mail_req').html( '<span style="color: green">'+data.message+'</span>' ); $('#mail_req').html( '<span style="color: green">'+data.message+'</span>' );
$mail_correct = true; $mail_correct = true;
} else { } else {
$('#mail_req').html( '<span style="color: red">'+data.message+'</span>' ); $('#mail_req').html( '<span style="color: #c00202">'+data.message+'</span>' );
$mail_correct = false; $mail_correct = false;
} }
$('#mail_req').css('display','block'); $('#mail_req').css('display','block');
@ -158,7 +92,7 @@
$passwd_correct = true; $passwd_correct = true;
} }
else { else {
$('#passwd_req').html( '<span style="color: red">'+'<%= l(:setting_password_min_length_limit, :count => Setting.password_min_length.to_i) %>'+'</span>'); $('#passwd_req').html( '<span style="color: #c00202">'+'<%= l(:setting_password_min_length_limit, :count => Setting.password_min_length.to_i) %>'+'</span>');
$passwd_correct = false; $passwd_correct = false;
} }
$('#passwd_req').css('display','block'); $('#passwd_req').css('display','block');
@ -174,7 +108,7 @@
$passwd_comfirm_correct = true; $passwd_comfirm_correct = true;
} }
else { else {
$('#confirm_req').html('<span style="color: red">'+'<%= l(:setting_password_error) %>'+'</span>'); $('#confirm_req').html('<span style="color: #c00202">'+'<%= l(:setting_password_error) %>'+'</span>');
$passwd_comfirm_correct = false; $passwd_comfirm_correct = false;
} }
@ -184,121 +118,90 @@
}); });
}); });
function user_name_keypress(e){
if (e.keyCode == '13') {
$('#main_login_form').submit();
}
}
function changeRegisterBtn(checkbox){
if(checkbox.checked == true){
$("#loginUpButton").removeClass('loginUpDisableButton');
$("#loginUpButton").addClass('loginUpButton');
}else{
$("#loginUpButton").removeClass('loginUpButton')
$("#loginUpButton").addClass('loginUpDisableButton');
}
}
</script> </script>
<div class="loginContentContainer">
<div class="loginContent"> <div class="new_login" id = "loginInBox">
<div class="loginLeft"> <div class="new_login_con">
<div class="loginLogo"><img src="images/trustie_big_log.png" width="100" height="88" alt="Trustie Logo" /></div> <div class="new_login_txt fl">
<div class="loginInro">&nbsp;&nbsp;欢迎加入Trustie创新实践社区在这里您的创新意识和创新潜力将得到充分发挥目前已有超过200所高校和科研机构在平台中开展在线协同开发、协同学习和协同研究。<br/><br/>&nbsp;&nbsp;Trustie社区的理想是让创新过程变的更美好</div> <h3> 欢迎加入Trustie创新实践社区</h3>
<p>在这里您的创新意识和创新潜力将得到充分发挥目前已有超过200所高校和科研机构在平台中开展在线协同开发、协同学习和协同研究。</p>
</div> </div>
<div class="loginRight"> <div class="new_login_box fr mr45 mt100">
<div id="loginInBox"> <h2 class="new_login_h2">登录
<div class="loginChooseBox"> <a href="<%= register_url_without_domain %>" class="fr mt5">立即注册</a><div class="cl"></div>
<div class="mb5"> </h2>
<ul class="loginChooseList"> <div class="new_login_form">
<li class="loginChoose fl"><span class="loginChooseTab">登录</span></li> <%= form_tag(signin_path,:id=>'main_login_form',:method=>'post') do %>
<li class="loginChooseBorder fl"></li> <%= back_url_hidden_field_tag %>
</ul> <ul>
</div> <li class="new_loggin_users">
<div class="loginSignAlert" style="color: red"><%= flash.empty? || flash[:error].nil? ? "" : flash[:error].html_safe %></div> <%= text_field_tag 'username', params[:username], :tabindex => '1', :class=>'new_loggin_input',:placeholder=>'请输入邮箱地址或登录名', :onkeypress => "user_name_keypress(event);"%>
</div> </li>
<div class="loginIn"> <li class="new_login_lock">
<%= password_field_tag 'password', nil, :tabindex => '2', :class => 'new_loggin_input' , :placeholder => '请输入登录密码', :onkeypress => "user_name_keypress(event);"%>
<p class="new_login_error"><%= flash.empty? || flash[:error].nil? ? "" : flash[:error].html_safe %></p>
</li>
<li>
<% if Setting.autologin? %>
<label><%= check_box_tag 'autologin', 1, true, :tabindex => 4, :class => "new_login_check" %><%= l(:label_stay_logged_in) %></label>
<% end %>
<a href="<%= lost_password_path %>" class="fr">
<% if Setting.lost_password? %>忘记密码<% end %>
</a>
<div class="cl"></div>
</li>
<li><button type="submit" class="new_login_submit"><a href="javascript:void(0);" id="login_btn" onclick="$('#main_login_form').submit();" style="text-decoration: none;">登录</a></button></li>
</ul>
<% end %>
</div>
<%= form_tag(signin_path,:id=>'main_login_form',:method=>'post') do %> </div>
<%= back_url_hidden_field_tag %> <div class="cl"></div>
<div class="mb20"> </div>
<%= text_field_tag 'username', params[:username], :tabindex => '1' , </div>
:class=>'loginSignBox',:placeholder=>'请输入邮箱地址或登录名', :onkeypress => "user_name_keypress(event);"%> <%# 注册 %>
<!--<input type="text" placeholder="请输入邮箱地址或昵称" class="loginSignBox" />--> <div class="new_register" id = "signUpBox">
</div> <div class="new_register_con">
<% if Setting.openid? %> <div class="new_login_txt fl new_register_left">
<div class="mb20"> <h3> 欢迎加入Trustie创新实践社区</h3>
<%= text_field_tag "openid_url", nil, :tabindex => '3',:placeholder=>'请输入OpenId URL' %> <p>在这里您的创新意识和创新潜力将得到充分发挥目前已有超过200所高校和科研机构在平台中开展在线协同开发、协同学习和协同研究。</p>
</div> </div>
<% end %> <div class="new_login_box fr mr45 mt50">
<div> <h2 class="new_login_h2">注册<a href="<%= signin_url_without_domain %>" class="fr mt5">已有账号 请登录</a><div class="cl"></div></h2>
<!--<input type="text" placeholder="请输密码" class="loginSignBox" />--> <div class="new_login_form">
<%= password_field_tag 'password', nil, :tabindex => '2',:class=>'loginSignBox' ,:placeholder=>'请输密码', :onkeypress => "user_name_keypress(event);"%> <%= form_for :user, :url => register_path,:method=>'post', :html => {:id=>'main_reg_form'} do |f| %>
</div> <%= error_messages_for 'user' %>
<div class="loginSignOption"> <ul>
<% if Setting.autologin? %> <li class="new_register_li">
<div class="fl mt3 mr5"> <%= f.text_field :mail, :size => 25, :class => 'new_register_input' , :placeholder => "请输入邮箱地址"%>
<%= check_box_tag 'autologin', 1, true, :tabindex => 4 %> <p class="new_login_error" id="mail_req" style="display: none" >请输入正确的邮箱</p>
</li>
<li class="new_register_li">
<%= f.password_field :password, :size => 25, :placeholder => "请输入密码", :class => 'new_register_input' %>
<p class="new_login_error" id="passwd_req" style="display: none">请输入6-16位密码区分大小写不能使用空格</p>
</li>
<li class="new_register_li">
<%= f.password_field :password_confirmation, :size => 25, :placeholder => "请再次输入密码", :class=> 'new_register_input' %>
<p class="new_login_error" id="confirm_req" style="display: none">两次密码不一致!</p>
</li>
<li class="new_register_li">
<%= f.text_field :login, :size => 25, :placeholder => "请输入用户登录名", :class => 'new_register_input'%>
<p class="new_login_error" id="login_req" style="display: none">用户登录名为2-18个中英文数字或下划线</p>
</li>
<li>
<label><input type="checkbox" checked id="read_and_confirm" onchange="changeRegisterBtn(this);" class=" new_login_check">我已阅读并接受<a href="<%= agreement_path %>" >Trustie服务协议条款</a></label>
</li>
<li>
<div class="new_login_submit" id="loginUpButton">
<a href="javascript:void(0);" id="regist_btn" onclick="register();" class ="db" style="text-decoration: none;">注册</a>
</div> </div>
<%= l(:label_stay_logged_in) %> </ul>
<% end %>
<a href="<%= lost_password_path %>" class="newsBlue mr40 fr">
<% if Setting.lost_password? %>
<u>忘记密码?</u>
<% end %>
</a></div>
<% end %> <% end %>
<div class="loginInButton" >
<a href="javascript:void(0);" id="login_btn" class="c_white db" onclick="$('#main_login_form').submit();">登录</a>
</div>
</div>
</div> </div>
<div id="signUpBox">
<div class="loginChooseBox">
<ul class="loginChooseList">
<li class="loginChoose fl"><span class="loginChooseTab">注册<%= link_to l(:label_login_with_open_id_option), signin_url if Setting.openid? %></a></span>
<li class="loginChooseBorder fl"></li>
</ul>
</div>
<div class="loginIn">
<%= form_for :user, :url => register_path,:method=>'post',:html=>{:id=>'main_reg_form'} do |f| %>
<%= error_messages_for 'user' %>
<div class="loginSignRow">
<!--<input type="text" placeholder="请输入邮箱地址" class="loginSignBox" />-->
<%= f.text_field :mail,:size => 25, :class=>'loginSignBox' ,:placeholder=>"请输入邮箱地址"%>
<div class="loginSignAlert" id="mail_req" style="display: none" >请输入有效邮箱地址</div>
</div>
<div class="loginSignRow">
<!--<input type="text" placeholder="请输入密码" class="loginSignBox" />-->
<%= f.password_field :password, :size => 25,:placeholder=>"请输入密码",:class=>'loginSignBox' %>
<div class="loginSignAlert" id="passwd_req" style="display: none">至少需要 6 个字符</div>
</div>
<div class="loginSignRow">
<!--<input type="text" placeholder="请再次输入密码" class="loginSignBox" />-->
<%= f.password_field :password_confirmation, :size => 25,:placeholder=>"请再次输入密码",:class=>'loginSignBox' %>
<div class="loginSignAlert" id="confirm_req" style="display: none">密码不一致</div>
</div>
<div class="loginSignRow">
<!--<input type="text" placeholder="请输入用户昵称" class="loginSignBox" />-->
<%= f.text_field :login, :size => 25,:placeholder=>"请输入用户登录名",:class=>'loginSignBox'%>
<div class="loginSignAlert" id="login_req" style="display: none">用户登录名为2-18个中英文数字或下划线</div>
</div>
<div class="loginSignOption">
<div class="fl mt3 mr5">
<input type="checkbox" id="read_and_confirm" onchange="changeRegisterBtn(this);"/>
</div>
我已阅读并接受<a href="<%= agreement_path %>" class="newsBlue"><u>Trustie服务协议</u></a>条款</div>
<div class="loginUpDisableButton" id="loginUpButton">
<a href="javascript:void(0);" class="c_white db" id="regist_btn" onclick="register();" >注册</a>
</div>
<% end %>
</div>
</div>
</div> </div>
<div class="cl"></div> <div class="cl"></div>
</div> </div>
</div> </div>

@ -1,127 +0,0 @@
<% @nav_dispaly_home_path_label = 1
@nav_dispaly_main_course_label = 1
@nav_dispaly_main_project_label = 1
@nav_dispaly_main_contest_label = 1 %>
<% @nav_dispaly_forum_label = 1%>
<!-- end -->
<h3><%= l(:label_register) %> <%= link_to l(:label_login_with_open_id_option), signin_url if Setting.openid? %></h3>
<%= labelled_form_for @user, :url => register_path do |f| %>
<%= error_messages_for 'user' %>
<div class="box tabular">
<% if @user.auth_source_id.nil? %>
<p><%= f.text_field :login, :size => 25, :required => true %><span id="valid_user_login"></span>
<em class="info" style="color: #acaeb1"><%= l(:label_max_number) %></em>
</p>
<p><%= f.password_field :password, :size => 25, :required => true %><span id="valid_user_password"></span>
<em class="info" style="color: #acaeb1"><%= l(:text_caracters_minimum, :count => Setting.password_min_length) %></em>
</p>
<p><%= f.password_field :password_confirmation, :size => 25, :required => true %><span id="valid_password" style="padding-left: 10px;"></span></p>
<% end %>
<p>
<%= f.text_field :mail,:size => 25, :required => true %>
<span id="valid_user_mail" ></span>
</p>
<p>
<em class="info" style="color: #acaeb1">
<p><%= "#{l(:label_mail_attention)} " %></p>
<p><%= "#{l(:label_mail_attention1)} " %></p>
</em>
</p>
<!-- end -->
</div>
<p>
<table>
<tr>
<td><%= submit_tag l(:button_submit) %></td>
</tr>
</table>
</p>
<% end %>
<% if Setting.openid? %>
<p><%= f.text_field :identity_url %></p>
<% end %>
<% @user.custom_field_values.select { |v| v.editable? || v.required? }.each do |value| %>
<p><%= custom_field_tag_with_label :user, value %></p>
<% end %>
</div>
<% password_min_length = Setting.password_min_length %>
<script type="text/javascript">
jQuery(document).ready(function () {
var $login = $('#user_login')
var $mail = $('#user_mail')
var $password = $('#user_password')
var $password_confirmation = $('#user_password_confirmation')
$login.blur(function (event) {
if ($(this).is('#user_login')) {
$.get(
'<%=account_valid_ajax_path%>',
{ valid: "login",
value: this.value },
function (data) {
if (data.valid) {
$('#valid_user_login').html('<span class="green">' + data.message + "</span>");
} else {
$('#valid_user_login').html('<span class="red">' + data.message + "</span>");
}
});
}
;
});
$mail.blur(function (event) {
if ($(this).is('#user_mail')) {
$.get('<%=account_valid_ajax_path%>',
{ valid: "mail",
value: this.value },
function (data) {
if (data.valid) {
$('#valid_user_mail').html('<span class="green">' + data.message + "</span>");
} else {
$('#valid_user_mail').html('<span class="red">' + data.message + "</span>");
}
});
}
;
});
$password.blur(function () {
var pas1 = document.getElementById("user_password").value;
var password_min_length = <%= password_min_length %>
if (pas1.length >= password_min_length) {
$('#valid_user_password').html('<span class="green">'+ "</span>");
}
else {
$('#valid_user_password').html('<span class="red">' + "<%= l(:setting_password_min_length_limit, :count => password_min_length) %>" + "</span>");
}
});
$password_confirmation.blur(function () {
var password_min_length = <%= password_min_length %>
var pas1 = document.getElementById("user_password").value;
var pas2 = document.getElementById("user_password_confirmation").value;
if (pas1.length >= password_min_length && pas1 == pas2 ) {
$('#valid_password').html('<span class="green">' + "<%= l(:setting_password_success) %>"+ "</span>");
}
else {
$('#valid_password').html('<span class="red">' + "<%= l(:setting_password_error) %>" + "</span>");
}
});
});
</script>

@ -27,6 +27,9 @@
<td class="center"> <td class="center">
<%= course.course_activities.count%> <%= course.course_activities.count%>
</td> </td>
<td class="center">
<%= course.time %>
</td>
<td class="buttons"> <td class="buttons">
<%= link_to( course.is_excellent == 1 || course.excellent_option == 1 ? "取消精品" : "设为精品", { :controller => 'admin', :action => 'set_excellent_course', :id => course.id },:remote=>true, :class => 'icon-del') %> <%= link_to( course.is_excellent == 1 || course.excellent_option == 1 ? "取消精品" : "设为精品", { :controller => 'admin', :action => 'set_excellent_course', :id => course.id },:remote=>true, :class => 'icon-del') %>
</td> </td>

@ -24,8 +24,8 @@
<th style="width: 100px;"> <th style="width: 100px;">
测试完成时间 测试完成时间
</th> </th>
<th style="width: 60px;"> <th style="width: 80px;">
<span style="float:left; margin-left:20px;">答题状态</span> <span style="float:left; margin-left:30px;">答题状态</span>
</th> </th>
<th style="width: 50px;"> <th style="width: 50px;">
<span style="float:left; margin-left:20px;">耗时</span> <span style="float:left; margin-left:20px;">耗时</span>
@ -76,6 +76,10 @@
<%= "代码超时" %> <%= "代码超时" %>
<% elsif test.status == -3 %> <% elsif test.status == -3 %>
<%= "请求超时" %> <%= "请求超时" %>
<% elsif test.status == -4 %>
<%= "judge代码出错!" %>
<% elsif test.status == -5 %>
<%= "trustie代码出错!" %>
<% else %> <% else %>
<%= "答题错误" %> <%= "答题错误" %>
<% end %> <% end %>

@ -39,7 +39,7 @@
<%= number_to_human_size(resource.filesize)%> <%= number_to_human_size(resource.filesize)%>
</td> </td>
<td style=" text-align: center;"> <td style=" text-align: center;">
课程资源 班级资源
</td> </td>
<td style=" text-align: center;"> <td style=" text-align: center;">
<%= format_date(resource.created_on)%> <%= format_date(resource.created_on)%>

@ -45,11 +45,14 @@
<th style="width: 25px;"> <th style="width: 25px;">
资源数 资源数
</th> </th>
<th style="width: 50px;"> <th style="width: 30px;">
帖子数 帖子数
</th> </th>
<th style="width: 50px;" class = "<%= @order == 'desc' ? 'st_up' : (@order == 'asc' ? 'st_down' : '') %>"> <th style="width: 30px;" class = "<%= @order == 'act' ? (@sort == 'desc' ? 'st_up' : (@sort == 'asc' ? 'st_down' : '')) : '' %>">
<%=link_to '动态数', excellent_all_courses_path(:order=> @order == "desc" ? 'asc' : 'desc') %> <%=link_to '动态数', excellent_all_courses_path(:sort=> @sort == "desc" ? 'asc' : 'desc', :order => 'act') %>
</th>
<th style="width: 40px;" class = "<%= @order == 'time' ? (@sort == 'desc' ? 'st_up' : (@sort == 'asc' ? 'st_down' : '')) : '' %>">
<%=link_to '开课学期', excellent_all_courses_path(:sort=> @sort == "desc" ? 'asc' : 'desc', :order => 'time') %>
</th> </th>
<th style="width: 40px;"> <th style="width: 40px;">
</tr> </tr>

@ -2,7 +2,7 @@
<h3> <h3>
<%=l(:label_excellent_courses_list)%> <%=l(:label_excellent_courses_list)%>
</h3> </h3>
<%= render 'tab_excellent_courses' %> <%= render 'admin/tab_excellent_courses' %>
<h3> <h3>
<%=l(:label_excellent_courses_list)%> <%=l(:label_excellent_courses_list)%>
@ -33,12 +33,14 @@
<th style="width: 25px;"> <th style="width: 25px;">
资源数 资源数
</th> </th>
<th style="width: 70px;"> <th style="width: 50px;">
帖子数 帖子数
</th> </th>
<th style="width: 70px;"> <th style="width: 50px;">
动态数 动态数
</th> </th>
<th style="width: 40px;">
</tr>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@ -74,6 +76,9 @@
<td class="center"> <td class="center">
<%= course.course_activities.count%> <%= course.course_activities.count%>
</td> </td>
<td class="buttons">
<%= link_to( course.is_excellent == 1 || course.excellent_option == 1 ? "取消精品" : "设为精品", { :controller => 'admin', :action => 'cancel_excellent_course', :id => course.id }, :class => 'icon-del') %>
</td>
</tr> </tr>
<% end %> <% end %>
</tbody> </tbody>

@ -59,12 +59,12 @@
<td class="center"> <td class="center">
<%= format_date(journal.created_on) %> <%= format_date(journal.created_on) %>
</td> </td>
<td style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" title='<%=journal.notes %>'> <td style="white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" title='<%=strip_html(journal.notes) %>'>
<%case journal.jour_type %> <%case journal.jour_type %>
<% when 'Principal' %> <% when 'Principal' %>
<%= link_to(journal.notes.html_safe, feedback_path(journal.jour_id)) %> <%= link_to(strip_html(journal.notes), feedback_path(journal.jour_id)) %>
<% when 'Course' %> <% when 'Course' %>
<%= link_to(journal.notes.html_safe, course_feedback_path(journal.jour_id)) %> <%= link_to(strip_html(journal.notes), course_feedback_path(journal.jour_id)) %>
<% end %> <% end %>
</td> </td>
<td class="center"> <td class="center">

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save