Merge branch 'rep_quality' into 'dev_hjq'

Rep quality

tedy

See merge request !3
dev_hjq
黄井泉 9 years ago
commit 266de9ac7d

7
.gitignore vendored

@ -7,6 +7,7 @@
/config/configuration.yml /config/configuration.yml
/config/additional_environment.rb /config/additional_environment.rb
/files/* /files/*
/log/* /log/*
/public/tmp/* /public/tmp/*
@ -30,3 +31,9 @@ vendor/cache
/public/files /public/files
/tags /tags
/config/initializers/gitlab_config.rb /config/initializers/gitlab_config.rb
1234567
public/javascripts/wechat/node_modules/
.ruby-version
.access_token
tmux*.log
config/wechat.yml

@ -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,11 +1,20 @@
source 'https://ruby.taobao.org' source 'https://ruby.taobao.org/'
#source 'http://ruby.sdutlinux.org/'
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
elsif RUBY_PLATFORM =~ /linux/
#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 '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'
gem 'rest-client' gem 'rest-client'
@ -16,8 +25,9 @@ gem 'delayed_job_active_record'#, :group => :production
gem 'daemons' gem 'daemons'
gem 'grape', '~> 0.9.0' gem 'grape', '~> 0.9.0'
gem 'grape-entity' gem 'grape-entity'
gem 'rack-cors', :require => 'rack/cors'
gem 'seems_rateable', '~> 1.0.13' gem 'seems_rateable', '~> 1.0.13'
gem "rails", "3.2.13" gem 'rails', '~> 3.2'
gem "jquery-rails", "~> 2.0.2" gem "jquery-rails", "~> 2.0.2"
gem "i18n", "~> 0.6.0" gem "i18n", "~> 0.6.0"
gem 'coderay', '~> 1.1.0' gem 'coderay', '~> 1.1.0'
@ -27,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'
@ -40,9 +49,16 @@ gem 'kaminari'
gem 'elasticsearch-model' gem 'elasticsearch-model'
gem 'elasticsearch-rails' gem 'elasticsearch-rails'
#rails 3.2.22.2 bug
gem "test-unit", "~>3.0"
### profile
gem 'oneapm_rpm'
group :development do group :development do
gem 'grape-swagger' gem 'grape-swagger'
gem 'better_errors', '~> 1.1.0' gem 'better_errors', '~> 1.1.0'
# gem "query_reviewer"
gem 'rack-mini-profiler', '~> 0.9.3' gem 'rack-mini-profiler', '~> 0.9.3'
if RUBY_PLATFORM =~ /w32/ if RUBY_PLATFORM =~ /w32/
gem 'win32console' gem 'win32console'
@ -72,7 +88,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'
@ -7,11 +9,25 @@ module Mobile
require_relative 'apis/upgrade' require_relative 'apis/upgrade'
require_relative 'apis/homeworks' require_relative 'apis/homeworks'
require_relative 'apis/comments' require_relative 'apis/comments'
require_relative 'apis/issues'
require_relative 'apis/activities'
require_relative 'apis/whomeworks'
require_relative 'apis/newss'
require_relative 'apis/journal_for_messages'
require_relative 'apis/messages'
require_relative 'apis/blog_comments'
require_relative 'apis/new_comment'
require_relative 'apis/praise'
require_relative 'apis/resources'
require_relative 'apis/syllabuses'
require_relative 'apis/projects'
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 Mobile::Middleware::ErrorHandler use ActionDispatch::Session::CookieStore
use Middleware::ErrorHandler
helpers do helpers do
def logger def logger
@ -19,16 +35,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 = session[:wechat_openid]
if openid
uw = UserWechat.find_by_openid(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
@ -39,9 +65,20 @@ module Mobile
mount Apis::Upgrade mount Apis::Upgrade
mount Apis::Homeworks mount Apis::Homeworks
mount Apis::Comments mount Apis::Comments
mount Apis::Issues
mount Apis::Activities
mount Apis::Whomeworks
mount Apis::Newss
mount Apis::JournalForMessages
mount Apis::Messages
mount Apis::BlogComments
mount Apis::NewComment
mount Apis::Praise
mount Apis::Resources
mount Apis::Syllabuses
mount Apis::Projects
#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

@ -0,0 +1,64 @@
#coding=utf-8
module Mobile
module Apis
class Activities< Grape::API
resources :activities do
desc "get user activities"
params do
requires :page, type: Integer
requires :token, type: String
requires :container_type, type: String
end
post do
authenticate!
user = current_user
container_type = params[:container_type] ? params[:container_type] : "All"
if container_type == "All" || container_type == "Project"
shield_project_ids = ShieldActivity.select("shield_id").where("container_type='User' and container_id=#{user.id} and shield_type='Project'").map(&:shield_id)
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(",") + ")"
project_types = "('Message','Issue','Project')"
end
if container_type == "All" || container_type == "Course"
shield_course_ids = ShieldActivity.select("shield_id").where("container_type='User' and container_id=#{user.id} and shield_type='Course'").map(&:shield_id)
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')"
end
page = params[:page] ? params[:page] : 0
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(','))
user_ids = "(" + user.id.to_s + watched_user_ids + ")"
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 + ")"
if container_type == "Course"
activities = UserActivity.where("(container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types})").order('updated_at desc')
elsif container_type == "Project"
activities = UserActivity.where("(container_type = 'Project' and container_id in #{user_project_ids} and act_type in #{project_types})").order('updated_at desc')
else
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
all_count = activities.count
activities = activities.limit(10).offset(page * 10)
count = activities.count
present :data, activities, with: Mobile::Entities::Activity,user: user
present :all_count, all_count
present :count, count
present :page, page
present :status, 0
present :container_type, container_type
end
end
end
end
end

@ -0,0 +1,26 @@
#coding=utf-8
module Mobile
module Apis
class BlogComments< Grape::API
resources :blog_comments do
desc "get special topic"
post ':id' do
user = current_user
#0一级回复的更多 1 二级回复的更多
type = params[:type] || 0
page = params[:page] || 0
blog = BlogComment.find params[:id]
present :data, blog, with: Mobile::Entities::BlogComment,user: user,type: type,page: page
present :type, type
present :page, page
present :status, 0
end
end
end
end
end

@ -115,7 +115,7 @@ module Mobile
desc '通知评论列表' desc '通知评论列表'
params do params do
requires :token, type: String #requires :token, type: String
requires :notice_id,type:Integer,desc:'通知id' requires :notice_id,type:Integer,desc:'通知id'
optional :page,type:Integer,desc:'页码' optional :page,type:Integer,desc:'页码'
end end

@ -14,9 +14,10 @@ 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,user: current_user
present :status, 0 present :status, 0
end end
@ -55,7 +56,7 @@ module Mobile
class_period: params[:class_period] class_period: params[:class_period]
} }
courses = cs.create_course(cs_params, current_user) courses = cs.create_course(cs_params, current_user)
present :data, courses, with: Mobile::Entities::Course present :data, courses, with: Mobile::Entities::Course,user: current_user
present :status, 0 present :status, 0
end end
@ -89,7 +90,7 @@ module Mobile
end end
cs.edit_course_authorize(current_user,course) cs.edit_course_authorize(current_user,course)
course = cs.edit_course(cs_params, course,current_user) course = cs.edit_course(cs_params, course,current_user)
present :data, course, with: Mobile::Entities::Course present :data, course, with: Mobile::Entities::Course,user: current_user
present :status, 0 present :status, 0
end end
post do post do
@ -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; "加入成功" message: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
@ -143,7 +138,7 @@ module Mobile
get 'search' do get 'search' do
cs = CoursesService.new cs = CoursesService.new
courses = cs.search_course(params,current_user.nil? ? User.find(2):current_user) courses = cs.search_course(params,current_user.nil? ? User.find(2):current_user)
present :data, courses, with: Mobile::Entities::Course present :data, courses, with: Mobile::Entities::Course,user: current_user
present :status, 0 present :status, 0
end end
@ -198,15 +193,20 @@ module Mobile
desc "返回单个课程" desc "返回单个课程"
params do params do
requires :id, type: Integer requires :id, type: Integer
optional :token, type: String requires :token,type:String
end end
route_param :id do route_param :id do
get do get do
# course = Course.find(params[:id])
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)
#course = Course.find(params[:id])
present :data, course, with: Mobile::Entities::Course if course[:course][:is_delete] == 1
{ status: 0} {status:-1, message: '该班级不存在或已被删除啦' }
else
present :data, course, with: Mobile::Entities::Course,user: current_user
present :status, 0
end
end end
end end
@ -217,7 +217,7 @@ module Mobile
get "homeworks/:id" do get "homeworks/:id" do
cs = CoursesService.new cs = CoursesService.new
homeworks = cs.homework_list params,current_user homeworks = cs.homework_list params,current_user
present :data, homeworks, with: Mobile::Entities::Homework present :data, homeworks, with: Mobile::Entities::Homework,user: current_user
present :status, 0 present :status, 0
end end
@ -264,7 +264,7 @@ module Mobile
post ":course_id/attachments" do post ":course_id/attachments" do
cs = CoursesService.new cs = CoursesService.new
count = cs.course_attachments params count = cs.course_attachments params
present :data, count, with: Mobile::Entities::Attachment present :data, count, with: Mobile::Entities::Attachment,user: current_user
present :status, 0 present :status, 0
end end
@ -389,7 +389,82 @@ module Mobile
end end
desc '获取测验列表'
params do
requires :token, type:String
end
get ':course_id/exercises' do
authenticate!
course = Course.find(params[:course_id])
exercises = course.exercises.where("exercise_status <> 1").reorder("created_at desc")
present :data,exercises,with:Mobile::Entities::Exercise,user: current_user
present :status,0
end
desc '删除课程'
params do
requires :token, type: String
end
post ':course_id/del' do
authenticate!
c = Course.find(params[:course_id])
# if c.members.count > 1
# {status: -1, message: '已经有成员加入,不能删除'}
# else
c.delete!
present :status,0
# end
end
desc "获取班级某成员角色信息"
params do
requires :id, type: Integer
requires :token, type: String
requires :user_id, type: Integer
end
post 'get_member_info' do
authenticate!
c = Course.find("#{params[:id]}")
my_member = c.member_principals.where("users.id=#{params[:user_id]}").first
if my_member && my_member.roles[0]
present :course_id,params[:id]
present :user_id,params[:user_id]
present :member_info,my_member, with: Mobile::Entities::ProjectMember
present :status, 0
else
present :status, -1
end
end
desc "修改班级某成员角色信息"
params do
requires :id, type: Integer
requires :token, type: String
requires :user_id, type: Integer
requires :role_id, type: Integer
end
post 'edit_member_role' do
authenticate!
c = Course.find("#{params[:id]}")
#7教辅 9教师 10学生
if c.tea_id == params[:user_id] || c.tea_id != current_user.id || !(params[:role_id] == 7 || params[:role_id] == 9 || params[:role_id] == 10)
present :status, -1
else
cs = CoursesService.new
status = cs.modify_user_course_role params
present :status, status
end
end
end end
end end

@ -0,0 +1,26 @@
#coding=utf-8
module Mobile
module Apis
class Issues< Grape::API
resources :issues do
include IssuesHelper
desc "get special issuse"
post ':id' do
authenticate!
user = current_user
#0一级回复的更多 1 二级回复的更多
type = params[:type] || 0
page = params[:page] || 0
issue = Issue.find params[:id]
present :data, issue, with: Mobile::Entities::Issue,user: user,type: type,page: page
present :type, type
present :page, page
present :status, 0
end
end
end
end
end

@ -0,0 +1,26 @@
#coding=utf-8
module Mobile
module Apis
class JournalForMessages< Grape::API
resources :journal_for_messages do
desc "get special journal"
post ':id' do
authenticate!
user = current_user
#0一级回复的更多 1 二级回复的更多
type = params[:type] || 0
page = params[:page] || 0
jour = JournalsForMessage.find params[:id]
present :data, jour, with: Mobile::Entities::Jours,user: user,type: type,page: page
present :type, type
present :page, page
present :status, 0
end
end
end
end
end

@ -0,0 +1,25 @@
#coding=utf-8
module Mobile
module Apis
class Messages< Grape::API
resources :messages do
desc "get special topic"
post ':id' do
authenticate!
user = current_user
#0一级回复的更多 1 二级回复的更多
type = params[:type] || 0
page = params[:page] || 0
message = Message.find params[:id]
present :data, message, with: Mobile::Entities::Message,user: user,type: type,page: page
present :type, type
present :page, page
present :status, 0
end
end
end
end
end

@ -0,0 +1,105 @@
#coding=utf-8
module Mobile
module Apis
class NewComment< Grape::API
include ApplicationHelper
include ApiHelper
resources :new_comment do
desc "add a new comment"
params do
requires :type, type: String
requires :content, type: String
requires :token, type: String
end
post ':id' do
authenticate!
type = params[:type]
result = 1
if params[:content]!="" && current_user
case type
when "HomeworkCommon"
homework_common = HomeworkCommon.find(params[:id])
feedback = HomeworkCommon.add_homework_jour(current_user, params[:content], params[:id])
if (feedback.errors.empty?)
homework_common.update_column(:updated_at, Time.now)
result = 2
end
when "News"
news = News.find(params[:id])
comment = Comment.new
comment.comments = params[:content]
comment.author = current_user
if news.comments << comment
result = 2
end
when "Message"
message = Message.find(params[:id])
board = Board.find(message.board_id)
topic = message.root
reply = Message.new
reply.author = current_user
reply.board = board
reply.content = params[:content]
reply.parent_id = params[:id]
reply.subject = "RE: #{topic.subject}"
if topic.children << reply
result = 2
end
when "JournalsForMessage"
jour = JournalsForMessage.find params[:id]
parent_id = params[:id]
author_id = current_user.id
reply_user_id = jour.user_id
reply_id = params[:id]
content = params[:content]
options = {:user_id => author_id,
:status => true,
:m_parent_id => parent_id,
:m_reply_id => reply_id,
:reply_id => reply_user_id,
:notes => content,
:is_readed => false}
jfm = jour.user.add_jour(nil, nil, nil, options)
if jfm.errors.empty?
(JournalsForMessage.find parent_id).update_attribute(:updated_on,Time.now)
result = 2
end
when 'Issue'
issue = Issue.find params[:id]
is_jour = Journal.new
is_jour.user_id = current_user.id
is_jour.notes = params[:content]
is_jour.journalized = issue
if is_jour.save
result = 2
end
when 'BlogComment'
blog = BlogComment.find(params[:id]).root
blogComment = BlogComment.new
blogComment.author = current_user
blogComment.blog = blog.blog
blogComment.content = params[:content]
blogComment.title = "RE: #{blog.title}"
if blog.children << blogComment
result = 2
end
end
if result == 2
update_course_activity_api(type,params[:id])
update_user_activity_api(type,params[:id])
update_org_activity_api(type,params[:id])
update_forge_activity_api(type,params[:id])
update_principal_activity_api(type,params[:id])
end
else
result = 3
end
present :result, result
present :status, 0
end
end
end
end
end

@ -0,0 +1,25 @@
#coding=utf-8
module Mobile
module Apis
class Newss< Grape::API
resources :newss do
desc "get special news"
post ':id' do
authenticate!
user = current_user
#0一级回复的更多 1 二级回复的更多
type = params[:type] || 0
page = params[:page] || 0
news = News.find params[:id]
present :data, news, with: Mobile::Entities::News,user: user,type: type,page: page
present :type, type
present :page, page
present :status, 0
end
end
end
end
end

@ -0,0 +1,42 @@
#coding=utf-8
module Mobile
module Apis
class Praise< Grape::API
include ApiHelper
resources :praise do
desc "praise an activity"
params do
requires :type, type: String
requires :token, type: String
end
post ':id' do
authenticate!
obj_id = params[:id]
obj_type = params[:type]
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
if pts.blank?
praise_or_cancel(obj_type,obj_id,user,1)
obj = PraiseTreadCache.where("object_id=? and object_type=?",obj_id,obj_type.to_s).first
num = get_activity_praise_num(obj) if !obj.blank?
else
pts.destroy if !pts.blank?
#再更新praise_tread_cache表 使相应的记录减1 当为0时删除
ptc = PraiseTreadCache.where("object_id=? and object_type=?",obj_id,obj_type.to_s).first
ptc.praise_minus(1) if !ptc.blank?
if ptc.praise_num == 0
ptc.delete
end
obj = PraiseTreadCache.where("object_id=? and object_type=?",obj_id,obj_type.to_s).first
num = !obj.blank? ? get_activity_praise_num(obj) : 0
end
present :data, num
present :status, 0
end
end
end
end
end

@ -0,0 +1,181 @@
#coding=utf-8
module Mobile
module Apis
class Projects < Grape::API
resources :projects do
desc "获取项目列表"
params do
requires :token, type: String
end
get do
authenticate!
ps = ProjectsService.new
projects = ps.user_projects(current_user)
present :data, projects, with: Mobile::Entities::Project,user: current_user
present :status, 0
end
desc "返回单个项目"
params do
requires :id, type: Integer
requires :token,type:String
end
route_param :id do
get do
# course = Course.find(params[:id])
ps = ProjectsService.new
project = ps.show_project(params,current_user)
if project[:status] == 9
{status:-1, message: '该项目不存在或已被删除啦' }
else
present :data, project, with: Mobile::Entities::Project,user: current_user
present :status, 0
end
end
end
desc "获取项目动态"
params do
requires :id, type: Integer
requires :token, type: String
end
post 'activities' do
authenticate!
user = current_user
project_types = "('Message','Issue','Project')"
activities = UserActivity.where("(container_type = 'Project' and container_id = #{params[:id]} and act_type in #{project_types})").order('updated_at desc')
page = params[:page] ? params[:page] : 0
all_count = activities.count
activities = activities.limit(10).offset(page * 10)
count = activities.count
present :data, activities, with: Mobile::Entities::Activity,user: user
present :all_count, all_count
present :count, count
present :page, page
present :status, 0
end
desc "获取项目成员"
params do
requires :id, type: Integer
requires :token, type: String
end
post 'members' do
authenticate!
project = Project.find("#{params[:id]}")
members = project.member_principals
master_members = project.member_principals.includes(:roles, :principal).where("member_roles.role_id=3").all.sort
master_members.each do |m|
if m.user_id == project.user_id
master_members.delete(m)
master_members.insert(0,m)
break
end
end
develop_members = project.member_principals.includes(:roles, :principal).where("member_roles.role_id=4").all.sort
report_members = project.member_principals.includes(:roles, :principal).where("member_roles.role_id=5").all.sort
present :master_members,master_members, with: Mobile::Entities::ProjectMember
present :develop_members,develop_members, with: Mobile::Entities::ProjectMember
present :report_members,report_members, with: Mobile::Entities::ProjectMember
present :status, 0
end
desc "获取项目某成员角色信息"
params do
requires :id, type: Integer
requires :token, type: String
requires :user_id, type: Integer
end
post 'get_member_info' do
authenticate!
project = Project.find("#{params[:id]}")
my_member = project.member_principals.where("users.id=#{params[:user_id]}").first
if my_member && my_member.roles[0]
present :project_id,params[:id]
present :user_id,params[:user_id]
present :member_info,my_member, with: Mobile::Entities::ProjectMember
present :status, 0
else
present :status, -1
end
end
desc "修改项目某成员角色信息"
params do
requires :id, type: Integer
requires :token, type: String
requires :user_id, type: Integer
requires :role_id, type: Integer
end
post 'edit_member_role' do
authenticate!
project = Project.find("#{params[:id]}")
my_member = project.member_principals.where("users.id=#{current_user.id}").first
#3管理 4开发 5报告
if !(my_member && my_member.roles[0] && my_member.roles[0].id == 3 ) || project.user_id == params[:user_id] || !(params[:role_id] == 3 || params[:role_id] == 4 || params[:role_id] == 5)
present :status, -1
else
ps = ProjectsService.new
status = ps.modify_user_project_role params
present :status, status
end
end
desc "新建项目"
params do
requires :token, type: String
requires :name, type: String, desc: '项目名称'
end
post 'create' do
authenticate!
ps = ProjectsService.new
status = ps.createNewProject params,current_user
present :status, 0
end
desc "加入项目"
params do
requires :token, type: String
requires :invite_code, type: String, desc: '邀请码'
end
post "join" do
authenticate!
# ps = ProjectsService.new
# status = ps.join_project({role: "5", openid: params[:openid], invite_code: params[:invite_code]}, current_user)
#
# present :status, status
{status:-1, message: '该功能将在近日开放,敬请期待!' }
end
end
end
end
end

@ -0,0 +1,119 @@
#coding=utf-8
module Mobile
module Apis
class Resources < Grape::API
resource :resources do
desc '获取所有课件'
params do
requires :token, type: String
requires :page, type: Integer
end
post do
authenticate!
page = params[:page] ? params[:page] : 0
rs = ResourcesService.new
# data = current_user.course_attachments
data = rs.all_course_attachments current_user
all_count = data.count
data = data.limit(10).offset(page * 10)
count = data.count
present :data, data, with: Mobile::Entities::Attachment,user: current_user
present :all_count, all_count
present :count, count
present :page, page
present :status, 0
end
desc '获取所有作业'
params do
requires :token, type: String
requires :page, type: Integer
end
post 'homeworks' do
authenticate!
page = params[:page] ? params[:page] : 0
rs = ResourcesService.new
homeworks = rs.all_homework_commons current_user
all_count = homeworks.count
homeworks = homeworks.limit(10).offset(page * 10)
count = homeworks.count
present :data, homeworks, with: Mobile::Entities::Homework,user: current_user
present :all_count, all_count
present :count, count
present :page, page
present :status, 0
end
desc '获取所有测验'
params do
requires :token, type: String
requires :page, type: Integer
end
post 'exercises' do
authenticate!
page = params[:page] ? params[:page] : 0
rs = ResourcesService.new
exercises = rs.all_exercises current_user
all_count = exercises.count
exercises = exercises.limit(10).offset(page * 10)
count = exercises.count
present :data, exercises, with: Mobile::Entities::Exercise,user: current_user
present :all_count, all_count
present :count, count
present :page, page
present :status, 0
end
desc '发送资源'
params do
requires :token, type: String
requires :course_ids, type: Array[Integer]
requires :send_id, type: Integer
requires :send_type, type: Integer
end
post 'send' do
authenticate!
rs = ResourcesService.new
ori = nil
flag = false
save_message = nil
case params[:send_type]
when 1
ori, flag, save_message = rs.send_resource_to_course(current_user,params)
when 2
ori, flag, save_message = rs.send_homework_to_course(current_user,params)
when 3
ori, flag, save_message = rs.send_exercise_to_course(current_user,params)
end
if flag
present :status, 0
else
{status: -1, message: save_message.first}
end
end
end
end
end
end

@ -0,0 +1,102 @@
#coding=utf-8
module Mobile
module Apis
class Syllabuses < Grape::API
resources :syllabuses do
desc "获取大纲列表"
params do
requires :token, type: String
end
get do
authenticate!
cs = SyllabusesService.new
courses = cs.user_syllabus(current_user)
present :data, courses, with: Mobile::Entities::Syllabus,user: current_user
present :status, 0
end
desc "获取某个大纲"
params do
requires :token, type: String
end
get ':id' do
authenticate!
ss = SyllabusesService.new
sy = ::Syllabus.find(params[:id])
sy.courses = sy.courses.not_deleted
present :data, sy, with: Mobile::Entities::Syllabus,user: current_user
present :status, 0
end
desc "获取新建大纲的权限"
params do
requires :token, type: String
end
post 'auth' do
authenticate!
auth = 0
if (current_user.user_extensions && current_user.user_extensions.identity == 0 && current_user.allowed_to?(:add_course, nil, :global => true))
auth = 1
end
present :auth, auth
end
desc "新建大纲"
params do
requires :token, type: String
requires :title, type: String, desc: '大纲标题'
requires :courses, type: Array[String], desc: '课程名'
end
post do
authenticate!
ss = SyllabusesService.new
sy = ss.create(current_user, params[:title],
params[:courses].map{|c| {name: c} })
if sy.new_record?
{status:-1, message: '创建大纲失败' }
else
present :data, sy, with: Mobile::Entities::Syllabus,user: current_user
present :status, 0
end
end
desc '编辑大纲'
params do
requires :token, type: String
requires :title, type: String, desc: '大纲标题'
# requires :add_courses, type: Array[String], desc: '课程名'
# requires :modify_courses, type: Array[Integer,String], desc: '课程名'
end
post ':id/edit' do
authenticate!
ss = SyllabusesService.new
#修改课程大纲
status = ss.edit(current_user, params)
if status == -1
{status:status, message: '修改课程信息失败' }
else
present :status, status
end
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, Time.now.strftime("%Y-%m-%d"))
present status: 0, message: '您已成功绑定Trustie平台'
end
desc "注册用户" desc "注册用户"
params do params do
requires :login, type: String, desc: 'username' requires :login, type: String, desc: 'username'
@ -11,11 +53,22 @@ module Mobile
requires :password, type: String, desc: 'password' requires :password, type: String, desc: 'password'
end end
post do post do
openid = session[:wechat_openid]
logger.debug "openid ============== #{openid}"
raise "无法获取到openid,请在微信中打开本页面" unless openid
us = UsersService.new us = UsersService.new
user = us.register params.merge(:password_confirmation => params[:password], user = us.register params.merge(:password_confirmation => params[:password],
:should_confirmation_password => true) :should_confirmation_password => true)
raise "该邮箱已经被注册过了" if user.new_record? raise user.errors.full_messages.first if user.new_record?
UserWechat.create!(
openid: openid,
user: user
)
ws = WechatService.new
ws.binding_succ_notice(user.id, "您已成功绑定Trustie平台。", user.login, Time.now.strftime("%Y-%m-%d"))
present :data, user, with: Mobile::Entities::User present :data, user, with: Mobile::Entities::User
present :status, 0 present :status, 0
end end

@ -0,0 +1,31 @@
#coding=utf-8
module Mobile
module Apis
class Whomeworks< Grape::API
resources :whomeworks do
desc "get one homework"
post ':id' do
authenticate!
user = current_user
#0一级回复的更多 1 二级回复的更多
type = params[:type] || 0
page = params[:page] || 0
if type == 0
homework = HomeworkCommon.find params[:id]
present :data, homework, with: Mobile::Entities::Whomework,user: user,type: type,page: page,comment_type: "homework"
else
jour = JournalsForMessage.find params[:id]
present :data, jour, with: Mobile::Entities::Jours,user: user,type: type,page: page,comment_type: "homework"
end
present :type, type
present :page, page
present :status, 0
end
end
end
end
end

@ -0,0 +1,149 @@
# encoding: utf-8
module Mobile
module Entities
class Activity <Grape::Entity
include ApplicationHelper
include ApiHelper
def self.act_expose(f)
expose f do |ac,opt|
if ac.is_a?(Hash) && ac.key?(f)
ac[f]
elsif ac.is_a?(::UserActivity)
if ac.respond_to?(f)
ac.send(f)
else
case f
when :user_act
if ac.act_type == "Project"
ac unless ac.nil?
else
ac.act unless ac.nil? || ac.act.nil?
end
when :reply_count
if ac.act_type == "HomeworkCommon"
ac.nil? || ac.act.nil? ? 0 : ac.act.journals_for_messages.count
elsif ac.act_type == "News"
ac.nil? || ac.act.nil? ? 0 : ac.act.comments.count
elsif ac.act_type == "Message" || ac.act_type == "BlogComment" || ac.act_type == "JournalsForMessage"
all_comments = []
ac.nil? || ac.act.nil? ? 0 : get_all_children(all_comments, ac.act).count
elsif ac.act_type == "Issue"
ac.nil? || ac.act.nil? ? 0 : ac.act.journals.where("notes is not null and notes != ''").count
end
when :subject
if ac.act_type == "HomeworkCommon"
ac.act.name unless ac.nil? || ac.act.nil?
elsif ac.act_type == "News" || ac.act_type == "BlogComment"
ac.act.title unless ac.nil? || ac.act.nil?
elsif ac.act_type == "Message" || ac.act_type == "Issue"
ac.act.subject unless ac.nil? || ac.act.nil?
elsif ac.act_type == "JournalsForMessage"
ac.act.private == 0 ? "留言" : "私信" unless ac.nil? || ac.act.nil?
end
when :description
if ac.act_type == "HomeworkCommon" || ac.act_type == "Issue" || ac.act_type == "News"
strip_html(ac.act.description) unless ac.nil? || ac.act.nil?
elsif ac.act_type == "Message" || ac.act_type == "BlogComment"
strip_html(ac.act.content) unless ac.nil? || ac.act.nil?
elsif ac.act_type == "JournalsForMessage"
strip_html(ac.act.notes) unless ac.nil? || ac.act.nil?
end
when :latest_update
time_from_now ac.updated_at unless ac.nil?
when :praise_count
if ac.act_type == "HomeworkCommon" || ac.act_type == "News" || ac.act_type == "Message" || ac.act_type == "BlogComment" || ac.act_type == "JournalsForMessage" || ac.act_type == "Issue"
ac.nil? || ac.act.nil? ? 0 : get_activity_praise_num(ac.act)
end
#when :homework_common_detail_manual
# if ac.act_type == "HomeworkCommon"
# ac.act.homework_detail_manual unless ac.nil? || ac.act.nil? || ac.act.homework_detail_manual.nil?
# end
when :course_project_name
if ac.container_type == "Course"
name = (get_course(ac.container_id)).name
name
elsif ac.container_type == "Project"
name = (get_project(ac.container_id)).name
name
elsif ac.container_type == "Blog"
"发表博客"
end
when :activity_type_name
if ac.container_type == "Course"
case ac.act_type
when "HomeworkCommon"
"课程作业"
when "News"
"课程通知"
when "Message"
"课程问答区"
when "Poll"
"课程问卷"
when "Course"
"课程"
end
elsif ac.container_type == "Project"
case ac.act_type
when "Issue"
"项目问题"
when "Message"
"项目讨论区"
when "Project"
"项目"
end
end
end
end
end
end
end
expose :act_type #缺陷/作业/讨论区/留言等类型
expose :act_id
expose :id
expose :container_type #课程/项目/博客/个人
expose :author, using: Mobile::Entities::User do |a, opt| #用户信息
if a.is_a? ::UserActivity
if a.act_type == "Project"
get_user(get_project(a.act_id).user_id)
elsif !a.act.nil?
if a.act_type == 'Issue' || a.act_type == 'News' || a.act_type == 'Message' || a.act_type == 'BlogComment'
a.act.author
elsif a.act_type == 'HomeworkCommon' || a.act_type == 'Poll' || a.act_type == 'JournalsForMessage'
a.act.user
elsif a.act_type == 'Course'
a.act.teacher
end
end
end
end
expose :homework_common_detail , using: Mobile::Entities::Whomework do |a, opt| #作业相关信息
if a.act_type == "HomeworkCommon"
a.act
end
end
expose :issue_detail, using: Mobile::Entities::Issue do |a, opt| #缺陷信息
if a.act_type == "Issue"
a.act
end
end
act_expose :reply_count #回复数
act_expose :praise_count #点赞数
#act_expose :user_act #某个动态
act_expose :subject #标题
act_expose :description #描述
act_expose :latest_update #最新更新时间
act_expose :course_project_name #课程/项目名字
act_expose :activity_type_name #课程问答区/项目缺陷等
expose :has_praise , if: lambda { |instance, options| options[:user] } do |instance, options|
if instance.act_type == "HomeworkCommon" || instance.act_type == "News" || instance.act_type == "Message" || instance.act_type == "BlogComment" || instance.act_type == "JournalsForMessage" || instance.act_type == "Issue"
has_praise = false
current_user = options[:user]
obj = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",instance.act_id,instance.act_type.to_s,current_user.id)
has_praise = obj.empty? ? false : true
has_praise
end
end
end
end
end

@ -2,6 +2,8 @@ module Mobile
module Entities module Entities
class Attachment < Grape::Entity class Attachment < Grape::Entity
include Redmine::I18n include Redmine::I18n
include ActionView::Helpers::NumberHelper
include ApplicationHelper
def self.attachment_expose(field) def self.attachment_expose(field)
expose field do |f,opt| expose field do |f,opt|
if f.is_a?(Hash) && f.key?(field) if f.is_a?(Hash) && f.key?(field)
@ -17,6 +19,11 @@ module Mobile
case field case field
when :file_dir when :file_dir
"attachments/download/" << f.send(:id).to_s << '/' "attachments/download/" << f.send(:id).to_s << '/'
when :attafile_size
(number_to_human_size(f.filesize)).gsub("ytes", "").to_s
when :coursename
f.course.nil? ? "" : f.course.name
end end
end end
end end
@ -29,6 +36,14 @@ module Mobile
attachment_expose :quotes attachment_expose :quotes
attachment_expose :created_on attachment_expose :created_on
attachment_expose :file_dir attachment_expose :file_dir
attachment_expose :attafile_size
attachment_expose :coursename #所属班级名
expose :current_user_is_teacher, if: lambda { |instance, options| options[:user] } do |instance, options|
current_user = options[:user]
current_user_is_teacher = false
current_user_is_teacher = is_course_teacher(current_user,instance.course)
current_user_is_teacher
end
end end
end end
end end

@ -0,0 +1,135 @@
module Mobile
module Entities
class BlogComment < Grape::Entity
include ApplicationHelper
include ApiHelper
def self.blog_comment_expose(f)
expose f do |u,opt|
if u.is_a?(Hash) && u.key?(f)
u[f]
elsif u.is_a?(::BlogComment)
if u.respond_to?(f)
if f == :created_at
format_time( u.send(f))
else
u.send(f)
end
else
case f
when :praise_count
get_activity_praise_num(u)
when :lasted_comment
time_from_now(u.created_at)
when :act_type
'BlogComment'
when :act_id
u.id
when :comment_count
# u.children.count
all_comments = []
get_all_children(all_comments, u).count
end
end
end
end
end
expose :user, using: Mobile::Entities::User do |c, opt|
if c.is_a?(::BlogComment)
c.author
end
end
blog_comment_expose :act_type
blog_comment_expose :act_id
blog_comment_expose :blog_id
blog_comment_expose :title
blog_comment_expose :content
blog_comment_expose :comment_count
blog_comment_expose :created_at
blog_comment_expose :lasted_comment
blog_comment_expose :id
blog_comment_expose :locked
blog_comment_expose :praise_count
expose :all_children, using:Mobile::Entities::BlogComment do |c,opt|
if c.is_a? (::BlogComment)
if !opt[:children]
if c.parent.nil? && opt[:type] == 0
opt[:children] = true
all_comments = []
tStart = opt[:page]*5
tEnd = (opt[:page]+1)*5 - 1
all_comments = get_all_children(all_comments, c)[tStart..tEnd]
all_comments
end
end
end
end
expose :has_praise, if: lambda { |instance, options| options[:user] } do |instance, options|
has_praise = false
current_user = options[:user]
obj = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",instance.id,instance.class.to_s,current_user.id)
has_praise = obj.empty? ? false : true
has_praise
end
expose :parents_count, if: lambda { |instance, options| options[:user] } do |instance, options|
parents_reply = []
parents_reply = get_reply_parents_no_root(parents_reply, instance)
parents_reply.count
end
expose :parents_reply_bottom, using:Mobile::Entities::BlogComment do |c,opt|
if c.is_a? (::BlogComment)
#取二级回复的底楼层
parents_reply = []
parents_reply = get_reply_parents_no_root(parents_reply, c)
if parents_reply.count > 0 && parents_reply.count != 2 && !opt[:bottom]
if opt[:type] == 1
# opt[:bottom] = true
# parents_reply[opt[:page]..opt[:page]]
else
opt[:bottom] = true
parents_reply[0..0]
end
else
[]
end
end
end
expose :parents_reply_top, using:Mobile::Entities::BlogComment do |c,opt|
if c.is_a? (::BlogComment)
#取二级回复的顶楼层
parents_reply = []
parents_reply = get_reply_parents_no_root(parents_reply, c)
if parents_reply.count >= 2 && !opt[:top]
if opt[:type] == 1
opt[:bottom] = true
tStart = (opt[:page]-1)*5+2
tEnd = (opt[:page])*5+2 - 1
if tEnd >= parents_reply.count - 1
tEnd = parents_reply.count - 2
end
if tStart <= parents_reply.count - 2
parents_reply = parents_reply.reverse[tStart..tEnd]
parents_reply.reverse
else
[]
end
else
opt[:top] = true
parents_reply = parents_reply.reverse[0..1]
parents_reply.reverse
end
else
[]
end
end
end
end
end
end

@ -9,7 +9,7 @@ module Mobile
elsif f.is_a?(::Comment) elsif f.is_a?(::Comment)
if f.respond_to?(field) if f.respond_to?(field)
if field == :created_on if field == :created_on
format_time(f.send(field)) time_from_now(f.send(field))
else else
f.send(field) f.send(field)
end end

@ -2,6 +2,8 @@ module Mobile
module Entities module Entities
class Course < Grape::Entity class Course < Grape::Entity
include Redmine::I18n include Redmine::I18n
include ApplicationHelper
include ApiHelper
def self.course_expose(field) def self.course_expose(field)
expose field do |f,opt| expose field do |f,opt|
c = nil c = nil
@ -15,6 +17,8 @@ module Mobile
#f.img_url if f.respond_to?(:img_url) #f.img_url if f.respond_to?(:img_url)
elsif field == :created_at || field == :updated_at elsif field == :created_at || field == :updated_at
(format_time(c[field]) if (c.is_a?(Hash) && c.key?(field))) || (format_time(c.send(field)) if c.respond_to?(field)) (format_time(c[field]) if (c.is_a?(Hash) && c.key?(field))) || (format_time(c.send(field)) if c.respond_to?(field))
elsif field == :member_count
::Course===c ? c.members.count : 0
else else
(c[field] if (c.is_a?(Hash) && c.key?(field))) || (c.send(field) if c.respond_to?(field)) (c[field] if (c.is_a?(Hash) && c.key?(field))) || (c.send(field) if c.respond_to?(field))
end end
@ -45,8 +49,33 @@ 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
course_expose :member_count
expose :can_setting, if: lambda { |instance, options| options[:user] } do |instance, options|
current_user = options[:user]
can_setting = false
if instance[:course]
course = instance[:course]
else
course = instance
end
member = course.members.where("user_id=#{current_user.id} and course_id=#{course.id}")[0]
roleName = member.roles[0].name if member
if roleName && (roleName == "TeachingAsistant" || roleName == "Teacher" )
can_setting = true
end
if course.tea_id == current_user.id
can_setting = true
end
can_setting
end
expose :teacher, using: Mobile::Entities::User do |c, opt| expose :teacher, using: Mobile::Entities::User do |c, opt|
if c.is_a? ::Course if c.is_a? ::Course
c.teacher c.teacher
@ -57,6 +86,15 @@ module Mobile
expose :my_homework,using: Mobile::Entities::Homework do |f, opt| expose :my_homework,using: Mobile::Entities::Homework do |f, opt|
f[:my_homework] if f.is_a?(Hash) && f.key?(:my_homework) f[:my_homework] if f.is_a?(Hash) && f.key?(:my_homework)
end end
expose :is_creator, if: lambda { |instance, options| options[:user] } do |instance, options|
if instance[:course]
course = instance[:course]
else
course = instance
end
current_user = options[:user]
course.tea_id == current_user.id
end
course_expose :current_user_is_member course_expose :current_user_is_member
course_expose :current_user_is_teacher course_expose :current_user_is_teacher
course_expose :work_unit course_expose :work_unit

@ -0,0 +1,40 @@
module Mobile
module Entities
class Exercise < Grape::Entity
include Redmine::I18n
include ApplicationHelper
include ApiHelper
def self.exercise_expose(field)
expose field do |f,opt|
if f.is_a?(Hash) && f.key?(field)
if field == :created_on
format_time(f[field])
else
f[field]
end
elsif f.is_a?(::Exercise)
if f.respond_to?(field)
f.send(field)
else
case field
when :coursename
f.course.nil? ? "" : f.course.name
end
end
end
end
end
expose :exercise_name
expose :exercise_description
exercise_expose :coursename #所属班级名
expose :current_user_is_teacher, if: lambda { |instance, options| options[:user] } do |instance, options|
current_user = options[:user]
current_user_is_teacher = false
current_user_is_teacher = is_course_teacher(current_user,instance.course)
current_user_is_teacher
end
end
end
end

@ -37,6 +37,8 @@ module Mobile
when :homework_anony_type when :homework_anony_type
val = f.homework_type == 1 && !f.homework_detail_manual.nil? val = f.homework_type == 1 && !f.homework_detail_manual.nil?
val val
when :coursename
f.course.nil? ? "" : f.course.name
end end
end end
end end
@ -94,6 +96,16 @@ module Mobile
homework_expose :homework_anony_type #是否是匿评作业 homework_expose :homework_anony_type #是否是匿评作业
homework_expose :coursename #所属班级名
expose :current_user_is_teacher, if: lambda { |instance, options| options[:user] } do |instance, options|
if instance[:current_user_is_teacher].nil?
current_user = options[:user]
current_user_is_teacher = false
current_user_is_teacher = is_course_teacher(current_user,instance.course)
current_user_is_teacher
end
end
end end
end end
end end

@ -0,0 +1,69 @@
module Mobile
module Entities
class Issue <Grape::Entity
include ApiHelper
include Redmine::I18n
def self.issue_expose(f)
expose f do |issue, opt|
if issue.is_a?(Hash) && issue.key?(f)
issue[f]
elsif issue.is_a?(::Issue)
if issue.respond_to?(f)
if f == :created_on
format_time(issue.send(f))
else
issue.send(f)
end
else
case f
when :issue_priority
get_issue_priority_api issue.priority_id
when :issue_assigned_to
(get_user(issue.assigned_to_id)).login
when :issue_status
IssueStatus.find(issue.status_id).name
when :comment_count
issue.journals.where("notes is not null and notes != ''").count
# all_comments = []
# get_all_children(all_comments, f).count
when :project_name
issue.project.name
when :praise_count
get_activity_praise_num(issue)
when :act_type
'Issue'
when :act_id
issue.id
end
end
end
end
end
expose :subject
expose :description
expose :author, using: Mobile::Entities::User
expose :done_ratio
issue_expose :act_type
issue_expose :act_id
issue_expose :created_on
issue_expose :issue_priority
issue_expose :issue_assigned_to
issue_expose :issue_status
issue_expose :comment_count
issue_expose :project_name
issue_expose :praise_count
expose :issue_journals, using: Mobile::Entities::Journal do |f, opt|
if f.is_a?(::Issue)
f.journals.where("notes is not null and notes != ''").reverse
end
end
expose :has_praise , if: lambda { |instance, options| options[:user] } do |instance, options|
has_praise = false
current_user = options[:user]
obj = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",instance.id,instance.class.to_s,current_user.id)
has_praise = obj.empty? ? false : true
has_praise
end
end
end
end

@ -0,0 +1,44 @@
module Mobile
module Entities
class Journal <Grape::Entity
include Redmine::I18n
=begin
include Redmine::I18n
include ApplicationHelper
include ApiHelper
include IssuesHelper
include ActionView::Helpers::TagHelper
include ActionView::Helpers::UrlHelper
=end
def self.journal_expose(f)
expose f do |journal, opt|
if journal.is_a?(Hash) && journal.key?(f)
journal[f]
elsif journal.is_a?(::Journal)
if journal.respond_to?(f)
if f == :created_on
time_from_now(journal.send(f))
else
journal.send(f)
end
else
case f
when :detail_journal
if journal.details.any?
details_to_strings(journal.details)
end
end
end
end
end
end
expose :notes
journal_expose :created_on
expose :user,using: Mobile::Entities::User do |f, opt|
f.user
end
#journal_expose :detail_journal
end
end
end

@ -3,7 +3,6 @@ module Mobile
#普通留言 #普通留言
class Jours < Grape::Entity class Jours < Grape::Entity
include Redmine::I18n include Redmine::I18n
include WordsHelper
def self.jours_expose(field) def self.jours_expose(field)
expose field do |f,opt| expose field do |f,opt|
if f.is_a?(Hash) && f.key?(field) if f.is_a?(Hash) && f.key?(field)
@ -15,13 +14,28 @@ module Mobile
f.send(field) f.send(field)
end end
else else
case f case field
when :course_name when :lasted_comment
f[:jour_type] == "Course" ? f.course.name : "" time_from_now f.created_on
when :comment_count
# f.children.count
all_comments = []
get_all_children(all_comments, f).count
when :praise_count
get_activity_praise_num(f)
when :act_type
'JournalsForMessage'
when :act_id
f.id
when :content
f.notes
end end
end end
end end
end end
jours_expose :act_type
jours_expose :act_id
jours_expose :id jours_expose :id
jours_expose :jour_type jours_expose :jour_type
jours_expose :jour_id jours_expose :jour_id
@ -29,9 +43,12 @@ module Mobile
f.user f.user
end end
jours_expose :created_on jours_expose :created_on
jours_expose :notes jours_expose :lasted_comment
jours_expose :content
jours_expose :m_reply_id jours_expose :m_reply_id
jours_expose :m_parent_id jours_expose :m_parent_id
jours_expose :comment_count
jours_expose :praise_count
expose :course,using:Mobile::Entities::Course do |f,opt| expose :course,using:Mobile::Entities::Course do |f,opt|
if f.is_a?(::JournalsForMessage) && f[:jour_type] == "Course" if f.is_a?(::JournalsForMessage) && f[:jour_type] == "Course"
f.course f.course
@ -40,11 +57,101 @@ module Mobile
expose :reply_user,using: Mobile::Entities::User do |f, opt| expose :reply_user,using: Mobile::Entities::User do |f, opt|
f.at_user f.at_user
end end
expose :child_reply,using: Mobile::Entities::Jours do |f, opt| expose :all_children,using: Mobile::Entities::Jours do |f, opt|
if f.is_a?(::JournalsForMessage) if f.is_a?(::JournalsForMessage)
fetch_user_leaveWord_reply(f) # f.children.reverse
if !opt[:children] && opt[:comment_type].nil?
if f.parent.nil? && opt[:type] == 0
opt[:children] = true
all_comments = []
tStart = opt[:page]*5
tEnd = (opt[:page]+1)*5 - 1
all_comments = get_all_children(all_comments, f)[tStart..tEnd]
all_comments
end end
end end
end end
end end
expose :has_praise , if: lambda { |instance, options| options[:user] } do |instance, options|
has_praise = false
current_user = options[:user]
obj = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",instance.id,instance.class.to_s,current_user.id)
has_praise = obj.empty? ? false : true
has_praise
end
expose :parents_count, if: lambda { |instance, options| options[:user] } do |instance, options|
parents_reply = []
if options[:comment_type].nil?
parents_reply = get_reply_parents_no_root(parents_reply, instance)
elsif options[:comment_type] == "homework"
parents_reply = get_reply_parents(parents_reply, instance)
end
parents_reply.count
end
expose :parents_reply_bottom, using:Mobile::Entities::Jours do |f,opt|
if f.is_a? (::JournalsForMessage)
#取二级回复的底楼层
parents_reply = []
if opt[:comment_type].nil?
parents_reply = get_reply_parents_no_root(parents_reply, f)
elsif opt[:comment_type] == "homework"
parents_reply = get_reply_parents(parents_reply, f)
end
if parents_reply.count > 0 && parents_reply.count != 2 && !opt[:bottom]
if opt[:type] == 1
# opt[:bottom] = true
# parents_reply[opt[:page]..opt[:page]]
else
opt[:bottom] = true
parents_reply[0..0]
end
else
[]
end
end
end
expose :parents_reply_top, using:Mobile::Entities::Jours do |f,opt|
if f.is_a? (::JournalsForMessage)
#取二级回复的顶楼层
parents_reply = []
if opt[:comment_type].nil?
parents_reply = get_reply_parents_no_root(parents_reply, f)
elsif opt[:comment_type] == "homework"
parents_reply = get_reply_parents(parents_reply, f)
end
if parents_reply.count >= 2 && !opt[:top]
if opt[:type] == 1
opt[:bottom] = true
tStart = (opt[:page]-1)*5+2
tEnd = (opt[:page])*5+2 - 1
if tEnd >= parents_reply.count - 1
tEnd = parents_reply.count - 2
end
if tStart <= parents_reply.count - 2
parents_reply = parents_reply.reverse[tStart..tEnd]
parents_reply.reverse
else
[]
end
else
opt[:top] = true
parents_reply = parents_reply.reverse[0..1]
parents_reply.reverse
end
else
[]
end
end
end
end
end
end end

@ -15,10 +15,25 @@ module Mobile
u.send(f) u.send(f)
end end
else else
# case f case f
# when :xx when :course_project_name
# # if u.board.project_id == -1
# end u.course.name
else
u.project.name
end
when :lasted_comment
time_from_now u.created_on
when :praise_count
get_activity_praise_num(u)
when :act_type
'Message'
when :act_id
u.id
when :comment_count
all_comments = []
get_all_children(all_comments, u).count
end
end end
end end
@ -30,15 +45,96 @@ module Mobile
c.author c.author
end end
end end
message_expose :act_type
message_expose :act_id
message_expose :course_project_name
message_expose :board_id message_expose :board_id
message_expose :subject message_expose :subject
message_expose :content message_expose :content
message_expose :replies_count message_expose :comment_count
message_expose :praise_count
message_expose :created_on message_expose :created_on
message_expose :locked
message_expose :id message_expose :id
expose :message_children,using:Mobile::Entities::Message do |c,opt| message_expose :lasted_comment
expose :all_children,using:Mobile::Entities::Message do |c,opt|
if c.is_a? (::Message)
# c.children.reverse
if !opt[:children]
if c.parent.nil? && opt[:type] == 0
opt[:children] = true
all_comments = []
tStart = opt[:page]*5
tEnd = (opt[:page]+1)*5 - 1
all_comments = get_all_children(all_comments, c)[tStart..tEnd]
all_comments
end
end
end
end
expose :has_praise , if: lambda { |instance, options| options[:user] } do |instance, options|
has_praise = false
current_user = options[:user]
obj = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",instance.id,instance.class.to_s,current_user.id)
has_praise = obj.empty? ? false : true
has_praise
end
expose :parents_count, if: lambda { |instance, options| options[:user] } do |instance, options|
parents_reply = []
parents_reply = get_reply_parents_no_root(parents_reply, instance)
parents_reply.count
end
expose :parents_reply_bottom, using:Mobile::Entities::Message do |c,opt|
if c.is_a? (::Message)
#取二级回复的底楼层
parents_reply = []
parents_reply = get_reply_parents_no_root(parents_reply, c)
if parents_reply.count > 0 && parents_reply.count != 2 && !opt[:bottom]
if opt[:type] == 1
# opt[:bottom] = true
# parents_reply[opt[:page]..opt[:page]]
else
opt[:bottom] = true
parents_reply[0..0]
end
else
[]
end
end
end
expose :parents_reply_top, using:Mobile::Entities::Message do |c,opt|
if c.is_a? (::Message) if c.is_a? (::Message)
c.children #取二级回复的顶楼层
parents_reply = []
parents_reply = get_reply_parents_no_root(parents_reply, c)
if parents_reply.count >= 2 && !opt[:top]
if opt[:type] == 1
opt[:bottom] = true
tStart = (opt[:page]-1)*5+2
tEnd = (opt[:page])*5+2 - 1
if tEnd >= parents_reply.count - 1
tEnd = parents_reply.count - 2
end
if tStart <= parents_reply.count - 2
parents_reply = parents_reply.reverse[tStart..tEnd]
parents_reply.reverse
else
[]
end
else
opt[:top] = true
parents_reply = parents_reply.reverse[0..1]
parents_reply.reverse
end
else
[]
end
end end
end end
end end

@ -2,15 +2,31 @@ module Mobile
module Entities module Entities
class News < Grape::Entity class News < Grape::Entity
include Redmine::I18n include Redmine::I18n
include ApiHelper
def self.news_expose(field) def self.news_expose(field)
expose field do |f,opt| expose field do |f,opt|
if f.is_a?(Hash) && f.key?(field) if f.is_a?(Hash) && f.key?(field)
f[field] f[field]
elsif f.is_a?(::News) elsif f.is_a?(::News)
if f.respond_to?(field)
if field == :created_on if field == :created_on
format_time(f.send(field)) if f.respond_to?(field) format_time(f.send(field))
else else
f.send(field) if f.respond_to?(field) f.send(field)
end
else
case field
when :course_name
get_course(f.course_id).name unless f.course_id == nil
when :praise_count
get_activity_praise_num(f)
when :act_type
'News'
when :act_id
f.id
when :comment_count
f.comments.count
end
end end
elsif f.is_a?(Hash) && !f.key?(field) elsif f.is_a?(Hash) && !f.key?(field)
n = f[:news] n = f[:news]
@ -40,6 +56,8 @@ module Mobile
end end
obj obj
end end
news_expose :act_type
news_expose :act_id
#作者id #作者id
news_expose :author_id news_expose :author_id
#作者名 #作者名
@ -51,17 +69,25 @@ module Mobile
#发布时间 #发布时间
news_expose :created_on news_expose :created_on
#评论数量 #评论数量
news_expose :comments_count news_expose :comment_count
news_expose :praise_count
#课程名字
news_expose :course_name
#评论 #评论
expose :comments, using: Mobile::Entities::Comment do |f, opt| expose :comments, using: Mobile::Entities::Comment do |f, opt|
if f.is_a?(Hash) && f.key?(:comments) if f.is_a?(Hash) && f.key?(:comments)
f[:comments] f[:comments]
elsif f.is_a?(::News) && f.respond_to?(:comments) elsif f.is_a?(::News) && f.respond_to?(:comments)
f.send(:comments) f.comments.reverse
end end
end end
expose :has_praise , if: lambda { |instance, options| options[:user] } do |instance, options|
has_praise = false
current_user = options[:user]
obj = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",instance.id,instance.class.to_s,current_user.id)
has_praise = obj.empty? ? false : true
has_praise
end
end end
end end
end end

@ -0,0 +1,32 @@
module Mobile
module Entities
class Project < Grape::Entity
expose :name
expose :id
expose :user_id
# expose :invite_code
# expose :qrcode
expose :can_setting, if: lambda { |instance, options| options[:user] } do |instance, options|
current_user = options[:user]
my_member = instance.member_principals.where("users.id=#{current_user.id}").first
can_setting = false
if my_member && my_member.roles[0] && my_member.roles[0].id == 3
can_setting = true
end
can_setting
end
expose :is_creator, if: lambda { |instance, options| options[:user] } do |instance, options|
current_user = options[:user]
current_user.id == instance.user_id
end
expose :member_count, if: lambda { |instance, options| options[:user] } do |instance, options|
instance.members.count
end
end
end
end

@ -0,0 +1,35 @@
module Mobile
module Entities
class ProjectMember < Grape::Entity
include Redmine::I18n
include ApplicationHelper
include ApiHelper
def self.member_expose(f)
expose f do |u,opt|
if u.is_a?(Hash) && u.key?(f)
u[f]
elsif u.is_a?(::Member)
if u.respond_to?(f)
u.send(f)
else
case f
when :roles_id
u.roles[0].id
end
end
end
end
end
expose :user, using: Mobile::Entities::User do |c, opt|
if c.is_a?(::Member)
c.user
end
end
member_expose :roles_id
end
end
end

@ -0,0 +1,15 @@
module Mobile
module Entities
class Syllabus < Grape::Entity
expose :title
expose :id
expose :can_setting, if: lambda { |instance, options| options[:user] } do |instance, options|
current_user = options[:user]
can_setting = instance.user_id == current_user.id ? true : false
can_setting = false if instance.id.nil?
can_setting
end
expose :courses, using: Mobile::Entities::Course
end
end
end

@ -13,7 +13,7 @@ module Mobile
else else
case f case f
when :img_url when :img_url
url_to_avatar(u) "/images/#{url_to_avatar(u)}"
when :gender when :gender
u.nil? || u.user_extensions.nil? || u.user_extensions.gender.nil? ? 0 : u.user_extensions.gender u.nil? || u.user_extensions.nil? || u.user_extensions.gender.nil? ? 0 : u.user_extensions.gender
when :work_unit when :work_unit
@ -24,6 +24,12 @@ module Mobile
u.nil? || u.user_extensions.nil? ? "" : u.user_extensions.brief_introduction u.nil? || u.user_extensions.nil? ? "" : u.user_extensions.brief_introduction
when :student_num when :student_num
u.nil? || u.user_extensions.nil? ? "" : u.user_extensions.student_id u.nil? || u.user_extensions.nil? ? "" : u.user_extensions.student_id
when :real_name
u.nil? ? "" : get_user_realname(u).gsub(/\s*/,"");
when :name
u.nil? ? "" : u.show_name
when :roles_id
u[:roles_id].nil? ? nil : u.roles_id
end end
end end
end end
@ -33,11 +39,13 @@ module Mobile
expose :id expose :id
#头像 #头像
user_expose :img_url
#昵称
expose :nickname expose :nickname
#真名 #真名
user_expose :img_url
#昵称
expose :realname expose :realname
#昵称
user_expose :real_name
#性别 #性别
user_expose :gender user_expose :gender
#我的二维码 #我的二维码
@ -55,6 +63,13 @@ module Mobile
user_expose :student_num user_expose :student_num
# 活跃值 # 活跃值
user_expose :active_count user_expose :active_count
user_expose :role_name
user_expose :roles_id
user_expose :name
end end
end end

@ -0,0 +1,94 @@
# encoding: utf-8
module Mobile
module Entities
class Whomework <Grape::Entity
include ApiHelper
include ApplicationHelper
include Redmine::I18n
def self.whomework_expose(f)
expose f do |wh, opt|
if wh.is_a?(Hash) && wh.key?(f)
wh[f]
elsif wh.is_a?(::HomeworkCommon)
if wh.respond_to?(f)
if f == :created_at
format_time(wh.send(f))
else
wh.send(f)
end
else
case f
when :absence_penalty
wh.nil? || wh.homework_detail_manual.nil? ? 0 : wh.homework_detail_manual.absence_penalty
when :evaluation_start
wh.nil? || wh.homework_detail_manual.nil? ? nil : convert_to_time(wh.homework_detail_manual.evaluation_start, 0)
when :evaluation_end
wh.nil? || wh.homework_detail_manual.nil? ? nil : convert_to_time(wh.homework_detail_manual.evaluation_end, 1)
when :praise_count
get_activity_praise_num(wh)
when :comment_count
wh.journals_for_messages.count
when :course_name
wh.course.name
when :act_type
'HomeworkCommon'
when :act_id
wh.id
end
end
end
end
end
expose :author, using: Mobile::Entities::User do |w, opt|
if w.is_a?(::HomeworkCommon)
w.user
end
end
expose :current_user, using: Mobile::Entities::User do |w, opt|
current_user
end
expose :name
expose :description
expose :publish_time
expose :end_time
expose :homework_type
expose :late_penalty
expose :course_id
expose :anonymous_comment
expose :quotes
expose :is_open
expose :id
whomework_expose :act_type
whomework_expose :act_id
whomework_expose :course_name
whomework_expose :created_at
whomework_expose :absence_penalty
whomework_expose :evaluation_start
whomework_expose :evaluation_end
whomework_expose :praise_count
whomework_expose :comment_count
expose :all_children, using: Mobile::Entities::Jours do |f, opt|
#f[:journals_for_messages] if f.is_a?(Hash) && f.key?(:journals_for_messages)
if f.is_a?(::HomeworkCommon)
# f.journals_for_messages.reverse
if !opt[:children] && opt[:type] == 0
opt[:children] = true
tStart = opt[:page]*5
tEnd = (opt[:page]+1)*5 - 1
all_comments = f.journals_for_messages.reorder("created_on desc")
all_comments[tStart..tEnd]
end
end
end
expose :has_praise , if: lambda { |instance, options| options[:user] } do |instance, options|
has_praise = false
current_user = options[:user]
obj = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",instance.id,instance.class.to_s,current_user.id)
has_praise = obj.empty? ? false : true
has_praise
end
end
end
end

@ -0,0 +1,13 @@
#coding=utf-8
#
module Mobile
module Exceptions
class AuthException < StandardError
attr_reader :err_code, :msg
def initialize(code, msg)
@err_code = code
@msg = msg
end
end
end
end

@ -1,3 +1,6 @@
#coding=utf-8
module Mobile module Mobile
module Middleware module Middleware
class ErrorHandler < Grape::Middleware::Base class ErrorHandler < Grape::Middleware::Base
@ -6,8 +9,12 @@ module Mobile
begin begin
@app.call(@env) @app.call(@env)
rescue =>e rescue =>e
message = {status: 1, message: e.message }.to_json code = 1
puts(e.backtrace.join("\n")) if Rails.env.development?
message = {status: code, message: e.message }.to_json
Rails.logger.error e.inspect
Rails.logger.error e.backtrace.join("\n")
status = 200 status = 200
headers = { 'Content-Type' => content_type } headers = { 'Content-Type' => content_type }
Rack::Response.new([message], status, headers).finish Rack::Response.new([message], status, headers).finish

@ -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 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 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 pull_requests 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 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 ShieldWechatMessages 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 sub_document_comments 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 sub_domains 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.

@ -24,7 +24,7 @@ class AdminController < ApplicationController
before_filter :require_admin before_filter :require_admin
helper :sort helper :sort
helper :Users helper :Users
helper :Settings helper :Settings,SchoolHelper
include SortHelper include SortHelper
def index def index
@ -32,32 +32,280 @@ class AdminController < ApplicationController
end end
def projects def projects
=begin
@status = params[:status] || 1 @status = params[:status] || 1
scope = Project.status(@status).order('id asc') scope = Project.status(@status)
scope = scope.like(params[:name]) if params[:name].present? scope = scope.like(params[:name]) if params[:name].present?
@projects = scope.where(project_type: Project::ProjectType_project).all @projects = scope.where(project_type: Project::ProjectType_project).reorder("created_on desc").all
=end
@projects = Project.like(@name).order('created_on desc')
@projects = paginateHelper @projects,30
@page = (params['page'] || 1).to_i - 1
render :action => "projects", :layout => false if request.xhr? render :action => "projects", :layout => false if request.xhr?
end end
def courses def syllabuses
@name = params[:name] @name = params[:name]
@courses = Course.like(@name) @syllabuses = Syllabus.like(@name).order('created_at desc')
@syllabuses = paginateHelper @syllabuses,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#为班级选择课程
def select_course_syllabus
@flag = false
if params[:syllabus_id] && params[:course_id]
course = Course.where("id = #{params[:course_id].to_i}").first
unless course.nil?
course.update_column('syllabus_id', params[:syllabus_id].to_i)
@flag = true
end
end
if @flag
render :text=> "succ"
else
render :text=>'fail'
end
end
#新建课程
def create_syllabus
if params[:course_id]
course = Course.where("id = #{params[:course_id]}").first
if course
@user = course.teacher
syllabus = Syllabus.new
syllabus.update_attributes(:title => params[:title], :eng_name => params[:eng_name], :user_id => @user.id)
syllabus.description = Message.where("id = 19412").first.nil? ? nil : Message.where("id = 19412").first.content
if syllabus.save
course.update_column('syllabus_id', syllabus.id)
@flag = params[:flag].to_i
@course = course
respond_to do |format|
format.js
end
end
end
end
end
def courses
@name = params[:name].to_s.strip.downcase
if @name && @name != ""
@courses = Course.select{ |course| course.teacher && ((course.teacher.show_name).include?(@name) || course.name.include?(@name))}
@courses = @courses.sort{|x, y| y.created_at <=> x.created_at}
else
@courses = Course.order('created_at desc')
end
@courses = paginateHelper @courses,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#未配置班级列表
def non_syllabus_courses
@name = params[:name].to_s.strip.downcase
if @name && @name != ""
@courses = Course.where("syllabus_id is null and is_delete = 0").select{ |course| (course.teacher[:lastname].to_s.downcase + course.teacher[:firstname].to_s.downcase).include?(@name) || course.name.include?(@name)}
@courses = @courses.sort{|x, y| y.created_at <=> x.created_at}
else
@courses = Course.where("syllabus_id is null and is_delete = 0").order('created_at desc')
end
@courses = paginateHelper @courses,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#修改班级名称
def update_course_name
@course = Course.where("id = #{params[:course_id].to_i}").first
unless @course.nil?
@course.update_column("name", params[:name])
respond_to do |format|
format.js
end
end
end
#修改课程名称
def update_syllabus_title
@syllabus = Syllabus.where("id = #{params[:syllabus_id].to_i}").first
unless @syllabus.nil?
@syllabus.update_column("title", params[:name])
respond_to do |format|
format.js
end
end
end
#管理员界面精品课程列表
def excellent_courses
@courses = Course.where("is_excellent =? or excellent_option =?", 1, 1 )
respond_to do |format|
format.html
end
end
# 单位名称列表下的已审批按照名字排序
def apply_shcool_sort
@order = ""
@sort = ""
if params[:sort] && (params[:order] == 'name')
# courses = School.find_by_sql("SELECT c.*,count(c.id) FROM courses c,course_activities ca WHERE c.id = ca.course_id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY count(c.id) #{params[:sort]}, c.id desc")
school = School.find_by_sql(" SELECT aas.name FROM apply_add_schools aas where aas.status = '0' ORDER BY CONVERT(aas.name USING gbk) #{params[:sort]}, aas.id asc ")
@order = params[:order]
@sort = params[:sort]
end
redirect_to unapplied_schools_url
end
#精品课程下的全部课程
def excellent_all_courses
name = params[:name]
@order = ""
@sort = ""
if params[:sort] && (params[:order] == 'act')
courses = Course.find_by_sql("SELECT c.*,count(c.id) FROM courses c,course_activities ca WHERE c.id = ca.course_id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY count(c.id) #{params[:sort]}, c.id desc")
@order = params[:order]
@sort = params[:sort]
elsif params[:sort] && (params[:order] == 'time')
courses = Course.find_by_sql("SELECT * FROM courses WHERE name like '%#{name}%' ORDER BY time #{params[:sort]}, id desc")
@order = params[:order]
@sort = params[:sort]
elsif params[:sort] && (params[:order] == 'post')
courses = Course.find_by_sql("SELECT c.*, count(m.id) count FROM boards b, courses c, messages m WHERE m.board_id = b.id AND b.course_id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY count #{params[:sort]}, c.id desc")
@order = params[:order]
@sort = params[:sort]
elsif params[:sort] && (params[:order] == 'res')
courses = Course.find_by_sql("SELECT c.*, count(at.container_id) cat FROM attachments at, courses c WHERE at.container_type = 'Course' AND at.container_id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY cat #{params[:sort]}, id desc")
@order = params[:order]
@sort = params[:sort]
elsif params[:sort] && (params[:order] == 'works')
courses = Course.find_by_sql("SELECT c.*, count(hc.id) chc FROM courses c, homework_commons hc,student_works sw WHERE c.id = hc.course_id AND sw.homework_common_id = hc.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY chc #{params[:sort]}, id desc")
@order = params[:order]
@sort = params[:sort]
elsif params[:sort] && (params[:order] == 'homework')
courses = Course.find_by_sql("SELECT c.*, count(sw.id) csw FROM student_works sw, courses c, homework_commons hc WHERE c.id = hc.course_id AND sw.id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY csw #{params[:sort]}, id desc")
@order = params[:order]
@sort = params[:sort]
elsif params[:sort] && (params[:order] == 'std')
courses = Course.find_by_sql("SELECT c.*, count(sfc.id) sfc FROM courses c, students_for_courses sfc WHERE sfc.course_id = c.id AND c.name like '%#{name}%' GROUP BY c.id ORDER BY sfc #{params[:sort]}, id desc")
@order = params[:order]
@sort = params[:sort]
elsif params[:sort] && (params[:order] == 'open')
courses = Course.find_by_sql("SELECT * FROM courses WHERE name like '%#{name}%' ORDER BY is_public #{params[:sort]},id desc")
@order = params[:order]
@sort = params[:sort]
else
courses = Course.like(name).order('created_at desc')
end
@courses = paginateHelper courses,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#设为精品
def set_excellent_course
@course = Course.find params[:id]
unless @course.nil?
if @course.is_excellent == 1 || @course.excellent_option == 1
@course.update_column('is_excellent', 0)
@course.update_column('excellent_option', 0)
else
@course.update_column('is_excellent', 1)
end
respond_to do |format|
format.js
end
end
end
#取消精品
def cancel_excellent_course
@course = Course.find params[:id]
unless @course.nil?
if @course.is_excellent == 1 || @course.excellent_option == 1
@course.update_column('is_excellent', 0)
@course.update_column('excellent_option', 0)
end
end
respond_to do |format|
format.html{
redirect_to excellent_courses_url
}
end
end
#管理员界面课程资源列表
def course_resource_list
if params[:sort] == 'file_size'
@resource = Attachment.where(:container_type => 'Course').order("filesize desc")
elsif params[:sort] == 'file_upload'
@resource = Attachment.where(:container_type => 'Course').order("created_on desc")
elsif params[:sort] == 'file_download_times'
@resource = Attachment.where(:container_type => 'Course').order("downloads desc")
else
@resource = Attachment.where(:container_type => 'Course').order("created_on desc")
end
@resource = paginateHelper @resource,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format| respond_to do |format|
format.html format.html
end end
end end
#管理员界面項目资源列表
def project_resource_list
if params[:sort] == 'file_size'
@pro_resource = Attachment.where(:container_type => 'Project').order("filesize desc")
elsif params[:sort] == 'file_upload'
@pro_resource = Attachment.where(:container_type => 'Project').order("created_on desc")
elsif params[:sort] == 'file_download_times'
@pro_resource = Attachment.where(:container_type => 'Project').order("downloads desc")
else
@pro_resource = Attachment.where(:container_type => 'Project').order("created_on desc")
end
@pro_resource = paginateHelper @pro_resource,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
def users def users
sort_init 'login', 'asc' sort_init 'login', 'asc'
sort_update %w(login firstname lastname mail admin created_on last_login_on) sort_update %w(login firstname lastname mail admin created_on last_login_on)
case params[:format] case params[:format]
when 'xml', 'json' when 'xml', 'json'
@offset, @limit = api_offset_and_limit({:limit => 15}) @offset, @limit = api_offset_and_limit({:limit => 50})
else else
@limit = 15#per_page_option @limit = 50 #per_page_option
end end
@status = params[:status] || 1 @status = params[:status] || 1
@ -337,7 +585,13 @@ class AdminController < ApplicationController
#组织 #组织
def organization def organization
@organizations = Organization.all @organizations = Organization.find_by_sql("SELECT * FROM organizations ORDER BY created_at DESC")
#@organizations = Organization.all.order("created_at desc")
@organization_count = @organizations.count
@organization_pages = Paginator.new @organization_count, 30, params['page'] || 1
@organizations = paginateHelper @organizations,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format| respond_to do |format|
format.html format.html
end end
@ -345,21 +599,131 @@ class AdminController < ApplicationController
#学校列表 #学校列表
def schools def schools
@school_name = params[:school_name]
if @school_name && @school_name != '' @schools = School.find_by_sql("SELECT * FROM schools ORDER BY created_at DESC")
@schools = School.where("name like '%#{@school_name}%'")
elsif @school_name.nil?
@schools = []
else @school_name && @school_name == ' '
@schools = School.where('1=1')
end
@school_count = @schools.count @school_count = @schools.count
@school_pages = Paginator.new @school_count, 100, params['page'] || 1
@schools = paginateHelper @schools,100 @school_pages = Paginator.new @school_count, 30, params['page'] || 1
@schools = paginateHelper @schools,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
# 获取申请的高校列表
# status: 0 未审批; 1 已批阅;
def applied_schools
@name = params[:name] || ""
condition = "#{@name.strip}".gsub(" ","")
@apply_status = ApplyAddSchools.where("status = 0 and name like '%#{condition}%'").order('created_at desc')
@apply_count = @apply_status.count
@apply_pages = Paginator.new @apply_count, 30, params['page'] || 1
@apply_status = paginateHelper @apply_status, 30
@page = (params['page'] || 1).to_i - 1
respond_to do |format| respond_to do |format|
format.html format.html
end end
end end
def has_applied_schools
@name = params[:name] || ""
condition = "#{@name.strip}".gsub(" ","")
@has_apply_status = ApplyAddSchools.where("(status = 1 or status = 2) and name like '%#{condition}%'").order('created_at desc')
@has_apply_count = @has_apply_status.count
@has_apply_pages = Paginator.new @has_apply_count, 30, params['page'] || 1
@has_apply_status = paginateHelper @has_apply_status, 30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
# 批准未审批的高校
# 消息发送,发送对象为申请人
# status: 0表示未批准 status1表示已批准 status 2表示已更改 status 3表示已拒绝
def approve_applied_schools
applied_school = ApplyAddSchools.find params[:id]
applied_school.update_column('status', 1) unless applied_school.nil?
school = applied_school.school
school.update_attribute("province", applied_school.province)
AppliedMessage.create(:user_id => applied_school.user_id, :status => 1, :viewed => true, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
# School.create(:user_id => applied_school.user_id, :status => 1, :viewed => true, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
respond_to do |format|
format.html{ redirect_to unapplied_schools_url }
end
end
# 更改申请的高校名称
# REDO: 修改该字段
# REDO: 同步修改使用了改名称的用户单位
def edit_applied_schools
aas = ApplyAddSchools.find(params[:applied_id])
# aas.update_attribute(:name, params[:name])
#applied_add_school = ApplyAddSchools.where(:name => aas.name)
school = School.find params[:school_id]
begin
aas.update_attribute(:status, 2)
AppliedMessage.create(:user_id => aas.user_id, :status => 2, :viewed => true, :applied_id => aas.id, :applied_type => "ApplyAddSchools", :name => school[0].name )
users = UserExtensions.where("school_id = #{aas.school_id}")
users.each do |user|
user.update_column("school_id", school[0].id)
end
aas.school.destroy
aas.update_attribute(:school_id, school[0].id)
rescue Exception => e
puts e
end
# applied_schools = ApplyAddSchools.find params[:applied_id]
# applied_schools.update_column('name', params[:name])
redirect_to unapplied_schools_url
end
def all_schools
apply_schools = ApplyAddSchools.where("status != 1")
apply_school_ids = apply_schools.empty? ? "(-1)" : "(" + apply_schools.map{|sc| sc.school_id}.join(',') + ")"
if !params[:search].nil?
search = "%#{params[:search].to_s.strip.downcase}%"
@schools = School.where("id not in #{apply_school_ids} and #{School.table_name}.name like :p",:p=>search)
#@schools = School.all
else
#@course = @user.courses.where("is_delete = 0 and #{Course.table_name}.id != #{homework.course_id}").select { |course| @user.allowed_to?(:as_teacher,course)}
@schools = School.where("id not in #{apply_school_ids}")
end
@edit_id = params[:school_id]
@search = params[:search]
respond_to do |format|
format.js
end
end
# 删除申请的高校
# REDO: destroy关联删除
# REDO: 删除确认提示,是否删除
# REDO: 给申请人发送消息
def delete_applied_schools
applied_school = ApplyAddSchools.find(params[:id])
applied_school.update_attribute(:status, 3)
AppliedMessage.create(:user_id => applied_school.user_id, :status => 3, :viewed => true, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
users = UserExtensions.where("school_id = #{applied_school.school_id}")
users.each do |user|
user.update_column("school_id", nil)
end
applied_school.school.destroy
if params[:tip] == "unapplied"
redirect_to unapplied_schools_url
elsif params[:tip] == "applied"
redirect_to applied_schools_url
end
end
#移动端版本管理 #移动端版本管理
def mobile_version def mobile_version
@versions = PhoneAppVersion.reorder('created_at desc') @versions = PhoneAppVersion.reorder('created_at desc')
@ -469,9 +833,27 @@ class AdminController < ApplicationController
end end
end end
#最近登录老师列表
def latest_login_teachers
scope = User.find_by_sql("SELECT * FROM users,user_extensions WHERE users.id = user_extensions.user_id AND user_extensions.identity=0 ORDER BY last_login_on DESC")
if params[:startdate].present?
scope = User.find_by_sql("SELECT * FROM users,user_extensions WHERE users.id = user_extensions.user_id AND user_extensions.identity=0 and last_login_on>= '#{params[:startdate]} 00:00:00' ORDER BY last_login_on DESC")
end
if params[:enddate].present?
scope = User.find_by_sql("SELECT * FROM users,user_extensions WHERE users.id = user_extensions.user_id AND user_extensions.identity=0 and last_login_on <= '#{params[:enddate]} 23:59:59' ORDER BY last_login_on DESC")
end
@teachers = scope
@teachers = paginateHelper @teachers,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
#作业 #作业
def homework def homework
@homework = HomeworkCommon.order('end_time desc') #@homework = HomeworkCommon.order('end_time desc')
@homework = HomeworkCommon.order( 'created_at desc ')
@homework = paginateHelper @homework,30 @homework = paginateHelper @homework,30
@page = (params['page'] || 1).to_i - 1 @page = (params['page'] || 1).to_i - 1
respond_to do |format| respond_to do |format|
@ -479,4 +861,64 @@ class AdminController < ApplicationController
end end
end end
#代码测试列表
def code_work_tests
#求出所有条数
tCount = CodeTests.count()
#设置个空的数组 以便paginateHelper来分页
@code_work_tests = []
if tCount >= 1
@code_work_tests[tCount-1] = {}
end
@code_work_tests = paginateHelper @code_work_tests,30
@page = (params['page'] || 1).to_i - 1
#取出需要的那一页数据
tStart = @page*30
@code_work_tests = CodeTests.find_by_sql("select * from code_tests order by id desc limit #{tStart},30 ")
#取出各个作品是否是模拟答题的
is_test = {}
#作品是否存在
link_swork = {}
#作业是否存在
link_hwork = {}
@code_work_tests.each do |test|
#作品是否存在
if is_test[test['student_work_id']] != nil
test['link_swork'] = link_swork[test['student_work_id']]
test['is_test'] = is_test[test['student_work_id']]
else
work = StudentWork.where("id=?",test['student_work_id']).first
test['link_swork'] = !work.nil?
test['is_test'] = work.nil? ? false : work.is_test
#test['is_test'] = CodeTests.find_by_sql("select is_test from student_works where id = #{test['student_work_id']}").first['is_test']
is_test[test['student_work_id']] = test['is_test']
link_swork[test['student_work_id']] = test['link_swork']
end
#作业是否存在
if link_hwork[test['homework_id']] != nil
test['link_hwork'] = link_hwork[test['homework_id']]
else
hwork = HomeworkCommon.where("id=?",test['homework_id']).first
test['link_hwork'] = !hwork.nil?
link_hwork[test['homework_id']] = test['link_hwork']
end
end
respond_to do |format|
format.html
end
end
#分享作业申请
def apply_for_homework
homeworks = ApplyHomework.where("user_id != 0")
@homework = paginateHelper homeworks,30
@page = (params['page'] || 1).to_i - 1
respond_to do |format|
format.html
end
end
end end

@ -363,7 +363,11 @@ class ApplicationController < ActionController::Base
when "contest" when "contest"
return true return true
when "Course" when "Course"
if @attachment.get_status_by_attach(User.current.id) == 2
return true
else
allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false) allowed = User.current.allowed_to?(:course_attachments_download, @course, :global => false)
end
else else
return true return true
end end
@ -503,7 +507,8 @@ class ApplicationController < ActionController::Base
# render_404 # render_404
# end # end
def self.model_object(model) def self.
model_object(model)
self.model_object = model self.model_object = model
end end
@ -912,4 +917,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

@ -1,44 +1,72 @@
class AppliedProjectController < ApplicationController class AppliedProjectController < ApplicationController
helper :watchers
#申请加入项目 #申请加入项目
def applied_join_project def applied_join_project
@user_id = params[:user_id] if params[:object_id]
@project = Project.find_by_id(params[:project_id]) @project = Project.find_by_id(params[:object_id])
if params[:project_join]
if @project
user = User.find @user_id
if user.member_of?(@project)
@status = 3
else
@applieds = AppliedProject.where("user_id = ? and project_id = ?", params[:user_id],params[:project_id])
if @applieds.count == 0
appliedproject = AppliedProject.create(:user_id => params[:user_id], :project_id => params[:project_id])
Mailer.run.applied_project(appliedproject)
@status = 2
else
@status = 1
end
end
else
@status = 0
end
respond_to do |format|
format.js
end end
return # @user_id = params[:user_id]
# if params[:project_join]
# if @project
# user = User.find @user_id
# if user.member_of?(@project)
# @status = 3
# else
# @applieds = AppliedProject.where("user_id = ? and project_id = ?", params[:user_id],params[:project_id])
# if @applieds.count == 0
# appliedproject = AppliedProject.create(:user_id => params[:user_id], :project_id => params[:project_id])
# Mailer.run.applied_project(appliedproject)
# @status = 2
# else
# @status = 1
# end
# end
# else
# @status = 0
# end
# respond_to do |format|
# format.js
# end
# return
# end
#
# @applieds = AppliedProject.where("user_id = ? and project_id = ?", params[:user_id],params[:project_id])
# if @applieds.count == 0
# appliedproject = AppliedProject.create(:user_id => params[:user_id], :project_id => params[:project_id])
# Mailer.run.applied_project(appliedproject)
# end
#
# #redirect_to project_path(params[:project_id])
# #redirect_to_referer_or {render :text => ( 'applied success.'), :layout => true}
# respond_to do |format|
# format.html { redirect_to_referer_or {render :text => (watching ? 'Watcher added.' : 'Watcher removed.'), :layout => true}}
# format.js { render :partial => 'set_applied'}
# end
end end
@applieds = AppliedProject.where("user_id = ? and project_id = ?", params[:user_id],params[:project_id]) # @flage:提示语标志1邀请码错误2已经是项目成员 3角色没有选择; 4申请成功
if @applieds.count == 0 # role:成员角色 => 04管理人员5开发人员6报告人员
appliedproject = AppliedProject.create(:user_id => params[:user_id], :project_id => params[:project_id]) # 申请成功则发送消息
Mailer.run.applied_project(appliedproject) def applied_project_info
if params[:project_id].nil?
@project = Project.where(:invite_code => params[:invite_code]).first
else
@project = Project.find(params[:project_id])
end end
if !@project || params[:invite_code].to_s != @project.invite_code
#redirect_to project_path(params[:project_id]) @flag = 1
#redirect_to_referer_or {render :text => ( 'applied success.'), :layout => true} elsif User.current.member_of?(@project)
respond_to do |format| @flag = 2
format.html { redirect_to_referer_or {render :text => (watching ? 'Watcher added.' : 'Watcher removed.'), :layout => true}} elsif params[:member].nil?
format.js { render :partial => 'set_applied'} @flag = 3
elsif !AppliedProject.where(:project_id => @project.id, :user_id => User.current.id).first.nil?
@flag = 5
else
@flag = 4
role = params[:member] == "member_manager" ? 3 : (params[:member] == "member_developer" ? 4 :5)
applied_project = AppliedProject.create(:user_id => User.current.id, :project_id => @project.id, :role => role)
# 申请成功则给项目管理员发送邮件及发送消息
# Mailer.run.applied_project(applied_project)
end end
end end

@ -8,6 +8,15 @@ class AtController < ApplicationController
users = find_at_users(params[:type], params[:id]) users = find_at_users(params[:type], params[:id])
@users = users @users = users
@users = users.uniq { |u| u.id }.delete_if { |u| u.id == User.current.id }.sort{|x,y| to_pinyin(x.show_name) <=> to_pinyin(y.show_name)} if users @users = users.uniq { |u| u.id }.delete_if { |u| u.id == User.current.id }.sort{|x,y| to_pinyin(x.show_name) <=> to_pinyin(y.show_name)} if users
#加上all
if @user && @users.size > 0
allUser = Struct.new(:id, :name).new
allUser.id = @users.map{|u| u.id}.join(",")
allUser.name = "all"
@users.insert(0, allUser)
end
@users
end end
private private
@ -38,6 +47,8 @@ class AtController < ApplicationController
find_journals_for_message(id) find_journals_for_message(id)
when 'Principal' when 'Principal'
find_principal(id) find_principal(id)
when 'BlogComment'
find_blog_comment(id)
when 'All' when 'All'
nil nil
else else
@ -59,7 +70,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
@ -157,8 +168,8 @@ class AtController < ApplicationController
#BlogComment #BlogComment
def find_blog_comment(id) def find_blog_comment(id)
blog = BlogComment.find(id).blog blog = BlogComment.find(id)
blog.users blog.author.watcher_users
end end
end end

@ -18,6 +18,8 @@
class AttachmentsController < ApplicationController class AttachmentsController < ApplicationController
layout "users_base" layout "users_base"
before_filter :verify_authenticity_token, only: [:uploa]
before_filter :find_project, :only => [:show, :download, :thumbnail, :destroy, :delete_homework]#, :except => [:upload, :autocomplete] before_filter :find_project, :only => [:show, :download, :thumbnail, :destroy, :delete_homework]#, :except => [:upload, :autocomplete]
before_filter :file_readable, :read_authorize, :only => [:show, :thumbnail]#Modified by young before_filter :file_readable, :read_authorize, :only => [:show, :thumbnail]#Modified by young
before_filter :delete_authorize, :only => [:destroy] before_filter :delete_authorize, :only => [:destroy]
@ -103,6 +105,9 @@ class AttachmentsController < ApplicationController
direct_download_history direct_download_history
end end
else else
# 记录用户行为
record_user_actions(params[:id])
# 直接下载历史版本
direct_download_history direct_download_history
end end
end end
@ -113,6 +118,14 @@ class AttachmentsController < ApplicationController
redirect_to "http://" + (Setting.host_name.to_s) +"/file_not_found.html" redirect_to "http://" + (Setting.host_name.to_s) +"/file_not_found.html"
end end
def record_user_actions id
if params[:action] == "download_history"
UserActions.create(:action_id => id, :action_type => "AttachmentHistory", :user_id => User.current.id) unless id.nil?
elsif params[:action] == "download"
UserActions.create(:action_id => id, :action_type => "Attachment", :user_id => User.current.id) unless id.nil?
end
end
def download def download
# modify by nwb # modify by nwb
# 下载添加权限设置 # 下载添加权限设置
@ -135,6 +148,8 @@ class AttachmentsController < ApplicationController
direct_download direct_download
end end
else else
# 记录用户行为
record_user_actions(params[:id])
direct_download direct_download
end end
end end
@ -251,7 +266,11 @@ class AttachmentsController < ApplicationController
@history.version = @old_history.nil? ? 1 : @old_history.version + 1 @history.version = @old_history.nil? ? 1 : @old_history.version + 1
@history.save #历史记录保存完毕 @history.save #历史记录保存完毕
#将最新保存的记录 数据替换到 需要修改的文件记录 #将最新保存的记录 数据替换到 需要修改的文件记录
@old_attachment.attributes = @attachment.attributes.dup.except("id","container_id","container_type","is_public","downloads") @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
@ -572,7 +591,16 @@ class AttachmentsController < ApplicationController
end end
end end
private #找到文件的所有的历史版本及当前版本
def attachment_history_download
@attachment = Attachment.find(params[:id])
@attachment_histories = @attachment.attachment_histories
respond_to do |format|
format.js
end
end
private
def find_project def find_project
@attachment = Attachment.find(params[:id]) @attachment = Attachment.find(params[:id])
# Show 404 if the filename in the url is wrong # Show 404 if the filename in the url is wrong
@ -586,7 +614,7 @@ private
@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 == '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
@ -638,8 +666,10 @@ private
end end
def has_login def has_login
unless @attachment && @attachment.container_type == "PhoneAppVersion" unless (@attachment && @attachment.container_type == "Organization").nil?
unless (@attachment && @attachment.container_type == "PhoneAppVersion").nil?
render_403 if !User.current.logged? && !(@attachment.container_type == 'OrgSubfield' && @attachment.container.organization.allow_guest_download) && !(@attachment.container_type == 'OrgDocumentComment' && @attachment.container.organization.allow_guest_download) render_403 if !User.current.logged? && !(@attachment.container_type == 'OrgSubfield' && @attachment.container.organization.allow_guest_download) && !(@attachment.container_type == 'OrgDocumentComment' && @attachment.container.organization.allow_guest_download)
end end
end end
end
end end

@ -70,19 +70,34 @@ class BlogCommentsController < ApplicationController
@course.outline = 0 @course.outline = 0
@course.save @course.save
redirect_to course_path(:id=>params[:course_id]) redirect_to course_path(:id=>params[:course_id])
elsif params[:user_activity_id]
@article.children.destroy
@article.destroy
redirect_to user_path(User.current.id)
else else
@article.children.delete @article.children.destroy
@article.delete @article.destroy
redirect_to user_blogs_path(:user_id=>User.current) redirect_to user_blogs_path(:user_id=>User.current)
end end
else#如果是回复被删, else#如果是回复被删,
if params[:course_id] #如果带了course_id过来了那么这是要跳到课程大纲去的 if params[:course_id] #如果带了course_id过来了那么这是要跳到课程大纲去的
@article.delete @article.destroy
redirect_to syllabus_course_path(:id=>params[:course_id]) redirect_to syllabus_course_path(:id=>params[:course_id])
elsif params[:user_activity_id]
if params[:homepage] && params[:homepage] == "1"
@in_user_homepage = true
end
@user_activity_id = params[:user_activity_id]
@blog_comment = @article.root
@article.destroy
respond_to do |format|
format.js
return
end
else else
root = @article.root root = @article.root
@article.delete @article.destroy
redirect_to user_blog_blog_comment_path(:user_id=>root.author_id,:blog_id=>root.blog_id,:id=>root.id) redirect_to user_blog_blog_comment_path(:user_id=>root.author_id,:blog_id=>root.blog_id,:id=>root.id)
end end
@ -91,20 +106,20 @@ class BlogCommentsController < ApplicationController
def edit def edit
@article = BlogComment.find(params[:id]) @article = BlogComment.find(params[:id])
if User.current.admin? || User.current.id == @article.author_id
respond_to do |format| respond_to do |format|
format.html {render :layout=>'new_base_user'} format.html { render :layout => 'new_base_user' }
end
else
render_403
end end
end end
def quote def quote
@blogComment = BlogComment.find(params[:id]) @blogComment = BlogComment.find(params[:id])
@subject = @blogComment.title
@subject = "RE: #{@subject}" unless @subject.starts_with?('RE:')
@content = "> #{ll(Setting.default_language, :text_user_wrote, @blogComment.author.realname)}\n> "
@temp = BlogComment.new @temp = BlogComment.new
@course_id = params[:course_id] @course_id = params[:course_id]
@temp.content = "<blockquote>#{ll(Setting.default_language, :text_user_wrote, @blogComment.author.realname)} <br/>#{@blogComment.content.html_safe}</blockquote>".html_safe
respond_to do | format| respond_to do | format|
format.js format.js
end end
@ -112,20 +127,30 @@ class BlogCommentsController < ApplicationController
#回复 #回复
def reply def reply
if params[:homepage] && params[:homepage] == "1"
@in_user_homepage = true
end
if params[:in_user_center] if params[:in_user_center]
@in_user_center = true @in_user_center = true
end end
@article = BlogComment.find(params[:id]).root @article = BlogComment.find(params[:id]).root
@quote = params[:quote][:quote]
@blogComment = BlogComment.new @blogComment = BlogComment.new
@blogComment.author = User.current @blogComment.author = User.current
@blogComment.blog = Blog.find(params[:blog_id]) @blogComment.blog = Blog.find(params[:blog_id])
params[:blog_comment][:sticky] = params[:blog_comment][:sticky] || 0 params[:blog_comment][:sticky] = params[:blog_comment][:sticky] || 0
params[:blog_comment][:locked] = params[:blog_comment][:locked] || 0 params[:blog_comment][:locked] = params[:blog_comment][:locked] || 0
@blogComment.safe_attributes = params[:blog_comment] @blogComment.safe_attributes = params[:blog_comment]
@blogComment.content = @quote + @blogComment.content
@blogComment.title = "RE: #{@article.title}" unless params[:blog_comment][:title] @blogComment.title = "RE: #{@article.title}" unless params[:blog_comment][:title]
if params[:parent_id]
@blogComment.content = params[:blog_comment][:content]
parent = BlogComment.find params[:parent_id]
@blogComment.reply_id = params[:id]
parent.children << @blogComment
else
@quote = params[:quote][:quote] || ""
@blogComment.content = @quote + @blogComment.content
@article.children << @blogComment @article.children << @blogComment
end
@article.save @article.save
# @article.update_attribute(:updated_on, @blogComment.updated_on) # @article.update_attribute(:updated_on, @blogComment.updated_on)
@user_activity_id = params[:user_activity_id] @user_activity_id = params[:user_activity_id]

@ -1,9 +1,55 @@
class BlogsController < ApplicationController class BlogsController < ApplicationController
before_filter :find_blog,:except => [:index,:create,:new,:set_homepage, :cancel_homepage] before_filter :find_blog,:except => [:index,:create,:new,:set_homepage, :cancel_homepage]
before_filter :find_user before_filter :find_user
include PraiseTreadHelper
def index def index
@article = BlogComment.new @article = BlogComment.new
@order, @b_sort,@type = params[:order] || 1, params[:sort] || 1, params[:type] || 1
#确定 sort_type 1升序 2 降序
if @order.to_i == @type.to_i
@b_sort = @b_sort.to_i == 1 ? 2 : 1
else
@b_sort = 2
end
sort_name = "updated_at"
sort_type = @b_sort == 1 ? "asc" : "desc"
@topics = @user.blog.articles.reorder("#{BlogComment.table_name}.sticky desc,#{BlogComment.table_name}.#{sort_name} #{sort_type}")
#根据 赞+回复数排序
if @order.to_i == 2
@type = 2
@topics.each do |topic|
topic[:infocount] = get_praise_num(topic) + (topic.parent ? topic.parent.children.count : topic.children.count)
if topic[:infocount] < 0
topic[:infocount] = 0
end
end
@b_sort == 1 ? @topics = @topics.sort{|x,y| x[:infocount] <=> y[:infocount] } : @topics = @topics.sort{|x,y| y[:infocount] <=> x[:infocount] }
@topics = sort_by_sticky @topics
@topics = sortby_time_countcommon_hassticky @topics,sort_name
else
@type = 1
end
#分页
@limit = 10
@is_remote = true
@atta_count = @topics.count
@atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
@offset ||= @atta_pages.offset
@topics = paginateHelper @topics,@limit
respond_to do |format| respond_to do |format|
format.js
format.html {render :layout=>'new_base_user'} format.html {render :layout=>'new_base_user'}
end end
end end
@ -29,7 +75,7 @@ class BlogsController < ApplicationController
def set_homepage def set_homepage
@blog = Blog.find(params[:id]) @blog = Blog.find(params[:id])
@blog.update_attribute(:homepage_id, params[:article_id]) @blog.update_attribute(:homepage_id, params[:article_id])
redirect_to user_blogs_path(params[:user_id]) redirect_to user_path(params[:user_id])
end end
def cancel_homepage def cancel_homepage

@ -28,6 +28,7 @@ class BoardsController < ApplicationController
helper :watchers helper :watchers
helper :project_score helper :project_score
helper :attachments helper :attachments
include PraiseTreadHelper
def index def index
#modify by nwb #modify by nwb
@flag = params[:flag] || false @flag = params[:flag] || false
@ -62,81 +63,105 @@ class BoardsController < ApplicationController
else else
render_403 render_403
end end
end end
end end
def show def show
# 讨论区消息状态更新(已读和未读) # 讨论区消息状态更新(已读和未读)
if @project @order, @b_sort,@type = params[:order] || 1, params[:sort] || 1, params[:type] || 1
query_forge_messages = @board.messages
query_forge_messages.each do |query_forge_message| #确定 sort_type 1升序 2 降序
query = query_forge_message.forge_messages if @order.to_i == @type.to_i
query.each do |forge_message| @b_sort = @b_sort.to_i == 1 ? 2 : 1
if User.current.id == forge_message.user_id else
forge_message.update_attributes(:viewed => true) @b_sort = 2
end
end
end end
sort_name = "updated_on"
sort_type = @b_sort == 1 ? "asc" : "desc"
if @project
ForgeMessage.where("user_id =? and project_id =? and viewed =?", User.current.id, @project.id, 0).update_all(:viewed => true)
# 更新@消息为已读 # 更新@消息为已读
@project.boards.each do |board| # 注释掉这句是因为和上面的方法代码重复,一个类型的消息,已经更新就不需要再更新
board.messages.each do |m| # @project.boards.each do |board|
User.current.at_messages.unviewed('Message', m.id).each {|x| x.viewed!} # board.messages.each do |m|
end # User.current.at_messages.unviewed('Message', m.id).each {|x| x.viewed!}
end # end
# end
elsif @course elsif @course
query_course_messages = @board.messages CourseMessage.where("user_id =? and course_id =? and viewed =?", User.current.id, @course.id, 0).update_all(:viewed => true)
query_course_messages.each do |query_course_message|
query = query_course_message.course_messages
query.each do |course_message|
if User.current.id == course_message.user_id
course_message.update_attributes(:viewed => true)
end
end
end
end end
sort_init 'updated_on', 'desc' # sort_init 'updated_on', 'desc'
sort_update 'created_on' => "#{Message.table_name}.created_on", # sort_update 'created_on' => "#{Message.table_name}.created_on",
'replies' => "#{Message.table_name}.replies_count", # 'replies' => "#{Message.table_name}.replies_count",
'updated_on' => "COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on)" # 'updated_on' => "COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on)"
@is_new = params[:is_new] @is_new = params[:is_new]
@topic_count = @board ? @board.topics.count : 0 @topic_count = @board ? @board.topics.count : 0
if @project if @project
if @board if @board
limit = 10;
@topic_count = @board.topics.count(); @topic_count = @board.topics.count();
@topic_pages = (params[:page] ? params[:page].to_i + 1 : 0) *10 @topic_pages = 0#(params[:page] ? params[:page].to_i + 1 : 0) *10
@topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on) desc"). @topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on) #{sort_type}").
limit(limit).offset(@topic_pages).includes(:last_reply). offset(@topic_pages).includes(:last_reply).
preload(:author, {:last_reply => :author}).all(); preload(:author, {:last_reply => :author}).all();
else else
@topics = []; @topics = [];
end end
elsif @course elsif @course
if (@board) if (@board)
limit = 10;
@topic_count = @board.topics.count(); @topic_count = @board.topics.count();
@topic_pages = (params[:page] ? params[:page].to_i + 1 : 0) *10 @topic_pages = 0 #(params[:page] ? params[:page].to_i + 1 : 0) *10
@topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on) desc"). @topics = @board.topics.reorder("#{Message.table_name}.sticky DESC, COALESCE(last_replies_messages.created_on, #{Message.table_name}.created_on) #{sort_type}").offset(@topic_pages).includes(:last_reply).preload(:author, {:last_reply => :author}).all();
limit(limit).offset(@topic_pages).includes(:last_reply).
preload(:author, {:last_reply => :author}).all();
else else
@topics = []; @topics = [];
end end
end end
#根据 赞+回复数排序
if @order.to_i == 2
@type = 2
@topics.each do |topic|
all_comments = []
count=get_all_children(all_comments, topic).count
topic[:infocount] = get_praise_num(topic) + count
if topic[:infocount] < 0
topic[:infocount] = 0
end
end
@b_sort == 1 ? @topics = @topics.sort{|x,y| x[:infocount] <=> y[:infocount] } : @topics = @topics.sort{|x,y| y[:infocount] <=> x[:infocount] }
@topics = sort_by_sticky @topics
@topics = sortby_time_countcommon_hassticky @topics,sort_name
else
@type = 1
end
#分页
@limit = 15
@is_remote = true
@atta_count = @topics.count
@atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
@offset ||= @atta_pages.offset
@topics = paginateHelper @topics,@limit
@page = params[:page] ? params[:page].to_i + 1 : 0 @page = params[:page] ? params[:page].to_i + 1 : 0
@message = Message.new(:board => @board) @message = Message.new(:board => @board)
#modify by nwb #modify by nwb
if (params[:page] || params[:order])
respond_to do |format|
format.js{render "show.js.erb"}
end
else
respond_to do |format| respond_to do |format|
format.js format.js
format.html { format.html {
if @project if @project
render :action => 'show', :layout => 'base_projects' render :action => 'show', :layout => 'base_projects'
elsif @course elsif @course
@left_nav_type = 2
@params=params @params=params
render :action => 'show', :layout => 'base_courses' render :action => 'show', :layout => 'base_courses'
end end
@ -152,15 +177,16 @@ class BoardsController < ApplicationController
elsif @course elsif @course
render_feed(@messages, :title => "#{@course}: #{@board}") render_feed(@messages, :title => "#{@course}: #{@board}")
end end
} }
end end
end end
end
def new def new
@board = @project.boards.build @board = @project.boards.build
@board.safe_attributes = params[:board] @board.safe_attributes = params[:board]
if @project.project_type == 1 if @project.project_type == 1
@left_nav_type = 2
render :layout => 'base_courses' render :layout => 'base_courses'
end end
end end
@ -182,6 +208,7 @@ class BoardsController < ApplicationController
def edit def edit
if @project.project_type == 1 if @project.project_type == 1
@left_nav_type = 2
render :layout => 'base_courses' render :layout => 'base_courses'
end end
end end

@ -19,8 +19,8 @@ class CommentsController < ApplicationController
default_search_scope :news default_search_scope :news
include ApplicationHelper include ApplicationHelper
model_object News model_object News
before_filter :find_model_object before_filter :find_model_object, :except => [:reply, :quote]
before_filter :find_project_from_association before_filter :find_project_from_association, :except => [:reply, :quote]
before_filter :authorize before_filter :authorize
def create def create
@ -73,8 +73,47 @@ class CommentsController < ApplicationController
def destroy def destroy
@news.comments.find(params[:comment_id]).destroy @news.comments.find(params[:comment_id]).destroy
if params[:user_activity_id]
@user_activity_id = params[:user_activity_id]
respond_to do |format|
format.js
return
end
else
redirect_to news_url(@news) redirect_to news_url(@news)
end end
end
def quote
@comment = Comment.find(params[:id])
respond_to do | format|
format.js
end
end
def reply
comment = Comment.find(params[:id])
@news = News.find comment.commented_id
new_comment = @news.comments.build(:author_id => User.current.id, :reply_id => params[:id], :comments => params[:content], :parent_id => comment.id)
@user_activity_id = params[:user_activity_id]
if new_comment.save
update_course_activity(@news.class,@news.id)
update_user_activity(@news.class,@news.id)
update_org_activity(@news.class,@news.id)
if @user_activity_id
respond_to do |format|
format.js
return
end
else
respond_to do |format|
format.html {
redirect_to news_path(@news)
}
end
end
end
end
private private
@ -87,5 +126,4 @@ class CommentsController < ApplicationController
@news @news
end end
end end

@ -7,6 +7,7 @@ class CoursesController < ApplicationController
helper :members helper :members
helper :words helper :words
helper :attachments helper :attachments
helper :files
helper :activity_notifys helper :activity_notifys
before_filter :auth_login1, :only => [:show, :course_activity, :feedback] before_filter :auth_login1, :only => [:show, :course_activity, :feedback]
@ -22,7 +23,7 @@ class CoursesController < ApplicationController
before_filter :can_show_course, :except => [] before_filter :can_show_course, :except => []
before_filter :logged_user_by_apptoken,:only => [:show,:feedback] before_filter :logged_user_by_apptoken,:only => [:show,:feedback]
before_filter :find_course, :except => [ :index, :search, :new,:join,:unjoin, :create, :new_join, :course,:join_private_courses] before_filter :find_course, :except => [ :index, :search, :new,:join,:unjoin, :create, :new_join, :course,:join_private_courses, :join_course_multi_role]
before_filter :authorize_course, :only => [:show, :settings, :update, :course] before_filter :authorize_course, :only => [:show, :settings, :update, :course]
before_filter :authorize_course_global, :only => [:new,:create] before_filter :authorize_course_global, :only => [:new,:create]
before_filter :toggleCourse, :only => [:finishcourse, :restartcourse] before_filter :toggleCourse, :only => [:finishcourse, :restartcourse]
@ -73,13 +74,29 @@ 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
end end
def join_course_multi_role
if User.current.logged?
cs = CoursesService.new
@user = User.current
join = cs.join_course_roles params,@user
@state = join[:state]
@course = join[:course]
else
@state = 5 #未登录
end
@object_id = @course.id if @course
respond_to do |format|
format.js
end
end
def unjoin def unjoin
if User.current.logged? if User.current.logged?
cs = CoursesService.new cs = CoursesService.new
@ -161,6 +178,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]
@ -184,9 +202,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,@score_sort_by)
@course_groups = @course.course_groups @course_groups = @course.course_groups
end end
@ -195,7 +215,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
@ -208,7 +230,7 @@ class CoursesController < ApplicationController
end end
@canShowCode = isCourseTeacher(User.current.id,@course) && params[:role] != '1' @canShowCode = isCourseTeacher(User.current.id,@course) && params[:role] != '1'
@is_remote = true @is_remote = true
@members = student_homework_score(0,0, 10,"desc")
@course_groups = @course.course_groups @course_groups = @course.course_groups
end end
@ -240,6 +262,18 @@ class CoursesController < ApplicationController
# req[:message] = l(:modal_valid_passing) if req[:message].blank? # req[:message] = l(:modal_valid_passing) if req[:message].blank?
render :json => req render :json => req
end end
def teacher_assign_group
member = Member.where(:course_id => @course.id, :user_id => params[:user_id]).first
member.course_group_id = params[:course_group_id].to_i
member.save
@course_groups = @course.course_groups
@canShowCode = isCourseTeacher(User.current.id,@course) && params[:role] != '1'
respond_to do |format|
format.js
end
end
def join_group def join_group
@subPage_title = l :label_student_list @subPage_title = l :label_student_list
group = CourseGroup.find(params[:object_id]) group = CourseGroup.find(params[:object_id])
@ -268,6 +302,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])
@ -282,9 +317,9 @@ class CoursesController < ApplicationController
def member def member
## 有角色参数的才是课程,没有的就是项目 ## 有角色参数的才是课程,没有的就是项目
if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course))) if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course)))
@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
@ -299,7 +334,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
@ -321,7 +356,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 desc") @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|
@ -337,28 +372,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
@ -371,6 +407,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=[]
@ -384,6 +429,9 @@ class CoursesController < ApplicationController
end end
def settings def settings
#添加成员消息状态
join_course_messages = CourseMessage.where("user_id =? and course_message_type =? and course_id =? and status = ? and viewed =?", User.current.id, 'JoinCourse', @course.id, 1, 0)
join_course_messages.update_all(:viewed => true)
if User.current.allowed_to?(:as_teacher,@course) if User.current.allowed_to?(:as_teacher,@course)
@select_tab = params[:tab] @select_tab = params[:tab]
@issue_custom_fields = IssueCustomField.sorted.all @issue_custom_fields = IssueCustomField.sorted.all
@ -450,6 +498,93 @@ class CoursesController < ApplicationController
#copy avatar #copy avatar
copy_avatar(@course, copy_course) copy_avatar(@course, copy_course)
if params[:course_content_type]
params[:course_content_type].each do |type|
case type
when "0"
homeworks = copy_course.homework_commons
homeworks.each do |homework|
new_homework = HomeworkCommon.new
new_homework.name = homework.name
new_homework.user_id = User.current.id
new_homework.description = homework.description
new_homework.publish_time = Date.today + 30
new_homework.end_time = Date.today + 60
new_homework.homework_type = homework.homework_type
new_homework.late_penalty = homework.late_penalty
new_homework.course_id = @course.id
new_homework.teacher_priority = homework.teacher_priority
new_homework.anonymous_comment = homework.anonymous_comment
new_homework.quotes = 0
new_homework.is_open = homework.is_open
homework.attachments.each do |attachment|
att = attachment.copy
att.container_id = nil
att.container_type = nil
att.copy_from = attachment.id
att.save
new_homework.attachments << att
end
homework_detail_manual = homework.homework_detail_manual
homework_detail_programing = homework.homework_detail_programing
homework_detail_group = homework.homework_detail_group
if homework_detail_manual
new_homework.homework_detail_manual = HomeworkDetailManual.new
new_homework_detail_manual = new_homework.homework_detail_manual
new_homework_detail_manual.ta_proportion = homework_detail_manual.ta_proportion
new_homework_detail_manual.comment_status = 0
new_homework_detail_manual.evaluation_start = Date.today + 67
new_homework_detail_manual.evaluation_end = Date.today + 74
new_homework_detail_manual.evaluation_num = homework_detail_manual.evaluation_num
new_homework_detail_manual.absence_penalty = homework_detail_manual.absence_penalty
end
if homework_detail_programing
new_homework.homework_detail_programing = HomeworkDetailPrograming.new
new_homework.homework_detail_programing.ta_proportion = homework_detail_programing.ta_proportion
new_homework.homework_detail_programing.language = homework_detail_programing.language
homework.homework_tests.each_with_index do |homework_test|
new_homework.homework_tests << HomeworkTest.new(
input: homework_test.input,
output: homework_test.output
)
end
end
if homework_detail_group
new_homework.homework_detail_group = HomeworkDetailGroup.new
new_homework.homework_detail_group.min_num = homework_detail_group.min_num
new_homework.homework_detail_group.max_num = homework_detail_group.max_num
new_homework.homework_detail_group.base_on_project = homework_detail_group.base_on_project
end
if new_homework.save
new_homework_detail_manual.save if new_homework_detail_manual
new_homework.homework_detail_programing.save if new_homework.homework_detail_programing
new_homework.homework_detail_group.save if new_homework.homework_detail_group
end
homework.update_attribute(:quotes, homework.quotes+1)
end
when "1"
attachments = copy_course.attachments
attachments.each do |attachment|
attach_copied_obj = attachment.copy
attach_copied_obj.tag_list.add(attachment.tag_list) # tag关联
attach_copied_obj.container = @course
attach_copied_obj.created_on = Time.now
attach_copied_obj.author_id = User.current.id
attach_copied_obj.copy_from = attachment.copy_from.nil? ? attachment.id : attachment.copy_from
attach_copied_obj.is_publish = 0
attach_copied_obj.publish_time = Date.today + 30
if attach_copied_obj.attachtype == nil
attach_copied_obj.attachtype = 4
end
attach_copied_obj.save
update_quotes attach_copied_obj
end
end
end
end
=begin
if params[:checkAll] if params[:checkAll]
attachments = copy_course.attachments attachments = copy_course.attachments
attachments.each do |attachment| attachments.each do |attachment|
@ -513,8 +648,15 @@ class CoursesController < ApplicationController
end end
end end
end end
=end
end end
if @course if @course
#发送微信消息
count = ShieldWechatMessage.where("container_type='User' and container_id=#{User.current.id} and shield_type='Course' and shield_id=#{@course.id}").count
if count == 0
ss = SyllabusesService.new
ss.send_wechat_create_class_notice User.current,@course
end
respond_to do |format| respond_to do |format|
flash[:notice] = l(:notice_successful_create) flash[:notice] = l(:notice_successful_create)
format.html {redirect_to course_url(@course)} format.html {redirect_to course_url(@course)}
@ -597,6 +739,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
@ -764,24 +907,28 @@ class CoursesController < ApplicationController
if params[:type].present? if params[:type].present?
case params[:type] case params[:type]
when "homework" when "homework"
@course_activities = course_activities.where("course_act_type = 'HomeworkCommon'").order('updated_at desc').limit(10).offset(@page * 10) @course_activities = course_activities.where("course_act_type = 'HomeworkCommon'").order('updated_at desc')
when "news" when "news"
@course_activities = course_activities.where("course_act_type = 'News'").order('updated_at desc').limit(10).offset(@page * 10) @course_activities = course_activities.where("course_act_type = 'News'").order('updated_at desc')
when "message" when "message"
@course_activities = course_activities.where("course_act_type = 'Message'").order('updated_at desc').limit(10).offset(@page * 10) @course_activities = course_activities.where("course_act_type = 'Message'").order('updated_at desc')
when "poll" when "poll"
@course_activities = course_activities.where("course_act_type = 'Poll'").order('updated_at desc').limit(10).offset(@page * 10) @course_activities = course_activities.where("course_act_type = 'Poll'").order('updated_at desc')
when "attachment" when "attachment"
@course_activities = course_activities.where("course_act_type = 'Attachment'").order('updated_at desc').limit(10).offset(@page * 10) @course_activities = course_activities.where("course_act_type = 'Attachment'").order('updated_at desc')
when "journalsForMessage" when "journalsForMessage"
@course_activities = course_activities.where("course_act_type = 'JournalsForMessage'").order('updated_at desc').limit(10).offset(@page * 10) @course_activities = course_activities.where("course_act_type = 'JournalsForMessage'").order('updated_at desc')
else else
@course_activities = course_activities.order('updated_at desc').limit(10).offset(@page * 10) @course_activities = course_activities.order('updated_at desc')
end end
else else
@course_activities = course_activities.order('updated_at desc').limit(10).offset(@page * 10) @course_activities = course_activities.order('updated_at desc')
end end
@course_activities_count = @course_activities.count
@course_activities = @course_activities.limit(10).offset(@page * 10)
@type = params[:type] @type = params[:type]
@left_nav_type = 1
respond_to do |format| respond_to do |format|
format.js format.js
format.html{render :layout => 'base_courses'} format.html{render :layout => 'base_courses'}
@ -800,10 +947,7 @@ class CoursesController < ApplicationController
end end
def feedback def feedback
@course.journals_for_messages.each do |messages| CourseMessage.where("user_id = ? and course_id = ?", User.current, @course.id).update_all(:viewed => true)
query = messages.course_messages.where("user_id = ?", User.current.id)
query.update_all(:viewed => true);
end
if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course))) if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course)))
page = params[:page] page = params[:page]
@ -816,6 +960,7 @@ class CoursesController < ApplicationController
end end
@jour = paginateHelper @jours,10 @jour = paginateHelper @jours,10
@state = false @state = false
@left_nav_type = 6
respond_to do |format| respond_to do |format|
format.html{render :layout => 'base_courses'} format.html{render :layout => 'base_courses'}
format.api format.api
@ -825,6 +970,82 @@ class CoursesController < ApplicationController
end end
end end
def search_homework_member homeworks,name
if name == ""
select_homework = homeworks
else
name = name.downcase
select_homework = homeworks.select{ |homework|
homework.user[:login].to_s.downcase.include?(name) || homework.user.user_extensions[:student_id].to_s.downcase.include?(name) || (homework.user[:lastname].to_s.downcase + homework.user[:firstname].to_s.downcase).include?(name)
}
end
select_homework
end
# 作业查重
def code_repeat
#代码查重新加的
@order,@b_sort,@name,@group = params[:order] || "score",params[:sort] || "desc",params[:name] || "",params[:group]
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
if !@is_teacher
render_403
return
end
@homework = HomeworkCommon.find params[:homework]
#order("#{@order} #{@b_sort}"
@student_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,IF(final_score = 0, 0, final_score - absence_penalty - late_penalty)) as score").order("simi_value desc").has_committed,@name
@works_hash = {}
@student_works.each do |tmpwork|
@works_hash[tmpwork.id] = tmpwork
puts tmpwork.id
end
#respond_to do |format|
#format.html {render :layout => 'base_courses'}
#end
end
def show_comparecode
src_id = params[:src_id]
dst_id = params[:dst_id]
@is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
if !@is_teacher
render_403
return
end
src_work = StudentWork.where("id =?", src_id).first
@homework = HomeworkCommon.find params[:homework_id]
@simi_value = src_work.simi_value.to_i
@src_code = src_work.description
src_user = User.where("id =?", src_work.user_id).first
@src_username = src_user.try(:realname) != " " ? src_user.lastname + src_user.firstname : src_user.try(:login)
#descriotion user name
dst_work = StudentWork.where("id =?", dst_id).first
@dst_code = dst_work.description
dst_user = User.where("id =?", dst_work.user_id).first
@dst_username = dst_user.try(:realname) != " " ? dst_user.lastname + dst_user.firstname : dst_user.try(:login)
respond_to do |format|
format.js
end
end
#根据已有课程复制课程 #根据已有课程复制课程
#param id:已有课程ID #param id:已有课程ID
def copy_course def copy_course
@ -897,7 +1118,7 @@ class CoursesController < ApplicationController
#删除课程 #删除课程
#删除课程只是将课程的is_deleted状态改为falseis_deleted为false状态的课程只有管理员可以看到 #删除课程只是将课程的is_deleted状态改为falseis_deleted为false状态的课程只有管理员可以看到
def destroy def destroy
@course.update_attributes(:is_delete => true) @course.delete!
@course = nil @course = nil
redirect_to user_url(User.current) redirect_to user_url(User.current)
end end
@ -923,6 +1144,29 @@ class CoursesController < ApplicationController
end end
end end
#统计
def statistics_course
@left_nav_type = 9
respond_to do |format|
format.html {render :layout => 'base_courses'}
end
end
#切换身份
def switch_role
members = @course.members.where("user_id = #{params[:user_id]}")
unless members.blank?
#role = MemberRole.where("member_id = #{members.first.id} and role_id = #{params[:role]}").first
curr_role = MemberRole.find_by_member_id_and_role_id(members.first.id, params[:curr_role])
tar_role = MemberRole.find_by_member_id_and_role_id(members.first.id, params[:tar_role])
unless (curr_role.nil? || tar_role.nil?)
curr_role.update_column('is_current', 0)
tar_role.update_column('is_current', 1)
end
end
redirect_to course_path(@course)
end
private private
def update_quotes attachment def update_quotes attachment
if attachment.copy_from if attachment.copy_from
@ -974,33 +1218,37 @@ 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
sql_select = "SELECT members.*,( sql_select = "SELECT members.*,(
SELECT SUM(IF(student_works.final_score is null,null,student_works.final_score - student_works.absence_penalty - student_works.late_penalty)) SELECT SUM(student_works.work_score)
FROM student_works,homework_commons FROM student_works,homework_commons
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(IF(student_works.final_score is null,null,student_works.final_score - student_works.absence_penalty - student_works.late_penalty)) SELECT SUM(student_works.work_score)
FROM student_works,homework_commons FROM student_works,homework_commons
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)
@ -1028,7 +1276,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)])
@ -1050,8 +1298,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
@ -1061,16 +1308,132 @@ 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
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 count_row += 1
end 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();

@ -29,6 +29,7 @@ class ExerciseController < ApplicationController
exercises = @course.exercises.where("exercise_status <> 1").order("created_at asc") exercises = @course.exercises.where("exercise_status <> 1").order("created_at asc")
end end
@exercises = paginateHelper exercises,20 #分页 @exercises = paginateHelper exercises,20 #分页
@left_nav_type = 8
respond_to do |format| respond_to do |format|
format.html format.html
end end
@ -49,6 +50,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
@ -67,6 +73,7 @@ class ExerciseController < ApplicationController
end end
# @percent = get_percent(@exercise,User.current) # @percent = get_percent(@exercise,User.current)
@exercise_questions = @exercise.exercise_questions @exercise_questions = @exercise.exercise_questions
@left_nav_type = 8
respond_to do |format| respond_to do |format|
format.html {render :layout => 'base_courses'} format.html {render :layout => 'base_courses'}
end end
@ -113,6 +120,7 @@ class ExerciseController < ApplicationController
end end
def edit def edit
@left_nav_type = 8
respond_to do |format| respond_to do |format|
format.html{render :layout => 'base_courses'} format.html{render :layout => 'base_courses'}
end end
@ -154,6 +162,7 @@ class ExerciseController < ApplicationController
@exercise = Exercise.find(params[:id]) @exercise = Exercise.find(params[:id])
exercise_questions = @exercise.exercise_questions exercise_questions = @exercise.exercise_questions
@exercise_questions = paginateHelper exercise_questions, 5 @exercise_questions = paginateHelper exercise_questions, 5
@left_nav_type = 8
respond_to do |format| respond_to do |format|
format.html{render :layout => 'base_courses'} format.html{render :layout => 'base_courses'}
end end
@ -374,6 +383,7 @@ class ExerciseController < ApplicationController
else else
@exercise_users_list = [] @exercise_users_list = []
end end
@left_nav_type = 8
respond_to do |format| respond_to do |format|
format.html format.html
format.xls { format.xls {
@ -506,7 +516,7 @@ class ExerciseController < ApplicationController
def commit_exercise def commit_exercise
# 老师不需要提交 # 老师不需要提交
if User.current.allowed_to?(:as_teacher,@course) if User.current.allowed_to?(:as_teacher,@course)
if @exercise.publish_time.nil? if @exercise.publish_time.nil? || @exercise.publish_time <= Time.now
@exercise.update_attributes(:show_result => params[:show_result]) @exercise.update_attributes(:show_result => params[:show_result])
@exercise.update_attributes(:exercise_status => 2) @exercise.update_attributes(:exercise_status => 2)
@exercise.update_attributes(:publish_time => Time.now) @exercise.update_attributes(:publish_time => Time.now)
@ -561,6 +571,7 @@ class ExerciseController < ApplicationController
eu = get_exercise_user(@exercise.id, @user.id) eu = get_exercise_user(@exercise.id, @user.id)
eu.update_attributes(:score => score) eu.update_attributes(:score => score)
@exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", @user.id, @exercise.id).first @exercise_user = ExerciseUser.where("user_id =? and exercise_id=?", @user.id, @exercise.id).first
@left_nav_type = 8
respond_to do |format| respond_to do |format|
format.html {render :layout => 'base_courses'} format.html {render :layout => 'base_courses'}
end end

@ -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] :search_files_in_subfield,:upload_files_menu,:file_hidden,:republish_file,:update_file_description]
helper :sort helper :sort
include SortHelper include SortHelper
@ -96,6 +96,33 @@ class FilesController < ApplicationController
end end
end end
def file_hidden
@file = Attachment.find params[:id]
@course = Course.find params[:course_id]
respond_to do |format|
format.js
end
end
def republish_file
@file = Attachment.find params[:id]
@course = Course.find params[:course_id]
if params[:publish_time]
unless params[:publish_time] == ""
@file.publish_time = params[:publish_time]
end
end
if @file.publish_time > Date.today
@file.is_publish = 0
else
@file.is_publish = 1
end
@file.save
respond_to do |format|
format.js
end
end
def search_project def search_project
sort = "" sort = ""
@sort = "" @sort = ""
@ -180,8 +207,7 @@ class FilesController < ApplicationController
sort = "created_on DESC" sort = "created_on DESC"
end end
if keywords != "%%" if keywords != "%%"
resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND filename LIKE :like ", like: "%#{keywords}%"). resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND filename LIKE :like ", like: "%#{keywords}%").reorder(sort)
reorder(sort)
else else
resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' "). reorder(sort) resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' "). reorder(sort)
end end
@ -230,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]
@ -333,6 +366,7 @@ class FilesController < ApplicationController
@tag_list = attachment_tag_list @all_attachments @tag_list = attachment_tag_list @all_attachments
@left_nav_type = 5
render :layout => 'base_courses' render :layout => 'base_courses'
elsif params[:org_subfield_id] elsif params[:org_subfield_id]
if params[:sort] if params[:sort]
@ -379,10 +413,14 @@ class FilesController < ApplicationController
@container_type = 2 @container_type = 2
@containers = [ OrgSubfield.includes(:attachments).reorder(sort).find(@org_subfield.id)] @containers = [ OrgSubfield.includes(:attachments).reorder(sort).find(@org_subfield.id)]
@organization = Organization.find(@containers.first.organization_id) @organization = Organization.find(@containers.first.organization_id)
if @organization.is_public? or User.current.admin? or User.current.member_of_org?(@organization)
show_attachments @containers show_attachments @containers
@tag_list = attachment_tag_list @all_attachments @tag_list = attachment_tag_list @all_attachments
@page = params[:page] || 1 @page = params[:page] || 1
render :layout => 'base_org' render :layout => 'base_org'
else
render_403
end
# @subfield = params[:org_subfield_id] # @subfield = params[:org_subfield_id]
end end
@ -408,6 +446,7 @@ class FilesController < ApplicationController
@versions = @project.versions.sort @versions = @project.versions.sort
@course_tag = @project.project_type @course_tag = @project.project_type
if @project.project_type == 1 if @project.project_type == 1
@left_nav_type = 5
render :layout => 'base_courses' render :layout => 'base_courses'
end end
end end
@ -428,10 +467,16 @@ class FilesController < ApplicationController
if params[:in_project_toolbar] if params[:in_project_toolbar]
@in_project_toolbar = params[:in_project_toolbar] @in_project_toolbar = params[:in_project_toolbar]
end end
# 发送邮件
attachments = Attachment.attach_filesex(@project, params[:attachments], params[:attachment_type]) attachments = Attachment.attach_filesex(@project, params[:attachments], params[:attachment_type])
if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added') if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added')
# 发送邮件
Mailer.run.attachments_added(attachments[:files]) Mailer.run.attachments_added(attachments[:files])
# 生成动态
attachments[:files].each do |file|
ForgeActivity.create(:user_id => User.current.id, :project_id => @project.id, :forge_act_id => file.id, :forge_act_type => "Attachment")
end
# 更新资源总数, 根据上传的附件数累加
@project.project_score.update_attribute(:attach_num, @project.project_score.attach_num + attachments[:files].count) unless @project.project_score.nil?
end end
# end # end
if params[:project_attachment_type] && params[:project_attachment_type].is_a?(Array) if params[:project_attachment_type] && params[:project_attachment_type].is_a?(Array)
@ -440,6 +485,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
@ -450,16 +496,12 @@ 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
end end
end end
# 更新资源总数, 根据上传的附件数累加
unless @project.project_score.nil?
@project.project_score.update_attribute(:attach_num, @project.project_score.attach_num + attachments[:files].count)
end
# end
# TODO: 临时用 nyan # TODO: 临时用 nyan
sort_init 'created_on', 'desc' sort_init 'created_on', 'desc'
sort_update 'created_on' => "#{Attachment.table_name}.created_on", sort_update 'created_on' => "#{Attachment.table_name}.created_on",
@ -502,6 +544,7 @@ class FilesController < ApplicationController
if attachment.publish_time > Date.today if attachment.publish_time > Date.today
attachment.is_publish = 0 attachment.is_publish = 0
end end
attachment.description = params[:description]
attachment.save attachment.save
end end
end end
@ -527,7 +570,8 @@ class FilesController < ApplicationController
end end
end end
# 更新课程英雄榜得分 # 更新课程英雄榜得分
update_contributor_score(@course, attachments[:files].first) course_member_score(@course.id, attachments[:files].first.author_id, "Attachment")
# end
# end # end
# TODO: 临时用 nyan # TODO: 临时用 nyan
sort_init 'created_on', 'desc' sort_init 'created_on', 'desc'
@ -560,6 +604,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
@ -570,6 +615,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
@ -596,20 +642,36 @@ class FilesController < ApplicationController
# redirect_to org_subfield_files_url(@org_subfield) # redirect_to org_subfield_files_url(@org_subfield)
# } # }
end end
# 组织添加附件,为了修改图片
elsif params[:organization_id]
@organization = Organization.find(params[:organization_id])
@addTag=false
# atttchment_type = 0为logo 1为banner
if params[:logo]
attachments = Attachment.attach_filesex(@organization, params[:attachments], false)
else
attachments = Attachment.attach_filesex(@organization, params[:attachments], true)
end end
end # TODO: 临时用 nyan
end sort_init 'created_on', 'desc'
sort_update 'created_on' => "#{Attachment.table_name}.created_on",
'filename' => "#{Attachment.table_name}.filename",
'size' => "#{Attachment.table_name}.filesize",
'downloads' => "#{Attachment.table_name}.downloads"
def update_contributor_score(course, file ) @containers = [Organization.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@organization.id)]
unless file.author.allowed_to?(:as_teacher, course)
course_contributor_score = CourseContributorScore.where("course_id =? and user_id =?", course.id, file.author.id).first show_attachments @containers
if course_contributor_score.nil? @tag_list = attachment_tag_list @all_attachments
CourseContributorScore.create(:course_id => course.id, :user_id => file.author.id, :message_num => 0, :message_reply_num => 0, @attachtype = 0
:news_reply_num => 0, :resource_num => 5, :journal_num => 0, :journal_reply_num => 0, :total_score => 5) @contenttype = 0
else
score = course_contributor_score.resource_num + 5 respond_to do |format|
total_score = course_contributor_score.total_score + 5 format.js
course_contributor_score.update_attributes(:resource_num => score, :total_score => total_score) # format.html {
# redirect_to org_subfield_files_url(@org_subfield)
# }
end
end end
end end
end end
@ -752,6 +814,7 @@ class FilesController < ApplicationController
@attachtype = params[:type].to_i @attachtype = params[:type].to_i
@contenttype = params[:contentType].to_s @contenttype = params[:contentType].to_s
# render layout: 'base_courses' # render layout: 'base_courses'
@left_nav_type = 5
respond_to do |format| respond_to do |format|
format.js format.js
format.html { format.html {
@ -833,7 +896,13 @@ class FilesController < ApplicationController
q = "%#{@q.strip}%" q = "%#{@q.strip}%"
@result = find_org_subfield_attache q,@org_subfield,sort @result = find_org_subfield_attache q,@org_subfield,sort
@result = visable_attachemnts @result @result = visable_attachemnts @result
if params[:other]
@result = @result.select{|attachment|
attachment.tag_list.index{|tag|tag != '软件' and tag != '媒体' and tag != '代码'}.present?
}
else
@result = @result.select{|attachment| attachment.tag_list.include?(@tag_name)} unless @tag_name.blank? @result = @result.select{|attachment| attachment.tag_list.include?(@tag_name)} unless @tag_name.blank?
end
@searched_attach = paginateHelper @result,10 @searched_attach = paginateHelper @result,10
@tag_list = get_org_subfield_tag_list @org_subfield @tag_list = get_org_subfield_tag_list @org_subfield
@ -849,5 +918,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

@ -6,24 +6,32 @@ class HomeworkCommonController < ApplicationController
include StudentWorkHelper include StudentWorkHelper
before_filter :find_course, :only => [:index,:new,:create] before_filter :find_course, :only => [:index,:new,:create]
before_filter :find_homework, :only => [:edit,:update,:alert_anonymous_comment,:start_anonymous_comment,:stop_anonymous_comment,:destroy,:start_evaluation_set,:set_evaluation_attr,:score_rule_set,:alert_forbidden_anonymous_comment] before_filter :find_homework, :only => [:edit,:update,:alert_anonymous_comment,:start_anonymous_comment,:stop_anonymous_comment,:destroy,:start_evaluation_set,:set_evaluation_attr,:score_rule_set,:alert_forbidden_anonymous_comment,:alert_open_student_works,:open_student_works]
before_filter :teacher_of_course, :only => [:new, :create, :edit, :update, :destroy, :start_anonymous_comment, :stop_anonymous_comment, :alert_anonymous_comment,:start_evaluation_set,:set_evaluation_attr,:score_rule_set,:alert_forbidden_anonymous_comment] before_filter :teacher_of_course, :only => [:new, :create, :edit, :update, :destroy, :start_anonymous_comment, :stop_anonymous_comment, :alert_anonymous_comment,:start_evaluation_set,:set_evaluation_attr,:score_rule_set,:alert_forbidden_anonymous_comment,:alert_open_student_works,:open_student_works]
before_filter :member_of_course, :only => [:index] before_filter :member_of_course, :only => [:index]
def index def index
#unless params[:page]
# update_homework_time(@course.homework_commons)
#end
search = "%#{params[:search].to_s.strip.downcase}%"
@new_homework = HomeworkCommon.new @new_homework = 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("created_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.where("name like '%#{search}%'").order("created_at desc")
else else
@homeworks = @course.homework_commons.where("publish_time <= '#{Date.today}'").order("created_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("name like '%#{search}%' and publish_time <= '#{Date.today}'").order("created_at desc")
end end
#update_homework_time @homework_commons
@is_student = User.current.logged? && (User.current.admin? || (User.current.member_of_course?(@course) && !@is_teacher)) @is_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|
@ -31,6 +39,7 @@ class HomeworkCommonController < ApplicationController
end end
end end
@left_nav_type = 3
respond_to do |format| respond_to do |format|
format.js format.js
format.html format.html
@ -51,10 +60,17 @@ class HomeworkCommonController < ApplicationController
@user = User.current @user = User.current
@is_in_course = params[:is_in_course].to_i @is_in_course = params[:is_in_course].to_i
@course_activity = params[:course_activity].to_i @course_activity = params[:course_activity].to_i
if @is_in_course == 1 || @course_activity == 1
@left_nav_type = 3
respond_to do |format|
format.html{render :layout => 'base_courses'}
end
else
respond_to do |format| respond_to do |format|
format.html{render :layout => 'new_base_user'} format.html{render :layout => 'new_base_user'}
end end
end end
end
def update def update
if params[:homework_common] if params[:homework_common]
@ -65,17 +81,26 @@ class HomeworkCommonController < ApplicationController
else else
@homework.publish_time = params[:homework_common][:publish_time] @homework.publish_time = params[:homework_common][:publish_time]
end end
homework_detail_manual = @homework.homework_detail_manual || HomeworkDetailManual.new
@homework.end_time = params[:homework_common][:end_time] || Time.now @homework.end_time = params[:homework_common][:end_time] || Time.now
@homework.course_id = params[:course_id] @homework.course_id = params[:course_id]
@homework.anonymous_comment = params[:homework_common][:anonymous_comment] ? params[:homework_common][:anonymous_comment] : 0 anonymous = params[:homework_common][:anonymous_comment] ? params[:homework_common][:anonymous_comment].to_i : 0
if anonymous != @homework.anonymous_comment
if anonymous == 1
homework_detail_manual.ta_proportion = @homework.homework_type == 1 ? 1.0 : 0.4
else
homework_detail_manual.ta_proportion = @homework.homework_type == 1 ? 0.6 : 0.3
end
end
homework_detail_manual = @homework.homework_detail_manual || HomeworkDetailManual.new
if @homework.publish_time <= Date.today && homework_detail_manual.comment_status == 0 if @homework.publish_time <= Date.today && homework_detail_manual.comment_status == 0
homework_detail_manual.comment_status = 1 homework_detail_manual.comment_status = 1
end end
homework_detail_manual.evaluation_start = params[:evaluation_start].blank? ? @homework.end_time + 7 : params[:evaluation_start] eval_start = homework_detail_manual.evaluation_start
homework_detail_manual.evaluation_end = params[:evaluation_end].blank? ? homework_detail_manual.evaluation_start + 7 : params[:evaluation_end] if eval_start.nil? || (eval_start <= @homework.end_time && homework_detail_manual.comment_status <= 1)
homework_detail_manual.evaluation_start = @homework.end_time + 7
homework_detail_manual.evaluation_end = homework_detail_manual.evaluation_start + 7
end
@homework.save_attachments(params[:attachments]) @homework.save_attachments(params[:attachments])
render_attachment_warning_if_needed(@homework) render_attachment_warning_if_needed(@homework)
@ -84,6 +109,13 @@ class HomeworkCommonController < ApplicationController
@homework.homework_detail_programing ||= HomeworkDetailPrograming.new @homework.homework_detail_programing ||= HomeworkDetailPrograming.new
@homework_detail_programing = @homework.homework_detail_programing @homework_detail_programing = @homework.homework_detail_programing
@homework_detail_programing.language = params[:language_type].to_i @homework_detail_programing.language = params[:language_type].to_i
if anonymous != @homework.anonymous_comment
if anonymous == 1
@homework_detail_programing.ta_proportion = 0.6
else
@homework_detail_programing.ta_proportion = 0.5
end
end
@homework.homework_tests.delete_all @homework.homework_tests.delete_all
inputs = params[:program][:input] inputs = params[:program][:input]
@ -106,8 +138,9 @@ class HomeworkCommonController < ApplicationController
@homework_detail_group.base_on_project = params[:base_on_project].to_i @homework_detail_group.base_on_project = params[:base_on_project].to_i
end end
@homework.anonymous_comment = params[:homework_common][:anonymous_comment] ? params[:homework_common][:anonymous_comment].to_i : 0
if @homework.save if @homework.save
@homework_detail_manual.save if @homework_detail_manual homework_detail_manual.save if homework_detail_manual
@homework_detail_programing.save if @homework_detail_programing @homework_detail_programing.save if @homework_detail_programing
@homework_detail_group.save if @homework_detail_group @homework_detail_group.save if @homework_detail_group
@ -148,7 +181,7 @@ class HomeworkCommonController < ApplicationController
@statue = 4 and return unless User.current.admin? || User.current.allowed_to?(:as_teacher,@course) @statue = 4 and return unless User.current.admin? || User.current.allowed_to?(:as_teacher,@course)
@statue = 5 and return if Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") @statue = 5 and return if Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d")
if @homework_detail_manual.comment_status == 1 if @homework_detail_manual.comment_status == 1
student_works = @homework.student_works student_works = @homework.student_works.has_committed
if student_works && student_works.size >= 2 if student_works && student_works.size >= 2
if @homework.homework_type == 3 if @homework.homework_type == 3
student_work_projects = @homework.student_work_projects.where("student_work_id is not null") student_work_projects = @homework.student_work_projects.where("student_work_id is not null")
@ -202,8 +235,8 @@ class HomeworkCommonController < ApplicationController
@homework_detail_manual.update_column('comment_status', 3) @homework_detail_manual.update_column('comment_status', 3)
@homework_detail_manual.update_column('evaluation_end', Date.today) @homework_detail_manual.update_column('evaluation_end', Date.today)
#计算缺评扣分 #计算缺评扣分
work_ids = "(" + @homework.student_works.map(&:id).join(",") + ")" work_ids = "(" + @homework.student_works.has_committed.map(&:id).join(",") + ")"
@homework.student_works.each do |student_work| @homework.student_works.has_committed.each do |student_work|
absence_penalty_count = student_work.user.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count - student_work.user.student_works_scores.where("student_work_id IN #{work_ids}").count absence_penalty_count = student_work.user.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count - student_work.user.student_works_scores.where("student_work_id IN #{work_ids}").count
student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * @homework_detail_manual.absence_penalty : 0 student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * @homework_detail_manual.absence_penalty : 0
student_work.save student_work.save
@ -233,11 +266,11 @@ class HomeworkCommonController < ApplicationController
@totle_size = 0 @totle_size = 0
if @homework_detail_manual.comment_status == 1 if @homework_detail_manual.comment_status == 1
@totle_size = @course.student.count @totle_size = @course.student.count
@cur_size = @homework.student_works.size @cur_size = @homework.student_works.has_committed.size
elsif @homework_detail_manual.comment_status == 2 elsif @homework_detail_manual.comment_status == 2
@homework.student_works.map { |work| @totle_size += work.student_works_evaluation_distributions.count} @homework.student_works.has_committed.map { |work| @totle_size += work.student_works_evaluation_distributions.count}
@cur_size = 0 @cur_size = 0
@homework.student_works.map { |work| @cur_size += work.student_works_scores.where(:reviewer_role => 3).count} @homework.student_works.has_committed.map { |work| @cur_size += work.student_works_scores.select("distinct user_id").where(:reviewer_role => 3).count}
end end
@percent = format("%.2f",(@cur_size.to_f / ( @totle_size == 0 ? 1 : @totle_size)) * 100) @percent = format("%.2f",(@cur_size.to_f / ( @totle_size == 0 ? 1 : @totle_size)) * 100)
@user_activity_id = params[:user_activity_id].to_i @user_activity_id = params[:user_activity_id].to_i
@ -261,6 +294,30 @@ class HomeworkCommonController < ApplicationController
end end
end end
def open_student_works
if @homework.is_open == 0
@homework.update_column('is_open', 1)
else
@homework.update_column('is_open', 0)
end
@user_activity_id = params[:user_activity_id]
@is_in_course = params[:is_in_course] if params[:is_in_course]
@course_activity = params[:course_activity] if params[:course_Activity]
end
def alert_open_student_works
if params[:user_activity_id]
@user_activity_id = params[:user_activity_id]
else
@user_activity_id = -1
end
@is_in_course = params[:is_in_course] if params[:is_in_course]
@course_activity = params[:course_activity] if params[:course_Activity]
respond_to do |format|
format.js
end
end
def programing_test def programing_test
test = {language:params[:language],src:Base64.encode64(params[:src]),input:[params[:input]],output:[params[:output]]} test = {language:params[:language],src:Base64.encode64(params[:src]),input:[params[:input]],output:[params[:output]]}
@index = params[:index] @index = params[:index]
@ -351,4 +408,56 @@ class HomeworkCommonController < ApplicationController
student_works += student_works student_works += student_works
student_works[index + 1 .. index + n] student_works[index + 1 .. index + n]
end end
def update_homework_time homeworks
unless homeworks.nil?
homeworks.each do |h|
if h.homework_type == 3 && h.homework_detail_group.base_on_project == 1
student_works = h.student_work_projects.where("is_leader = 1 && project_id != -1")
time = h.updated_at
unless student_works.nil?
student_works.each do |s|
project = Project.find s.project_id
unless project.nil? && project.gpid.nil?
project_time=project.updated_on
project_time=ForgeActivity.where("project_id=?",project.id).last.updated_at if ForgeActivity.where("project_id=?",project.id).last
if time.strftime('%Y-%m-%d %H:%M:%S') < project_time.strftime('%Y-%m-%d %H:%M:%S')
time = project_time
end
begin
# gitlab端获取默认分支
g = Gitlab.client
default_branch = g.project(project.gpid).default_branch
changesets = g.commits(project.gpid, :ref_name => default_branch)
changesets_latest_coimmit = changesets[0]
unless changesets[0].blank?
if time.strftime('%Y-%m-%d %H:%M:%S') <changesets_latest_coimmit.created_at.strftime('%Y-%m-%d %H:%M:%S')
time = changesets_latest_coimmit.created_at
end
end
rescue
end
end
end
end
s_time = time
if time.strftime('%Y-%m-%d %H:%M:%S') > h.updated_at.strftime('%Y-%m-%d %H:%M:%S')
h.update_column('updated_at', s_time)
course_activity = CourseActivity.where("course_act_type=? and course_act_id =?", 'HomeworkCommon', h.id).first
if course_activity && (time.strftime('%Y-%m-%d %H:%M:%S') > course_activity.updated_at.strftime('%Y-%m-%d %H:%M:%S'))
course_activity.update_column('updated_at', s_time)
end
user_activity = UserActivity.where("act_type=? and act_id =?", 'HomeworkCommon', h.id).first
if user_activity && (time.strftime('%Y-%m-%d %H:%M:%S') > user_activity.updated_at.strftime('%Y-%m-%d %H:%M:%S'))
user_activity.update_column('updated_at', s_time)
end
org_activity = OrgActivity.where("org_act_type=? and org_act_id =?", 'HomeworkCommon', h.id).first
if org_activity && (time.strftime('%Y-%m-%d %H:%M:%S') > org_activity.updated_at.strftime('%Y-%m-%d %H:%M:%S'))
org_activity.update_column('updated_at', s_time)
end
end
end
end
end
end
end end

@ -118,6 +118,9 @@ class IssuesController < ApplicationController
end end
def show def show
# 打开编辑内容
@is_edit = true unless params[:edit].nil?
# 当前用户查看指派给他的缺陷消息,则设置消息为已读 # 当前用户查看指派给他的缺陷消息,则设置消息为已读
query = ForgeMessage.where("forge_message_type =? and user_id =? and forge_message_id =?", "Issue", User.current, @issue).first query = ForgeMessage.where("forge_message_type =? and user_id =? and forge_message_id =?", "Issue", User.current, @issue).first
query.update_attribute(:viewed, true) unless query.nil? query.update_attribute(:viewed, true) unless query.nil?
@ -387,6 +390,9 @@ class IssuesController < ApplicationController
end end
def destroy def destroy
# 增加删除页面类型,如果是个人主页,则返回该主页,项目动态则返回项目动态页眉
page_classify = params[:page_classify] unless params[:page_classify].nil?
page_id = params[:page_id] unless params[:page_id].nil?
@hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f @hours = TimeEntry.sum(:hours, :conditions => ['issue_id IN (?)', @issues]).to_f
if @hours > 0 if @hours > 0
case params[:todo] case params[:todo]
@ -415,7 +421,11 @@ class IssuesController < ApplicationController
end end
end end
respond_to do |format| respond_to do |format|
if page_classify
format.html { redirect_back_or_default _project_issues_path(@project, page_classify, page_id) }
else
format.html { redirect_back_or_default _project_issues_path(@project) } format.html { redirect_back_or_default _project_issues_path(@project) }
end
format.api { render_api_ok } format.api { render_api_ok }
end end
end end
@ -430,7 +440,7 @@ class IssuesController < ApplicationController
jour.save jour.save
update_user_activity(@issue.class,@issue.id) update_user_activity(@issue.class,@issue.id)
update_forge_activity(@issue.class,@issue.id) update_forge_activity(@issue.class,@issue.id)
@allowed_statuses = @issue.new_statuses_allowed_to(User.current)
@user_activity_id = params[:user_activity_id] @user_activity_id = params[:user_activity_id]
if params[:issue_id] if params[:issue_id]
@issue_id = params[:issue_id] @issue_id = params[:issue_id]
@ -463,7 +473,6 @@ class IssuesController < ApplicationController
def reply def reply
@issue = Issue.find(params[:id]) @issue = Issue.find(params[:id])
@jour = Journal.find(params[:journal_id]) @jour = Journal.find(params[:journal_id])
@tempContent = "<blockquote>#{ll(Setting.default_language, :text_user_wrote, @jour.user.realname.blank? ? @jour.user.login: @jour.user.realname)} <br/>#{@jour.notes.html_safe}</blockquote>".html_safe
respond_to do |format| respond_to do |format|
format.js format.js
end end
@ -472,27 +481,52 @@ class IssuesController < ApplicationController
#给issue添加journ。回复内容包含 对某个被回复的journ的内容 #给issue添加journ。回复内容包含 对某个被回复的journ的内容
def add_reply def add_reply
if User.current.logged? if User.current.logged?
jour = Journal.new jour = Journal.find(params[:journal_id])
jour.user_id = User.current.id
jour.notes = params[:quote]+params[:notes]
@issue = Issue.find params[:id] @issue = Issue.find params[:id]
jour.journalized = @issue @project = @issue.project
jour.save @allowed_statuses = @issue.new_statuses_allowed_to(User.current)
@priorities = IssuePriority.active
new_jour = Journal.new
new_jour.user_id = User.current.id
new_jour.reply_id = params[:journal_id]
new_jour.parent_id = jour.id
new_jour.notes = params[:content]
new_jour.journalized = @issue
new_jour.save_attachments(params[:attachments])
# new_jour = @issue.journals.build(:user_id => User.current.id, :reply_id => params[:journal_id], :notes => params[:content], :parent_id => jour.id)
@user_activity_id = params[:user_activity_id]
if new_jour.save
update_user_activity(@issue.class,@issue.id) update_user_activity(@issue.class,@issue.id)
update_forge_activity(@issue.class,@issue.id) update_forge_activity(@issue.class,@issue.id)
respond_to do |format| respond_to do |format|
format.js format.js
end end
end end
end end
end
# # 需要刷新详情页面,代码同步一致
# 获取project和issue状态是为了刷新页面
# 值所以用delete是因为issue和journal在act_as_attachment中是同一个类型
# 非动态页面直接刷新,动态页面手动刷新
def delete_journal def delete_journal
@issue = Issue.find(params[:id]) @issue = Issue.find(params[:id])
Journal.destroy(params[:journal_id]) begin
forge_acts = ForgeMessage.where(:forge_message_type => "Journal", :forge_message_id => params[:journal_id]).first
forge_acts.destroy unless forge_acts.nil?
at_message = AtMessage.where(:at_message_type => "Journal", :at_message_id => params[:journal_id]).first
at_message.destroy unless at_message.nil?
Journal.delete(params[:journal_id])
rescue Exception => e
puts e
end
@user_activity_id = params[:user_activity_id]
respond_to do |format| respond_to do |format|
if @user_activity_id
format.js format.js
else
format.html{ redirect_to issue_url(@issue)}
end
end end
end end

@ -17,10 +17,11 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class MembersController < ApplicationController class MembersController < ApplicationController
helper :users
model_object Member model_object Member
before_filter :find_model_object, :except => [:index, :create, :autocomplete] before_filter :find_model_object, :except => [:index, :create, :autocomplete, :allow_to_join_project, :refused_allow_to_join_project]
#before_filter :find_model_object_contest, :except => [:index, :create, :autocomplete] #before_filter :find_model_object_contest, :except => [:index, :create, :autocomplete]
before_filter :find_project_from_association, :except => [:index, :create, :autocomplete] before_filter :find_project_from_association, :except => [:index, :create, :autocomplete, :allow_to_join_project, :refused_allow_to_join_project]
before_filter :find_project_by_project_id, :only => [:index, :create, :autocomplete] before_filter :find_project_by_project_id, :only => [:index, :create, :autocomplete]
before_filter :authorize before_filter :authorize
accept_api_auth :index, :show, :create, :update, :destroy accept_api_auth :index, :show, :create, :update, :destroy
@ -49,6 +50,62 @@ class MembersController < ApplicationController
end end
end end
# 同意消息中申请加入项目
# 之所以role不在参数中传送是考虑到安全问题
# status(1申请的消息2已操作过该消息包括同意或者拒绝消息状态更新3决绝消息4:被拒人收到消息5拒绝者收到消息6同意后申请人收到消息7同意后批准人收到消息)
def allow_to_join_project
@applied_message = AppliedMessage.find(params[:applied_message_id])
applied_project = @applied_message.applied
user = User.find(@applied_message.applied_user_id)
project = Project.find(applied_project.project_id)
if user.member_of?(project)
@flash_message = "您已经是项目成员了"
@applied_message.update_attribute(:status, 2)
else
ap_role = applied_project.try(:role)
if ap_role
begin
members = []
user_grades = []
project_info = []
members << Member.new(:role_ids => ["#{ap_role}"], :user_id => @applied_message.applied_user_id)
user_grades << UserGrade.new(:user_id => @applied_message.applied_user_id, :project_id => project.id)
role = Role.find(ap_role)
project_info << ProjectInfo.new(:project_id => project.id, :user_id => @applied_message.applied_user_id) if role.allowed_to?(:is_manager)
project.members << members
project.project_infos << project_info
project.user_grades << user_grades unless user_grades.first.user_id.nil?
@applied_message.update_attribute(:status, 2)
# 添加成功后,申请人收到消息
AppliedMessage.create(:user_id => @applied_message.applied_user_id, :applied_type => "AppliedProject", :applied_id => applied_project.id ,
:status => 6, :viewed => true, :applied_user_id => @applied_message.user_id, :role => applied_project.role, :project_id => applied_project.project_id)
# 添加成功后,批准人收到消息
AppliedMessage.create(:user_id => @applied_message.user_id, :applied_type => "AppliedProject", :applied_id => applied_project.id ,
:status => 7, :viewed => true, :applied_user_id => @applied_message.applied_user_id, :role => applied_project.role, :project_id => applied_project.project_id)
rescue Exception => e
puts e
end
end
end
end
# 同意消息中拒绝加入项目
# params[:user_id]为申请者ID
# params[:send_id]为拒绝人ID
# status(1申请的消息2已操作过该消息包括同意或者拒绝消息状态更新3拒绝消息4:被拒人收到消息5拒绝者收到消息6同意后申请人收到消息7同意后批准人收到消息)
def refused_allow_to_join_project
@applied_message = AppliedMessage.find(params[:applied_message_id])
@applied_message.update_attribute(:status, 3)
applied_project = @applied_message.applied
# 发送消息给被拒者,user_id对应的收到信息的用户
AppliedMessage.create(:user_id => @applied_message.applied_user_id, :applied_type => "AppliedProject", :applied_id => applied_project.id ,:status => 4,
:viewed => true, :applied_user_id => @applied_message.user_id, :role => applied_project.role, :project_id => applied_project.project_id)
# 发送消息给拒绝者
AppliedMessage.create(:user_id => @applied_message.user_id, :applied_type => "AppliedProject", :applied_id => applied_project.id ,:status => 5,
:viewed => true, :applied_user_id => @applied_message.applied_user_id, :role => applied_project.role, :project_id => applied_project.project_id)
applied_project.delete
end
def create def create
if params[:refusal_button] if params[:refusal_button]
members = [] members = []
@ -154,9 +211,11 @@ class MembersController < ApplicationController
user_ids = attrs.delete(:user_ids) user_ids = attrs.delete(:user_ids)
user_ids.each do |user_id| user_ids.each do |user_id|
member = Member.new(:role_ids => params[:membership][:role_ids], :user_id => user_id) member = Member.new(:role_ids => params[:membership][:role_ids], :user_id => user_id)
role = Role.find_by_id(params[:membership][:role_ids])
role_ids = attrs.delete(:role_ids)
#role = Role.find(params[:membership][:role_ids])
# 这里的判断只能通过角色名,可以弄成常量 # 这里的判断只能通过角色名,可以弄成常量
if role && (role.name == "学生" || role.name == "Student") if role_ids && role_ids.include?("10")
StudentsForCourse.create(:student_id => user_id, :course_id =>@course.id) StudentsForCourse.create(:student_id => user_id, :course_id =>@course.id)
end end
@ -252,7 +311,10 @@ class MembersController < ApplicationController
if (params[:membership][:role_ids]) if (params[:membership][:role_ids])
role = Role.find(params[:membership][:role_ids][0]) role = Role.find(params[:membership][:role_ids][0])
# 这里的判断只能通过角色名,可以弄成常量 # 这里的判断只能通过角色名,可以弄成常量
if role.name == "学生" || role.name == "Student" attrs = params[:membership].dup
role_ids = attrs.delete(:role_ids)
if role_ids && role_ids.include?("10")
StudentsForCourse.create(:student_id => @member.user_id, :course_id =>@course.id) StudentsForCourse.create(:student_id => @member.user_id, :course_id =>@course.id)
else else
joined = StudentsForCourse.where('student_id = ? and course_id = ?', @member.user_id,@course.id) joined = StudentsForCourse.where('student_id = ? and course_id = ?', @member.user_id,@course.id)
@ -313,6 +375,11 @@ class MembersController < ApplicationController
grade.destroy grade.destroy
end end
end end
# 移出的时候删除申请消息,不需要删除消息,所以不必要关联删除
applied_projects = AppliedProject.where(:project_id => @project.id, :user_id => @member.user_id).first
unless applied_projects.nil?
applied_projects.delete
end
#移出项目发送消息 #移出项目发送消息
ForgeMessage.create(:user_id => @member.user_id, :project_id => @project.id, :forge_message_type => "RemoveFromProject", :viewed => false, :forge_message_id => User.current.id) ForgeMessage.create(:user_id => @member.user_id, :project_id => @project.id, :forge_message_type => "RemoveFromProject", :viewed => false, :forge_message_id => User.current.id)
end end

@ -37,16 +37,6 @@ class MessagesController < ApplicationController
# Show a topic and its replies # Show a topic and its replies
def show def show
=begin
if @course
topic_id = params[:r]?params[:r]:params[:id]
parent_id = params[:id]
url = course_boards_path(@course,:topic_id => topic_id,:parent_id=>parent_id);
redirect_to url
return;
end
=end
@isReply = true @isReply = true
page = params[:page] page = params[:page]
# Find the page of the requested reply # Find the page of the requested reply
@ -54,16 +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
all_comments = []
@reply_count = @topic.children.count @reply_count = get_all_children(all_comments, @topic).count
# @reply_pages = Paginator.new @reply_count, REPLIES_PER_PAGE, page
# @replies = @topic.children.
# includes(:author, :attachments, {:board => :project}).
# reorder("#{Message.table_name}.created_on DESC").
# limit(@reply_pages.per_page).
# offset(@reply_pages.offset).
# all
@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.
@ -74,6 +56,7 @@ class MessagesController < ApplicationController
all all
@replies = paginateHelper messages_replies,10 @replies = paginateHelper messages_replies,10
@reply = Message.new(:subject => "RE: #{@message.subject}") @reply = Message.new(:subject => "RE: #{@message.subject}")
@left_nav_type = 2
render :action => "show", :layout => "base_courses"#by young render :action => "show", :layout => "base_courses"#by young
elsif @project elsif @project
@reply_pages = Paginator.new @reply_count, REPLIES_PER_PAGE, page @reply_pages = Paginator.new @reply_count, REPLIES_PER_PAGE, page
@ -142,6 +125,7 @@ class MessagesController < ApplicationController
end end
else else
@left_nav_type = 2
respond_to do |format| respond_to do |format|
format.html { format.html {
layout_file = @project ? 'base_projects' : 'base_courses' layout_file = @project ? 'base_projects' : 'base_courses'
@ -156,17 +140,21 @@ 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 @topic = params[:activity_id].nil? ? parent : Message.find(params[:activity_id].to_i)
(redirect_to project_boards_path(@project), :notice => l(:label_reply_empty);return) @reply = Message.new
elsif @course @reply.author = User.current
(redirect_to course_boards_path(@course), :notice => l(:label_reply_empty);return) @reply.board = parent.board
end @reply.content = params[:content]
@reply.subject = "RE: #{@topic.subject}"
@reply.reply_id = params[:id]
# @reply.reply_id = params[:id]
parent.children << @reply
@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 else
(redirect_to board_message_url(@board, @topic, :r => @reply), :notice => l(:label_reply_empty);return)
end
end
@quote = params[:quote][:quote] @quote = params[:quote][:quote]
@reply = Message.new @reply = Message.new
@reply.author = User.current @reply.author = User.current
@ -174,8 +162,10 @@ class MessagesController < ApplicationController
@reply.safe_attributes = params[:reply] @reply.safe_attributes = params[:reply]
@reply.content = @quote + @reply.content @reply.content = @quote + @reply.content
@reply.subject = "RE: #{@topic.subject}" unless params[:reply][:subject] @reply.subject = "RE: #{@topic.subject}" unless params[:reply][:subject]
# @reply.reply_id = params[:id]
@topic.children << @reply @topic.children << @reply
# @reply.reply_id = params[:id]
end
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)
@ -201,14 +191,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
@ -257,6 +243,7 @@ class MessagesController < ApplicationController
if @project if @project
layout_file = 'base_projects' layout_file = 'base_projects'
elsif @course elsif @course
@left_nav_type = 2
layout_file = 'base_courses' layout_file = 'base_courses'
elsif @org_subfield elsif @org_subfield
@organization = @org_subfield.organization @organization = @org_subfield.organization
@ -270,6 +257,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
@ -318,12 +316,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]

@ -56,7 +56,7 @@ class NewsController < ApplicationController
:order => "#{News.table_name}.created_on DESC", :order => "#{News.table_name}.created_on DESC",
:offset => @page * 10, :offset => @page * 10,
:limit => 10) :limit => 10)
@left_nav_type = 4
respond_to do |format| respond_to do |format|
format.html { format.html {
@news = News.new # for adding news inline @news = News.new # for adding news inline
@ -70,26 +70,73 @@ class NewsController < ApplicationController
end end
elsif @course elsif @course
if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course))) if (User.current.admin? || @course.is_public == 1 || (@course.is_public == 0 && User.current.member_of_course?(@course)))
@order, @b_sort,@type = params[:order] || 1, params[:sort] || 1, params[:type] || 1
#确定 sort_type 1升序 2 降序
if @order.to_i == @type.to_i
@b_sort = @b_sort.to_i == 1 ? 2 : 1
else
@b_sort = 2
end
sort_name = "updated_at"
sort_type = @b_sort == 1 ? "asc" : "desc"
#scope = News.find_by_sql("select a.*,b.updated_at from news a, course_activities b where a.course_id = 532 and a.course_id = b.course_id and b.course_act_id = a.id ) ")
scope = @course ? @course.news.course_visible : News.course_visible scope = @course ? @course.news.course_visible : News.course_visible
news_arr = scope.map{|news| news.id} news_arr = scope.map{|news| news.id}
@page = params[:page] ? params[:page].to_i + 1 : 0 @page = params[:page] ? params[:page].to_i + 1 : 0
news_page = @page *10 news_page = 0 #@page *10
@news_count = scope.count @news_count = scope.count
@is_new = params[:is_new] @is_new = params[:is_new]
@q = params[:subject] @q = params[:subject]
if params[:subject].nil? || params[:subject].blank? if params[:subject].nil? || params[:subject].blank?
scope_order = scope.reorder("#{News.table_name}.sticky DESC, #{News.table_name}.created_on DESC").limit(10).offset(news_page).includes(:author,:course).all() scope_order = scope.reorder("#{News.table_name}.sticky DESC, #{News.table_name}.created_on #{sort_type}").offset(news_page).includes(:author,:course).all()
#all(:include => [:author, :course], #all(:include => [:author, :course],
#:order => "#{News.table_name}.sticky DESC, #{News.table_name}.created_on DESC").limit(10).offset(news_page) #:order => "#{News.table_name}.sticky DESC, #{News.table_name}.created_on DESC").limit(10).offset(news_page)
else else
scope_order = scope.where("#{News.table_name}.title like '#{'%' << params[:subject].to_s << '%'}'").reorder("#{News.table_name}.sticky DESC, #{News.table_name}.created_on DESC").limit(10).offset(news_page).includes(:author,:course).all() scope_order = scope.where("#{News.table_name}.title like '#{'%' << params[:subject].to_s << '%'}'").reorder("#{News.table_name}.sticky DESC, #{News.table_name}.#{sort_name} #{sort_type}").offset(news_page).includes(:author,:course).all()
#.all(:include => [:author, :course],:order => "#{News.table_name}.sticky DESC, #{News.table_name}.created_on DESC") #.all(:include => [:author, :course],:order => "#{News.table_name}.sticky DESC, #{News.table_name}.created_on DESC")
end end
scope_order.each do |topic|
topic[:updated_at] = topic.course_acts.first.updated_at
#topic[:updated_at] = CourseActivity.where("course_act_type='#{topic.class}' and course_act_id =#{topic.id}").first.updated_at
end
#根据 赞+回复数排序
if @order.to_i == 2
@type = 2
scope_order.each do |topic|
topic[:infocount] = get_praise_num(topic) + topic.comments.count
if topic[:infocount] < 0
topic[:infocount] = 0
end
end
@b_sort == 1 ? scope_order = scope_order.sort{|x,y| x[:infocount] <=> y[:infocount] } : scope_order = scope_order.sort{|x,y| y[:infocount] <=> x[:infocount] }
scope_order = sort_by_sticky scope_order
scope_order = sortby_time_countcommon_hassticky scope_order,sort_name
else
@type = 1
@b_sort == 1 ? scope_order = scope_order.sort{|x,y| x[:updated_at] <=> y[:updated_at] } : scope_order = scope_order.sort{|x,y| y[:updated_at] <=> x[:updated_at] }
scope_order = sort_by_sticky scope_order
end
@newss = scope_order @newss = scope_order
#分页
@limit = 15
@is_remote = true
@atta_count = @newss.count
@atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
@offset ||= @atta_pages.offset
@newss = paginateHelper @newss,@limit
#@newss = paginateHelper scope_order,10 #@newss = paginateHelper scope_order,10
@left_nav_type = 4
respond_to do |format| respond_to do |format|
format.html { format.html {
@news = News.new @news = News.new
@ -107,32 +154,18 @@ class NewsController < ApplicationController
def show def show
# 更新news对应的forge_messages的消息viewed字段 # 更新news对应的forge_messages的消息viewed字段
ids = @news.comments.map { |comment| comment.id }.join(",") unless @news.comments.nil?
if @project if @project
query_message_news = @news.forge_messages # 更新新闻
query_message_news = ForgeMessage.where("forge_message_id =? and user_id =? and viewed =?", @news.id, User.current.id, 0).first
# 更新新闻的时候一并更新回复
ForgeMessage.where("forge_message_id in (#{ids}) and forge_message_type = 'Comment' and user_id = #{User.current.id}").update_all(:viewed => true) unless ids.blank?
else else
query_message_news = @news.course_messages query_message_news = CourseMessage.where("course_message_id =? and user_id =? and viewed =?", @news.id, User.current.id, 0).first
end CourseMessage.where("course_message_id in (#{ids}) and course_message_type = 'Comment' and user_id = #{User.current.id}").update_all(:viewed => true) unless ids.blank?
query_message_news.each do |query|
if User.current.id == query.user_id
query.update_attributes(:viewed => true)
end end
end query_message_news.update_attribute(:viewed, true) unless query_message_news.nil?
# 更新项目新闻的评阅的消息viewed字段 # over
current_message_comments = @news.comments
current_message_comments.each do |current_message_comment|
if @project
query_message_comment = current_message_comment.forge_messages
else
query_message_comment = current_message_comment.course_messages
end
query_message_comment.each do |query|
if User.current.id == query.user_id
query.update_attributes(:viewed => true)
end
end
end
# end
cs = CoursesService.new cs = CoursesService.new
result = cs.show_course_news params,User.current result = cs.show_course_news params,User.current
@news = result[:news] @news = result[:news]
@ -144,6 +177,7 @@ class NewsController < ApplicationController
if @news.course_id if @news.course_id
@course = Course.find(@news.course_id) @course = Course.find(@news.course_id)
if @course if @course
@left_nav_type = 4
render :layout => 'base_courses' render :layout => 'base_courses'
end end
elsif @news.org_subfield_id elsif @news.org_subfield_id
@ -247,6 +281,7 @@ class NewsController < ApplicationController
@organization = @org_subfield.organization @organization = @org_subfield.organization
end end
if @course if @course
@left_nav_type = 4
render :layout => "base_courses" render :layout => "base_courses"
elsif @org_subfield elsif @org_subfield
render :layout => 'base_org' render :layout => 'base_org'

@ -1,6 +1,7 @@
class OrgDocumentCommentsController < ApplicationController class OrgDocumentCommentsController < ApplicationController
before_filter :find_organization, :only => [:new, :create, :show, :index] before_filter :find_organization, :only => [:new, :create, :show, :index]
helper :attachments before_filter :authorize_allowed, :only => [:create, :add_reply, :add_reply_in_doc]
helper :attachments,:organizations
layout 'base_org' layout 'base_org'
def new def new
@ -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
@ -79,7 +86,7 @@ class OrgDocumentCommentsController < ApplicationController
def add_reply def add_reply
@document = OrgDocumentComment.find(params[:id]).root @document = OrgDocumentComment.find(params[:id]).root
@act = OrgActivity.find(params[:id]) @act = OrgActivity.find(params[:act_id])
@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_content] @comment.content = params[:org_content]
@document.children << @comment @document.children << @comment
@ -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])
if params[:org_comment].blank?
@comment.content = params[:org_content]
else
@comment.content = params[:org_comment][:org_content] @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,12 +113,24 @@ 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 = @org_document_comment.organization @org_sub_id = @org_document_comment.org_subfield_id
org = @org_document_comment.root.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)
end end
if params[:user_activity_id]
@act = OrgActivity.find(params[:user_activity_id])
@document = @org_document_comment.root
end
if @org_document_comment.destroy if @org_document_comment.destroy
end end
respond_to do |format| respond_to do |format|
@ -125,48 +149,26 @@ class OrgDocumentCommentsController < ApplicationController
end end
def quote def quote
@org_comment = OrgDocumentComment.find(params[:id]) @org_comment = OrgDocumentComment.find(params[:id])
@subject = @org_comment.content
@subject = "RE: #{@subject}" unless @subject.starts_with?('RE:')
@content = "> #{ll(Setting.default_language, :text_user_wrote, User.find(@org_comment.creator_id).realname)}\n> "
@temp = OrgDocumentComment.new @temp = OrgDocumentComment.new
#@course_id = params[:course_id]
@temp.content = "<blockquote>#{ll(Setting.default_language, :text_user_wrote, User.find(@org_comment.creator_id).realname)} <br/>#{@org_comment.content.html_safe}</blockquote>".html_safe
respond_to do | format| respond_to do | format|
format.js format.js
end end
end end
def reply def reply
@document = OrgDocumentComment.find(params[:id]).root @document = OrgDocumentComment.find(params[:id])
@quote = params[:quote][:quote]
@org_document = OrgDocumentComment.new(:creator_id => User.current.id, :reply_id => params[:id]) @org_document = OrgDocumentComment.new(:creator_id => User.current.id, :reply_id => params[:id])
# params[:blog_comment][:sticky] = params[:blog_comment][:sticky] || 0
# params[:blog_comment][:locked] = params[:blog_comment][:locked] || 0
@org_document.title = params[:org_document_comment][:title] @org_document.title = params[:org_document_comment][:title]
@org_document.content = params[:org_document_comment][:content] @org_document.content = params[:org_document_comment][:content]
@org_document.content = @quote + @org_document.content
#@org_document.title = "RE: #{@article.title}" unless params[:blog_comment][:title]
@document.children << @org_document @document.children << @org_document
# @user_activity_id = params[:user_activity_id] @document = @document.root
# user_activity = UserActivity.where("act_type='BlogComment' and act_id =#{@article.id}").first @user_activity_id = params[:user_activity_id]
# if user_activity @act = OrgActivity.find(@user_activity_id) if @user_activity_id
# user_activity.updated_at = Time.now
# user_activity.save
# end
# attachments = Attachment.attach_files(@org_document, params[:attachments])
# render_attachment_warning_if_needed(@org_document)
#@article.save
# redirect_to user_blogs_path(:user_id=>params[:user_id])
respond_to do |format| respond_to do |format|
format.html { format.html {
# if params[:course_id] #如果呆了course_id过来了那么这是要跳到课程大纲去的
# redirect_to syllabus_course_path(:id=>params[:course_id])
# else
redirect_to org_document_comment_path(:id => @document.id, :organization_id => @document.organization_id) redirect_to org_document_comment_path(:id => @document.id, :organization_id => @document.organization_id)
# end
} }
format.js format.js
end end

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

@ -5,22 +5,42 @@ class OrgSubfieldsController < ApplicationController
def create def create
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
@subfield = OrgSubfield.create(:name => params[:name])
@organization = Organization.find(params[:organization_id]) @organization = Organization.find(params[:organization_id])
@organization.org_subfields << @subfield @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]) SubfieldSubdomainDir.create(:org_subfield_id => @subfield.id, :name => params[:sub_dir].downcase)
end end
end end
@subfield.update_attributes(:priority => @subfield.id, :field_type => params[:field_type]) #默认类型为帖子
@subfield.update_attributes(:field_type => params[:field_type]||"Post")
# admin配置的类型
update_status_by_type(@subfield, params[:field_type]||"Post")
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 = ""
@ -30,11 +50,17 @@ class OrgSubfieldsController < ApplicationController
if params[:id] if params[:id]
@organization = Organization.find(params[:id]) @organization = Organization.find(params[:id])
else else
@organization = Organization.where("domain=?",request.subdomain).first domain = Secdomain.where("subname=?", request.subdomain).first
@organization = Organization.find(domain.pid)
end end
if @organization.is_public? or User.current.admin? or User.current.member_of_org?(@organization)
@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)
@ -81,12 +107,15 @@ class OrgSubfieldsController < ApplicationController
sort = "#{Attachment.table_name}.created_on desc" sort = "#{Attachment.table_name}.created_on desc"
end end
@container_type = 2 @container_type = 2
@containers = [ OrgSubfield.includes(:attachments).reorder(sort).find(@org_subfield.id)] @containers = [OrgSubfield.includes(:attachments).reorder(sort).find(@org_subfield.id)]
@organization = Organization.find(@containers.first.organization_id) @organization = Organization.find(@containers.first.organization_id)
show_attachments @containers show_attachments @containers
@tag_list = attachment_tag_list @all_attachments @tag_list = attachment_tag_list @all_attachments
end end
@page = params[:page] || 1 @page = params[:page] || 1
else
render_403
end
#render :layout => 'base_org' #render :layout => 'base_org'
end end
@ -120,6 +149,18 @@ class OrgSubfieldsController < ApplicationController
end end
end end
def update_priority
@org_subfield = OrgSubfield.find(params[:id])
@org_subfield.update_attribute(:priority, params[:priority].to_i)
@organization = @org_subfield.organization
end
def update_status
@subfield = OrgSubfield.find(params[:id])
@organization = Organization.find(@subfield.organization_id)
@subfield.update_attributes(:status => params[:status])
end
def show_attachments obj def show_attachments obj
@attachments = [] @attachments = []
obj.each do |container| obj.each do |container|

@ -28,18 +28,27 @@ 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] 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
end end
def new def new
@organization = Organization.new @organization = Organization.new
render :layout => 'new_base' render :layout => 'new_base'
end end
def edit def edit
@organization = Organization.find(params[:id]) # @organization = Organization.find(params[:id])
begin
@organization = Organization.where("id =?", params[:id])
ensure
render_404
end
end end
def destroy def destroy
@ -56,6 +65,7 @@ class OrganizationsController < ApplicationController
@organization.description = params[:organization][:description] @organization.description = params[:organization][:description]
@organization.is_public = params[:organization][:is_public] @organization.is_public = params[:organization][:is_public]
@organization.allow_guest_download = params[:organization][:allow_guest_download] == '1' ? 1 : 0 @organization.allow_guest_download = params[:organization][:allow_guest_download] == '1' ? 1 : 0
@organization.show_mode = 0
@organization.creator_id = User.current.id @organization.creator_id = User.current.id
member = OrgMember.new(:user_id => User.current.id) member = OrgMember.new(:user_id => User.current.id)
@ -67,12 +77,65 @@ class OrganizationsController < ApplicationController
end end
def show def show
# 组织新类型 show_mode判断标准 1为新类型0为旧
if @organization.switch_type && params[:list] .nil?
if @organization.is_public? || User.current.admin? || User.current.member_of_org?(@organization)
unless params[:org_subfield_id].nil?
@org_subfield = OrgSubfield.where(:id => params[:org_subfield_id]).first
@subfield_acts = get_subfield_acts(@org_subfield)
end
@subfield_content = @organization.org_subfields.order("priority")
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
course_types = "('Message','News','HomeworkCommon','Poll','Course')"
@project_acts = get_project_activities_org @organization, project_ids
@course_acts = get_course_activities_org @organization, course_ids
# 精品课程, 不符合条件的组织则不查询
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
render_403
end
else
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)
@organization = Organization.find(params[:id]) @organization = Organization.find(params[:id])
# params[:org_subfield_id] 存在即对应的栏目,否则进入组织动态
if params[:org_subfield_id] if params[:org_subfield_id]
@org_subfield = OrgSubfield.find(params[:org_subfield_id]) @org_subfield = OrgSubfield.find(params[:org_subfield_id])
if @org_subfield.field_type == "Comptec" || @org_subfield.field_type == "Compstu"
# @org_teachers = User.find_by_sql("select u.*, ue.technical_title, ue.school_id,( SELECT `courses`.* FROM `courses` INNER JOIN `members` ON `courses`.`id` = `members`.`course_id` WHERE `members`.`user_id` = u.id AND (courses.status<>9)) as course_count
# from users u, user_extensions ue where u.id = ue.user_id and ue.identity=0 order by course_count desc")
@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 order by course_count desc")
# @org_count = @org_teachers.count
# @limit = 25
# @is_remote = true
# @atta_count = @attachments.count
# @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
# @offset ||= @atta_pages.offset
# #@curse_attachments_all = @all_attachments[@offset, @limit]
# @attachments = paginateHelper @attachments,25
else
@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)
end
else else
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)
@ -82,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'
@ -111,6 +174,201 @@ class OrganizationsController < ApplicationController
end end
end end
end
def teachers
q = params[:search].nil? ? "" : "#{params[:search].strip}"
@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]
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 == "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
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")
end
limit = 10
# @is_remote = true
@teachers_count = @org_teachers.count
@atta_pages = Paginator.new @teachers_count, limit, params['page'] || 1
@offset ||= @atta_pages.offset
#@curse_attachments_all = @all_attachments[@offset, @limit]
@org_teachers = paginateHelper @org_teachers, limit
respond_to do |format|
format.html
format.js
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
#searchPeopleByRoles(project, StudentRoles)
mems = []
if name != ""
name = name.to_s.downcase
members.each do |m|
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))
mems << m
end
end
else
mems = members
end
mems
end
def get_project_message_activities_org org
project_ids = org.projects.map{|project| project.id}.join(",")
unless project_ids.blank?
project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{project_ids}) and container_type = 'project' and org_act_type = 'Message' order by updated_at desc limit 2;")
else
project_acts = nil
end
end
def get_project_issue_activities_org org
project_ids = org.projects.map{|project| project.id}.join(",")
unless project_ids.blank?
project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{project_ids}) and container_type = 'project' and org_act_type = 'issue' order by updated_at desc limit 4;")
else
project_acts = nil
end
#project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{project_ids}) and container_type = 'project' and org_act_type = 'issue' order by updated_at desc limit 4;")
end
# 获取整过项目的动态
def get_project_activities_org org, project_ids
unless project_ids.blank?
project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{project_ids.join(',')}) and container_type = 'project'
and org_act_type in ('Message', 'Issue') order by updated_at desc limit 5;")
else
project_acts = nil
end
#project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{project_ids}) and container_type = 'project' and org_act_type = 'issue' order by updated_at desc limit 4;")
end
# 获取整过课程的动态
def get_course_activities_org org, course_ids
unless course_ids.blank?
project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{course_ids.join(',')}) and container_type = 'course'
and org_act_type in ('HomeworkCommon', 'Poll', 'Message', 'News', 'Course') order by updated_at desc limit 5;")
else
project_acts = nil
end
#project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{course_ids}) and container_type = 'course' order by updated_at desc limit 5;")
#project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{course_ids}) and container_type = 'course' and org_act_type = 'HomeworkCommon' order by updated_at desc limit 1;")
end
def get_course_homework_activities_org org
course_ids = org.courses.map{|course| course.id}.join(",")
unless course_ids.blank?
project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{course_ids}) and container_type = 'course' and org_act_type = 'HomeworkCommon' order by updated_at desc limit 1;")
else
project_acts = nil
end
#project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{course_ids}) and container_type = 'course' order by updated_at desc limit 5;")
#project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{course_ids}) and container_type = 'course' and org_act_type = 'HomeworkCommon' order by updated_at desc limit 1;")
end
def get_course_message_activities_org org
course_ids = org.courses.map{|course| course.id}.join(",")
unless course_ids.blank?
project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{course_ids}) and container_type = 'course' and org_act_type = 'Message' order by updated_at desc limit 1;")
else
project_acts = nil
end
end
def get_course_news_activities_org org
course_ids = org.courses.map{|course| course.id}.join(",")
unless course_ids.blank?
project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{course_ids}) and container_type = 'course' and org_act_type = 'News' order by updated_at desc limit 1;")
else
project_acts = nil
end
#project_acts = OrgActivity.find_by_sql("SELECT * FROM org_activities where container_id in (#{course_ids}) and container_type = 'course' and org_act_type = 'News' order by updated_at desc limit 1;")
end
def update def update
@organization = Organization.find(params[:id]) @organization = Organization.find(params[:id])
@organization.name = params[:organization][:name] @organization.name = params[:organization][:name]
@ -118,12 +376,18 @@ class OrganizationsController < ApplicationController
# @organization.domain = params[:organization][:domain] # @organization.domain = params[:organization][:domain]
@organization.is_public = params[:organization][:is_public] == 'on' ? 1 : 0 @organization.is_public = params[:organization][:is_public] == 'on' ? 1 : 0
@organization.allow_guest_download = params[:organization][:allow_guest_download] == 'on' ? 1 : 0 @organization.allow_guest_download = params[:organization][:allow_guest_download] == 'on' ? 1 : 0
@organization.allow_teacher = params[:organization][:allow_teacher] == 'on' ? 1 : 0
@organization.show_mode = params[:show_mode]
#@organization.name = params[:organization][:name] #@organization.name = params[:organization][:name]
@organization.save @organization.save
respond_to do |format| respond_to do |format|
if @organization.show_mode == 1
format.html { redirect_to organization_path(@organization)}
else
format.html { redirect_to setting_organization_path(@organization)} format.html { redirect_to setting_organization_path(@organization)}
end end
end end
end
def check_uniq def check_uniq
@check = false; @check = false;
@ -139,13 +403,20 @@ class OrganizationsController < ApplicationController
end end
def check_uniq_domain def check_uniq_domain
@is_exist = (Organization.where("domain=?", params[:org_domain]).count > 0) @is_exist = (Secdomain.where("subname=?",params[:org_domain]).count > 0)
end end
def find_organization def find_organization
@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])
@ -155,11 +426,6 @@ class OrganizationsController < ApplicationController
end end
end end
def clear_org_avatar_temp
end
def set_homepage def set_homepage
@org = Organization.find(params[:id]) @org = Organization.find(params[:id])
@org.home_id = params[:home_id] @org.home_id = params[:home_id]
@ -222,8 +488,13 @@ class OrganizationsController < ApplicationController
if !params[:name].nil? if !params[:name].nil?
condition = "%#{params[:name].strip}%".gsub(" ","") condition = "%#{params[:name].strip}%".gsub(" ","")
end end
sql = "select courses.* from courses inner join members on courses.id = members.course_id where members.user_id = #{User.current.id} and courses.name like '#{condition}'"+ if User.current.admin?
"and courses.id not in (select distinct org_courses.course_id from org_courses where org_courses.organization_id = #{@organization.id})" sql = "select courses.* from courses where courses.is_public = 1 and courses.name like '#{condition}'"+
"and courses.id not in (select distinct org_courses.course_id from org_courses where org_courses.organization_id = #{@organization.id}) and courses.is_delete=0"
else
sql = "select courses.* from courses inner join members on courses.id = members.course_id where members.user_id = #{User.current.id} and courses.is_public = 1 and courses.name like '#{condition}'"+
"and courses.id not in (select distinct org_courses.course_id from org_courses where org_courses.organization_id = #{@organization.id}) and courses.is_delete=0"
end
#user_courses = Course.find_by_sql(sql) #user_courses = Course.find_by_sql(sql)
@courses = Course.find_by_sql(sql) @courses = Course.find_by_sql(sql)
# @added_course_ids = @organization.courses.map(&:id) # @added_course_ids = @organization.courses.map(&:id)
@ -266,8 +537,13 @@ class OrganizationsController < ApplicationController
if !params[:name].nil? if !params[:name].nil?
condition = "%#{params[:name].strip}%".gsub(" ","") condition = "%#{params[:name].strip}%".gsub(" ","")
end end
sql = "select projects.* from projects inner join members on projects.id = members.project_id where members.user_id = #{User.current.id} and projects.status != 9 and projects.name like '#{condition}'" + if User.current.admin?
" and projects.id not in (select org_projects.project_id from org_projects where organization_id = #{@organization.id})" sql = "select projects.* from projects where projects.status != 9 and projects.is_public = 1 and projects.name like '#{condition}'" +
" and projects.id not in (select org_projects.project_id from org_projects where organization_id = #{@organization.id}) and status=1"
else
sql = "select projects.* from projects inner join members on projects.id = members.project_id where members.user_id = #{User.current.id} and projects.status != 9 and projects.is_public = 1 and projects.name like '#{condition}'" +
" and projects.id not in (select org_projects.project_id from org_projects where organization_id = #{@organization.id}) and status=1"
end
#user_projects = Course.find_by_sql(sql) #user_projects = Course.find_by_sql(sql)
@projects = Course.find_by_sql(sql) @projects = Course.find_by_sql(sql)
# @added_course_ids = @organization.projects.map(&:id) # @added_course_ids = @organization.projects.map(&:id)
@ -290,6 +566,40 @@ 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
@ex_teacher = User.find(params[:user])
@ex_teacher.update_column(:excellent_teacher, 1)
end
# 取消名师
def reset_excellent_teacher
@ex_teacher = User.find(params[:user])
@ex_teacher.update_column(:excellent_teacher, 0)
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)
@ -315,14 +625,19 @@ class OrganizationsController < ApplicationController
@organization = Organization.find(params[:id]) @organization = Organization.find(params[:id])
admins = User.where("admin=1") admins = User.where("admin=1")
admins.each do |admin| admins.each do |admin|
OrgMessage.create(:user_id => admin.id, :organization_id => @organization.id, :message_type => 'ApplySubdomain', :message_id => @organization.id, :sender_id => User.current.id, :viewed => 0, :content => params[:domain]) OrgMessage.create(:user_id => admin.id, :organization_id => @organization.id, :message_type => 'ApplySubdomain', :message_id => @organization.id, :sender_id => User.current.id, :viewed => 0, :content => params[:domain].downcase)
end end
end end
def agree_apply_subdomain def agree_apply_subdomain
@organization = Organization.find(params[:organization_id]) @organization = Organization.find(params[:organization_id])
OrgMessage.find(params[:act_id]).update_attribute(:viewed, 1) OrgMessage.find(params[:act_id]).update_attribute(:viewed, 1)
@organization.update_attribute(:domain, params[:org_domain]) if Secdomain.where("pid=? and sub_type=2",@organization.id).count > 0
domain = Secdomain.where("pid=? and sub_type=2",params[:organization_id]).first
Secdomain.update(domain.id, :subname => params[:org_domain])
else
Secdomain.create(:sub_type => 2, :pid => params[:organization_id], :subname => params[:org_domain])
end
if OrgMessage.where("message_type='AgreeApplySubdomain' and organization_id=#{@organization.id} and content=?",params[:org_domain]).count == 0 if OrgMessage.where("message_type='AgreeApplySubdomain' and organization_id=#{@organization.id} and content=?",params[:org_domain]).count == 0
OrgMessage.create(:user_id => params[:user_id], :organization_id => @organization.id, :message_type => 'AgreeApplySubdomain', :message_id => @organization.id, :sender_id => User.current.id, :viewed => 0, :content => params[:org_domain]) OrgMessage.create(:user_id => params[:user_id], :organization_id => @organization.id, :message_type => 'AgreeApplySubdomain', :message_id => @organization.id, :sender_id => User.current.id, :viewed => 0, :content => params[:org_domain])
end end

@ -15,6 +15,7 @@ class PollController < ApplicationController
polls = Poll.where("polls_type = 'Course' and polls_group_id = #{@course.id} and polls_status = 2") polls = Poll.where("polls_type = 'Course' and polls_group_id = #{@course.id} and polls_status = 2")
end end
@polls = paginateHelper polls,20 #分页 @polls = paginateHelper polls,20 #分页
@left_nav_type = 7
respond_to do |format| respond_to do |format|
format.html{render :layout => 'base_courses'} format.html{render :layout => 'base_courses'}
end end
@ -25,7 +26,7 @@ class PollController < ApplicationController
def show def show
@poll = Poll.find params[:id] @poll = Poll.find params[:id]
if @poll.polls_status != 2 && (!User.current.allowed_to?(:as_teacher,@course) || User.current.admin?) if @poll.polls_status != 2 && !(User.current.allowed_to?(:as_teacher,@course) || User.current.admin?)
render_403 render_403
return return
end end
@ -44,6 +45,7 @@ class PollController < ApplicationController
@percent = get_percent(@poll,User.current) @percent = get_percent(@poll,User.current)
poll_questions = @poll.poll_questions poll_questions = @poll.poll_questions
@poll_questions = paginateHelper poll_questions,5 #分页 @poll_questions = paginateHelper poll_questions,5 #分页
@left_nav_type = 7
respond_to do |format| respond_to do |format|
format.html {render :layout => 'base_courses'} format.html {render :layout => 'base_courses'}
end end
@ -78,6 +80,7 @@ class PollController < ApplicationController
def edit def edit
respond_to do |format| respond_to do |format|
@left_nav_type = 7
format.html{render :layout => 'base_courses'} format.html{render :layout => 'base_courses'}
end end
end end
@ -112,6 +115,7 @@ class PollController < ApplicationController
@poll = Poll.find(params[:id]) @poll = Poll.find(params[:id])
poll_questions = @poll.poll_questions poll_questions = @poll.poll_questions
@poll_questions = paginateHelper poll_questions, 5 @poll_questions = paginateHelper poll_questions, 5
@left_nav_type = 7
respond_to do |format| respond_to do |format|
format.html{render :layout => 'base_courses'} format.html{render :layout => 'base_courses'}
end end
@ -393,6 +397,7 @@ class PollController < ApplicationController
#显示某个学生某份问卷的填写结果 #显示某个学生某份问卷的填写结果
def poll_result def poll_result
@poll_questions = paginateHelper @poll.poll_questions,5 @poll_questions = paginateHelper @poll.poll_questions,5
@left_nav_type = 7
respond_to do |format| respond_to do |format|
format.html{render :layout => 'base_courses'} format.html{render :layout => 'base_courses'}
end end
@ -423,9 +428,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

@ -66,6 +66,7 @@ class ProjectsController < ApplicationController
helper :words helper :words
helper :project_score helper :project_score
helper :user_score helper :user_score
include UsersHelper
### added by william ### added by william
include ActsAsTaggableOn::TagsHelper include ActsAsTaggableOn::TagsHelper
@ -99,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
@ -237,6 +238,10 @@ class ProjectsController < ApplicationController
#end #end
@project.members << m @project.members << m
@project.project_infos << project_info @project.project_infos << project_info
p = Project.find("#{@project.id}")
ps = ProjectsService.new
ps.send_wechat_create_project_notice User.current,p
#end #end
respond_to do |format| respond_to do |format|
format.html { format.html {
@ -294,71 +299,53 @@ class ProjectsController < ApplicationController
def show def show
# 更新消息为已读 # 更新消息为已读
update_message_status(User.current, @project) update_message_status(User.current, @project)
# over
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
=begin
cond = @project.project_condition(Setting.display_subprojects_issues?)
has = {
"show_issues" => true ,
"show_files" => true,
"show_documents" => true,
"show_messages" => true,
"show_news" => true,
"show_bids" => true,
"show_contests" => true,
"show_wiki_edits"=>true,
"show_journals_for_messages" => true
}
# 读取项目默认展示的动态时间天数
@days = Setting.activity_days_default.to_i
@date_to ||= Date.today + 1
# 时间跨度不能太大,不然很慢,所以删掉了-1.years
@date_from = @date_to - @days
@with_subprojects = params[:with_subprojects].nil? ? Setting.display_subprojects_issues? : (params[:with_subprojects] == '1')
=end
@author = params[:user_id].blank? ? nil : User.active.find(params[:user_id]) @author = params[:user_id].blank? ? nil : User.active.find(params[:user_id])
# 决定显示所用用户或单个用户活动
=begin
@activity = Redmine::Activity::Fetcher.new(User.current,
:project => @project,
:with_subprojects => @with_subprojects,
:author => @author)
@activity.scope_select {|t| !has["show_#{t}"].nil?}
=end
@page = params[:page] ? params[:page].to_i + 1 : 0 @page = params[:page] ? params[:page].to_i + 1 : 0
# 根据私密性,取出符合条件的所有数据 # 根据私密性,取出符合条件的所有数据
if User.current.member_of?(@project) || User.current.admin? if User.current.member_of?(@project) || User.current.admin?
case params[:type] case params[:type]
when nil when nil
@events_pages = ForgeActivity.where("project_id = ? and forge_act_type in ('Issue', 'Message','News', 'ProjectCreateInfo')",@project).order("updated_at desc").limit(10).offset(@page * 10) @events_pages = ForgeActivity.where("project_id = ? and forge_act_type in ('Issue', 'Message','News', 'Project', 'Attachment','Commit')", @project).includes(:forge_act).order("updated_at desc").limit(10).offset(@page * 10)
when 'issue' when 'issue'
@events_pages = ForgeActivity.where("project_id = ? and forge_act_type = 'Issue'",@project).order("updated_at desc").limit(10).offset(@page * 10) @events_pages = ForgeActivity.where("project_id = ? and forge_act_type = 'Issue'", @project).includes(:forge_act).order("updated_at desc").limit(10).offset(@page * 10)
when 'news' when 'news'
@events_pages = ForgeActivity.where("project_id = ? and forge_act_type = 'News'",@project).order("updated_at desc").limit(10).offset(@page * 10) @events_pages = ForgeActivity.where("project_id = ? and forge_act_type = 'News'", @project).includes(:forge_act).order("updated_at desc").limit(10).offset(@page * 10)
when 'message' when 'message'
@events_pages = ForgeActivity.where("project_id = ? and forge_act_type = 'Message'",@project).order("updated_at desc").limit(10).offset(@page * 10) @events_pages = ForgeActivity.where("project_id = ? and forge_act_type = 'Message'", @project).includes(:forge_act).order("updated_at desc").limit(10).offset(@page * 10)
when 'attachment'
@events_pages = ForgeActivity.where("project_id = ? and forge_act_type = 'Attachment'", @project).includes(:forge_act).order("updated_at desc").limit(10).offset(@page * 10)
end end
#events = @activity.events(@date_from, @date_to)
else else
@events_pages = ForgeActivity.includes(:project).where("forge_activities.project_id = ? and projects.is_public @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);
= ? and forge_act_type != ? ",@project,1, "Document").order("created_at desc") end
.page(params['page'|| 1]).per(10);
# @events = @activity.events(@date_from, @date_to, :is_public => 1) # 版本库统计图
end unless @project.gpid.nil? || @project.project_score.changeset_num == 0
# rep_statics_commit = @project.rep_statics.order("commits_num desc")
=begin rep_statics_commit = RepStatics.find_by_sql("SELECT * FROM `rep_statics` where project_id = #{@project.id} order by commits_num desc limit 10")
@events_pages = Paginator.new events.count, 10, params['page'] rep_statics_code = RepStatics.find_by_sql("SELECT * FROM `rep_statics` where project_id = #{@project.id} order by changeset desc limit 10")
# 总的数据中取出某一页 # rep_statics_code = @project.rep_statics.sort_by {|u| u.changeset}.reverse
events = events.slice(@events_pages.offset,10) @a_uname = rep_statics_commit.map {|s| s.uname }
# 按天分组 @a_uname_code = rep_statics_code.map {|s| s.uname }
@events_by_day = events.group_by {|event| User.current.time_to_date(event.event_datetime)} @a_commits_num = rep_statics_commit.map {|s| s.commits_num.to_i }
=end @a_commits_add = rep_statics_code.map {|s| s.add.to_i }
boards = @project.boards.includes(:last_message => :author).all @a_commits_del = rep_statics_code.map {|s| s.del.to_i }
@topic_count = @project.boards.count @a_commits_changeset = rep_statics_code.map {|s| s.changeset.to_i }
g = Gitlab.client
begin
gid = @project.gpid
g_project = g.project(gid)
g_branch = g_project.default_branch.to_s
rescue =>e
logger.error("get default branch failed: " + e)
end
@rev = g_branch.nil? ? "master" : g_branch
end
# 根据对应的请求,返回对应的数据 # 根据对应的请求,返回对应的数据
respond_to do |format| respond_to do |format|
format.html format.html
@ -405,11 +392,17 @@ class ProjectsController < ApplicationController
end end
flash.now[:error] = html if !html.to_s.blank? flash.now[:error] = html if !html.to_s.blank?
end end
# for设置默认分支
scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first scm = params[:repository_scm] || (Redmine::Scm::Base.all & Setting.enabled_scm).first
@repository = Repository.factory(scm) @repository = Repository.factory(scm)
@repository.is_default = @project.repository.nil? @repository.is_default = @project.repository.nil?
@repository.project = @project @repository.project = @project
unless @project.gpid.nil?
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
end end
# 项目邀请用户加入实现过程 # 项目邀请用户加入实现过程
@ -590,18 +583,9 @@ class ProjectsController < ApplicationController
end end
def update_message_status(user, project) def update_message_status(user, project)
project_invite_messages = ForgeMessage.where("user_id =? and project_id =? and forge_message_type =?", user, project, "ProjectInvite") # 更新加入项目消息
project_invite_messages.each do |project_invite_message| project__messages = ForgeMessage.where("forge_message_type in ('ProjectInvite', 'JoinProject', 'RemoveFromProject') and user_id =? and project_id =? ", user, project)
project_invite_message.update_attribute(:viewed, true) project__messages.update_all(:viewed => true) unless project__messages.blank?
end
#更新被加入项目消息的viewed字段
join_project_messages = ForgeMessage.where("user_id =? and project_id =? and forge_message_type=?", user, project, "JoinProject")
join_project_messages.each do |join_project|
join_project.update_attribute(:viewed, true)
end
#更新被移出项目消息的viewed字段
remove_project_messages = ForgeMessage.where("user_id =? and project_id =? and forge_message_type=?", user, project, "RemoveFromProject")
remove_project_messages.update_all(:viewed => true)
end end
def message_invite(message_id, key) def message_invite(message_id, key)
@ -665,13 +649,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
gproject = g.project(@project.gpid) params[:project][:is_public] == "on" ? g.edit_project(@project.gpid, 20, params[:branch]) : g.edit_project(@project.gpid, 0, params[:branch])
params[:project][:is_public] ? g.edit_project(gproject.id, 20) : g.edit_project(gproject.id, 0)
end end
# end # end
if validate_parent_id && @project.save if validate_parent_id && @project.save
@ -809,6 +792,11 @@ class ProjectsController < ApplicationController
members = Member.where(:user_id => User.current.id, :project_id=>params[:id]).first members = Member.where(:user_id => User.current.id, :project_id=>params[:id]).first
if members != nil && members.roles.first.to_s != "Manager" if members != nil && members.roles.first.to_s != "Manager"
members.destroy members.destroy
# 移出的时候删除申请消息,不需要删除消息,所以不必要关联删除
applied_projects = AppliedProject.where(:project_id => @project.id, :user_id => members.user_id).first
unless applied_projects.nil?
applied_projects.delete
end
end end
respond_to do |format| respond_to do |format|
format.js format.js

@ -0,0 +1,74 @@
class PullRequestsController < ApplicationController
before_filter :find_project_and_repository
before_filter :connect_gitlab, :only => [:index, :show, :create, :accept_pr]
layout "base_projects"
# 返回json格式
def index
@requests = @g.merge_requests(@project.gpid)
end
def new
end
# Creates a merge request.
# If the operation is successful, 200 and the newly created merge request is returned. If an error occurs, an error number and a message explaining the reason is returned.
#
# @example
# Gitlab.create_merge_request(5, 'New merge request',
# :source_branch => 'source_branch', :target_branch => 'target_branch')
# Gitlab.create_merge_request(5, 'New merge request',
# :source_branch => 'source_branch', :target_branch => 'target_branch', :assignee_id => 42)
#
# @param [Integer] project The ID of a project.
# @param [String] title The title of a merge request.
# @param [Hash] options A customizable set of options.
# @option options [String] :source_branch (required) The source branch name.
# @option options [String] :target_branch (required) The target branch name.
# @option options [Integer] :assignee_id (optional) The ID of a user to assign merge request.
# @return [Gitlab::ObjectifiedHash] Information about created merge request.
def create
title = params[:title]
description = params[:description]
source_branch = params[:source_branch]
target_branch = params[:target_branch]
g.create_merge_request(@project.gpid, :title => title, :description => description, :source_branch => source_branch, :target_branch => target_branch)
end
def show
@request = @g.merge_request(@rpoject.gpid, id)
end
# Accept a merge request.
# If merge success you get 200 OK.
# Accept a merge request.
#
# @example
# Gitlab.accept_pull_rquest(5, 1)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a merge request.
# @return [Gitlab::ObjectifiedHash]
def accept_pr
commit_id = parmas[:commit_id]
status = @g.accept_pull_rquest(@project.gpid, commit_id)
if status == '200'
# 需跳入的地方
end
end
private
def connect_gitlab
@g = Gitlab.client
end
def find_project_and_repository
@project = Project.find(params[:project_id])
render_404 if @project.gpid.blank?
@repository = Repository.where(:project_id => @project.id, :type => "Repository::Gitlab")
rescue ActiveRecord::RecordNotFound
render_404
end
end

@ -0,0 +1,288 @@
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, :delete]
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}"
# 考虑到历史数据有些用户创建类job但是build失败,即sonar没有结果这个时候需要把job删除,并且删掉quality_analyses表数据
# 如果不要这句则需要迁移数据
@sonar_address = Redmine::Configuration['sonar_address']
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_an = QualityAnalysis.where(:sonar_name => sonar_name).first
if @client.job.exists?(job_name) && QualityAnalysis.where(:sonar_name => sonar_name).select{|qa| arr.include?(qa.sonar_name)}.blank?
aa = @client.job.delete("#{job_name}")
quality_an.delete unless quality_an.blank?
end
# 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 = quality_an.nil? ? 1 : quality_an.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..360 do
sleep(5)
@current_build_status = @client.job.get_current_build_status("#{job_name}")
if (@current_build_status == "success" || @current_build_status == "failure")
break
if i == 360
@build_console_result = false
break
end
end
end
# sonar 缓冲sonar生成数据
sleep(10)
# 获取sonar output结果
console_build = @client.job.get_console_output("#{job_name}", build_num = 0, start = 0, mode = 'text')["output"]
logger.info("@current_build_status is ==> #{@current_build_status}")
# 两种情况需要删除job
# 1/创建成功但是build失败则删除job
# 2/creat和build成功调用sonar启动失败则删除job
# 错误信息存储需存到Trustie数据库否则一旦job删除则无法获取这些信息
if jenkins_job == '200' && code != '201'
@client.job.delete("#{job_name}")
else
if @current_build_status == "failure"
reg_console = /Exception:.*?\r/.match(console_build)
output = reg_console[0].gsub("\r", "") unless reg_console.nil?
se = SonarError.where(:jenkins_job_name => job_name).first
se.nil? ? SonarError.create(:project_id => @project.id, :jenkins_job_name => job_name, :output => output) : se.update_column(:output, output)
@client.job.delete("#{job_name}")
elsif @current_build_status == "success"
if quality_an.blank?
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
end
# end
rescue => e
@message = e.message
end
respond_to do |format|
if @current_build_status == "success"
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)}
elsif @current_build_status == "failure"
format.html{redirect_to error_list_project_quality_analysi_path(:project_id => @project.id, :job_name => job_name)}
end
end
end
def error_list
@error_list = SonarError.where(:jenkins_job_name => params[:job_name]).first
respond_to do |format|
format.html
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
# 删除的时候主要删除三方面数据1/Trustie数据 2/jenkins数据 3/sonar数据
# 如果只删除数据1则新建的时候会有冲突
def delete
begin
qa = QualityAnalysis.find(params[:id])
rep_id = Repository.where(:project_id => @project.id, :identifier => qa.rep_identifier).first.try(:id)
job_name = "#{qa.author_login}-#{rep_id}"
logger.info("result: job_name ###################==>#{job_name}")
logger.info("result: @client.job ###################==>#{@client.job}")
d_job = @client.job.delete(job_name)
logger.info("result: delete job ###################==>#{d_job}")
qa.delete
respond_to do |format|
format.html{redirect_to :controller => 'repositories', :action => 'show', :id => @project, :repository_id => gitlab_repository(@project).identifier}
end
rescue Exception => e
puts e
end
end
# 更新Jenkins job主要包括相关配置文件参数的更新Trustie平台数据的更新
def update_jenkins_job
begin
rep_id = Repository.where(:project_id => @project.id).first.try(:id)
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)
# 数据更新到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']
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
filter = "sqale_rating,function_complexity,duplicated_lines_density,comment_lines_density,sqale_index,lines,files,functions,classes,directories,blocker_violations,critical_violations,major_violations,minor_violations,info_violations,violations"
complexity_date = open(@sonar_address + "/api/resources/index?resource=#{@resource_id}&depth=0&metrics=#{filter}").read
@complexity =JSON.parse(complexity_date).first
# 按名称转换成hash键值对
@ha = {}
@complexity["msr"].each do |com|
key = com["key"]
if key == "sqale_index"
value = com["frmt_val"]
else
value = com["val"]
end
@ha.store(key,value)
end
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']
jenkins_username = Redmine::Configuration['jenkins_username']
jenkins_password = Redmine::Configuration['jenkins_password']
# connect jenkins
@client = JenkinsApi::Client.new(:server_url => @jenkins_address, :username => jenkins_username, :password => jenkins_password)
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,15 @@ 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] 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] 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] before_filter :authorize , :except => [:newrepo,:newcreate,:fork, :to_gitlab, :forked, :commit_diff, :project_archive, :quality_analysis]
# 链接gitlab
before_filter :connect_gitlab, :only => [:quality_analysis, :show, :commit_diff, :find_project_repository]
# 版本库新增权限
before_filter :show_rep, :only => [:show]
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 ]
@ -42,7 +48,7 @@ class RepositoriesController < ApplicationController
include RepositoriesHelper include RepositoriesHelper
helper :project_score helper :project_score
#@root_path = RepositoriesHelper::ROOT_PATH #@root_path = RepositoriesHelper::ROOT_PATH
$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
@ -95,6 +101,13 @@ class RepositoriesController < ApplicationController
end end
# 一键ZIP下载
def project_archive
g = Gitlab.client
g.get()
# g.project_archive(params[:gpid].to_i, params[:rev])
end
# 判断用户是否已经fork过该项目 # 判断用户是否已经fork过该项目
def has_forked?(project, user) def has_forked?(project, user)
projects = Project.where("user_id =?", user) projects = Project.where("user_id =?", user)
@ -140,7 +153,7 @@ class RepositoriesController < ApplicationController
attrs = {:parent_id => project.parent_id}.reject {|k,v| v.nil?} attrs = {:parent_id => project.parent_id}.reject {|k,v| v.nil?}
redirect_to new_project_url(attrs, :course => '0') redirect_to new_project_url(attrs, :course => '0')
else else
redirect_to settings_project_url(project) redirect_to project_path(project)
end end
} }
format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'projects', :action => 'show', :id => project.id) } format.api { render :action => 'show', :status => :created, :location => url_for(:controller => 'projects', :action => 'show', :id => project.id) }
@ -299,6 +312,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
@ -318,69 +362,48 @@ 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 @project.hidden_repo
render_403
return -1
end
end
# unless @repository.gitlab? # 获取版本库目录结构
# # redirect_to to_gitlab_project_repository_path(@project, @repository)
# render :to_gitlab
# return
# end
#if( !User.current.member_of?(@project) || @project.hidden_repo)
@repository.fetch_changesets if Setting.autofetch_changesets? && @path.empty?
# :name, :path, :kind, :size, :lastrev, :changeset
@entries = @repository.entries(@path, @rev) @entries = @repository.entries(@path, @rev)
# @trees = g.trees(project, @path)
@changeset = @repository.find_changeset_by_name(@rev)
#@project_path_cut = RepositoriesHelper::PROJECT_PATH_CUT
#@ip = RepositoriesHelper::REPO_IP_ADDRESS
if request.xhr? if request.xhr?
@entries ? render(:partial => 'dir_list_content') : render(:nothing => true) @entries ? render(:partial => 'dir_list_content') : render(:nothing => true)
else else
#Modified by young @changesets = @g.commits(@project.gpid, :ref_name => @rev)
# (show_error_not_found; return) unless @entries # 最近一次提交
g = Gitlab.client @changesets_latest_coimmit = @changesets[0]
@changesets = g.commits(@project.gpid, :ref_name => @rev) g_project = @g.project(@project.gpid)
# @changesets = @repository.latest_changesets(@path, @rev) # 总的提交数
# @changesets_count = @repository.latest_changesets(@path, @rev).count @changesets_all_count = @g.user_static(@project.gpid, :rev => @rev).count
@changesets_all_count = @project.gpid.nil? ? 0 : g.project(@project.gpid).commit_count
# 访问该页面的是会后则刷新 # 获取默认分支
if @project.project_score.nil? @g_default_branch = g_project.default_branch.nil? ? "master" : g_project.default_branch
# 访问版本庫后更新project_score表数据changeset_num为提交总数
project_score = @project.project_score
if project_score.nil?
ProjectScore.create(:project_id => @project.id, :score => false) ProjectScore.create(:project_id => @project.id, :score => false)
else
project_score.update_column(:changeset_num, @changesets_all_count)
end end
if @changesets_all_count != @project.project_score.changeset_num && @changesets_all_count != 0
update_commits_count(@project, @changesets_all_count) # unless @changesets_latest_coimmit.blank?
end # update_commits_date(@project, @changesets_latest_coimmit)
# end # end
@changesets_latest_coimmit = @changesets[0] @creator = @project.owner.to_s
unless @changesets[0].blank?
update_commits_date(@project, @changesets_latest_coimmit)
end
@properties = @repository.properties(@path, @rev)
@repositories = @project.repositories
@course_tag = params[:course]
project_path_cut = RepositoriesHelper::PROJECT_PATH_CUT
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
# 获取版本库路径主要分为两种一种随Gitlab类型另一种为Git类型Git类型为无用数据最终需要删掉这种类型。
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+"/" + @creator + "/" + @repository.identifier+"."+"git"
else else
@repos_url = "http://"+@repository.login.to_s+"_"+@repository.identifier.to_s+"@"+ip.to_s + @repository.url.slice(project_path_cut, @repository.url.length).to_s @repos_url = "http://"+@repository.login.to_s+"_"+@repository.identifier.to_s+"@"+ip.to_s + @repository.url.slice(project_path_cut, @repository.url.length).to_s
end end
if @course_tag == 1
render :action => 'show', :layout => 'base_courses'
else
render :action => 'show', :layout => 'base_projects' render :action => 'show', :layout => 'base_projects'
end end
end end
end
alias_method :browse, :show alias_method :browse, :show
@ -390,7 +413,7 @@ update
g = Gitlab.client g = Gitlab.client
limit = 20 limit = 20
#每次页面的换回值从1开始,但是gitlab的页面查询是从0开始,所以先改变page的类型减一在改回来 #每次页面的换回值从1开始,但是gitlab的页面查询是从0开始,所以先改变page的类型减一在改回来
@commits = g.commits(@project.gpid, page:(params[:page].to_i - 1).to_s) @commits = g.commits(@project.gpid, page:(params[:page].to_i - 1).to_s, ref_name:@rev)
#add by hx #add by hx
#rep_count = commit_count(@project) #rep_count = commit_count(@project)
@ -431,8 +454,11 @@ update
def entry def entry
entry_and_raw(false) entry_and_raw(false)
@content = @repository.cat(@path, @rev)
if is_entry_text_data?(@content, @path)
render :layout => 'base_projects' render :layout => 'base_projects'
end end
end
def entry_and_raw(is_raw) def entry_and_raw(is_raw)
@entry = @repository.entry(@path, @rev) @entry = @repository.entry(@path, @rev)
@ -443,9 +469,7 @@ update
@content = @repository.cat(@path, @rev) @content = @repository.cat(@path, @rev)
(show_error_not_found; return) unless @content (show_error_not_found; return) unless @content
if is_raw || if is_raw || (@content.size && @content.size > Setting.file_max_size_displayed.to_i.kilobyte) || !is_entry_text_data?(@content, @path)
(@content.size && @content.size > Setting.file_max_size_displayed.to_i.kilobyte) ||
! is_entry_text_data?(@content, @path)
# Force the download # Force the download
send_opt = { :filename => filename_for_content_disposition(@path.split('/').last) } send_opt = { :filename => filename_for_content_disposition(@path.split('/').last) }
send_type = Redmine::MimeType.of(@path) send_type = Redmine::MimeType.of(@path)
@ -523,8 +547,8 @@ update
# 每次提交对应的文件差异 # 每次提交对应的文件差异
def commit_diff def commit_diff
@commit_diff = $g.commit_diff(@project.gpid, params[:changeset]) @commit_diff = @g.commit_diff(@project.gpid, params[:changeset])
@commit_details = $g.commit(@project.gpid, params[:changeset]) @commit_details = @g.commit(@project.gpid, params[:changeset])
render :layout => 'base_projects' render :layout => 'base_projects'
end end
@ -564,10 +588,32 @@ update
end end
def stats def stats
@project_id = params[:id] if @project.gpid.nil?
@repository_id = @repository.identifier render 404
# 提交次数统计 return
@status_commit_count = Changeset.count(:conditions => ["#{Changeset.table_name}.repository_id = ?", @repository.id]) end
project_id = @project.gpid
# @repository_id = @repository.identifier
# creator = params[:creator]
rev = params[:rev]
g = Gitlab.client
begin
@static_total_per_user = g.rep_stats(project_id, :rev => rev)
# 更新rep_statics统计数
@static_total_per_user.each do |static|
rep_static = RepStatics.where("project_id =? and email =?", @project.id, static.email.to_s).first
if rep_static.nil?
RepStatics.create(:project_id => @project.id, :uname => static.uname, :commits_num => static.commits_num, :email => static.email, :add => static.add, :del => static.del, :changeset => static.changes)
else
if @rev == params[:default_branch]
rep_static.update_attributes(:uname => static.uname, :commits_num => static.commits_num, :email => static.email, :add => static.add, :del => static.del, :changeset => static.changes)
end
end
end
rescue
render_404
return
end
render :layout => 'base_projects' render :layout => 'base_projects'
end end
@ -604,6 +650,25 @@ 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
begin
@g = Gitlab.client
unless @project.gpid.nil?
@g_project = @g.project(@project.gpid)
end
rescue => e
logger.error("failed to connect gitlab ==> #{e}")
end
end
def show_rep
if !User.current.member_of?(@project) && @project.hidden_repo
render_403
return
end
end
def find_repository def find_repository
@repository = Repository.find(params[:id]) @repository = Repository.find(params[:id])
@project = @repository.project @project = @repository.project
@ -633,9 +698,11 @@ update
end end
(render_404; return false) unless @repository (render_404; return false) unless @repository
@path = params[:path].is_a?(Array) ? params[:path].join('/') : params[:path].to_s @path = params[:path].is_a?(Array) ? params[:path].join('/') : params[:path].to_s
@rev = params[:rev].blank? ? @repository.default_branch : params[:rev].to_s.strip # gitlab端获取默认分支
g = Gitlab.client
gitlab_branchs = g.project(@project.gpid).default_branch
@project.gpid.nil? ? (@rev = params[:rev].blank? ? @repository.default_branch : params[:rev].to_s.strip) : (@rev = params[:rev].blank? ? gitlab_branchs : params[:rev].to_s.strip)
@rev_to = params[:rev_to] @rev_to = params[:rev_to]
unless @rev.to_s.match(REV_PARAM_RE) && @rev_to.to_s.match(REV_PARAM_RE) unless @rev.to_s.match(REV_PARAM_RE) && @rev_to.to_s.match(REV_PARAM_RE)
if @repository.branches.blank? if @repository.branches.blank?
raise InvalidRevisionParam raise InvalidRevisionParam

@ -150,4 +150,135 @@ 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名称已存在 3.失败
data[:result] = 0
#检验参数
if params[:name] == "" || params[:province] == "" || params[:city] == "" || params[:address] == ""
data[:result] = 1
else
school = School.where("name = '#{params[:name]}'").first
if school
data[:result] = 2
else
school = School.new
school.name = params[:name].strip
school.pinyin = Pinyin.t(params[:name].strip, splitter: '')
school.province = params[:province]
#status 0未处理 1通过 2拒绝
applyschool = ApplyAddSchools.new
#用belongs_to 可以一起存数据库
applyschool.school = school
applyschool.name = school.name
applyschool.province = params[:province]
applyschool.city = params[:city]
applyschool.address = params[:address]
applyschool.remarks = params[:remarks]
applyschool.user_id = User.current.id
if applyschool.save
data[:school_id] = school.id
user_extention= User.current.extensions
user_extention.school_id = school.id
user_extention.save!
# status=4 向管理员发送信息
users = User.where(:admin => 1)
users.each do |user|
AppliedMessage.create(:user_id => user.id, :status => 4, :applied_user_id => User.current.id, :viewed => true, :applied_id => school.id, :applied_type => "ApplyAddSchools", :name => school.name )
end
else
data[:result] = 3
end
end
end
render :json =>data
end
def search_repeat_schoolname
status = 0 #没有重复的
name = params[:name]
if name
school = School.where("name = '#{name}'").first
if school
status = 1 #有重复的
end
end
render :json =>status
end
def edit_apply_name
name = params[:name] || ""
status = -1
if name != ""
applyschool = ApplyAddSchools.where("id=?",params[:id]).first
applyschool.name = name.strip
if applyschool.school
applyschool.school.name = name
applyschool.school.pinyin = Pinyin.t(name.strip, splitter: '')
applyschool.school.save!
end
applyschool.save!
status = 0
end
render :json=>{:status=>status,:id=>params[:id],:name=>name}
end
def edit_apply_address
address = params[:address] || ""
status = -1
if address != ""
applyschool = ApplyAddSchools.where("id=?",params[:id]).first
applyschool.address = address
applyschool.save!
status = 0
end
render :json=>{:status=>status,:id=>params[:id],:address=>address}
end
def edit_apply_province
province = params[:province] || ""
city = params[:city] || ""
status = -1
if(province != "") &&(city != "")
applyschool = ApplyAddSchools.where("id=?",params[:id]).first
applyschool.province = province
applyschool.city = city
if applyschool.school
applyschool.school.province = province
applyschool.school.save!
end
applyschool.save!
if applyschool.user_id && applyschool.user_id != 0
user = User.find(applyschool.user_id)
user_extention= user.extensions
user_extention.location = province
user_extention.location_city = city
user_extention.save!
end
status = 0
end
render :json=>{:status=>status,:id=>params[:id],:province=>province,:city=>city}
end
end end

@ -32,6 +32,10 @@ class SettingsController < ApplicationController
hidden_non_project = Setting.find_by_name("hidden_non_project") hidden_non_project = Setting.find_by_name("hidden_non_project")
@text = (hidden_non_project && hidden_non_project.value == "0") ? l(:label_show_non_project) : l(:label_hidden_non_project) @text = (hidden_non_project && hidden_non_project.value == "0") ? l(:label_show_non_project) : l(:label_hidden_non_project)
#1隐藏了课程信息 0显示了课程信息
hidden_courses = Setting.find_by_name("hidden_courses")
@text_1 = (hidden_courses && hidden_courses.value == "1") ? l(:label_show_courses) : l(:label_hidden_courses)
@notifiables = Redmine::Notifiable.all @notifiables = Redmine::Notifiable.all
if request.post? && params[:settings] && params[:settings].is_a?(Hash) if request.post? && params[:settings] && params[:settings].is_a?(Hash)
settings = (params[:settings] || {}).dup.symbolize_keys settings = (params[:settings] || {}).dup.symbolize_keys
@ -89,4 +93,22 @@ class SettingsController < ApplicationController
redirect_to settings_url redirect_to settings_url
end end
#隐藏/显示课程信息
def hidden_courses
@notifiable = Setting.find_by_name("hidden_courses")
if @notifiable
@notifiable.value == "1" ? @notifiable.value = 0 : @notifiable.value = 1
@notifiable.save
else
@notifiable = Setting.new()
@notifiable.name = "hidden_courses"
@notifiable.value = 1
@notifiable.save
end
redirect_to settings_url
end
end end

@ -0,0 +1,36 @@
class ShieldWechatMessagesController < ApplicationController
def create
if params[:user_id]
@user = User.find params[:user_id]
if params[:project_id]
ShieldWechatMessage.create(:container_type => 'User', :container_id => params[:user_id].to_i, :shield_type => 'Project', :shield_id => params[:project_id].to_i)
#@cp = 1
#@projects = @user.projects.visible.select("projects.*, (SELECT MAX(updated_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS a").order("a desc").limit(5)
elsif params[:course_id]
ShieldWechatMessage.create(:container_type => 'User', :container_id => params[:user_id].to_i, :shield_type => 'Course', :shield_id => params[:course_id].to_i)
#@cp = 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 a").order("a desc").limit(5)
end
end
end
def show_messages
if params[:user_id]
@user = User.find params[:user_id]
if params[:project_id]
ShieldWechatMessage.where("container_type='User' and container_id=#{params[:user_id].to_i} and shield_type='Project' and shield_id=#{params[:project_id]}").each do |act|
act.destroy
end
#@cp = 1
#@projects = @user.projects.visible.select("projects.*, (SELECT MAX(updated_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS a").order("a desc").limit(5)
# ShieldActivity.create(:container_type => 'Organization', :container_id => params[:org_id].to_i, :shield_type => 'Project', :shield_id => params[:project_id].to_i)
elsif params[:course_id]
ShieldWechatMessage.where("container_type='User' and container_id=#{params[:user_id].to_i} and shield_type='Course' and shield_id=#{params[:course_id]}").each do |act|
act.destroy
end
#@cp = 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 a").order("a desc").limit(5)
end
end
end
end

@ -0,0 +1,86 @@
#coding=utf-8
require 'base64'
require 'json'
require 'openssl'
## 单点登录 <=> 北斗
class SsosController < ApplicationController
skip_before_filter :check_if_login_required
layout false
def show
begin
# suRh2nFEJd0Ai_TFbqZ-1yQXnGfIB-YD_f4KTA3O4dQGSBMiXfOMt-0mzizgXekWTjHKfn62nJ60iHM3_eY_KS0Qn8SF8vANfa46GhzZRt4T0iC5ZOSs4cWeK43OU0RoekQLZZAo5OyOVibxabmiPGzEFCnVVtdmRk9d7X_B0Is=
@auth = params[:auth]
@options = parse(params[:auth])
if params[:login].present?
@options["name"] = params[:login]
end
logger.debug @options
## 认证
sso = login(@options)
## 加入组织
@organization = Organization.find(82)
unless @organization.org_members.exists?(user_id: sso.user_id)
member = OrgMember.create(:user_id => sso.user_id, :created_at => Time.now)
# member = OrgMember.new(:user_id => sso.user_id)
@organization.org_members << member
OrgMemberRole.create(:org_member_id => member.id, :role_id => 12)
end
## 选择性跳转
redirect_to @organization
rescue => e
logger.error e
if e.message == "exist user"
render 'ssos/show', :layout => false
else
raise e
end
end
end
## 改用户名
def create
show and return
end
private
def base64_safe(content)
content = content.gsub('-', '+')
content.gsub('_', '/')
end
def parse(auth)
content = decrypt(auth)
ActiveSupport::JSON.decode(content)
end
def login(opt)
sso = Sso.sync_user(opt)
start_user_session(sso.user)
sso
end
def decrypt(auth)
crypted_str = Base64.decode64(base64_safe(auth))
pkey = OpenSSL::PKey::RSA.new(File.new(File.join(Rails.root,"config/private.key")))
#to large
max_dec_len = 1024/8
size = (crypted_str.size + max_dec_len-1) / max_dec_len
content = ''
size.times do |time|
tmps = crypted_str[time*max_dec_len, max_dec_len]
content += pkey.private_decrypt(tmps,OpenSSL::PKey::RSA::PKCS1_PADDING)
end
content
end
end

@ -1,14 +1,16 @@
#encoding: utf-8
class StudentWorkController < ApplicationController class StudentWorkController < ApplicationController
layout "base_courses" layout "base_courses"
include StudentWorkHelper include StudentWorkHelper
include ApplicationHelper include ApplicationHelper
require 'bigdecimal' require 'bigdecimal'
require "base64" require "base64"
before_filter :find_homework, :only => [:new, :index, :create, :student_work_absence_penalty, :absence_penalty_list, :evaluation_list, :program_test,:set_score_rule,:forbidden_anonymous_comment,:delete_work,:new_student_work_project,:student_work_project,:cancel_relate_project,:search_course_students] before_filter :find_homework, :only => [:new, :index, :create, :student_work_absence_penalty, :absence_penalty_list, :evaluation_list, :program_test,:program_test_ex,:set_score_rule,:forbidden_anonymous_comment,:delete_work,:new_student_work_project,:student_work_project,:cancel_relate_project,:search_course_students,:work_canrepeat]
before_filter :find_work, :only => [:edit, :update, :show, :destroy, :add_score, :praise_student_work,:retry_work,:revise_attachment] before_filter :find_work, :only => [:edit, :update, :show, :destroy, :add_score, :praise_student_work,:retry_work,:revise_attachment]
before_filter :member_of_course, :only => [:index, :new, :create, :show, :add_score, :praise_student_work] before_filter :member_of_course, :only => [:new, :create, :show, :add_score, :praise_student_work]
before_filter :author_of_work, :only => [:edit, :update, :destroy] before_filter :author_of_work, :only => [:edit, :update, :destroy]
before_filter :teacher_of_course, :only => [:student_work_absence_penalty, :absence_penalty_list, :evaluation_list, :set_score_rule, :forbidden_anonymous_comment] before_filter :teacher_of_course, :only => [:student_work_absence_penalty, :absence_penalty_list, :evaluation_list, :set_score_rule, :forbidden_anonymous_comment]
before_filter :is_logged, :only => [:index]
### ###
def program_test def program_test
@ -35,12 +37,301 @@ class StudentWorkController < ApplicationController
unless student_work.save unless student_work.save
resultObj[:status] = 200 resultObj[:status] = 200
else else
student_work.name = params[:title]
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")
student_work.late_penalty = @homework.late_penalty
else
student_work.late_penalty = 0
end
student_work.save
resultObj[:status] = result["status"].to_i resultObj[:status] = result["status"].to_i
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
end
end
render :json => resultObj
end
#行尾空格替换成□
def space_replace_1(str)
for i in 0 .. str.size
tChar = str[i]
if tChar != ' ' && tChar != "\n"
sFlag = false
eFlag = false
elsif tChar == ' ' && sFlag == false
tStart = i
sFlag = true
elsif tChar == "\n"
tEnd = i - 1
if sFlag == true
for j in tStart .. tEnd
str[j] = ""
end
sFlag = false
end
end
end
end
#由于负载问题 不要使用全局变量
#根据传入的tIndex确定是第几次测试
#之后如果觉得很卡 可以改成将结果传回JS再以参数形式传回来
def program_test_ex
tStarttime = Time.now
is_test = params[:is_test] == 'true'
resultObj = {status: 0, results: [], error_msg: '', time: Time.now.strftime('%Y-%m-%d %T'),tseq:1,tcount:1,testid:1} #保存每测试一次返回的结果
student_work = find_or_save_student_work(is_test)
resultObj[:tcount] = @homework.homework_tests.size
unless student_work
resultObj[:status] = 100
else
if @homework.homework_type == 2 && @homework.homework_detail_programing
#找到第index个测试的输入输出
index = params[:tIndex].to_i
resultObj[:tseq] = index
test = @homework.homework_tests[index - 1]
#请求测试
begin
result = test_realtime_ex(test, params[:src])
rescue Timeout::Error
tEndtime = Time.now
tUsedtime = (tEndtime.to_i-tStarttime.to_i)*1000+(tEndtime.usec - tStarttime.usec)/1000
logger.debug "program_test_ex user wait time = #{tUsedtime} 毫秒"
#status 0:答案正确 -5program_test_ex 函数出错 -4judge代码出错 -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)
rescue => e
#-4 judge代码 出错
logger.debug "program_test_error #{e}"
resultObj[:status] = -4
tmpstatus = -4
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
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
logger.debug result
#-1 默认值 0全部正确并结束 2 超时 -2 编译错误
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
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
tmpstatus = 0
end
unless student_work.save
resultObj[:status] = 200
else
student_work.name = params[:title]
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")
student_work.late_penalty = @homework.late_penalty
else
student_work.late_penalty = 0
end
#每次从数据库取出上次的结果加上本次的结果再存入数据库
if result["status"].to_i != -2
result["results"].first['user_wait'] = tUsedtime
if result["results"][0]["status"].to_i == 2
result["status"] = 2
end
end
status = result["status"]
if index == 1
student_work_test = student_work.student_work_tests.build(status: status,
results: [resultObj[:results]],src: params[:src])
student_work_test.save!
resultObj[:testid] = student_work_test.id
else
#先从数据库取出result
student_work_test = StudentWorkTest.find(params[:testid])
results = student_work_test.results
results << resultObj[:results]
student_work_test.results = results
student_work_test.status = (result["status"] != 0 ? result["status"] : student_work_test.status)
student_work_test.save!
status = student_work_test.status
resultObj[:testid] = student_work_test.id
end
#超时或编译错误则直接返回了并存入数据库
if resultObj[:status] == 2 || resultObj[:status] == -2 || index == @homework.homework_tests.size
if status == 0
resultObj[:status] = 0
end
student_work.save!
resultObj[:time] = student_work_test.created_at.strftime(format='%Y-%m-%d %H:%M:%S')
resultObj[:index] = student_work.student_work_tests.count
end
#将每次用户等待时间都存起来以便管理界面显示用
tEndtime = Time.now
tUsedtime = (tEndtime.to_i-tStarttime.to_i)*1000+(tEndtime.usec - tStarttime.usec)/1000
logger.debug "program_test_ex user wait time = #{tUsedtime} 毫秒"
time_used = 0
if result["status"].to_i != -2
#至少一毫秒
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
rescue
#-5 program_test_ex 函数出错
logger.debug "program_test_error 2"
resultObj[:status] = -5
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
#渲染返回结果
render :json => resultObj
end
end
end
#找出该作业的所有提交作业
def find_all_student_work_by_homeid()
all_studentwork = StudentWork.where("homework_common_id = #{@homework.id} and is_test = 0 ")
all_studentwork
end
def request_code_repeattest(src)
url = "#{Redmine::Configuration['jplag_server']}api/realtime_test.json"
factor = []
src.each do |test|
factor << {work_id: test.id, des: test.description,created_at:test.created_at.to_i}
end end
solutions = {
homeid:@homework.id,
language:@homework.homework_detail_programing.language,
factor: factor
}
uri = URI(url)
body = solutions.to_json
logger.debug "send body"
logger.debug body
res = Net::HTTP.new(uri.host, uri.port).start do |client|
request = Net::HTTP::Post.new(uri.path)
request.body = body
request["Content-Type"] = "application/json"
client.request(request)
end
JSON.parse(res.body)
end
#点击代码查重按钮
def work_canrepeat
@homework_id = params[:homework]
@course_id = params[:course_id]
all_studentwork = find_all_student_work_by_homeid()
@work_count = all_studentwork.has_committed.count
end
#代码查重 status: 0完成 -2不需要查重 -1查重失败不支持该语言
def code_repeattest
tStarttime = Time.now
logger.debug "code_repeattest start is #{tStarttime}}"
resultObj = {status: -2}
@homework = HomeworkCommon.find params[:homework]
all_studentwork = find_all_student_work_by_homeid().has_committed
if all_studentwork == nil
resultObj[:status] = -2
elsif all_studentwork.count <= 1
resultObj[:status] = -2
else
#@homework.homework_detail_programing.language、id、description
logger.debug "time1 is #{Time.now.usec} "
result = request_code_repeattest(all_studentwork)
logger.debug "time2 is #{Time.now.usec} "
resultObj[:status] = result['status'].to_i
# resultObj[:results] = result['results']
#Time.now, simi_id = simiworkid , simi_value = simivalue
if resultObj[:status] == 0
@homework.simi_time = Time.now
resultObj[:comparetime] = @homework.simi_time
@homework.update_column('simi_time', @homework.simi_time)
logger.debug "time3 is #{Time.now.usec} "
result['results'].each do |key,value|
@student_work = StudentWork.where("id =?", key.to_i).first
@student_work.update_column('simi_id', value['simiworkid'].to_i)
@student_work.update_column('simi_value', value['simivalue'].to_i)
# sqlstr = "update student_works set simi_id=#{value['simiworkid']},simi_value=#{value['simivalue']} where id=#{key.to_i} "
# dbh.execute(sqlstr)
end
logger.debug "time4 is #{Time.now.usec} "
end
end
tEndtime = Time.now
logger.debug "code_repeattest end is #{tEndtime}}"
tUsedtime = (tEndtime.to_i-tStarttime.to_i)*1000000+(tEndtime.usec - tStarttime.usec)
logger.debug "code_repeattest userd utime is #{tUsedtime}"
render :json => resultObj
end
#上次代码查重时间
def last_codecomparetime
resultObj = {status: 0}
@homework = HomeworkCommon.find params[:homework]
#转换一下
if @homework.simi_time != nil
resultObj[:comparetime] = Time.parse(@homework.simi_time.to_s).strftime("%Y-%m-%d %H:%M:%S")
else
resultObj[:comparetime] = 0
end end
render :json => resultObj render :json => resultObj
@ -53,6 +344,13 @@ class StudentWorkController < ApplicationController
homework_message.update_attributes(:viewed => true) if homework_message.viewed == 0 homework_message.update_attributes(:viewed => true) if homework_message.viewed == 0
end end
end end
#修改作品提示消息更新
student_work_messages = CourseMessage.where("user_id =? and course_id =? and course_message_type =? and viewed =?", User.current.id, @homework.course, StudentWork.name, 0)
student_work_messages.each do |message|
message.update_attribute(:viewed, true)
end
# 作品打分消息状态更新 # 作品打分消息状态更新
studentworks_scores = CourseMessage.where("user_id =? and course_id =? and course_message_type =? and viewed =?", User.current.id, @homework.course, "StudentWorksScore", 0) studentworks_scores = CourseMessage.where("user_id =? and course_id =? and course_message_type =? and viewed =?", User.current.id, @homework.course, "StudentWorksScore", 0)
studentworks_scores.each do |studentworks_score| studentworks_scores.each do |studentworks_score|
@ -76,35 +374,60 @@ 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
course_group = CourseGroup.find_by_id(@group) if @group # 0表示没有分组的学生-1表示所有分组的学生
if course_group if @group
if @group == "0"
none_group_students = @course.members.select{ |member| member.course_group_id == 0 }
if none_group_students.empty?
student_in_group = '(0)'
else
student_in_group = '(' + none_group_students.map{ |member| member.user_id }.join(',') + ')'
end
elsif @group == "-1"
all_group_students = @course.members.select{ |member| member.course_group_id }
if all_group_students.empty?
student_in_group = '(0)'
else
student_in_group = '(' + all_group_students.map{ |member| member.user_id }.join(',') + ')'
end
else
course_group = CourseGroup.find_by_id(@group)
group_students = course_group.users group_students = course_group.users
if group_students.empty? if group_students.empty?
student_in_group = '(0)' student_in_group = '(0)'
else else
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 && @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.has_committed.where(:user_id => User.current.id).empty?)
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
elsif @order == 'student_id'
@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}").joins("join user_extensions on student_works.user_id = user_extensions.user_id").order("#{@order} #{@b_sort}"),@name
else
@stundet_works = search_homework_member @homework.student_works.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name
end end
#老师 || 超级管理员 || 禁用匿评&&作业截止&&已提交作品 显示所有列表
if @is_teacher || @homework.homework_detail_manual.nil? ||
(@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?)
@stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name
@show_all = true @show_all = true
elsif @homework.homework_detail_manual.comment_status == 1 #学生 && 未开启匿评 只看到自己的 elsif User.current.member_of_course?(@course)
if @homework.homework_detail_manual.comment_status == 1 #学生 && 未开启匿评 只看到自己的
if @homework.homework_type == 3 if @homework.homework_type == 3
pro = @homework.student_work_projects.where(:user_id => User.current.id).first pro = @homework.student_work_projects.where(:user_id => User.current.id).first
if pro.nil? if pro.nil?
@stundet_works = [] @stundet_works = []
else else
@stundet_works = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:id => pro.student_work_id) @stundet_works = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:id => pro.student_work_id)
end end
else else
@stundet_works = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) @stundet_works = @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
end end
elsif @homework.homework_detail_manual.comment_status == 2 #学生 && 开启匿评 看到匿评列表 elsif @homework.homework_detail_manual.comment_status == 2 #学生 && 开启匿评 看到匿评列表
if @homework.homework_type == 3 if @homework.homework_type == 3
@ -115,7 +438,7 @@ class StudentWorkController < ApplicationController
my_work = @homework.student_works.where(:id => pro.student_work_id) my_work = @homework.student_works.where(:id => pro.student_work_id)
end end
else else
my_work = @homework.student_works.where(:user_id => User.current.id) my_work = @homework.student_works.has_committed.where(:user_id => User.current.id)
end end
@stundet_works = my_work + User.current.student_works_evaluation_distributions.map(&:student_work).select { |work| work.homework_common_id == @homework.id} @stundet_works = my_work + User.current.student_works_evaluation_distributions.map(&:student_work).select { |work| work.homework_common_id == @homework.id}
elsif @homework.homework_detail_manual.comment_status == 3 #学生 && 关闭匿评 未提交作品之前列表为空,提交了作品看到所有的 elsif @homework.homework_detail_manual.comment_status == 3 #学生 && 关闭匿评 未提交作品之前列表为空,提交了作品看到所有的
@ -124,35 +447,53 @@ class StudentWorkController < ApplicationController
if pro.nil? if pro.nil?
my_work = [] my_work = []
else else
my_work = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:id => pro.student_work_id) my_work = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:id => pro.student_work_id)
end end
else else
my_work = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) my_work = @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
end end
if my_work.empty? if my_work.empty?
@stundet_works = [] @stundet_works = []
else else
@stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name if @order == 'lastname'
@stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@b_sort}, login #{@b_sort}"),@name
elsif @order == 'student_id'
@stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").joins("join user_extensions on student_works.user_id = user_extensions.user_id").order("#{@order} #{@b_sort}"),@name
else
@stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name
end
@show_all = true @show_all = true
end end
else else
@stundet_works = [] @stundet_works = []
end end
@student_work_count = (search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name).count
else else
if @is_teacher || @homework.homework_detail_manual.nil? || (@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?) #老师 || 超级管理员 显示所有列表 render_403
@stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").order("#{@order} #{@b_sort}"),@name return
end
@student_work_count = (search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins(:user).where("users.id in #{student_in_group}").order("#{@order} #{@b_sort}"),@name).count
else
if (@homework.is_open == 1 &&@course.is_public == 1) || (@homework.is_open == 1 && @course.is_public == 0 && User.current.member_of_course?(@course)) || @is_teacher || User.current.admin? || (User.current.member_of_course?(@course) && @homework.anonymous_comment == 1 && Time.parse(@homework.end_time.to_s).strftime("%Y-%m-%d") < Time.now.strftime("%Y-%m-%d") && !@homework.student_works.has_committed.where(:user_id => User.current.id).empty?)
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
elsif @order == 'student_id'
@stundet_works = search_homework_member @homework.student_works.select("student_works.*,student_works.work_score as score").joins("join user_extensions on student_works.user_id = user_extensions.user_id").order("#{@order} #{@b_sort}"),@name
else
@stundet_works = search_homework_member @homework.student_works.select("student_works.*,student_works.work_score as score").order("#{@order} #{@b_sort}"),@name
end
@show_all = true @show_all = true
elsif @homework.homework_detail_manual.comment_status == 1 #学生 && 未开启匿评 只看到自己的 elsif User.current.member_of_course?(@course)
if @homework.homework_detail_manual.comment_status == 1 #学生 && 未开启匿评 只看到自己的
if @homework.homework_type == 3 if @homework.homework_type == 3
pro = @homework.student_work_projects.where(:user_id => User.current.id).first pro = @homework.student_work_projects.where(:user_id => User.current.id).first
if pro.nil? if pro.nil?
@stundet_works = [] @stundet_works = []
else else
@stundet_works = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:id => pro.student_work_id) @stundet_works = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:id => pro.student_work_id)
end end
else else
@stundet_works = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) @stundet_works = @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
end end
elsif @homework.homework_detail_manual.comment_status == 2 #学生 && 开启匿评 看到匿评列表 elsif @homework.homework_detail_manual.comment_status == 2 #学生 && 开启匿评 看到匿评列表
if @homework.homework_type == 3 if @homework.homework_type == 3
@ -163,7 +504,7 @@ class StudentWorkController < ApplicationController
my_work = @homework.student_works.where(:id => pro.student_work_id) my_work = @homework.student_works.where(:id => pro.student_work_id)
end end
else else
my_work = @homework.student_works.where(:user_id => User.current.id) my_work = @homework.student_works.has_committed.where(:user_id => User.current.id)
end end
@stundet_works = my_work + User.current.student_works_evaluation_distributions.map(&:student_work).select { |work| work.homework_common_id == @homework.id} @stundet_works = my_work + User.current.student_works_evaluation_distributions.map(&:student_work).select { |work| work.homework_common_id == @homework.id}
elsif @homework.homework_detail_manual.comment_status == 3 #学生 && 关闭匿评 未提交作品之前列表为空,提交了作品看到所有的 elsif @homework.homework_detail_manual.comment_status == 3 #学生 && 关闭匿评 未提交作品之前列表为空,提交了作品看到所有的
@ -172,25 +513,38 @@ class StudentWorkController < ApplicationController
if pro.nil? if pro.nil?
my_work = [] my_work = []
else else
my_work = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:id => pro.student_work_id) my_work = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:id => pro.student_work_id)
end end
else else
my_work = @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").where(:user_id => User.current.id) my_work = @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").where(:user_id => User.current.id)
end end
if my_work.empty? if my_work.empty?
@stundet_works = [] @stundet_works = []
else else
@stundet_works = search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").order("#{@order} #{@b_sort}"),@name if @order == 'lastname'
@stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins(:user).order("CONVERT(lastname USING gbk) COLLATE gbk_chinese_ci #{@b_sort}, login #{@b_sort}"),@name
elsif @order == 'student_id'
@stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").joins("join user_extensions on student_works.user_id = user_extensions.user_id").order("#{@order} #{@b_sort}"),@name
else
@stundet_works = search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").order("#{@order} #{@b_sort}"),@name
end
@show_all = true @show_all = true
end end
else else
@stundet_works = [] @stundet_works = []
end end
@student_work_count = (search_homework_member @homework.student_works.select("student_works.*,IF(final_score is null,null,final_score - absence_penalty - late_penalty) as score").order("#{@order} #{@b_sort}"),@name).count else
render_403
return
end end
@student_work_count = (search_homework_member @homework.student_works.has_committed.select("student_works.*,student_works.work_score as score").order("#{@order} #{@b_sort}"),@name).count
end
@score = @b_sort == "desc" ? "asc" : "desc" @score = @b_sort == "desc" ? "asc" : "desc"
@is_focus = params[:is_focus] ? params[:is_focus].to_i : 0
# 消息传过来的ID
@message_student_work_id = params[:student_work_id]
@left_nav_type = 3
respond_to do |format| respond_to do |format|
format.js format.js
format.html format.html
@ -212,10 +566,10 @@ class StudentWorkController < ApplicationController
return return
end end
@user = User.current @user = User.current
@student_work = @homework.student_works.where("user_id = ?",User.current.id).first #@student_work = @homework.student_works.where("user_id = ?",User.current.id).first
if @student_work.nil? #if @student_work.nil?
@student_work = StudentWork.new @student_work = StudentWork.new
end #end
respond_to do |format| respond_to do |format|
format.html{ render :layout => "new_base_user"} format.html{ render :layout => "new_base_user"}
end end
@ -225,7 +579,7 @@ class StudentWorkController < ApplicationController
# 提交作品前先判断是否已经提交 # 提交作品前先判断是否已经提交
@has_commit = false; @has_commit = false;
if hsd_committed_work?(User.current.id, @homework.id) if hsd_committed_work?(User.current.id, @homework.id)
@work = StudentWork.where("user_id =? and homework_common_id =?", User.current.id, @homework.id).first @work = StudentWork.where("user_id =? and homework_common_id =? and work_status != 0", User.current.id, @homework.id).first
@has_commit = true; @has_commit = true;
#flash[:notice] = l(:notice_successful_create) #flash[:notice] = l(:notice_successful_create)
#redirect_to edit_student_work_url(params[:student_work]) #redirect_to edit_student_work_url(params[:student_work])
@ -237,8 +591,9 @@ class StudentWorkController < ApplicationController
if params[:student_work] if params[:student_work]
@submit_result = true @submit_result = true
student_work = StudentWork.find(params[:student_work_id]) if params[:student_work_id] student_work = StudentWork.find(params[:student_work_id]) if params[:student_work_id]
student_work = StudentWork.where("user_id =? and homework_common_id =? and work_status = 0", User.current.id, @homework.id).first
student_work ||= StudentWork.new student_work ||= StudentWork.new
student_work.name = params[:student_work][:name] student_work.name = params[:student_work][:name] == "#{@homework.name}的作品提交(可修改)" ? "#{@homework.name}的作品提交" : params[:student_work][:name]
student_work.description = params[:student_work][:description] student_work.description = params[:student_work][:description]
student_work.homework_common_id = @homework.id student_work.homework_common_id = @homework.id
student_work.user_id = User.current.id student_work.user_id = User.current.id
@ -251,8 +606,10 @@ class StudentWorkController < ApplicationController
#提交作品时,计算是否迟交 #提交作品时,计算是否迟交
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
student_work.work_status = 2
else else
student_work.late_penalty = 0 student_work.late_penalty = 0
student_work.work_status = 1
end end
if student_work.save if student_work.save
if @homework.homework_type == 3 && @homework.homework_detail_group.base_on_project == 1 if @homework.homework_type == 3 && @homework.homework_detail_group.base_on_project == 1
@ -284,6 +641,7 @@ class StudentWorkController < ApplicationController
stu_project.save stu_project.save
end end
end end
@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)
@ -323,6 +681,8 @@ class StudentWorkController < ApplicationController
@work.save_attachments(params[:attachments]) @work.save_attachments(params[:attachments])
render_attachment_warning_if_needed(@work) render_attachment_warning_if_needed(@work)
if @work.save if @work.save
#如果学生作品被打分后修改,应该给老师提示
send_message_to_teacher(@work)
if @homework.homework_type == 3 if @homework.homework_type == 3
@student_work_project = @homework.student_work_projects.where("user_id=?",User.current.id).first @student_work_project = @homework.student_work_projects.where("user_id=?",User.current.id).first
student_work_projects = @homework.student_work_projects.where("student_work_id=? and is_leader =?",@work.id,0) student_work_projects = @homework.student_work_projects.where("student_work_id=? and is_leader =?",@work.id,0)
@ -411,7 +771,7 @@ class StudentWorkController < ApplicationController
end end
end end
end end
redirect_to user_homeworks_user_path(User.current.id) redirect_to student_homeworks_user_path(User.current.id)
end end
def retry_work def retry_work
@ -443,45 +803,67 @@ class StudentWorkController < ApplicationController
#老师、教辅可以随时评分,学生只能在匿评作业的匿评阶段进行评分 #老师、教辅可以随时评分,学生只能在匿评作业的匿评阶段进行评分
render_403 and return unless @is_teacher || @homework.homework_detail_manual.comment_status == 2 render_403 and return unless @is_teacher || @homework.homework_detail_manual.comment_status == 2
@score = student_work_score @work,User.current @score = student_work_score @work,User.current
if @score #@score.comment = params[:new_form][:user_message] if params[:new_form] && params[:new_form][:user_message] && params[:new_form][:user_message] != ""
@score.comment = params[:new_form][:user_message] if params[:new_form] && params[:new_form][:user_message] && params[:new_form][:user_message] != "" #@score.score = params[:score] if params[:score]
@score.score = params[:score] if params[:score] #if User.current.admin?
# @score.reviewer_role = 1
#else
# role = User.current.members.where("course_id = ?",@course.id).first.roles.first.name
# @score.reviewer_role = get_role_by_name(role)
#end
#@is_new = false
@is_last_a = @work.student_works_scores.empty?
@new_score = StudentWorksScore.new
if @score && params[:score]
@new_score.score = params[:score].to_i == -1 ? @score.score : params[:score]
elsif @score.nil? && params[:score]
@new_score.score = params[:score].to_i == -1 ? nil : params[:score]
end
@new_score.comment = params[:new_form][:user_message] if params[:new_form] && params[:new_form][:user_message] && params[:new_form][:user_message] != ""
@new_score.user_id = User.current.id
@new_score.student_work_id = @work.id
if @is_teacher && @work.work_status == 0
@work.update_column('work_status', 1)
end
if User.current.admin? if User.current.admin?
@score.reviewer_role = 1 @new_score.reviewer_role = 1
else else
role = User.current.members.where("course_id = ?",@course.id).first.roles.first.name role = User.current.members.where("course_id = ?",@course.id).first.roles.first.name
@score.reviewer_role = get_role_by_name(role) @new_score.reviewer_role = get_role_by_name(role)
end end
@is_new = false if @score
else if @is_teacher
@is_last_a = @work.student_works_scores.empty? @is_new = true
@score = StudentWorksScore.new @is_last_a = false
@score.score = params[:score] if params[:score]
@score.comment = params[:new_form][:user_message] if params[:new_form] && params[:new_form][:user_message] && params[:new_form][:user_message] != ""
@score.user_id = User.current.id
@score.student_work_id = @work.id
if User.current.admin?
@score.reviewer_role = 1
else else
role = User.current.members.where("course_id = ?",@course.id).first.roles.first.name @is_new = false
@score.reviewer_role = get_role_by_name(role)
end end
else
@is_new = true @is_new = true
end end
@score.save_attachments(params[:attachments]) @new_score.save_attachments(params[:attachments])
render_attachment_warning_if_needed(@score) render_attachment_warning_if_needed(@new_score)
if @score.save if @new_score.save
case @score.reviewer_role case @new_score.reviewer_role
when 1 #教师评分:最后一个教师评分为最终评分 when 1 #教师评分:最后一个教师评分为最终评分
@work.teacher_score = @score.score @work.teacher_score = @new_score.score
when 2 #教辅评分 教辅评分显示平均分 when 2 #教辅评分 教辅评分显示平均分
@work.teaching_asistant_score = @work.student_works_scores.where(:reviewer_role => 2).average(:score).try(:round, 2).to_f #@work.teaching_asistant_score = @work.student_works_scores.where(:reviewer_role => 2).average(:score).try(:round, 2).to_f
ts_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 = 2 AND score IS NOT NULL ORDER BY created_at DESC) AS t GROUP BY user_id) AS a")
@work.teaching_asistant_score = ts_score.first.score.nil? ? nil : ts_score.first.score.try(:round, 2).to_f
when 3 #学生评分 学生评分显示平均分 when 3 #学生评分 学生评分显示平均分
@work.student_score = @work.student_works_scores.where(:reviewer_role => 3).average(:score).try(:round, 2).to_f #@work.student_score = @work.student_works_scores.where(:reviewer_role => 3).average(:score).try(:round, 2).to_f
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
end end
@homework.update_column('updated_at', Time.now)
update_course_activity(@homework.class,@homework.id)
update_user_activity(@homework.class,@homework.id)
update_org_activity(@homework.class,@homework.id)
if @work.save if @work.save
@work = @homework.student_works.select("student_works.*,student_works.work_score as score").where(:id => @work.id).first
respond_to do |format| respond_to do |format|
format.js format.js
end end
@ -514,6 +896,14 @@ class StudentWorkController < ApplicationController
end end
end end
#提交未评分的评语
def add_comments_to_work
@work = StudentWork.find params[:id]
respond_to do |format|
format.js
end
end
#为作品点赞 #为作品点赞
def praise_student_work def praise_student_work
pt = PraiseTread.new pt = PraiseTread.new
@ -547,6 +937,7 @@ class StudentWorkController < ApplicationController
ORDER BY absence #{order}") ORDER BY absence #{order}")
end end
@order = order == "desc" ? "asc" : "desc" @order = order == "desc" ? "asc" : "desc"
@left_nav_type = 3
respond_to do |format| respond_to do |format|
format.html format.html
end end
@ -598,11 +989,9 @@ class StudentWorkController < ApplicationController
student_work.late_penalty = @homework.late_penalty student_work.late_penalty = @homework.late_penalty
student_work.save student_work.save
end end
@homework.save
end end
unless homework_detail_manual.absence_penalty.to_s == params[:absence_penalty].to_s if params[:absence_penalty] && homework_detail_manual.absence_penalty.to_s != params[:absence_penalty].to_s
homework_detail_manual.absence_penalty = params[:absence_penalty] homework_detail_manual.absence_penalty = params[:absence_penalty]
if homework_detail_manual.comment_status == 3 #当前作业处于匿评结束状态,修改缺评扣分才会修改每个作品应扣分的值 if homework_detail_manual.comment_status == 3 #当前作业处于匿评结束状态,修改缺评扣分才会修改每个作品应扣分的值
work_ids = "(" + @homework.student_works.map(&:id).join(",") + ")" work_ids = "(" + @homework.student_works.map(&:id).join(",") + ")"
@ -620,9 +1009,8 @@ class StudentWorkController < ApplicationController
if homework_detail_manual.ta_proportion.to_s != params[:ta_proportion].to_s || @homework.teacher_priority.to_s != teacher_priority.to_s || (homework_detail_programing && homework_detail_programing.ta_proportion.to_s != params[:sy_proportion].to_s) if homework_detail_manual.ta_proportion.to_s != params[:ta_proportion].to_s || @homework.teacher_priority.to_s != teacher_priority.to_s || (homework_detail_programing && homework_detail_programing.ta_proportion.to_s != params[:sy_proportion].to_s)
homework_detail_manual.ta_proportion = params[:ta_proportion] homework_detail_manual.ta_proportion = params[:ta_proportion]
homework_detail_programing.ta_proportion = params[:sy_proportion] if homework_detail_programing homework_detail_programing.ta_proportion = params[:sy_proportion] if homework_detail_programing
@homework.teacher_priority = teacher_priority @homework.update_column('teacher_priority', teacher_priority)
@homework.save
homework_detail_manual.save if homework_detail_manual homework_detail_manual.save if homework_detail_manual
homework_detail_programing.save if homework_detail_programing homework_detail_programing.save if homework_detail_programing
@ -631,6 +1019,8 @@ class StudentWorkController < ApplicationController
student_work.save student_work.save
end end
end end
@homework.save
if params[:student_path] if params[:student_path]
redirect_to student_work_index_url(:homework => @homework.id) redirect_to student_work_index_url(:homework => @homework.id)
else else
@ -670,6 +1060,10 @@ class StudentWorkController < ApplicationController
end end
attachment = @work.attachments.where("attachtype = 7").first attachment = @work.attachments.where("attachtype = 7").first
attachment.update_attributes(:description => params[:description]) attachment.update_attributes(:description => params[:description])
if attachment.attachtype == 7
student_work = StudentWork.find attachment.container_id
CourseMessage.create(:user_id => student_work.homework_common.user_id, :course_id => student_work.homework_common.course_id, :viewed => false,:course_message_id=>attachment.container_id,:course_message_type=>'StudentWork',:status=>2)
end
respond_to do |format| respond_to do |format|
format.js format.js
end end
@ -728,7 +1122,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
@ -747,6 +1142,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 = []
@ -765,7 +1174,7 @@ class StudentWorkController < ApplicationController
end end
def hsd_committed_work?(user, homework) def hsd_committed_work?(user, homework)
sw = StudentWork.where("user_id =? and homework_common_id =?", user, homework).first sw = StudentWork.where("user_id =? and homework_common_id =? and work_status != 0", user, homework).first
sw.nil? ? result = false : result = true sw.nil? ? result = false : result = true
result result
end end
@ -802,6 +1211,10 @@ class StudentWorkController < ApplicationController
render_403 unless User.current.allowed_to?(:as_teacher,@course) || User.current.admin? render_403 unless User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
end end
def is_logged
redirect_to signin_path unless User.current.logged?
end
#根据条件过滤作业结果 #根据条件过滤作业结果
def search_homework_member homeworks,name def search_homework_member homeworks,name
if name == "" if name == ""
@ -822,41 +1235,98 @@ 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), 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
sheet1[count_row,5] = homework.name sheet1[count_row,5] = homework.name
sheet1[count_row,6] = homework.teacher_score.nil? ? l(:label_without_score) : format("%.2f",homework.teacher_score) sheet1[count_row,6] = strip_html homework.description if !homework.description.nil?
sheet1[count_row,7] = homework.teaching_asistant_score.nil? ? l(:label_without_score) : format("%.2f",homework.teaching_asistant_score) sheet1[count_row,7] = homework.teacher_score.nil? ? l(:label_without_score) : homework.teacher_score.round(2)
sheet1[count_row,8] = homework.student_score.nil? ? l(:label_without_score) : format("%.2f",homework.student_score) sheet1[count_row,8] = homework.teaching_asistant_score.nil? ? l(:label_without_score) : homework.teaching_asistant_score.round(2)
sheet1[count_row,9] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : format("%.2f",homework.score) : l(:label_without_score) if @homework.anonymous_comment ==0
sheet1[count_row,10] = format_time(homework.created_at) sheet1[count_row,9] = homework.student_score.nil? ? l(:label_without_score) : homework.student_score.round(2)
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), 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
sheet1[count_row,5] = homework.name sheet1[count_row,5] = homework.name
sheet1[count_row,6] = homework.teacher_score.nil? ? l(:label_without_score) : format("%.2f",homework.teacher_score) sheet1[count_row,6] = homework.description
sheet1[count_row,7] = homework.teaching_asistant_score.nil? ? l(:label_without_score) : format("%.2f",homework.teaching_asistant_score) sheet1[count_row,7] = homework.teacher_score.nil? ? l(:label_without_score) : homework.teacher_score.round(2)
sheet1[count_row,8] = homework.system_score.nil? ? l(:label_without_score) : format("%.2f",homework.system_score) 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) : format("%.2f",homework.student_score) sheet1[count_row,9] = homework.system_score.nil? ? l(:label_without_score) : homework.system_score.round(2)
sheet1[count_row,10] = homework.respond_to?("score") ? homework.score.nil? ? l(:label_without_score) : format("%.2f",homework.score) : l(:label_without_score) if @homework.anonymous_comment ==0
sheet1[count_row,11] = format_time(homework.created_at) sheet1[count_row,10] = homework.student_score.nil? ? l(:label_without_score) : homework.student_score.round(2)
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
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 count_row += 1
end end
end end
@ -933,7 +1403,6 @@ class StudentWorkController < ApplicationController
student_work student_work
end end
def test_realtime(student_work, src) def test_realtime(student_work, src)
url = "#{Redmine::Configuration['judge_server']}api/realtime_test.json" url = "#{Redmine::Configuration['judge_server']}api/realtime_test.json"
@ -957,6 +1426,28 @@ class StudentWorkController < ApplicationController
JSON.parse(res.body) JSON.parse(res.body)
end end
def test_realtime_ex(test, src)
url = "#{Redmine::Configuration['judge_server']}api/realtime_test.json"
factor = []
factor << {input: test.input, output: test.output}
solutions = {
src:src,
language:@homework.homework_detail_programing.language,
factor: factor
}
uri = URI(url)
body = solutions.to_json
res = Net::HTTP.new(uri.host, uri.port).start do |client|
request = Net::HTTP::Post.new(uri.path)
request.body = body
request["Content-Type"] = "application/json"
client.request(request)
end
JSON.parse(res.body)
end
#成绩计算 #成绩计算
def set_final_score homework,student_work def set_final_score homework,student_work
if homework && homework.homework_detail_manual if homework && homework.homework_detail_manual
@ -964,6 +1455,7 @@ class StudentWorkController < ApplicationController
if homework.teacher_priority == 1 #教师优先 if homework.teacher_priority == 1 #教师优先
if student_work.teacher_score if student_work.teacher_score
student_work.final_score = student_work.teacher_score student_work.final_score = student_work.teacher_score
student_work.work_score = student_work.teacher_score
else else
if student_work.teaching_asistant_score.nil? if student_work.teaching_asistant_score.nil?
student_work.final_score = student_work.student_score student_work.final_score = student_work.student_score
@ -976,6 +1468,12 @@ class StudentWorkController < ApplicationController
final_score = final_ta_score + final_s_score final_score = final_ta_score + final_s_score
student_work.final_score = format("%.2f",final_score.to_f) student_work.final_score = format("%.2f",final_score.to_f)
end end
if student_work.final_score
score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty
student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
else
student_work.work_score = nil
end
end end
else #不考虑教师评分 else #不考虑教师评分
if student_work.teaching_asistant_score.nil? if student_work.teaching_asistant_score.nil?
@ -989,11 +1487,18 @@ class StudentWorkController < ApplicationController
final_score = final_ta_score + final_s_score final_score = final_ta_score + final_s_score
student_work.final_score = format("%.2f",final_score.to_f) student_work.final_score = format("%.2f",final_score.to_f)
end end
if student_work.final_score
score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty
student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
else
student_work.work_score = nil
end
end end
elsif homework.homework_type == 2 && homework.homework_detail_programing #编程作业-----设定:系统评分必定不为空 elsif homework.homework_type == 2 && homework.homework_detail_programing #编程作业-----设定:系统评分必定不为空
if homework.teacher_priority == 1 #教师优先 if homework.teacher_priority == 1 #教师优先
if student_work.teacher_score if student_work.teacher_score
student_work.final_score = student_work.teacher_score student_work.final_score = student_work.teacher_score
student_work.work_score = student_work.teacher_score
else else
if student_work.teaching_asistant_score.nil? #教辅未评分 if student_work.teaching_asistant_score.nil? #教辅未评分
if student_work.student_score.nil? if student_work.student_score.nil?
@ -1022,6 +1527,12 @@ class StudentWorkController < ApplicationController
final_score = final_sy_score + final_ts_score + final_st_score final_score = final_sy_score + final_ts_score + final_st_score
student_work.final_score = format("%.2f",final_score.to_f) student_work.final_score = format("%.2f",final_score.to_f)
end end
if student_work.final_score
score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty
student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
else
student_work.work_score = nil
end
end end
else #不考虑教师评分 else #不考虑教师评分
if student_work.teaching_asistant_score.nil? #教辅未评分 if student_work.teaching_asistant_score.nil? #教辅未评分
@ -1051,6 +1562,12 @@ class StudentWorkController < ApplicationController
final_score = final_sy_score + final_ts_score + final_st_score final_score = final_sy_score + final_ts_score + final_st_score
student_work.final_score = format("%.2f",final_score.to_f) student_work.final_score = format("%.2f",final_score.to_f)
end end
if student_work.final_score
score = student_work.final_score - student_work.absence_penalty - student_work.late_penalty
student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f) if score
else
student_work.work_score = nil
end
end end
end end
end end

@ -0,0 +1,218 @@
class SubDocumentCommentsController < ApplicationController
before_filter :find_subdomain_and_subfield, :only => [:new, :create, :show, :index, :destroy, :edit]
before_filter :find_subfield_content, :only => [:show, :index]
before_filter :authorize_allowed, :only => [:create, :add_reply]
helper :attachments,:organizations
layout 'base_org_custom'
def new
@sub_document_comment = SubDocumentComment.new
end
def create
@sub_document_comment = SubDocumentComment.new(:sub_domain_id => params[:sub_domain_id], :creator_id => User.current.id, :org_subfield_id => params[:org_subfield_id])
@sub_document_comment.title = params[:sub_document_comment][:title]
@sub_document_comment.content = params[:sub_document_comment][:content]
# @sub_document_comment.save_attachments(params[:attachments])
if params[:field_id]
@sub_document_comment.org_subfield_id = params[:field_id].to_i
end
if @sub_document_comment.save
flash.keep[:notice] = l(:notice_successful_create)
redirect_to org_subfield_sub_domain_sub_document_comments_path(:org_subfield_id => @org_subfield.id, :sub_domain_id => @subdomain.id)
# EditorOfDocument.create(:editor_id => User.current.id, :org_document_comment_id => @sub_document_comment.id, :created_at => @sub_document_comment.updated_at)
# if params[:field_id]
# @org_subfield = OrgSubfield.find(params[:field_id])
# if @org_subfield.subfield_subdomain_dir.nil?
# redirect_to organization_path(@organization, :org_subfield_id => params[:field_id])
# else
# redirect_to show_org_subfield_organization_path(:id => @organization.id, :sub_dir_name => @org_subfield.subfield_subdomain_dir.name)
# end
# else
# redirect_to organization_org_document_comments_path(@organization)
# end
else
redirect_to new_org_document_comment_path(:organization_id => @organization.id)
end
end
def show
if @organization.is_public? || User.current.admin? || User.current.member_of_org?(@organization)
@document = SubDocumentComment.find(params[:id])
respond_to do |format|
format.html {render :layout => @organization.switch_type ? 'base_org_custom' : 'base_org'}
end
else
render_403
end
end
def index
if @organization.is_public? || User.current.admin? || User.current.member_of_org?(@organization)
@documents = @subdomain.sub_document_comments.where("parent_id is null").order("created_at desc")
@is_remote = true
@limit = 20
@atta_count = @documents.count
@atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
@offset ||= @atta_pages.offset
@documents = paginateHelper @documents,20
respond_to do |format|
format.html {render :layout => @organization.switch_type ? 'base_org_custom' : 'base_org'}
end
else
render_403
end
end
def update
@sub_document = SubDocumentComment.find(params[:id])
@sub_document.update_attributes(:title => params[:sub_document_comment][:title], :content => params[:sub_document_comment][:content])
@organization = OrgSubfield.find(params[:org_subfield_id]).organization
# Attachment.attach_files(@org_document, params[:attachments])
# @org_document.save_attachments(params[:attachments])
if @sub_document.parent.nil?
act = OrgActivity.where("org_act_type='SubDocumentComment' and org_act_id =?", @sub_document.id).first
act.update_attributes(:updated_at => @sub_document.updated_at)
# EditorOfDocument.create(:editor_id => User.current.id, :org_document_comment_id => @org_document.id, :created_at => Time.now)
end
respond_to do |format|
format.html {
if params[:flag].to_i == 0
# render :action => 'index', :layout => @organization.switch_type ? 'base_sub_domain' : 'base_org'
redirect_to org_subfield_sub_domain_sub_document_comments_path(:org_subfield_id => params[:org_subfield_id], :sub_domain_id => params[:sub_domain_id])
# render :layout => @organization.switch_type ? 'base_sub_domain' : 'base_org'
# redirect_to organization_path(@organization)
else
redirect_to org_subfield_sub_domain_sub_document_comment_path(:org_subfield_id => params[:org_subfield_id], :sub_domain_id => params[:sub_domain_id])
end
}
end
end
def edit
@sub_document = SubDocumentComment.find(params[:id])
@flag = params[:flag]
render :layout => @organization.switch_type ? 'base_sub_domain' : 'base_org'
end
def add_reply
@document = SubDocumentComment.find(params[:id]).root
@subdomain = @document.sub_domain
@org_subfield = @subdomain.org_subfield
@organization = @org_subfield.organization
@act = OrgActivity.find(params[:id])
@comment = SubDocumentComment.new(:sub_domain_id => @document.sub_domain, :creator_id => User.current.id, :reply_id => params[:id])
@comment.content = params[:sub_content]
@document.children << @comment
@document.save
end
def add_reply_in_doc
@document = SubDocumentComment.find(params[:id]).root
@subdomain = @document.sub_domain
@org_subfield = @subdomain.org_subfield
@organization = @org_subfield.organization
@comment = SubDocumentComment.new(:sub_domain_id => @document.sub_domain_id, :creator_id => User.current.id, :reply_id => params[:id])
@comment.content = params[:flag] ? params[:sub_content] : params[:org_comment][:sub_content]
@document.children << @comment
@document.save
respond_to do |format|
format.html {redirect_to org_subfield_sub_domain_sub_document_comment_path(:id => @document.id, :org_subfield_id => @org_subfield.id, :sub_domain_id => @subdomain.id)}
end
end
def destroy
@sub_document_comment = SubDocumentComment.find(params[:id])
@sub_document_comment.destroy
@sub_domain = @sub_document_comment.sub_domain
@org_subfield = @sub_domain.org_subfield
rescue ActiveRecord::RecordNotFound
respond_to do |format|
# format.html{
# redirect_to org_subfield_sub_domain_sub_document_comments_path(:id => params[:sub_domain_id], :org_subfield_id => params[:org_subfield_id])
# }
format.js
end
end
def delete_reply
@sub_document_comment = OrgDocumentComment.find(params[:id])
@document = @sub_document_comment.root
org = @sub_document_comment.organization
@sub_document_comment.destroy
respond_to do |format|
format.html {redirect_to org_document_comment_path(:id => @document.id, :organization_id => @document.organization_id)}
end
end
def quote
@org_comment = OrgDocumentComment.find(params[:id])
@subject = @org_comment.content
@subject = "RE: #{@subject}" unless @subject.starts_with?('RE:')
@content = "> #{ll(Setting.default_language, :text_user_wrote, User.find(@org_comment.creator_id).realname)}\n> "
@temp = OrgDocumentComment.new
#@course_id = params[:course_id]
@temp.content = "<blockquote>#{ll(Setting.default_language, :text_user_wrote, User.find(@org_comment.creator_id).realname)} <br/>#{@org_comment.content.html_safe}</blockquote>".html_safe
respond_to do | format|
format.js
end
end
def reply
@document = OrgDocumentComment.find(params[:id]).root
@quote = params[:quote][:quote]
@org_document = OrgDocumentComment.new(:creator_id => User.current.id, :reply_id => params[:id])
# params[:blog_comment][:sticky] = params[:blog_comment][:sticky] || 0
# params[:blog_comment][:locked] = params[:blog_comment][:locked] || 0
@org_document.title = params[:org_document_comment][:title]
@org_document.content = params[:org_document_comment][:content]
@org_document.content = @quote + @org_document.content
#@org_document.title = "RE: #{@article.title}" unless params[:blog_comment][:title]
@document.children << @org_document
# @user_activity_id = params[:user_activity_id]
# user_activity = UserActivity.where("act_type='BlogComment' and act_id =#{@article.id}").first
# if user_activity
# user_activity.updated_at = Time.now
# user_activity.save
# end
# attachments = Attachment.attach_files(@org_document, params[:attachments])
# render_attachment_warning_if_needed(@org_document)
#@article.save
# redirect_to user_blogs_path(:user_id=>params[:user_id])
respond_to do |format|
format.html {
# if params[:course_id] #如果呆了course_id过来了那么这是要跳到课程大纲去的
# redirect_to syllabus_course_path(:id=>params[:course_id])
# else
redirect_to org_document_comment_path(:id => @document.id, :organization_id => @document.organization_id)
# end
}
format.js
end
end
private
def find_subdomain_and_subfield
@subdomain = SubDomain.find(params[:sub_domain_id])
@org_subfield = OrgSubfield.find(params[:org_subfield_id])
@organization = @org_subfield.organization
rescue ActiveRecord::RecordNotFound
# source_subdomain_subfield not found
render_404
end
def find_subfield_content
@subfield_content = @organization.org_subfields.order("priority")
end
def authorize_allowed
unless User.current.logged?
redirect_to signin_url
return
end
end
end

@ -0,0 +1,66 @@
class SubDomainsController < ApplicationController
layout 'base_org'
before_filter :find_org_subfield_and_subdomain, :only => [:show, :index, :domain_update_priority, :destroy, :update, :hide_sub_domain, :show_sub_domain]
def new
@subdomain = SubDomain.new
@org_subfield = OrgSubfield.find(params[:org_subfield_id])
@organization = @org_subfield.organization
end
def create
if SubDomain.where("org_subfield_id=#{params[:org_subfield_id]} and name=?",params[:name]).count == 0
@res = true
@subfield = OrgSubfield.find(params[:org_subfield_id])
@organization = @subfield.organization
@subdomain = SubDomain.create(:name => params[:name], :org_subfield_id => params[:org_subfield_id], :priority => @subfield.sub_domains.blank? ? 1 : @subfield.sub_domains.order("priority").last.priority + 1)
@subdomain.update_column(:field_type, params[:field_type])
else
@res = false
end
respond_to do |format|
format.js
end
end
def update
@subdomain.update_column(:name, params[:name])
end
def domain_update_priority
@subdomain.update_attribute(:priority, params[:priority].to_i)
end
def destroy
@subdomain.destroy
end
def show
render_404
# @subfield_content = @organization.org_subfields.order("priority")
# render layout: @organization.switch_type ? 'base_sub_domain' : 'base_org'
end
def index
end
def hide_sub_domain
@subdomain.update_attribute(:hide, 1)
end
def show_sub_domain
@subdomain.update_attribute(:hide, 0)
end
private
def find_org_subfield_and_subdomain
@subfield = OrgSubfield.find(params[:org_subfield_id])
@subdomain = SubDomain.find(params[:id])
@organization = @subfield.organization
rescue ActiveRecord::RecordNotFound
# source_subdomain not found
render_404
end
end

@ -0,0 +1,181 @@
# 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, :edit_syllabus_title, :update_base_info, :delete_syllabus, :delete_des]
def index
user = User.current
@syllabuses = user.syllabuses
end
def show
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.not_deleted.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 = @syllabus.courses.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}")
#根据 作业+资源数排序
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_title
if @syllabus && params[:title] != ""
@syllabus.update_column("title",params[:title])
end
respond_to do |format|
format.js
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

File diff suppressed because it is too large Load Diff

@ -0,0 +1,408 @@
#coding=utf-8
class WechatsController < ActionController::Base
wechat_responder
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
on :text do |request, content|
#邀请码
if join_class_request(request)
sendBindClass(request, {invite_code: content})
# elsif join_project_request(request)
# sendBindProject(request, {invite_code: content})
else
request.reply.text "您的意见已收到,非常感谢~ \n更多问题可以通过以下方式联系我们:\n官方QQ群173184401\n我们会认真聆听您的意见和建议。"
end
end
# When receive 'help', will trigger this responder
on :text, with: 'help' do |request|
request.reply.text 'help content'
end
# When receive '<n>news', will match and will got count as <n> as parameter
on :text, with: /^(\d+) news$/ do |request, count|
# Wechat article can only contain max 10 items, large than 10 will dropped.
news = (1..count.to_i).each_with_object([]) { |n, memo| memo << { title: 'News title', content: "No. #{n} news content" } }
request.reply.news(news) do |article, n, index| # article is return object
article.item title: "#{index} #{n[:title]}", description: n[:content], pic_url: 'http://www.baidu.com/img/bdlogo.gif', url: 'http://www.baidu.com/'
end
end
on :event, with: 'subscribe' do |request|
default_msg(request)
end
# When unsubscribe user scan qrcode qrscene_xxxxxx to subscribe in public account
# notice user will subscribe public account at same time, so wechat won't trigger subscribe event any more
on :scan, with: 'qrscene_xxxxxx' do |request, ticket|
request.reply.text "Unsubscribe user #{request[:FromUserName]} Ticket #{ticket}"
end
# When subscribe user scan scene_id in public account
on :scan, with: 'scene_id' do |request, ticket|
sendBindClass(request, {ticket: ticket})
end
# When no any on :scan responder can match subscribe user scaned scene_id
on :event, with: 'scan' do |request|
if request[:EventKey].present?
sendBindClass(request, {ticket: request[:Ticket]})
end
end
# When enterprise user press menu BINDING_QR_CODE and success to scan bar code
on :scan, with: 'BINDING_QR_CODE' do |request, scan_result, scan_type|
request.reply.text "User #{request[:FromUserName]} ScanResult #{scan_result} ScanType #{scan_type}"
end
# Except QR code, wechat can also scan CODE_39 bar code in enterprise account
on :scan, with: 'BINDING_BARCODE' do |message, scan_result|
if scan_result.start_with? 'CODE_39,'
message.reply.text "User: #{message[:FromUserName]} scan barcode, result is #{scan_result.split(',')[1]}"
end
end
# When user click the menu button
on :click, with: 'BOOK_LUNCH' do |request, key|
request.reply.text "User: #{request[:FromUserName]} click #{key}"
end
on :click, with: 'DEV' do |request, key|
uw = user_binded?(request[:FromUserName])
unless uw
sendBind(request)
else
request.reply.text "此功能正在开发中,很快就会上线,谢谢!"
end
end
# When user view URL in the menu button
on :view, with: 'http://wechat.somewhere.com/view_url' do |request, view|
request.reply.text "#{request[:FromUserName]} view #{view}"
end
# When user sent the imsage
on :image do |request|
request.reply.image(request[:MediaId]) # Echo the sent image to user
end
# When user sent the voice
on :voice do |request|
request.reply.voice(request[:MediaId]) # Echo the sent voice to user
end
# When user sent the video
on :video do |request|
nickname = wechat.user(request[:FromUserName])['nickname'] # Call wechat api to get sender nickname
request.reply.video(request[:MediaId], title: 'Echo', description: "Got #{nickname} sent video") # Echo the sent video to user
end
# When user sent location
on :location do |request|
request.reply.text("Latitude: #{message[:Latitude]} Longitude: #{message[:Longitude]} Precision: #{message[:Precision]}")
end
on :event, with: 'unsubscribe' do |request|
request.reply.success # user can not receive this message
end
# When user enter the app / agent app
on :event, with: 'enter_agent' do |request|
request.reply.text "#{request[:FromUserName]} enter agent app now"
end
# When batch job create/update user (incremental) finished.
on :batch_job, with: 'sync_user' do |request, batch_job|
request.reply.text "sync_user job #{batch_job[:JobId]} finished, return code #{batch_job[:ErrCode]}, return message #{batch_job[:ErrMsg]}"
end
# When batch job replace user (full sync) finished.
on :batch_job, with: 'replace_user' do |request, batch_job|
request.reply.text "replace_user job #{batch_job[:JobId]} finished, return code #{batch_job[:ErrCode]}, return message #{batch_job[:ErrMsg]}"
end
# When batch job invent user finished.
on :batch_job, with: 'invite_user' do |request, batch_job|
request.reply.text "invite_user job #{batch_job[:JobId]} finished, return code #{batch_job[:ErrCode]}, return message #{batch_job[:ErrMsg]}"
end
# When batch job replace department (full sync) finished.
on :batch_job, with: 'replace_party' do |request, batch_job|
request.reply.text "replace_party job #{batch_job[:JobId]} finished, return code #{batch_job[:ErrCode]}, return message #{batch_job[:ErrMsg]}"
end
# Any not match above will fail to below
on :fallback, respond: 'fallback message'
on :click, with: 'FEEDBACK' do |request, key|
request.reply.text "如有反馈问题,请直接切换至输入框,发微信给我们即可"
end
on :click, with: 'MY_NEWS' do |request, key|
default_msg(request)
end
on :click, with: 'PROJECT' do |request, key|
request.reply.text "该功能将在近日开放,敬请期待!"
end
on :click, with: 'JOIN_PROJECT' do |request, key|
request.reply.text "该功能将在近日开放,敬请期待!"
# uw = user_binded?(request[:FromUserName])
# unless uw
# sendBind(request)
# else
# request.reply.text "请直接回复6位项目邀请码\n(不区分大小写):"
# 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 join_class_request(request)
openid = request[:FromUserName]
wl = WechatLog.where("openid = '#{openid}' and request_raw like '%\"Event\":\"click\"%'").order('id desc').first
wl && JSON(wl.request_raw)["EventKey"] == 'JOIN_CLASS'
end
def join_project_request(request)
openid = request[:FromUserName]
wl = WechatLog.where("openid = '#{openid}' and request_raw like '%\"Event\":\"click\"%'").order('id desc').first
wl && JSON(wl.request_raw)["EventKey"] == 'JOIN_PROJECT'
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 sendBindProject(request, params)
begin
uw = user_binded?(request[:FromUserName])
if !uw
return sendBind(request)
else
return join_project(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)
uw = user_binded?(request[:FromUserName])
if uw && uw.user
request.reply.text "欢迎回来, #{uw.user.show_name}"
else
sendBind(request)
end
end
def sendBind(request)
news = (1..1).each_with_object([]) { |n, memo| memo << { title: '绑定登录', content: "欢迎使用Trustie创新实践服务平台
" } }
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=#{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]}",
description: n[:content],
pic_url: pic_url,
url: url
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
#取出用户角色类型
role = 10
cs = CoursesService.new
status = cs.join_course({invite_code: course.invite_code}, user)
logger.info status
if status[:state] != 0
raise CoursesService::JoinCourseError.message(status[:state])
end
news = (1..1).each_with_object([]) { |n, memo| memo << { title: '恭喜您成功加入班级,开始学习吧!',
content: "课程名称:#{course.name}\n班级名称:#{course.name}\n任课老师:#{course.teacher.show_name}\n进入班级,和小伙伴愉快的学习吧!"} }
return 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=#{ROOT_URL+'/wechat/user_activities#/class?id='+course.id.to_s}&response_type=code&scope=snsapi_base&state=myclass#wechat_redirect"
pic_url = "#{ROOT_URL}/images/wechat/class.jpg"
article.item title: "#{n[:title]}",
description: n[:content],
pic_url: pic_url,
url: url
end
end
def join_project(params, user, request)
project = nil
project = Project.where(qrcode: params[:ticket]).first if params[:ticket]
project = Project.where(invite_code: params[:invite_code]).first if params[:invite_code]
raise "项目不存在,请确认您的邀请码是否输入正确,谢谢!" unless project
#取出用户角色类型
role = 5
ps = ProjectsService.new
status = ps.join_project({invite_code: project.invite_code}, user)
if status[:state] != 0
raise ProjectService::JoinProjectError.message(status)
end
creator = User.find(project.user_id)
news = (1..1).each_with_object([]) { |n, memo| memo << { title: '恭喜您成功加入项目,开始研发吧!',
content: "项目名称:#{project.name}\n发起人:#{creator.name}\n进入项目,和小伙伴轻松的研发吧!"} }
return 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=#{ROOT_URL+'/wechat/user_activities#/project?id='+project.id.to_s}&response_type=code&scope=snsapi_base&state=myproject#wechat_redirect"
pic_url = "#{ROOT_URL}/images/wechat/class.jpg"
article.item title: "#{n[:title]}",
description: n[:content],
pic_url: pic_url,
url: url
end
end
### controller method
module Controllers
def get_bind
begin
code = params[:code] || session[:wechat_code]
openid = get_openid_from_code(code)
raise "无法获取到微信openid" unless openid
uw = UserWechat.where(openid: openid).first
raise "还未绑定trustie帐户" unless uw
logger.debug "get_bind ============= #{uw}"
user = uw.user
::ApiKey.delete_all(user_id: user.id)
key = ::ApiKey.create!(user_id: user.id)
render :json =>{status: 0, token: key.access_token}
rescue Exception=>e
render :json => {status: -1, message: e.message}
end
end
def bind
begin
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/user_activities', layout: nil
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
unless user_binded?(open_id)
@path = '/login'
else
if params[:state] == 'myclass'
@course_id = params[:id];
elsif params[:state] == 'myproject'
@project_id = params[:id];
end
session[:wechat_openid] = open_id
if params[:code]
redirect_to "/wechat/user_activities##{@path}?id=#{params[:id]}" and return
end
end
render 'wechats/user_activities', layout: nil
end
private
def get_openid_from_code(code)
return 'oCnvgvz8R7QheXE-R9Kkr39j8Ndg' if code =='only-for-test'
openid = session[:wechat_openid]
unless openid
if code
openid = wechat.web_access_token(code)["openid"]
end
end
if openid
session[:wechat_openid] = openid
end
return openid
end
def user_binded?(openid)
uw = UserWechat.where(openid: openid).first
end
end
include Controllers
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 {
@ -74,9 +75,8 @@ class WordsController < ApplicationController
# render 'test/index' # render 'test/index'
# } # }
format.js { format.js {
#@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]
} }
end end
@ -91,22 +91,31 @@ 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
redirect_to feedback_path(@user)
return
end
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
@is_in_course = params[:is_in_course].to_i @is_in_course = params[:is_in_course].to_i
@course_activity = params[:course_activity].to_i @course_activity = params[:course_activity].to_i
elsif @journal_destroyed.jour_type == 'Syllabus'
@syllabus = Syllabus.find @journal_destroyed.jour_id
@count = @syllabus.journals_for_messages.count
@comments = @syllabus.journals_for_messages.reorder("created_on desc").limit(3)
end end
respond_to do |format| respond_to do |format|
format.js format.js
@ -259,6 +268,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?
@ -271,7 +302,7 @@ class WordsController < ApplicationController
ids = params[:asset_id].split(',') ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,feedback[:id],OwnerTypeHelper::JOURNALSFORMESSAGE update_kindeditor_assets_owner ids,feedback[:id],OwnerTypeHelper::JOURNALSFORMESSAGE
end end
@homework_common.update_column('updated_at', Time.now)
update_course_activity(@homework_common.class,@homework_common.id) update_course_activity(@homework_common.class,@homework_common.id)
update_user_activity(@homework_common.class,@homework_common.id) update_user_activity(@homework_common.class,@homework_common.id)
update_org_activity(@homework_common.class,@homework_common.id) update_org_activity(@homework_common.class,@homework_common.id)
@ -292,6 +323,69 @@ class WordsController < ApplicationController
end end
end end
#作业的二级回复
def reply_to_homework
if User.current.logged?
@user = User.current
reply = JournalsForMessage.find params[:id].to_i
@homework_common = HomeworkCommon.find reply.jour_id
if params[:reply_message].size>0 && User.current.logged? && @user
options = {:notes => params[:reply_message], :reply_id => reply.user_id,:user_id => @user.id,:m_parent_id => params[:id].to_i,:m_reply_id => params[:id].to_i}
feedback = HomeworkCommon.add_homework_jour(@user, params[:reply_message], reply.jour_id, options)
if (feedback.errors.empty?)
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,feedback[:id],OwnerTypeHelper::JOURNALSFORMESSAGE
end
@homework_common.update_column('updated_at', Time.now)
update_course_activity(@homework_common.class,@homework_common.id)
update_user_activity(@homework_common.class,@homework_common.id)
update_org_activity(@homework_common.class,@homework_common.id)
respond_to do |format|
format.js{
@user_activity_id = params[:user_activity_id].to_i
@is_in_course = params[:is_in_course].to_i
@course_activity = params[:course_activity].to_i
}
end
else
flash[:error] = feedback.errors.full_messages[0]
end
end
else
render_403
end
end
#课程大纲的二级回复
def reply_to_syllabus
if User.current.logged?
@user = User.current
reply = JournalsForMessage.find params[:id].to_i
@syllabus = Syllabus.find reply.jour_id
if params[:reply_message].size>0 && User.current.logged? && @user
options = {:notes => params[:reply_message], :reply_id => reply.user_id,:user_id => @user.id,:m_parent_id => params[:id].to_i,:m_reply_id => params[:id].to_i}
feedback = Syllabus.add_syllabus_jour(@user, params[:reply_message], reply.jour_id, options)
if (feedback.errors.empty?)
if params[:asset_id]
ids = params[:asset_id].split(',')
update_kindeditor_assets_owner ids,feedback[:id],OwnerTypeHelper::JOURNALSFORMESSAGE
end
@syllabus.update_column('updated_at', Time.now)
@count = @syllabus.journals_for_messages.count
@comments = @syllabus.journals_for_messages.reorder("created_on desc").limit(3)
respond_to do |format|
format.js
end
else
flash[:error] = feedback.errors.full_messages[0]
end
end
else
render_403
end
end
def add_brief_introdution def add_brief_introdution
user = User.current user = User.current
message = params[:new_form][:user_introduction] message = params[:new_form][:user_introduction]
@ -299,6 +393,27 @@ class WordsController < ApplicationController
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
def find_user def find_user
@ -335,28 +450,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 end
raise "create reply obj unknow type.#{obj.class}" # obj = obj_distinguish_url_origin || User.find_by_id(2)
end # 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
@ -134,8 +138,11 @@ class ZipdownController < ApplicationController
homework_common.student_works.each do |work| homework_common.student_works.each do |work|
unless work.attachments.empty? unless work.attachments.empty?
out_file = zip_student_work_by_user(work) out_file = zip_student_work_by_user(work)
bid_homework_path << out_file.file_path bid_homework_path << out_file.file_path
digests << out_file.file_digest digests << out_file.file_digest
end end
end end
homework_id = homework_common.id homework_id = homework_common.id
@ -172,7 +179,11 @@ class ZipdownController < ApplicationController
} }
end end
def zip_student_work_by_user work def make_zip_name(work)
"#{work.user.show_name}_#{((work.user.user_extensions.nil? || work.user.user_extensions.student_id.nil?) ? "" : work.user.user_extensions.student_id)}_#{Time.now.to_i.to_s}"
end
def zip_student_work_by_user(work)
homeworks_attach_path = [] homeworks_attach_path = []
not_exist_file = [] not_exist_file = []
# 需要将所有homework.attachments遍历加入zip # 需要将所有homework.attachments遍历加入zip
@ -186,11 +197,24 @@ class ZipdownController < ApplicationController
digests << 'not_exist_file' digests << 'not_exist_file'
end end
end end
#单个文件的话,不需要压缩,只改名
out_file = nil
if homeworks_attach_path.size == 1
out_file = find_or_pack(work.homework_common_id, work.user_id, digests.sort){ out_file = find_or_pack(work.homework_common_id, work.user_id, digests.sort){
zipping("#{work.user.show_name}_#{((work.user.user_extensions.nil? || work.user.user_extensions.student_id.nil?) ? "" : work.user.user_extensions.student_id)}_#{Time.now.to_i.to_s}.zip", des_path = "#{OUTPUT_FOLDER}/#{make_zip_name(work)}_#{File.basename(homeworks_attach_path.first)}"
FileUtils.cp homeworks_attach_path.first, des_path
des_path
}
else
out_file = find_or_pack(work.homework_common_id, work.user_id, digests.sort){
zipping("#{make_zip_name(work)}.zip",
homeworks_attach_path, OUTPUT_FOLDER, true, not_exist_file) homeworks_attach_path, OUTPUT_FOLDER, true, not_exist_file)
} }
end end
out_file
end
def find_or_pack(homework_id, user_id, digests) def find_or_pack(homework_id, user_id, digests)
@ -222,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))

@ -27,6 +27,10 @@ module ApiHelper
location location
end end
def get_user_realname user
name = user.lastname + user.firstname
name.empty? || name.nil? || name == " " ? user.login : name
end
def get_assigned_homeworks(homeworks, n, index) def get_assigned_homeworks(homeworks, n, index)
homeworks += homeworks homeworks += homeworks
@ -178,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
@ -201,5 +205,310 @@ module ApiHelper
end end
#日期转换为时间
def convert_to_time date, num
if num == 0
date = date.to_s + " 00:00"
elsif num == 1
date = date.to_s + " 23:59"
end
return date
end
#获取用户
def get_user user_id
user = User.find user_id
user
end
#获取项目
def get_project project_id
project = Project.find project_id
project
end
#获取课程
def get_course course_id
course = Course.find course_id
course
end
#获取点赞数
def get_activity_praise_num(object)
obj_type = object.class
obj_id = object.id
record = PraiseTreadCache.find_by_object_id_and_object_type(obj_id,obj_type)
if record
return ((record.praise_num.nil? ? 0 : record.praise_num.to_i)-(record.tread_num.nil? ? 0 : record.tread_num.to_i))
else
return 0
end
end
#获取缺陷的优先级
def get_issue_priority_api value
issuetype = ""
if value == 4
issuetype = "紧急"
elsif value == 2
issuetype = "正常"
elsif value == 3
issuetype = ""
elsif value == 1
issuetype = ""
else
issuetype = "立刻"
end
end
def jdetails_to_strings(details, no_html=false, options={})
options[:only_path] = (options[:only_path] == false ? false : true)
options[:token] = options[:token] if options[:token]
strings = []
values_by_field = {}
details.each do |detail|
if detail.property == 'cf'
field_id = detail.prop_key
field = CustomField.find_by_id(field_id)
if field && field.multiple?
values_by_field[field_id] ||= {:added => [], :deleted => []}
if detail.old_value
values_by_field[field_id][:deleted] << detail.old_value
end
if detail.value
values_by_field[field_id][:added] << detail.value
end
next
end
end
strings << jshow_detail(detail, no_html, options)
end
values_by_field.each do |field_id, changes|
detail = JournalDetail.new(:property => 'cf', :prop_key => field_id)
if changes[:added].any?
detail.value = changes[:added]
strings << jshow_detail(detail, no_html, options)
elsif changes[:deleted].any?
detail.old_value = changes[:deleted]
strings << jshow_detail(detail, no_html, options)
end
end
strings
end
# Returns the textual representation of a single journal detail
def jshow_detail(detail, no_html=false, options={})
multiple = false
case detail.property
when 'attr'
field = detail.prop_key.to_s.gsub(/\_id$/, "")
label = l(("field_" + field).to_sym)
case detail.prop_key
when 'due_date', 'start_date'
value = format_date(detail.value.to_date) if detail.value
old_value = format_date(detail.old_value.to_date) if detail.old_value
when 'project_id', 'status_id', 'tracker_id', 'assigned_to_id',
'priority_id', 'category_id', 'fixed_version_id'
value = find_name_by_reflection(field, detail.value)
old_value = find_name_by_reflection(field, detail.old_value)
when 'estimated_hours'
value = "%0.02f" % detail.value.to_f unless detail.value.blank?
old_value = "%0.02f" % detail.old_value.to_f unless detail.old_value.blank?
when 'parent_id'
label = l(:field_parent_issue)
value = "##{detail.value}" unless detail.value.blank?
old_value = "##{detail.old_value}" unless detail.old_value.blank?
when 'is_private'
value = l(detail.value == "0" ? :general_text_No : :general_text_Yes) unless detail.value.blank?
old_value = l(detail.old_value == "0" ? :general_text_No : :general_text_Yes) unless detail.old_value.blank?
end
when 'cf'
custom_field = CustomField.find_by_id(detail.prop_key)
if custom_field
multiple = custom_field.multiple?
label = custom_field.name
value = format_value(detail.value, custom_field.field_format) if detail.value
old_value = format_value(detail.old_value, custom_field.field_format) if detail.old_value
end
when 'attachment'
label = l(:label_attachment)
end
call_hook(:helper_issues_show_detail_after_setting,
{:detail => detail, :label => label, :value => value, :old_value => old_value })
label ||= detail.prop_key
value ||= detail.value
old_value ||= detail.old_value
unless no_html
label = content_tag('strong', label)
old_value = content_tag("i", old_value) if detail.old_value
old_value = content_tag("del", old_value) if detail.old_value and detail.value.blank?
if detail.property == 'attachment' && !value.blank? && atta = Attachment.find_by_id(detail.prop_key)
# Link to the attachment if it has not been removed
if options[:token].nil?
value = atta.filename
else
value = atta.filename
end
# 放大镜搜索功能
# if options[:only_path] != false && atta.is_text?
# value += link_to(
# image_tag('magnifier.png'),
# :controller => 'attachments', :action => 'show',
# :id => atta, :filename => atta.filename
# )
# end
else
value = content_tag("i", value) if value
end
end
# 缺陷更新结果在消息中显示样式
if no_html == "message"
label = content_tag(:span, label, :class => "issue_update_message")
old_value = content_tag("span", old_value) if detail.old_value
old_value = content_tag("del", old_value) if detail.old_value and detail.value.blank?
if detail.property == 'attachment' && !value.blank? && atta = Attachment.find_by_id(detail.prop_key)
# Link to the attachment if it has not been removed
if options[:token].nil?
value = atta.filename
else
value = atta.filename
end
else
value = content_tag(:span, value, :class => "issue_update_message_value") if value
end
end
if detail.property == 'attr' && detail.prop_key == 'description'
s = l(:text_journal_changed_no_detail, :label => label)
unless no_html
diff_link = link_to l(:label_diff),
{:controller => 'journals', :action => 'diff', :id => detail.journal_id,
:detail_id => detail.id, :only_path => options[:only_path]},
:title => l(:label_view_diff)
s << " (#{ diff_link })"
end
s.html_safe
elsif detail.value.present?
case detail.property
when 'attr', 'cf'
if detail.old_value.present?
l(:text_journal_changed, :label => label, :old => old_value, :new => value).html_safe
elsif multiple
l(:text_journal_added, :label => label, :value => value).html_safe
else
l(:text_journal_set_to, :label => label, :value => value).html_safe
end
when 'attachment'
l(:text_journal_added, :label => label, :value => value).html_safe
end
else
l(:text_journal_deleted, :label => label, :old => old_value).html_safe
end
end
#课程动态的更新
def update_course_activity_api type, id
course_activity = CourseActivity.where("course_act_type=? and course_act_id =?", type.to_s, id.to_i).first
if course_activity
course_activity.updated_at = Time.now
course_activity.save
end
end
#首页动态更新
def update_user_activity_api type, id
user_activity = UserActivity.where("act_type=? and act_id =?", type.to_s, id.to_i).first
if user_activity
user_activity.updated_at = Time.now
user_activity.save
end
end
#项目动态更新
def update_forge_activity_api type, id
forge_activity = ForgeActivity.where("forge_act_type=? and forge_act_id=?", type.to_s, id.to_i).first
if forge_activity
forge_activity.updated_at = Time.now
forge_activity.save
end
end
#组织动态更新
def update_org_activity_api type , id
org_activity = OrgActivity.where("org_act_type=? and org_act_id =?", type.to_s, id.to_i).first
if org_activity
org_activity.updated_at = Time.now
org_activity.save
end
end
#个人动态更新
def update_principal_activity_api type, id
principal_activity = PrincipalActivity.where("principal_act_type=? and principal_act_id =?", type.to_s, id.to_i).first
if principal_activity
principal_activity.updated_at = Time.now
principal_activity.save
end
end
#赞/取消赞
def praise_or_cancel(type,id,user,flag)
unless id.nil? and type.nil?
#首先创建或更新praise_tread 表
pt = PraiseTread.new
pt.user_id = user.id
pt.praise_tread_object_id = id.to_i
pt.praise_tread_object_type = type
pt.praise_or_tread = flag
pt.save
# end
#再创建或更新praise_tread_cache表
#@ptc = PraiseTreadCache.find_by_object_id_and_object_type(id,type)
ptc = PraiseTreadCache.where("object_id = ? and object_type = ?",id.to_i,type).first
ptc = ptc.nil? ? PraiseTreadCache.new : ptc
ptc.object_id = id.to_i
ptc.object_type = type
ptc.save
ptc.praise_plus(flag,1)
end
end
def praise_plus(flag,num)
case flag
when 1
self.update_attribute(:praise_num, self.praise_num.to_i + num)
end
end
def praise_minus(num)
self.update_attribute(:praise_num, self.praise_num.to_i - num)
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

@ -33,6 +33,62 @@ module ApplicationHelper
extend Forwardable extend Forwardable
def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter def_delegators :wiki_helper, :wikitoolbar_for, :heads_for_wiki_formatter
# def user_blogs_path(resource,parameters={})
# super
# end
# 通过系统外部邮箱查找用户,如果用户不存在则用邮箱替换
def get_user_by_mail mail
user = User.find_by_mail(mail)
user.nil? ? User.find(2) : user
end
# 历史数据(老版本库数据)处理完则可以修改该放放
def get_rep_identifier_by_project project
identifier = Repository.where(:project_id => project.id, :type => "Repository::Gitlab").first.try(:identifier)
result = identifier.nil? ? Repository.where(:project_id => project.id).first.try(:identifier) : identifier
result
end
# 获取用户单位
# 优先获取高校信息如果改信息不存在则获取occupation
def get_occupation_from_user user
School.where("id=?",user.user_extensions.school_id).first.try(:name).nil? ? user.user_extensions.try(:occupation) : School.where("id=?",user.user_extensions.school_id).first.try(:name)
end
def update_visiti_count container
container.update_column(:visits, container.visits + 1)
end
def if_hidden_subdomain field
domains = field.sub_domains.select{|domain| domain.hide.to_i == 0}
result = domains.length > 0 ? true : false
return result
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 从硬盘上删除对应的资源文件
@ -72,6 +128,7 @@ module ApplicationHelper
# 获取组织成员中文名字 # 获取组织成员中文名字
def get_org_member_role_name member def get_org_member_role_name member
unless member.roles[0].nil?
case member.roles[0].name case member.roles[0].name
when 'orgManager' when 'orgManager'
'管理人员' '管理人员'
@ -79,6 +136,7 @@ module ApplicationHelper
'组织成员' '组织成员'
end end
end end
end
# 判断组织左侧展开或者隐藏 # 判断组织左侧展开或者隐藏
def is_hide_org_left obj def is_hide_org_left obj
@ -110,46 +168,102 @@ module ApplicationHelper
end end
end end
# 更新课程英雄榜得分 # 更新课程活跃度得分
# user传过来必须是学生
def course_member_score(course_id,user_id,type) def course_member_score(course_id,user_id,type)
course_contributor_score = CourseContributorScore.where("course_id =? and user_id =?", course_id, user_id).first course_contributor_score = CourseContributorScore.where("course_id =? and user_id =?", course_id, user_id).first
case type case type
when "JournalForMessage" when "HomeworkCommon"
if course_contributor_score.nil? if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :message_num => 0, :message_reply_num => 0, CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :homework_journal_num => 1)
:news_reply_num => 0, :resource_num => 0, :journal_num => 1, :journal_reply_num => 0, :total_score => 1)
else else
score = course_contributor_score.journal_num + 1 score = course_contributor_score.homework_journal_num.to_i + 1
total_score = course_contributor_score.total_score + 1 course_contributor_score.update_column(:homework_journal_num, score)
course_contributor_score.update_attributes(:journal_num => score, :total_score => total_score) end
# 课程留言
when "Course"
if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :journal_num => 1)
else
score = course_contributor_score.journal_num.to_i + 1
course_contributor_score.update_column(:journal_num, score)
end end
when "Message" when "Message"
if course_contributor_score.nil? if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :message_num => 2, :message_reply_num => 0, CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :message_num => 1)
:news_reply_num => 0, :resource_num => 0, :journal_num => 0, :journal_reply_num => 0, :total_score => 2)
else else
score = course_contributor_score.message_num + 2 score = course_contributor_score.message_num.to_i + 1
total_score = course_contributor_score.total_score + 2 course_contributor_score.update_column(:message_num, score)
course_contributor_score.update_attributes(:message_num => score, :total_score => total_score)
end end
when "MessageReply" when "MessageReply"
if course_contributor_score.nil? if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :message_num => 0, :message_reply_num => 1, CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :message_reply_num => 1)
:news_reply_num => 0, :resource_num => 0, :journal_num => 0, :journal_reply_num => 0, :total_score => 1)
else else
score = course_contributor_score.message_reply_num + 1 score = course_contributor_score.message_reply_num.to_i + 1
total_score = course_contributor_score.total_score + 1 course_contributor_score.update_column(:message_reply_num, score)
course_contributor_score.update_attributes(:message_reply_num => score, :total_score => total_score)
end end
when "NewReply" when "NewReply"
if course_contributor_score.nil? if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :message_num => 0, :message_reply_num => 0, CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :news_reply_num => 1)
:news_reply_num => 1, :resource_num => 0, :journal_num => 0, :journal_reply_num => 0, :total_score => 1) else
score = course_contributor_score.news_reply_num.to_i + 1
course_contributor_score.update_column(:news_reply_num, score)
end
when "News"
if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :news_num => 1)
else else
score = course_contributor_score.news_reply_num + 1 score = course_contributor_score.news_num.to_i + 1
total_score = course_contributor_score.total_score + 1 course_contributor_score.update_column(:news_num, score)
course_contributor_score.update_attributes(:news_reply_num => score, :total_score => total_score) end
when "Attachment"
if course_contributor_score.nil?
CourseContributorScore.create(:course_id => course_id, :user_id => user_id, :resource_num => 1)
else
score = course_contributor_score.resource_num.to_i + 1
course_contributor_score.update_column(:resource_num, score)
end
end
end
# 删除某条记录相应减少课程统计数
def down_course_score_num (course_id,user_id,type)
course_contributor_score = CourseContributorScore.where("course_id =? and user_id =?", course_id, user_id).first
case type
when "HomeworkCommon"
unless course_contributor_score.nil?
score = course_contributor_score.homework_journal_num.to_i - 1
course_contributor_score.update_column(:homework_journal_num, score < 0 ? 0 : score)
end
# 课程留言
when "Course"
unless course_contributor_score.nil?
score = course_contributor_score.journal_num.to_i - 1
course_contributor_score.update_column(:journal_num, score < 0 ? 0 : score)
end
when "Message"
unless course_contributor_score.nil?
score = course_contributor_score.message_num.to_i - 1
course_contributor_score.update_column(:message_num, score < 0 ? 0 : score)
end
when "MessageReply"
unless course_contributor_score.nil?
score = course_contributor_score.message_reply_num.to_i - 1
course_contributor_score.update_column(:message_reply_num, score < 0 ? 0 : score)
end
when "NewReply"
unless course_contributor_score.nil?
score = course_contributor_score.news_reply_num.to_i - 1
course_contributor_score.update_column(:news_reply_num, score < 0 ? 0 : score)
end
when "News"
unless course_contributor_score.nil?
score = course_contributor_score.news_num.to_i - 1
course_contributor_score.update_column(:news_num, score < 0 ? 0 : score)
end
when "Attachment"
unless course_contributor_score.nil?
score = course_contributor_score.resource_num.to_i - 1
course_contributor_score.update_column(:resource_num, score < 0 ? 0 : score)
end end
end end
end end
@ -288,6 +402,7 @@ module ApplicationHelper
subject = truncate(subject, :length => 60) subject = truncate(subject, :length => 60)
end end
end end
# status_id3、已解决 5、已关闭
if issue.status_id == 3 if issue.status_id == 3
s = link_to text, issue_path(issue), :class => "text_line_s", :title => title s = link_to text, issue_path(issue), :class => "text_line_s", :title => title
elsif issue.status_id == 5 elsif issue.status_id == 5
@ -307,7 +422,7 @@ module ApplicationHelper
def link_to_short_attachment(attachment, options={}) def link_to_short_attachment(attachment, options={})
length = options[:length] ? options[:length]:23 length = options[:length] ? options[:length]:23
text = h(truncate(options.delete(:text) || attachment.filename, length: length, omission: '...')) text = h(truncate(options.delete(:text) || attachment.filename, length: length, omission: '...'))
route_method = options.delete(:download) ? :download_named_attachment_path : :named_attachment_path route_method = options.delete(:download) ? :download_named_attachment_url_without_domain : :named_attachment_url_without_domain
html_options = options.slice!(:only_path) html_options = options.slice!(:only_path)
url = send(route_method, attachment, attachment.filename, options) url = send(route_method, attachment, attachment.filename, options)
link_to text, url, html_options link_to text, url, html_options
@ -699,29 +814,41 @@ module ApplicationHelper
return @result return @result
end end
# 必须是项目成,项目必须提交过代码
def allow_pull_request project
return false if project.gpid.nil?
g = Gitlab.client
count = g.user_static(project.gpid, :rev => "master").count
if User.current.member_of?(project) && count > 0
true
else
false
end
end
# 判断版本库是否初始为gitlab # 判断版本库是否初始为gitlab
def rep_is_gitlab?(project) def rep_is_gitlab?(project)
rep = Repository.where("project_id =? and type =?", project, "Repository::Gitlab") rep = project.repositories.where("type =?", "Repository::Gitlab")
return rep.blank? ? true :false return rep.blank? ? true :false
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
@ -735,7 +862,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
@ -778,7 +905,7 @@ module ApplicationHelper
def project_member_check_box_tags_ex name, principals def project_member_check_box_tags_ex name, principals
s = '' s = ''
principals.each do |principal| principals.each do |principal|
s << "<li>#{ check_box_tag name, principal.id, false, :id => nil } #{h link_to principal.userInfo, user_path( principal.id)}</li>\n" s << "<li>#{ check_box_tag name, principal.id, false, :id => nil } #{h link_to principal.userInfo, user_url_in_org( principal.id)}</li>\n"
end end
s.html_safe s.html_safe
end end
@ -981,9 +1108,11 @@ module ApplicationHelper
elsif @organization elsif @organization
title << @organization.name title << @organization.name
elsif @user elsif @user
title << @user.login title << @user.try(:realname)
elsif @syllabus
title << @syllabus.title
else else
title << User.current.login 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
@ -1666,20 +1795,21 @@ module ApplicationHelper
link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)") link_to_function(l(:button_uncheck_all), "checkAll('#{form_name}', false)")
end end
# 本次修改,修改为只显示关闭的所占%比
def progress_bar(pcts, options={}) def progress_bar(pcts, options={})
pcts = [pcts, pcts] unless pcts.is_a?(Array) pcts = [pcts] unless pcts.is_a?(Array)
pcts = pcts.collect(&:round) pcts = pcts.collect(&:round)
pcts[1] = pcts[1] - pcts[0] # pcts[1] = pcts[1] + pcts[0]
pcts << (100 - pcts[1] - pcts[0]) pcts << (100 - pcts[0])
width = options[:width] || '100px;' width = options[:width] || '100px;'
legend = options[:legend] || '' legend = options[:legend] || ''
content_tag('table', content_tag('table',
content_tag('tr', content_tag('tr',
(pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed') : ''.html_safe) + (pcts[0] > 0 ? content_tag('td', '', :style => "width: #{pcts[0]}%;", :class => 'closed', :title => "已关闭:#{pcts[0]}%") : ''.html_safe) +
(pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done') : ''.html_safe) + # (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'done', :title => "开发中:#{pcts[1]}%") : ''.html_safe) +
(pcts[2] > 0 ? content_tag('td', '', :style => "width: #{pcts[2]}%;", :class => 'todo') : ''.html_safe) (pcts[1] > 0 ? content_tag('td', '', :style => "width: #{pcts[1]}%;", :class => 'todo', :title => "未完成:#{pcts[1]}%") : ''.html_safe), :style => "width: #{width}"
), :class => 'progress', :style => "width: #{width};").html_safe + ), :class => 'progress').html_safe
content_tag('p', legend, :class => 'percent').html_safe # + content_tag('p', legend, :class => 'percent').html_safe
end end
def checked_image(checked=true) def checked_image(checked=true)
@ -2000,13 +2130,13 @@ 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) 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
@ -2020,25 +2150,29 @@ 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)
candown = true org = attachment.container.organization
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)
candown = true org = attachment.container.organization
candown = User.current.member_of_org?(org) || (org.is_public && attachment.is_public == 1)
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.course attachment.container.board.course
course = attachment.container.board.course course = attachment.container.board.course
candown= User.current.member_of_course?(course) || (course.is_public==1 && attachment.is_public == 1) candown= User.current.member_of_course?(course) || (course.is_public==1 && attachment.is_public == 1)
elsif attachment.container.class.to_s=="Organization"
candown = true
elsif attachment.container.class.to_s=="HomeworkAttach" elsif attachment.container.class.to_s=="HomeworkAttach"
candown = true candown = true
elsif attachment.container.class.to_s=="StudentWorksScore" elsif attachment.container.class.to_s=="StudentWorksScore"
@ -2072,6 +2206,20 @@ module ApplicationHelper
end end
#如果学生作品被打分后修改,应该给老师提示
def send_message_to_teacher student_work
if StudentWork === student_work
if student_work.student_works_scores.any?
course = student_work.homework_common.course
course.members.map(&:user_id).uniq.each do|user_id|
if User.find(user_id).allowed_to?(:as_teacher, course)
student_work.course_messages << CourseMessage.new(:user_id => user_id, :course_id => course.id, :viewed => false, :status => 1)
end
end
end
end
end
private private
def wiki_helper def wiki_helper
@ -2512,14 +2660,14 @@ module ApplicationHelper
#获取匿评相关连接代码 #获取匿评相关连接代码
def homework_anonymous_comment (homework, is_in_course, user_activity_id = -1, course_activity = -1) def homework_anonymous_comment (homework, is_in_course, user_activity_id = -1, course_activity = -1)
if Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") if homework.homework_detail_manual.comment_status == 0 ||Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d")
link = link_to "启动匿评","javascript:void(0)", :class => "postOptionLink", :title => "作业截止日期之前不可以启动匿评" link = link_to "启动匿评","javascript:void(0)", :class => "postOptionLink", :title => "作业截止日期之前不可以启动匿评"
elsif homework.student_works.count >= 2 && homework.homework_detail_manual#作业份数大于2 elsif homework.student_works.has_committed.count >= 2 && homework.homework_detail_manual#作业份数大于2
case homework.homework_detail_manual.comment_status case homework.homework_detail_manual.comment_status
when 1 when 1
link = link_to '启动匿评', alert_anonymous_comment_homework_common_path(homework,:is_in_course=>is_in_course,:user_activity_id=>user_activity_id,:course_activity=>course_activity), id: "#{homework.id}_start_anonymous_comment", remote: true, disable_with: '加载中...',:class => 'postOptionLink' link = link_to '启动匿评', Setting.protocol + "://" + Setting.host_name + "/homework_common/" + homework.id.to_s + "/alert_anonymous_comment?is_in_course=" + is_in_course.to_s + "&user_activity_id=" + user_activity_id.to_s + "&course_activity=" + course_activity.to_s, id: "#{homework.id}_start_anonymous_comment", remote: true, disable_with: '加载中...',:class => 'postOptionLink'
when 2 when 2
link = link_to '关闭匿评', alert_anonymous_comment_homework_common_path(homework,:is_in_course=>is_in_course,:user_activity_id=>user_activity_id,:course_activity=>course_activity), id: "#{homework.id}_stop_anonymous_comment", remote: true,:class => 'postOptionLink' link = link_to '关闭匿评', Setting.protocol + "://" + Setting.host_name + "/homework_common/" + homework.id.to_s + "/alert_anonymous_comment?is_in_course=" + is_in_course.to_s + "&user_activity_id=" + user_activity_id.to_s + "&course_activity=" + course_activity.to_s, id: "#{homework.id}_stop_anonymous_comment", remote: true,:class => 'postOptionLink'
when 3 when 3
# link = link_to "匿评结束","javascript:void(0)", :class => "postOptionLink", :title => "匿评结束" # link = link_to "匿评结束","javascript:void(0)", :class => "postOptionLink", :title => "匿评结束"
end end
@ -2564,40 +2712,41 @@ module ApplicationHelper
#根据传入作业确定显示为编辑作品还是新建作品,或者显示作品数量 #根据传入作业确定显示为编辑作品还是新建作品,或者显示作品数量
def user_for_homework_common homework,is_teacher def user_for_homework_common homework,is_teacher
count = homework.student_works.has_committed.count
if User.current.member_of_course?(homework.course) if User.current.member_of_course?(homework.course)
if is_teacher #老师显示作品数量 if is_teacher #老师显示作品数量
link_to "作品(#{homework.student_works.count})",student_work_index_path(:homework => homework.id),:class => "c_blue" link_to "作品(#{count})", student_work_index_url_in_org(homework.id), :class => "c_blue"
else #学生显示提交作品、修改作品等按钮 else #学生显示提交作品、修改作品等按钮
work = cur_user_works_for_homework homework work = cur_user_works_for_homework homework
project = cur_user_projects_for_homework homework project = cur_user_projects_for_homework homework
if work.nil? && Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") if work.nil? && Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d")
if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1 if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
link_to "提交作品(#{homework.student_works.count})","javascript:void(0)", :class => 'c_grey',:style=>"cursor:not-allowed",:title => '请先关联项目再提交作品' link_to "提交作品(#{count})","javascript:void(0)", :class => 'c_grey',:style=>"cursor:not-allowed",:title => '请先关联项目再提交作品'
else else
link_to "提交作品(#{homework.student_works.count})", new_student_work_path(:homework => homework.id),:class => 'c_blue' link_to "提交作品(#{count})", new_student_work_url_without_domain(homework.id),:class => 'c_blue'
end end
elsif work.nil? && Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") < Time.now.strftime("%Y-%m-%d") elsif work.nil? && Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") < Time.now.strftime("%Y-%m-%d")
if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1 if homework.homework_type ==3 && project.nil? && homework.homework_detail_group.base_on_project == 1
link_to "补交作品(#{homework.student_works.count})","javascript:void(0)", :class => 'c_grey',:style=>"cursor:not-allowed",:title => '请先关联项目再补交作品' link_to "补交作品(#{count})","javascript:void(0)", :class => 'c_grey',:style=>"cursor:not-allowed",:title => '请先关联项目再补交作品'
else else
link_to "补交作品(#{homework.student_works.count})", new_student_work_path(:homework => homework.id),:class => 'c_red' link_to "补交作品(#{count})", new_student_work_url_without_domain(homework.id),:class => 'c_red'
end end
else else
if homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 2 #匿评作业,且作业状态不是在开启匿评之前 if homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 2 #匿评作业,且作业状态不是在开启匿评之前
link_to "作品匿评", student_work_index_path(:homework => homework.id), :class => 'c_blue', :title => "开启匿评后不可修改作品" link_to "作品匿评", student_work_index_url_in_org(homework.id), :class => 'c_blue', :title => "开启匿评后不可修改作品"
elsif homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 3 elsif homework.homework_detail_manual && homework.homework_detail_manual.comment_status == 3
link_to "查看作品(#{homework.student_works.count})", student_work_index_path(:homework => homework.id), :class => 'c_blue', :title => "匿评已结束" link_to "查看作品(#{count})",student_work_index_url_in_org(homework.id), :class => 'c_blue', :title => "匿评已结束"
elsif homework.homework_type == 2 && Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d")#编程作业不能修改作品 elsif homework.homework_type == 2 && Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d")#编程作业不能修改作品
link_to "修改作品(#{homework.student_works.count})", new_student_work_path(:homework => homework.id),:class => 'c_blue' link_to "修改作品(#{count})", new_student_work_url_without_domain(homework.id),:class => 'c_blue'
elsif Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") && work.user_id == User.current.id elsif Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d") && work.user_id == User.current.id
link_to "修改作品(#{homework.student_works.count})", edit_student_work_path(work.id),:class => 'c_blue' link_to "修改作品(#{count})", edit_student_work_url_without_domain(work.id),:class => 'c_blue'
else else
link_to "查看作品(#{homework.student_works.count})", student_work_index_path(:homework => homework.id), :class => 'c_blue', :title => "作业截止后不可修改作品" link_to "查看作品(#{count})", student_work_index_url_in_org(homework.id), :class => 'c_blue', :title => "作业截止后不可修改作品"
end end
end end
end end
else else
link_to "作品(#{homework.student_works.count})",student_work_index_path(:homework => homework.id),:class => "c_blue" link_to "作品(#{count})",student_work_index_url_in_org(homework.id),:class => "c_blue"
end end
end end
@ -2635,7 +2784,7 @@ module ApplicationHelper
#获取当前用户在指定作业下提交的作业的集合 #获取当前用户在指定作业下提交的作业的集合
def cur_user_works_for_homework homework def cur_user_works_for_homework homework
work = homework.student_works.where("user_id = ?",User.current).first work = homework.student_works.where("user_id = ? && work_status != 0",User.current).first
if homework.homework_type == 3 if homework.homework_type == 3
pro = homework.student_work_projects.where("user_id = #{User.current.id}").first pro = homework.student_work_projects.where("user_id = #{User.current.id}").first
if pro.nil? || pro.student_work_id == "" || pro.student_work_id.nil? if pro.nil? || pro.student_work_id == "" || pro.student_work_id.nil?
@ -2872,7 +3021,369 @@ int main(int argc, char** argv){
unless projects.empty? unless projects.empty?
project_ids = '('+projects.map{|pro|pro.project_id}.join(',')+')' project_ids = '('+projects.map{|pro|pro.project_id}.join(',')+')'
sort_projects = ForgeActivity.find_by_sql("SELECT MAX(updated_at) AS updated_at,user_id, project_id FROM forge_activities WHERE project_id IN #{project_ids} GROUP BY project_id ORDER BY MAX(updated_at) DESC") sort_projects = ForgeActivity.find_by_sql("SELECT MAX(updated_at) AS updated_at,user_id, project_id FROM forge_activities WHERE project_id IN #{project_ids} GROUP BY project_id ORDER BY MAX(updated_at) DESC")
#sort_projects = sort_projects.sort_by{|sp| (!sp.project.project_score.nil? && !sp.project.project_score.commit_time.nil?) ? '' : sp.project.project_score.commit_time}
return sort_projects return sort_projects
end end
end end
def project_sort_first projects
unless projects.empty?
project_ids = '('+projects.map{|pro|pro.project_id}.join(',')+')'
sort_projects = ForgeActivity.find_by_sql("SELECT updated_at,user_id, project_id FROM forge_activities WHERE project_id IN #{project_ids} ORDER BY updated_at DESC limit 1")
return sort_projects
end
end
end
def user_url_in_org(user_id)
Setting.protocol + "://" + Setting.host_name + "/users/" + user_id.to_s
end
def project_issues_url_in_org(project_id)
Setting.protocol + "://" + Setting.host_name + "/projects/" + project_id.to_s + "/issues"
end
def issue_url_in_org(id)
Setting.protocol + "://" + Setting.host_name + "/issues/" + id.to_s
end
def project_boards_url_in_org(id)
Setting.protocol + "://" + Setting.host_name + "/projects/" + id.to_s + "/boards"
end
def board_message_url_in_org(board_id, message_id)
Setting.protocol + "://" + Setting.host_name + "/boards/" + board_id.to_s + "/topics/" + message_id.to_s
end
def project_url_in_org(id)
Setting.protocol + "://" + Setting.host_name + "/projects/" + id.to_s
end
def homework_common_index_url_in_org(course_id)
Setting.protocol + "://" + Setting.host_name + "/homework_common?course=" + course_id.to_s
end
def student_work_index_url_in_org(homework_id, is_focus = '', show_work_id = '')
if is_focus != ''
Setting.protocol + "://" + Setting.host_name + "/student_work?homework=" + homework_id.to_s + "&is_focus=" + is_focus.to_s
elsif show_work_id != ''
Setting.protocol + "://" + Setting.host_name + "/student_work?homework=" + homework_id.to_s + "&show_work_id=" + show_work_id.to_s
else
Setting.protocol + "://" + Setting.host_name + "/student_work?homework=" + homework_id.to_s
end
end
def course_url_in_org(course_id)
Setting.protocol + "://" + Setting.host_name + "/courses/" + course_id.to_s
end
def user_watchlist_url_in_org(id)
Setting.protocol + "://" + Setting.host_name + "/users/" + id.to_s + "/user_watchlist"
end
def user_fanslist_url_in_org(id)
Setting.protocol + "://" + Setting.host_name + "/users/" + id.to_s + "/user_fanslist"
end
def user_blogs_url_in_org(user_id)
Setting.protocol + "://" + Setting.host_name + "/users/" + user_id.to_s + "/blogs"
end
def feedback_url_in_org(user_id)
Setting.protocol + "://" + Setting.host_name + "/users/" + user_id.to_s + "/user_newfeedback"
end
def user_activities_url_in_org(user_id)
Setting.protocol + "://" + Setting.host_name + "/users/" + user_id.to_s + "/user_activities"
end
def course_news_index_url_in_org(course_id)
Setting.protocol + "://" + Setting.host_name + "/courses/" + course_id.to_s + "/news"
end
def news_url_in_org(news_id)
Setting.protocol + "://" + Setting.host_name + "/news/" + news_id.to_s
end
def course_boards_url_in_org(course_id)
Setting.protocol + "://" + Setting.host_name + "/courses/" + course_id.to_s + "/boards"
end
def logout_url_without_domain
Setting.protocol + "://" + Setting.host_name + "/logout"
end
def signin_url_without_domain
Setting.protocol + "://" + Setting.host_name + "/login?login=true"
end
def register_url_without_domain
Setting.protocol + "://" + Setting.host_name + "/login?login=false"
end
def new_student_work_url_without_domain(homework_id)
Setting.protocol + "://" + Setting.host_name + "/student_work/new?homework=" + homework_id.to_s
end
def edit_student_work_url_without_domain(homework_id)
Setting.protocol + "://" + Setting.host_name + "/student_work/" + homework_id.to_s + "/edit"
end
def download_named_attachment_url_without_domain(id, filename, option={})
attachment_id = (Attachment === id ? id.id : id)
Setting.protocol + "://" + Setting.host_name + "/attachments/download/" + attachment_id.to_s + "/" + filename
end
def named_attachment_url_without_domain(id, filename, option={})
attachment_id = (Attachment === id ? id.id : id)
Setting.protocol + "://" + Setting.host_name + "/attachments/" + attachment_id.to_s + "/" + filename
end
#判断是否为默认的组织栏目
def is_default_field? field
(field.name == 'activity' || field.name == 'course' || field.name == 'project' ) && field.field_type == 'default'
end
def host_with_protocol
return Setting.protocol + "://" + Setting.host_name
end
def secdomain_with_protocol secdomain
return Setting.protocol + "://" + secdomain + ".trustie.net"
end
#获取回复的所有父节点
def get_reply_parents parents_rely, comment
unless comment.parent.nil?
parents_rely << comment.parent
get_reply_parents parents_rely, comment.parent
end
parents_rely
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.kind_of? BlogComment) || (jour.kind_of? OrgDocumentComment)
jour.children.each do |jour_child|
result << jour_child
get_all_children result, jour_child
end
end
if jour.respond_to?(:created_on)
result.sort! { |a,b| b.created_on <=> a.created_on }
elsif jour.respond_to?(:created_at)
result.sort! { |a,b| b.created_at <=> a.created_at }
end
result
end
#将有置顶属性的提到数组前面
def sort_by_sticky topics
tmpTopics = []
tmpIndex = 0
topics.each do |topic|
if topic.sticky == 1
tmpTopics[tmpIndex] = topic
tmpIndex = tmpIndex + 1
end
end
topics.each do |topic|
if topic.sticky == 0
tmpTopics[tmpIndex] = topic
tmpIndex = tmpIndex + 1
end
end
return tmpTopics
end
#按人气排序的时候 相同的人气必须按某种时间顺序排序 有置顶属性
def sortby_time_countcommon_hassticky topics,sortstr
tmpTopics = []
tmpTopics = topics
tStart = -1
tEnd = -1
tmpTopics_1 = []
tmpIndex = 0
tmpTopics.each_with_index do |topic,index|
if topic.sticky == 0
if tStart == -1
if (index != tmpTopics.count-1) && (topic[:infocount] == tmpTopics[index+1][:infocount])
tStart = index
end
else
if ((topic[:infocount] == tmpTopics[index-1][:infocount]) && ((index != tmpTopics.count-1) && (topic[:infocount] == tmpTopics[index+1][:infocount])))
tEnd = index
else
if (topic[:infocount] == tmpTopics[index-1][:infocount])
tEnd = index
end
if tEnd > tStart
for i in tStart..tEnd
tmpTopics_1[tmpIndex] = tmpTopics[i]
tmpIndex = tmpIndex + 1
end
if sortstr == "created_at"
tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:created_at].to_i <=> x[:created_at].to_i }
elsif sortstr == "created_on"
tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:created_on].to_i <=> x[:created_on].to_i }
elsif sortstr == "updated_at"
tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:updated_at].to_i <=> x[:updated_at].to_i }
elsif sortstr == "updated_on"
tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:updated_on].to_i <=> x[:updated_on].to_i }
end
tmpIndex = 0
for i in tStart..tEnd
tmpTopics[i] = tmpTopics_1[tmpIndex]
tmpIndex = tmpIndex + 1
end
end
tStart = -1
tEnd = -1
tmpTopics_1 = []
tmpIndex = 0
end
end
end
end
return tmpTopics
end
#按人气排序的时候 相同的人气必须按某种时间顺序排序 无置顶属性
def sortby_time_countcommon_nosticky topics,sortstr
tmpTopics = []
tmpTopics = topics
tStart = -1
tEnd = -1
tmpTopics_1 = []
tmpIndex = 0
tmpTopics.each_with_index do |topic,index|
if tStart == -1
if (index != tmpTopics.count-1) && (topic[:infocount] == tmpTopics[index+1][:infocount])
tStart = index
end
else
if ((topic[:infocount] == tmpTopics[index-1][:infocount]) && ((index != tmpTopics.count-1) && (topic[:infocount] == tmpTopics[index+1][:infocount])))
tEnd = index
else
if (topic[:infocount] == tmpTopics[index-1][:infocount])
tEnd = index
end
if tEnd > tStart
for i in tStart..tEnd
tmpTopics_1[tmpIndex] = tmpTopics[i]
tmpIndex = tmpIndex + 1
end
if sortstr == "created_at"
tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:created_at].to_i <=> x[:created_at].to_i }
elsif sortstr == "created_on"
tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:created_on].to_i <=> x[:created_on].to_i }
elsif sortstr == "updated_at"
tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:updated_at].to_i <=> x[:updated_at].to_i }
elsif sortstr == "updated_on"
tmpTopics_1 = tmpTopics_1.sort{|x,y| y[:updated_on].to_i <=> x[:updated_on].to_i }
end
tmpIndex = 0
for i in tStart..tEnd
tmpTopics[i] = tmpTopics_1[tmpIndex]
tmpIndex = tmpIndex + 1
end
end
tStart = -1
tEnd = -1
tmpTopics_1 = []
tmpIndex = 0
end
end
end
return tmpTopics
end
def strip_html(text,len=0,endss="...")
ss = ""
if !text.nil? && text.length>0
ss=text.gsub(/<\/?.*?>/, '').strip
ss = ss.gsub(/&nbsp;*/, ' ')
if len > 0 && ss.length > len
ss = ss[0, len] + endss
elsif len > 0 && ss.length <= len
ss = ss
#ss = truncate(ss, :length => len)
end
end
return ss
end
def message_content content
content = (strip_html content).strip
content = content.gsub(/\s+/, " ")
if content.gsub(" ", "") == ""
content = "[非文本消息]"
end
content
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
def course_syllabus_option user = User.current
syllabuses = user.syllabuses
type = []
option1 = []
option1 << "请选择课程"
option1 << 0
type << option1
unless syllabuses.empty?
syllabuses.each do |syllabus|
option = []
option << syllabus.title
option << syllabus.id
type << option
end
end
type
end end

@ -24,40 +24,20 @@ module CoursesHelper
def find_excelletn_course keywords, current_course def find_excelletn_course keywords, current_course
# 获取tag匹配结果ID # 获取tag匹配结果ID
a_tags = [] a_tags = []
# kc = keywords.to_a Course.where("is_excellent =? and is_public =?", 1, 1).each do |ec|
Course.visible.where("is_excellent =?", 1).each do |ec|
if ec.tags.any?{|value| current_course.name.include?(value.to_s)} if ec.tags.any?{|value| current_course.name.include?(value.to_s)}
a_tags << ec.id a_tags << ec.id
end end
end end
# sql = "SELECT distinct c.* FROM `courses` c, tags t, taggings ts where t.id = ts.tag_id and ts.taggable_id = c.id and c.is_excellent = 1 and is_delete = 0 and
# ts.taggable_type = 'Course' and t.name like '%#{keywords}%'"
# a_tags = Course.find_by_sql(sql).select{|course| course.is_public ==1 unless User.current.member_of_course?(course)}
# 通过elastic结果获取精品课程
a_courses = []
#courses = Course.search(keywords)
#courses.each do |c|
# a_courses << c.id
#end
a_courses << a_tags unless a_tags.length == 0
# 课程本身不能搜索显示自己 # 课程本身不能搜索显示自己
excellent_ids = a_courses.flatten.uniq.delete_if{|i| i == current_course.id} excellent_ids = a_tags.uniq.delete_if{|i| i == current_course.id}
limit = 5 - excellent_ids.length.to_i
sql = "SELECT distinct c.id FROM course_activities cs, courses c where cs.course_id = c.id sql = "SELECT distinct c.id FROM course_activities cs, courses c where cs.course_id = c.id
and c.is_excellent =1 and c.id != #{current_course.id} order by cs.updated_at desc;" and (c.is_excellent =1 or c.excellent_option =1) and c.is_public = 1 and c.id != #{current_course.id} order by cs.updated_at desc;"
default_ecourse_ids = Course.find_by_sql(sql).flatten default_ids = Course.find_by_sql(sql).flatten.map { |c| c.id }
# REDO:时间紧,待优化 excellent_ids << default_ids.flatten
default_ids =[] arr_result = excellent_ids.flatten.uniq.first(3)
default_ecourse_ids.each do |de| excellent_courses = Course.find(arr_result)
default_ids << de.id return excellent_courses
end
default_ids = default_ids - excellent_ids
#default_ecourse = Course.where("id is not in (?)", ids).find_by_sql(sql).flatten.delete_if{|i| i == current_course.id}.flatten
arr_result = excellent_ids << default_ids
arr_result = arr_result.flatten.first(5)
return arr_result
# 过滤条件:精品课程、本身不在搜索范围
#e_courses = Course.where("is_excellent =? and id in (?)",1, arr_result).where("id !=?", current_course.id)
end end
# 判断精品课程是否可见,非课程成员无法查看私有课程 # 判断精品课程是否可见,非课程成员无法查看私有课程
@ -71,6 +51,11 @@ module CoursesHelper
project.members.count project.members.count
end end
# 统计课程中作品的数量
def student_works_num course
StudentWork.find_by_sql("SELECT * FROM student_works WHERE homework_common_id IN (SELECT id FROM homework_commons WHERE course_id = '#{course.id}')").count
end
# 返回教师数量即roles表中定义的Manager # 返回教师数量即roles表中定义的Manager
def teacherCount project def teacherCount project
project ? project.members.count - studentCount(project).to_i : 0 project ? project.members.count - studentCount(project).to_i : 0
@ -93,18 +78,18 @@ module CoursesHelper
#生成课程老师成员链接 #生成课程老师成员链接
def course_teacher_link teacher_num def course_teacher_link teacher_num
if User.current.member_of_course?(@course) || User.current.admin? if User.current.member_of_course?(@course) || User.current.admin?
link_to "#{teacher_num}", course_member_path(@course, :role => 1), :class => 'info_foot_num c_blue', :id => 'teacher_number' link_to "#{teacher_num}", course_member_path(@course, :role => 1), :class => 'sy_cblue', :id => 'teacher_number'
else else
content_tag 'span',teacher_num, :class => 'info_foot_num c_blue' content_tag 'span',teacher_num, :class => 'sy_cblue'
end end
end end
#生成课程学生列表连接 #生成课程学生列表连接
def course_student_link student_num def course_student_link student_num
if (User.current.logged? && @course.open_student == 1) || (User.current.member_of_course?(@course)) || User.current.admin? if (User.current.logged? && @course.open_student == 1) || (User.current.member_of_course?(@course)) || User.current.admin?
link_to "#{student_num}", course_member_path(@course, :role => 2), :class => 'info_foot_num c_blue', :id => "student_number" link_to "#{student_num}", course_member_path(@course, :role => 2), :class => 'sy_cblue', :id => "student_number"
else else
content_tag 'span',student_num, :class => 'info_foot_num c_blue' content_tag 'span',student_num, :class => 'sy_cblue'
end end
end end
@ -116,7 +101,7 @@ module CoursesHelper
@course.journals_for_messages.where('m_parent_id IS NULL').count @course.journals_for_messages.where('m_parent_id IS NULL').count
end end
#当前学期 #当前学期(2015春季学期)
def current_time_and_term course def current_time_and_term course
str = "" str = ""
term = cur_course_term term = cur_course_term
@ -144,6 +129,22 @@ module CoursesHelper
val val
end end
#当前学期(2015春)
def current_time_and_term_short 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[0]
elsif course.time == Time.now.year && set_term_value(cur_course_term) <= set_term_value(course.term)
str = course.time.to_s + course.term[0]
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[0]
else
str = Time.now.year.to_s + cur_course_term[0]
end
str
end
# 返回学生数量即roles表中定义的Reporter # 返回学生数量即roles表中定义的Reporter
#def studentCount project #def studentCount project
# searchStudent(project).count # searchStudent(project).count
@ -237,7 +238,7 @@ module CoursesHelper
# 学生人数计算 # 学生人数计算
# add by nwb # add by nwb
def studentCount course def studentCount course
course ? course.student.count.to_s : 0#course.student.count course ? course.student.count.to_i : 0#course.student.count
end end
#课程成员数计算 #课程成员数计算
@ -272,12 +273,22 @@ module CoursesHelper
def searchTeacherAndAssistant project def searchTeacherAndAssistant project
#searchPeopleByRoles(project, TeacherRoles) #searchPeopleByRoles(project, TeacherRoles)
members = [] members = []
project.members.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)
members << m if m && m.user && m.user.has_teacher_role(project)
end end
members members
end end
def TeacherAndAssistantCount course
#students_count = course.student.count
#number = course.members.count - students_count
member_ids = course.members.includes(:user).blank? ? "(-1)" : "(" + course.members.includes(:user).map { |mem| mem.id}.join(",") + ")"
role_ids = "(3, 7, 9)"
number = MemberRole.where("member_id in #{member_ids} and role_id in #{role_ids}").count
#number = (searchTeacherAndAssistant course).count
end
def search_student_in_group(project, course_group_id) def search_student_in_group(project, course_group_id)
#searchPeopleByRoles(project, StudentRoles) #searchPeopleByRoles(project, StudentRoles)
members = [] members = []
@ -585,6 +596,44 @@ module CoursesHelper
Course.tagged_with(tag_name).order('updated_at desc') Course.tagged_with(tag_name).order('updated_at desc')
end end
# 获取动态列表名称
def get_acts_list_type type
case type
when "homework"
l(:label_homework_acts)
when "news"
l(:label_news_acts)
when "attachment"
l(:label_attachment_acts)
when "message"
l(:label_message_acts)
when "journalsForMessage"
l(:label_journalsForMessage_acts)
when "poll"
l(:label_poll_acts)
else
l(:label_all_cats)
end
end
#分班下拉框
def course_group_option course
type = []
option1 = []
option1 << "暂无"
option1 << 0
type << option1
unless course.course_groups.nil?
course.course_groups.each do |cg|
option = []
option << cg.name
option << cg.id
type << option
end
end
type
end
#课程实践年份下拉框 #课程实践年份下拉框
def course_time_option year def course_time_option year
type = [] type = []
@ -647,6 +696,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()
@ -727,17 +792,17 @@ module CoursesHelper
#加入课程、退出课程按钮 #加入课程、退出课程按钮
def join_in_course_header(course, user, options=[]) def join_in_course_header(course, user, options=[])
if user.logged? if user.logged?
joined = course.members.map{|member| member.user_id}.include? user.id joined = course.members.includes(:user).map{|member| member.user_id}.include? user.id
text = joined ? l(:label_course_exit_student) : l(:label_course_join_student) text = joined ? l(:label_course_exit_student) : l(:label_course_join_student)
url = joined ? join_path(:object_id => course.id) : try_join_path(:object_id => course.id) url = joined ? join_path(:object_id => course.id) : join_private_courses_courses_path()
method = joined ? 'delete' : 'post' method = joined ? 'delete' : 'post'
if joined if joined
link = link_to(text, url, :remote => true, :method => method, :class => "pr_join_a", :id => "#{course.id}", :confirm => l(:text_are_you_sure_out)) link = link_to(text, url, :remote => true, :method => method, :class => "sy_btn_grey fl", :id => "#{course.id}", :confirm => l(:text_are_you_sure_out))
else else
link = link_to(text, url, :remote => true, :method => method, :id => "#{course.id}", :class => "pr_join_a") link = link_to(text, url, :remote => true, :method => method, :id => "#{course.id}", :class => "sy_btn_grey fl")
end end
else else
link = "<span class='pr_join_span mr5' >#{l(:label_course_join_student)}</span>" link = "<a href='javascript:void(0)' class='sy_btn_grey fl ml10' >#{l(:label_course_join_student)}</a>"
end end
link.html_safe link.html_safe
end end
@ -746,13 +811,22 @@ module CoursesHelper
return[] unless course return[] unless course
result = [] result = []
course.attachments.each do |attachment| course.attachments.each do |attachment|
if attachment.is_public? ||User.current.allowed_to?(:as_teacher,Course.find(attachment.container_id))|| (User.current.member_of_course?(course) && attachment.is_publish == 1) || User.current.admin? if (attachment.is_public? && attachment.is_publish == 1) ||User.current == attachment.author ||User.current.allowed_to?(:as_teacher,course)|| (User.current.member_of_course?(course) && attachment.is_publish == 1) || User.current.admin?
result << attachment result << attachment
end end
end end
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)
@ -762,6 +836,10 @@ module CoursesHelper
result = l(:label_student) result = l(:label_student)
elsif role == "Manager" elsif role == "Manager"
result = l(:field_admin) result = l(:field_admin)
elsif role.include?("TeachingAsistant") && role.include?("Student")
result = l(:label_TA) + " " + l(:label_student)
elsif role.include?("Teacher") && role.include?("Student")
result = l(:label_teacher) + " " + l(:label_student)
end end
result result
end end
@ -823,10 +901,10 @@ module CoursesHelper
desc.html_safe desc.html_safe
end end
# 学生按作业总分排序,取前8 # 学生按作业总分排序,取前3
def hero_homework_score(course, score_sort_by) def hero_homework_score(course, score_sort_by)
sql_select = "SELECT members.*,( sql_select = "SELECT members.*,(
SELECT SUM(IF(student_works.final_score is null,null,student_works.final_score - student_works.absence_penalty - student_works.late_penalty)) SELECT SUM(work_score)
FROM student_works,homework_commons FROM student_works,homework_commons
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}
@ -835,13 +913,25 @@ module CoursesHelper
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} limit 9" WHERE members.course_id = #{course.id} ORDER BY score #{score_sort_by} limit 3"
homework_scores = Member.find_by_sql(sql_select) homework_scores = Member.find_by_sql(sql_select)
end end
def contributor_course_scor(course_id) def contributor_course_scor(course_id)
ccs = CourseContributorScore.where("course_id =?", course_id).order("total_score desc") .limit(9) ccs = CourseContributorScore.find_by_sql("SELECT * FROM `course_contributor_scores` where course_id = #{course_id} order by
(message_num*2 + message_reply_num + news_reply_num + news_num +
resource_num*5 + journal_num + homework_journal_num ) desc limit 3;")
end end
#用户在该课程是否具有某个角色
def get_user_member_roles_course course, user, role
members = course.members.where("user_id = #{user.id}")
result = false
unless members.blank?
m_roles = MemberRole.where("member_id = #{members.first.id} and role_id = #{role}")
end
result = !m_roles.blank?
result
end
end end

@ -86,6 +86,31 @@ module ExerciseHelper
return result return result
end end
def convert_to_chi_num num
result = ""
case num.to_i
when 1
result = '一'
when 2
result = '二'
when 3
result = '三'
when 4
result = '四'
when 5
result = '五'
when 6
result = '六'
when 7
result = '七'
when 8
result = '八'
when 9
result = '九'
end
return result
end
def get_current_score exercise def get_current_score exercise
score = 0 score = 0
unless exercise.nil? unless exercise.nil?

@ -121,12 +121,13 @@ module FilesHelper
def visable_attachemnts attachments def visable_attachemnts attachments
result = [] result = []
attachments.each do |attachment| attachments.each do |attachment|
if attachment.is_public? || if (attachment.is_public? && attachment.container_type != "Course") ||
(attachment.is_public? && attachment.container_type == "Course" && attachment.is_publish == 1)||
(attachment.container_type == "Project" && User.current.member_of?(attachment.project)) || (attachment.container_type == "Project" && User.current.member_of?(attachment.project)) ||
(attachment.container_type == "Course" && User.current.allowed_to?(:as_teacher,Course.find(attachment.container_id)))|| (attachment.container_type == "Course" && User.current.allowed_to?(:as_teacher,Course.find(attachment.container_id)))||
(attachment.container_type == "Course" && User.current.member_of_course?(Course.find(attachment.container_id)) && attachment.is_publish == 1)|| (attachment.container_type == "Course" && User.current.member_of_course?(Course.find(attachment.container_id)) && attachment.is_publish == 1)||
attachment.author_id == User.current.id || attachment.author_id == User.current.id ||
attachment.container_type == "OrgSubfield" (attachment.container_type == "OrgSubfield" and User.current.member_of_org?(attachment.container.organization))
result << attachment result << attachment
end end
end end

@ -19,7 +19,7 @@
module IssuesHelper module IssuesHelper
include ApplicationHelper include ApplicationHelper
include TagsHelper
def issue_list(issues, &block) def issue_list(issues, &block)
ancestors = [] ancestors = []
issues.each do |issue| issues.each do |issue|
@ -80,7 +80,7 @@ module IssuesHelper
issuetype << "support fl" issuetype << "support fl"
issuetype << "支持" issuetype << "支持"
elsif value == "功能" || value == 2 elsif value == "功能" || value == 2
issuetype << "function fl" issuetype << "issues-function fl"
issuetype << "功能" issuetype << "功能"
else else
issuetype << "weekly fl" issuetype << "weekly fl"
@ -111,9 +111,9 @@ module IssuesHelper
def principals_options_for_isuue_list(project) def principals_options_for_isuue_list(project)
if User.current.member_of?(project) if User.current.member_of?(project)
project.members.order("lower(users.login)").map{|c| [c.name, c.user_id]}.unshift(["<< #{l(:label_me)} >>", User.current.id]).unshift(["指派给", 0]) project.members.includes(:user).order("lower(users.login)").map{|c| [c.name, c.user_id]}.unshift(["<< #{l(:label_me)} >>", User.current.id]).unshift(["指派给", 0])
else else
project.members.order("lower(users.login)").map{|c| [c.name, c.user_id]}.unshift(["指派给", 0]) project.members.includes(:user).order("lower(users.login)").map{|c| [c.name, c.user_id]}.unshift(["指派给", 0])
end end
end end

@ -9,7 +9,7 @@ module OrgMemberHelper
principals = paginateHelper scope,10 principals = paginateHelper scope,10
s = content_tag('ul', project_member_check_box_tags_ex('membership[user_ids][]', principals), :class => 'mb5', :id => 'principals') s = content_tag('ul', project_member_check_box_tags_ex('membership[user_ids][]', principals), :class => 'mb5', :id => 'principals')
links = pagination_links_full(@obj_pages, @obj_count, :per_page_links => false, :remote => false, :flag => true){|text, parameters, options| links = pagination_links_full(@obj_pages, @obj_count, :per_page_links => false, :remote => false, :flag => true){|text, parameters, options|
link_to text, org_member_autocomplete_org_member_index_path(parameters.merge(:q => params[:q],:flag => true,:org=> org, :format => 'js')), :remote => true link_to text, host_with_protocol + "/org_member/org_member_autocomplete?" + parameters.merge(:q => params[:q],:flag => true,:org=> org, :format => 'js').to_query, :remote => true
} }
s + content_tag('ul', links,:class => 'wlist',:style=>'float:left !important', :id => "org_member_pagination_links" ) s + content_tag('ul', links,:class => 'wlist',:style=>'float:left !important', :id => "org_member_pagination_links" )
end end

@ -1,6 +1,7 @@
# encoding: utf-8 # encoding: utf-8
module OrganizationsHelper module OrganizationsHelper
include ApplicationHelper include ApplicationHelper
include FilesHelper
def find_user_not_in_current_org_by_name org def find_user_not_in_current_org_by_name org
@ -22,10 +23,306 @@ 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
end end
def get_message_org(org_id, field_id)
OrgDocumentComment.find_by_sql("SELECT * FROM org_document_comments where organization_id = #{org_id} and org_subfield_id = #{field_id} and parent_id is null order by updated_at desc limit 8;")
end
def get_message_reply_org(org_id, ids)
# OrgDocumentComment.find_by_sql("SELECT * FROM org_document_comments where organization_id = #{org_id} and parent_id is not null order by updated_at desc limit 1;")
OrgDocumentComment.find_by_sql("SELECT * FROM org_document_comments where organization_id = #{org_id} and parent_id in (#{ids}) order by updated_at desc limit 1;")
end
def get_attach_org(field_id)
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
# 获取两种类型的隐藏状态数量大于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)
org_attachments = field.attachments
attachments = User.current.admin? ? org_attachments.first(5) : visable_attachemnts(org_attachments).first(5)
attachments.sort_by{|x| x.created_on}.reverse
end
# 从内容中获取路径
def get_image_path_from_content content
r = Regexp.new(/src="\/files\/uploads\/image(.+?)"/)
if r.match(content).nil?
image_path = nil
else
image_path = r.match(content)[1]
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
type = []
option1 = []
option1 << "左一"
option1 << "1"
type << option1
option2 = []
option2 << "左二"
option2 << "2"
type << option2
option3 = []
option3 << "左三"
option3 << "3"
type << option3
type
end
# 课程和项目不参与某些模块的排列
def subfield_status_option_default
type = []
option1 = []
option1 << "左一"
option1 << "1"
type << option1
option2 = []
option2 << "左二"
option2 << "2"
type << option2
option3 = []
option3 << "左三"
option3 << "2"
type << option3
option4 = []
option4 << "右一"
option4 << "3"
type << option4
option5 = []
option5 << "右二"
option5 << "5"
type << option5
type
end
def subfield_list_type subfield
case subfield.to_i
when 1
resulet = "左一"
when 2
resulet = "左二"
when 3
resulet = "左二"
when 4
resulet = "右一"
when 5
resulet = "右二"
when 6
resulet = "右三"
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
unless field.nil?
org_subfield = OrgSubfield.find(field.id)
org_subfield_ids = org_subfield.org_document_comments.map(&:id) << 0
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
def org_subfield_had_created?(org, type)
sub_field = org.org_subfields.select{|subfield| subfield.field_type == type}
result = sub_field.length > 0 ? true : false
end
def org_subfield_type(field)
case field.field_type
when "Post"
result = "帖子"
when "Resource"
result = "资源"
when "Compstu"
result = "学生"
when "Comptec"
result = "教师"
when "Complex"
result = "综合"
when "Compcou"
result = "课程"
when "Comppro"
result = "项目"
when "Compact"
result = "动态"
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
results = Attachment.find_by_sql("SELECT * FROM attachments where author_id = #{user.id};").count
end
def org_teacher_course_count user
results = Course.find_by_sql("select * from courses where courses.tea_id = #{user.id}").count
end
def org_student_course_count user
course_ids = user.courses.map { |c| c.is_delete == 0 && c.id}
results = Member.find_by_sql("select id from courses where courses.tea_id = #{user.id}").count
end
def excellent_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 order by course_count desc").first(5)
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

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

Loading…
Cancel
Save