Merge branch 'dev_aliyun' into dev_cxt

chromesetting
cxt 5 years ago
commit de6056cdbb

@ -65,7 +65,7 @@ $(document).on('turbolinks:load', function() {
},
matcher: matcherFunc
});
}
};
$.ajax({
url: '/api/schools/for_option.json',

@ -107,7 +107,7 @@ $(document).on('turbolinks:load', function() {
},
templateResult: function (item) {
if(!item.id || item.id === '') return item.text;
var ele = '<span>'
var ele = '<span>';
ele += '<span>' + item.name + '</span>';
ele += '<span class="font-12"> -- ' + item.creator_name + '</span>';
ele += '<span class="font-12"> -- ' + item.status_text+ '</span>';
@ -116,10 +116,9 @@ $(document).on('turbolinks:load', function() {
return $(ele);
},
templateSelection: function(item){
if (item.id) {
}
var ele = '<span>' + (item.name || item.text) + '<span class="font-12"> -- ' + item.creator_name + '</span></span>'
return $(ele);
if(!item.id || item.id === '') return item.text;
var ele = '<span>' + (item.name || item.text) + '<span class="font-12"> -- ' + item.creator_name + '</span></span>';
return $(ele);
}
});

@ -125,7 +125,7 @@ class Competitions::CompetitionsController < Competitions::BaseController
end
@all_records = @competition.competition_teams.joins(:competition_scores).where(competition_scores: {competition_stage_id: @stage&.id.to_i})
.select("competition_teams.*, score, cost_time").order("score desc, cost_time desc")
.select("competition_teams.*, score, cost_time").order("score desc, cost_time asc")
current_team_ids = @competition.team_members.where(user_id: current_user.id).pluck(:competition_team_id).uniq
@user_ranks = @all_records.select{|com_team| current_team_ids.include?(com_team.id)}
@ -213,7 +213,7 @@ class Competitions::CompetitionsController < Competitions::BaseController
if personal
row_cells_column << record_user.real_name
row_cells_column << record_user.school_name
row_cells_column << record_user.student_id.present? ? (record_user.student_id.to_s + "\t") : "--"
row_cells_column << (record_user.student_id.present? ? (record_user.student_id.to_s + "\t") : "--")
else
row_cells_column << record.name
row_cells_column << record.teachers_name

@ -4,85 +4,83 @@ class ExerciseAnswersController < ApplicationController
include ExercisesHelper
def create #每一次答案的点击,请求一次,实训题不在这里回答
ActiveRecord::Base.transaction do
begin
q_type = @exercise_question.question_type #试卷的类型
choice_id = params[:exercise_choice_id].present? ? params[:exercise_choice_id] : ""
answer_text = params[:answer_text].present? ? params[:answer_text].strip : "" #为字符串
if q_type < Exercise::SUBJECTIVE && (q_type != Exercise::MULTIPLE) && choice_id.blank?
normal_status(-1,"请选择序号")
else
ea = @exercise_question.exercise_answers.search_answer_users("user_id",current_user.id) #试卷的当前用户的答案
if q_type == Exercise::SINGLE || q_type == Exercise::JUDGMENT #选择题(单选)/判断题
if ea.exists?
ea.first.update_attribute(:exercise_choice_id,choice_id )
else
answer_option = {
:user_id => current_user.id,
:exercise_question_id => @exercise_question.id,
:exercise_choice_id => choice_id,
:answer_text => ""
}
ex_a = ExerciseAnswer.new(answer_option)
ex_a.save!
end
elsif q_type == Exercise::MULTIPLE #多选题的
choice_ids = params[:exercise_choice_id].present? ? params[:exercise_choice_id] : []
ea_ids = ea.pluck(:exercise_choice_id)
common_answer_ids = choice_ids & ea_ids #已经存在的试卷选项id
new_ids = choice_ids - common_answer_ids # 新增的id
old_ids = ea_ids - common_answer_ids #没有选择的,则删掉
if new_ids.size > 0
new_ids.each do |e|
answer_option = {
:user_id => current_user.id,
:exercise_question_id => @exercise_question.id,
:exercise_choice_id => e,
:answer_text => ""
}
ex_a = ExerciseAnswer.new(answer_option)
ex_a.save!
end
end
if old_ids.size > 0
ea_answer = ea.search_answer_users("exercise_choice_id",old_ids)
ea_answer.destroy_all
end
elsif q_type == Exercise::COMPLETION #填空题
answer_option = {
:user_id => current_user.id,
:exercise_question_id => @exercise_question.id,
:exercise_choice_id => choice_id,
:answer_text => answer_text
}
ea_answer = ea.search_answer_users("exercise_choice_id",choice_id)
if ea.present? && ea_answer.present?
ea_answer.update(answer_option)
else
ex_new = ExerciseAnswer.new(answer_option)
ex_new.save!
end
elsif q_type == Exercise::SUBJECTIVE #简答题
begin
q_type = @exercise_question.question_type #试卷的类型
choice_id = params[:exercise_choice_id].present? ? params[:exercise_choice_id] : ""
answer_text = params[:answer_text].present? ? params[:answer_text].strip : "" #为字符串
if q_type < Exercise::SUBJECTIVE && (q_type != Exercise::MULTIPLE) && choice_id.blank?
normal_status(-1,"请选择序号")
else
ea = @exercise_question.exercise_answers.search_answer_users("user_id",current_user.id) #试卷的当前用户的答案
if q_type == Exercise::SINGLE || q_type == Exercise::JUDGMENT #选择题(单选)/判断题
if ea.exists?
ea.first.update_attribute(:exercise_choice_id,choice_id )
else
answer_option = {
:user_id => current_user.id,
:exercise_question_id => @exercise_question.id
:user_id => current_user.id,
:exercise_question_id => @exercise_question.id,
:exercise_choice_id => choice_id,
:answer_text => ""
}
if ea.present? #已经回答了的,
ea.first.update_attribute("answer_text",answer_text)
else
answer_option.merge!(answer_text:answer_text)
ex_a = ExerciseAnswer.new(answer_option)
ex_a.save!
end
elsif q_type == Exercise::MULTIPLE #多选题的
choice_ids = params[:exercise_choice_id].present? ? params[:exercise_choice_id] : []
ea_ids = ea.pluck(:exercise_choice_id)
common_answer_ids = choice_ids & ea_ids #已经存在的试卷选项id
new_ids = (choice_ids - common_answer_ids).uniq # 新增的id
old_ids = (ea_ids - common_answer_ids).uniq #没有选择的,则删掉
if new_ids.size > 0
new_ids.each do |e|
answer_option = {
:user_id => current_user.id,
:exercise_question_id => @exercise_question.id,
:exercise_choice_id => e,
:answer_text => ""
}
ex_a = ExerciseAnswer.new(answer_option)
ex_a.save!
end
end
normal_status(0,"回答成功")
if old_ids.size > 0
ea_answer = ea.search_answer_users("exercise_choice_id",old_ids)
ea_answer.destroy_all
end
elsif q_type == Exercise::COMPLETION #填空题
answer_option = {
:user_id => current_user.id,
:exercise_question_id => @exercise_question.id,
:exercise_choice_id => choice_id,
:answer_text => answer_text
}
ea_answer = ea.search_answer_users("exercise_choice_id",choice_id)
if ea.present? && ea_answer.present?
ea_answer.update(answer_option)
else
ex_new = ExerciseAnswer.new(answer_option)
ex_new.save!
end
elsif q_type == Exercise::SUBJECTIVE #简答题
answer_option = {
:user_id => current_user.id,
:exercise_question_id => @exercise_question.id
}
if ea.present? #已经回答了的,
ea.first.update_attribute("answer_text",answer_text)
else
answer_option.merge!(answer_text:answer_text)
ex_a = ExerciseAnswer.new(answer_option)
ex_a.save!
end
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception("页面调用失败!")
raise ActiveRecord::Rollback
normal_status(0,"回答成功")
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception("页面调用失败!")
raise ActiveRecord::Rollback
end
end

@ -20,8 +20,8 @@ class HomeController < ApplicationController
shixuns = shixuns.where(homepage_show: true)
subjects = subjects.where(homepage_show: true)
else
shixuns = shixuns.where(laboratory_shixuns: { homepage: true })
subjects = subjects.where(laboratory_subjects: { homepage: true })
shixuns = shixuns.joins(:laboratory_shixuns).where(laboratory_shixuns: { homepage: true, laboratory_id: current_laboratory.id})
subjects = subjects.joins(:laboratory_subjects).where(laboratory_subjects: { homepage: true, laboratory_id: current_laboratory.id})
end
@shixuns = shixuns.includes(:tag_repertoires, :challenges).limit(8)

@ -294,7 +294,7 @@ class HomeworkCommonsController < ApplicationController
HomeworksService.new.update_myshixun_work_score work, myshixun, games, @homework, challenge_settings
normal_status("更新成功")
else
normal_status("开启挑战,暂不能更新成绩")
normal_status("开启挑战,暂不能更新成绩")
end
rescue Exception => e
uid_logger(e.message)
@ -591,6 +591,10 @@ class HomeworkCommonsController < ApplicationController
# tip_exception("challenge_id参数的长度与challenge_score参数的长度不匹配") if
# params[:challenge_settings][:challenge_score].length != params[:challenge_settings][:challenge_id].length
sum_challenge_score = params[:challenge_settings].pluck(:challenge_score).reject(&:blank?).map{|score| score.to_f}.sum
total_score = params[:work_efficiency] ? (params[:eff_score].to_f + sum_challenge_score) : sum_challenge_score
tip_exception("分值之和必须等于总分值:#{params[:total_score]}") if params[:total_score].to_f.round(2) != total_score.to_f.round(2)
current_eff_score = @homework.eff_score.to_f.round(2)
@homework.total_score = params[:total_score]
@homework.work_efficiency = params[:work_efficiency]

@ -6,119 +6,117 @@ class PollVotesController < ApplicationController
def create #每一次答案的点击,请求一次
ActiveRecord::Base.transaction do
begin
question_votes = @poll_question.poll_votes
question_type = @poll_question.question_type
question_answer_id = params[:poll_answer_id] ? params[:poll_answer_id] : nil #该答案的id
question_answer_text = params[:vote_text].present? ? params[:vote_text] : nil #其他选项的内容
user_votes = question_votes.find_current_vote("user_id",current_user.id) #当前用户的答案,可能有多个
# 当前用户的当前答案,如果已存在,当再次点击的时候,取消答案,即删除该答案
current_vote_text = nil
begin
question_votes = @poll_question.poll_votes
question_type = @poll_question.question_type
question_answer_id = params[:poll_answer_id] ? params[:poll_answer_id] : -1 #该答案的id
question_answer_text = params[:vote_text].present? ? params[:vote_text] : nil #其他选项的内容
user_votes = question_votes.find_current_vote("user_id",current_user.id) #当前用户的答案,可能有多个
# 当前用户的当前答案,如果已存在,当再次点击的时候,取消答案,即删除该答案
current_vote_text = nil
# if user_votes.find_vote_text.present?
# current_vote_text = user_votes.find_vote_text.first
# end
# if user_votes.find_vote_text.present?
# current_vote_text = user_votes.find_vote_text.first
# end
vote_answer_params = {
:user_id => current_user.id,
:poll_question_id => @poll_question.id,
:poll_answer_id => question_answer_id,
:vote_text => question_answer_text
}
#begin
if question_type == 1
if user_votes.present? #用户曾经回答过的,答案选择不一样,否则新建
current_user_answer = user_votes.first
if current_user_answer&.poll_answer_id != question_answer_id #如果说更换了答案,则以前的答案删除,并新建记录
current_user_answer.destroy
PollVote.create(vote_answer_params)
else
vote_answer_params = {
:user_id => current_user.id,
:poll_question_id => @poll_question.id,
:poll_answer_id => question_answer_id,
:vote_text => question_answer_text
}
#begin
if question_type == 1
if user_votes.present? #用户曾经回答过的,答案选择不一样,否则新建
current_user_answer = user_votes.first
if current_user_answer&.poll_answer_id != question_answer_id #如果说更换了答案,则以前的答案删除,并新建记录
current_user_answer.destroy
PollVote.create(vote_answer_params)
else
if question_answer_text.present?
current_user_answer.update_attribute("vote_text", question_answer_text)
end
if question_answer_text.present?
current_user_answer.update_attribute("vote_text", question_answer_text)
end
else
PollVote.create(vote_answer_params)
end
elsif question_type == 2 #多选题的话答案应该是1个以上
question_answer_ids = params[:poll_answer_id] ? params[:poll_answer_id] : [] #该答案的id
if question_answer_ids.present?
if question_answer_text.present? #有文字输入,但是不存在其他选项的
ques_vote_id = question_answer_ids.map(&:to_i).max
if user_votes.find_vote_text.present?
current_vote_text = user_votes.find_vote_text.first
current_vote_text.update_attribute("vote_text", question_answer_text)
else
answer_option = {
:user_id => current_user.id,
:poll_question_id => @poll_question.id,
:poll_answer_id => ques_vote_id,
:vote_text => question_answer_text
}
PollVote.create(answer_option)
end
# if current_vote_text.present? #已有其他输入文字的选项
# current_vote_text.update_attribute("vote_text", question_answer_text)
# else
#
# end
else
PollVote.create(vote_answer_params)
end
elsif question_type == 2 #多选题的话答案应该是1个以上
question_answer_ids = params[:poll_answer_id] ? params[:poll_answer_id] : [] #该答案的id
if question_answer_ids.present?
if question_answer_text.present? #有文字输入,但是不存在其他选项的
ques_vote_id = question_answer_ids.map(&:to_i).max
if user_votes.find_vote_text.present?
current_vote_text = user_votes.find_vote_text.first
current_vote_text.update_attribute("vote_text", question_answer_text)
else
answer_option = {
:user_id => current_user.id,
:poll_question_id => @poll_question.id,
:poll_answer_id => ques_vote_id,
:vote_text => question_answer_text
}
PollVote.create(answer_option)
end
# if current_vote_text.present? #已有其他输入文字的选项
# current_vote_text.update_attribute("vote_text", question_answer_text)
# else
#
# end
end
ea_ids = user_votes.pluck(:poll_answer_id)
common_answer_ids = question_answer_ids & ea_ids #已经存在的试卷选项id
new_ids = question_answer_ids - common_answer_ids # 新增的id
old_ids = ea_ids - common_answer_ids #没有选择的,则删掉
if new_ids.size > 0
new_ids.each do |e|
answer_option = {
:user_id => current_user.id,
:poll_question_id => @poll_question.id,
:poll_answer_id => e,
:vote_text => nil
}
ex_a = PollVote.new(answer_option)
ex_a.save!
end
end
if old_ids.size > 0
ea_answer = user_votes.find_current_vote("poll_answer_id",old_ids)
ea_answer.destroy_all
ea_ids = user_votes.pluck(:poll_answer_id)
common_answer_ids = question_answer_ids & ea_ids #已经存在的试卷选项id
new_ids = question_answer_ids - common_answer_ids # 新增的id
old_ids = ea_ids - common_answer_ids #没有选择的,则删掉
if new_ids.size > 0
new_ids.each do |e|
answer_option = {
:user_id => current_user.id,
:poll_question_id => @poll_question.id,
:poll_answer_id => e,
:vote_text => nil
}
ex_a = PollVote.new(answer_option)
ex_a.save!
end
else
user_votes.destroy_all
end
else #主观题的输入
# current_vote_text = user_votes.find_vote_text
if user_votes.present?
user_votes.first.update_attribute("vote_text", question_answer_text)
# if question_answer_text.present?
# user_votes.first.update_attribute("vote_text", question_answer_text)
# else
# user_votes.destroy_all
# end
else
PollVote.create(vote_answer_params)
if old_ids.size > 0
ea_answer = user_votes.find_current_vote("poll_answer_id",old_ids)
ea_answer.destroy_all
end
else
user_votes.destroy_all
end
@current_question_number = @poll_question.question_number
@current_question_necessary = @poll_question.is_necessary
#问答记录存在,且有值,才会有返回值。
@current_question_status = 0
new_user_votes = question_votes.where(user_id: current_user.id)
if new_user_votes.present?
vote_answer_id = new_user_votes.pluck(:poll_answer_id).reject(&:blank?).size
vote_text_count = new_user_votes.pluck(:vote_text).reject(&:blank?).size
if vote_text_count > 0 || vote_answer_id > 0
@current_question_status = 1
end
else #主观题的输入
# current_vote_text = user_votes.find_vote_text
if user_votes.present?
user_votes.first.update_attribute("vote_text", question_answer_text)
# if question_answer_text.present?
# user_votes.first.update_attribute("vote_text", question_answer_text)
# else
# user_votes.destroy_all
# end
else
PollVote.create(vote_answer_params)
end
end
@current_question_number = @poll_question.question_number
@current_question_necessary = @poll_question.is_necessary
#问答记录存在,且有值,才会有返回值。
@current_question_status = 0
new_user_votes = question_votes.where(user_id: current_user.id)
if new_user_votes.present?
vote_answer_id = new_user_votes.pluck(:poll_answer_id).reject(&:blank?).size
vote_text_count = new_user_votes.pluck(:vote_text).reject(&:blank?).size
if vote_text_count > 0 || vote_answer_id > 0
@current_question_status = 1
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception("页面调用失败!")
raise ActiveRecord::Rollback
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception("页面调用失败!")
raise ActiveRecord::Rollback
end
end

@ -6,7 +6,9 @@ class Weapps::CodeSessionsController < Weapps::BaseController
logged = false
result = Wechat::Weapp.jscode2session(params[:code])
Rails.logger.info("###########result: #{result}")
Rails.logger.info("###########result: #{result['session_key']}")
Rails.logger.info("###########result: #{result['unionid']}")
# 能根据 code 拿到 unionid
open_user = OpenUsers::Wechat.find_by(uid: result['unionid'])
if open_user.present? && open_user.user

@ -1,6 +1,7 @@
class Weapps::CoursesController < Weapps::BaseController
before_action :require_login
before_action :set_course, :user_course_identity, except: [:create]
before_action :check_account, only: [:create]
before_action :teacher_allowed, only: [:edit, :update]
before_action :teacher_or_admin_allowed, only: [:change_member_roles, :delete_course_teachers]

@ -48,8 +48,9 @@ class Laboratory < ApplicationRecord
def shixuns
if main_site?
Shixun.where.not(id: laboratory_shixuns.pluck(:shixun_id))
elsif sync_subject
not_shixun_ids = Shixun.joins(:laboratory_shixuns).where("laboratory_shixuns.laboratory_id != #{Laboratory.current.id}")
Shixun.where.not(id: not_shixun_ids.pluck(:shixun_id))
elsif sync_shixun
laboratory_shixun_ids = laboratory_shixuns.pluck(:shixun_id)
school_shixun_ids = Shixun.joins("join user_extensions on shixuns.user_id=user_extensions.user_id").where(user_extensions: { school_id: school_id }).pluck(:id)
shixun_ids = laboratory_shixun_ids + school_shixun_ids
@ -61,7 +62,8 @@ class Laboratory < ApplicationRecord
def subjects
if main_site?
Subject.where.not(id: laboratory_subjects.pluck(:subject_id))
not_subject_ids = Subject.joins(:laboratory_subjects).where("laboratory_subjects.laboratory_id != #{Laboratory.current.id}")
Subject.where.not(id: not_subject_ids.pluck(:subject_id))
elsif sync_subject
laboratory_subject_ids = laboratory_subjects.pluck(:subject_id)
school_subject_ids = Subject.joins("join user_extensions on subjects.user_id=user_extensions.user_id").where(user_extensions: { school_id: school_id }).pluck(:id)

@ -3,6 +3,12 @@ class ApplicationService
Error = Class.new(StandardError)
def regix_emoji content
" " if content.blank?
regex = /[^a-zA-Z0-9\u4E00-\u9FFF]/
content.gsub(regex, '')
end
private
def strip(str)

@ -17,7 +17,8 @@ class Oauth::CreateOrFindQqAccountService < ApplicationService
new_user = true
# 新用户
login = User.generate_login('Q')
@user = User.new(login: login, nickname: params.dig('info', 'nickname'), type: 'User', status: User::STATUS_ACTIVE)
#nickname = regix_emoji params.dig('info', 'nickname')
@user = User.new(login: login, type: 'User', status: User::STATUS_ACTIVE)
end
ActiveRecord::Base.transaction do
@ -31,7 +32,7 @@ class Oauth::CreateOrFindQqAccountService < ApplicationService
Util.download_file(params.dig('info', 'image'), avatar_path)
end
new_open_user = OpenUsers::QQ.create!(user: user, uid: params['uid'], extra: params.dig('extra', 'raw_info'))
new_open_user = OpenUsers::QQ.create!(user: user, uid: params['uid'])
Rails.cache.write(new_open_user.can_bind_cache_key, 1, expires_in: 1.hours) if new_user # 方便后面进行账号绑定
end

@ -24,7 +24,10 @@ class Oauth::CreateOrFindWechatAccountService < ApplicationService
new_user = true
# 新用户
login = User.generate_login('w')
@user = User.new(login: login, nickname: result['nickname'], type: 'User', status: User::STATUS_ACTIVE)
# result['nickname'] = regix_emoji(result['nickname'])
@user = User.new(login: login, type: 'User', status: User::STATUS_ACTIVE)
#@user = User.new(login: login, nickname: result['nickname'], type: 'User', status: User::STATUS_ACTIVE)
end
ActiveRecord::Base.transaction do
@ -39,7 +42,7 @@ class Oauth::CreateOrFindWechatAccountService < ApplicationService
Util.download_file(result['headimgurl'], avatar_path)
end
new_open_user= OpenUsers::Wechat.create!(user: user, uid: result['unionid'], extra: result)
new_open_user= OpenUsers::Wechat.create!(user: user, uid: result['unionid'])
Rails.cache.write(new_open_user.can_bind_cache_key, 1, expires_in: 1.hours) if new_user # 方便后面进行账号绑定
end

@ -44,7 +44,7 @@ class SearchService < ApplicationService
when 'subject' then
{ where: { id: Laboratory.current.subjects.pluck(:id) } }
when 'course' then
{ where: { id: Laboratory.current.all_courses } }
{ where: { id: Laboratory.current.all_courses.pluck(:id) } }
else
{}
end

@ -20,7 +20,7 @@ class ShixunSearchService < ApplicationService
if type == "mine"
@shixuns = @shixuns.where(id: User.current.shixuns)
else
if User.current.admin? || User.current.business?
if User.current.admin? || User.current.business? || !User.current.school_id
@shixuns = @shixuns.where(hidden: 0)
else
none_shixun_ids = ShixunSchool.where("school_id != #{User.current.school_id}").pluck(:shixun_id)

@ -21,7 +21,7 @@ class Users::ShixunService
def category_scope_shixuns
case params[:category]
when 'study' then
laboratory.shixuns.where(id: user.study_shixuns)
user.study_shixuns.where(shixuns: {id: laboratory.shixuns})
when 'manage' then
laboratory.shixuns.where(id: user.shixuns)
else
@ -43,8 +43,6 @@ class Users::ShixunService
def user_policy_filter(relations)
# 只有自己或者管理员才有过滤筛选及查看全部状态下实训功能
Rails.logger.info("self_or_admin?: #{self_or_admin?}")
Rails.logger.info("user: #{user.id}")
if self_or_admin?
relations = relations.where.not(status: -1)
status_filter(relations)

@ -18,6 +18,7 @@ json.shixun_list do
json.title highlights.delete(:name)&.join('...') || obj.searchable_title
json.description highlights[:description]&.join('...') || Util.extract_content(obj.description)[0..300]&.gsub(atta_reg, '')
json.pic url_to_avatar(obj)
json.content highlights
json.level level_to_s(obj.trainee)
json.subjects obj.subjects.uniq do |subject|

@ -6,6 +6,7 @@ json.members_count course.course_members_count
json.homework_commons_count get_tasks_count course
json.attachments_count course.attachments.count
json.visits course.visits
json.school course.school&.name
json.first_category_url module_url(course.course_modules.where(hidden: 0).order(position: :desc).first, course)

@ -0,0 +1,17 @@
class AddUniqIndexToExerciseAnswer < ActiveRecord::Migration[5.2]
def change
remove_index :exercise_answers, column: [:exercise_question_id, :user_id]
change_column_default :exercise_answers, :exercise_choice_id, from: nil, to: -1
ExerciseAnswer.where(exercise_choice_id: nil).update_all(exercise_choice_id: -1)
sql = %Q(delete from exercise_answers where (exercise_question_id, user_id, exercise_choice_id) in
(select * from (select exercise_question_id, user_id, exercise_choice_id from exercise_answers group by exercise_question_id, user_id, exercise_choice_id having count(*) > 1) a)
and id not in (select * from (select min(id) from exercise_answers group by exercise_question_id, user_id, exercise_choice_id having count(*) > 1 order by id) b))
ActiveRecord::Base.connection.execute sql
add_index :exercise_answers, [:exercise_question_id, :user_id, :exercise_choice_id], name: 'exercise_choice_index', unique: true
end
end

@ -0,0 +1,16 @@
class AddUniqIndexToPollVotes < ActiveRecord::Migration[5.2]
def change
remove_index :poll_votes, column: [:poll_question_id, :user_id]
change_column_default :poll_votes, :poll_question_id, from: nil, to: -1
PollVote.where(poll_answer_id: nil).update_all(poll_answer_id: -1)
sql = %Q(delete from poll_votes where (poll_question_id, user_id, poll_answer_id) in
(select * from (select poll_question_id, user_id, poll_answer_id from poll_votes group by poll_question_id, user_id, poll_answer_id having count(*) > 1) a)
and id not in (select * from (select min(id) from poll_votes group by poll_question_id, user_id, poll_answer_id having count(*) > 1 order by id) b))
ActiveRecord::Base.connection.execute sql
add_index :poll_votes, [:poll_question_id, :user_id, :poll_answer_id], name: 'poll_answer_index', unique: true
end
end

File diff suppressed because one or more lines are too long

@ -139935,6 +139935,29 @@ $(document).on('turbolinks:load', function() {
}
})
;
$(document).on('turbolinks:load', function(){
if ($('body.admins-shixun-feedback-messages-index-page').length > 0) {
var baseOptions = {
autoclose: true,
language: 'zh-CN',
format: 'yyyy-mm-dd 00:00:00',
startDate: '2017-04-01'
}
var defineDateRangeSelect = function(element){
var options = $.extend({inputs: $(element).find('.start-date, .end-date')}, baseOptions);
$(element).datepicker(options);
$(element).find('.start-date').datepicker().on('changeDate', function(e){
$(element).find('.end-date').datepicker('setStartDate', e.date);
})
};
defineDateRangeSelect('.grow-date-input-daterange');
}
})
;
$(document).on('turbolinks:load', function() {
if ($('body.admins-shixun-settings-index-page').length > 0) {
let searchContainer = $(".shixun-settings-list-form");

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -11,7 +11,8 @@ const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
// const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
// const TerserPlugin = require('terser-webpack-plugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');
@ -55,6 +56,10 @@ const extractTextPluginOptions = shouldUseRelativeAssetPaths
// 上线用的
// console.log('publicPath ', publicPath)
module.exports = {
// optimization: {
// minimize: true,
// minimizer: [new TerserPlugin()],
// },
// externals: {
// 'react': 'window.React'
// },
@ -372,7 +377,7 @@ module.exports = {
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new MonacoWebpackPlugin(),
// new MonacoWebpackPlugin(),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.

@ -15,6 +15,7 @@ import actions from '../../redux/actions';
import MultipTags from './components/multiptags';
import { Link } from 'react-router-dom';
import CONST from '../../constants';
import { withRouter } from 'react-router';
const {tagBackground, diffText} = CONST;
const { Search } = Input;
@ -96,66 +97,67 @@ const testMaps = {
}
}
/**
* 表格列
*/
const options = {
title: '操作',
key: 'action',
fixed: 'right',
width: 100,
render: (text, record) => (
<span>
<Button type="primary">
<Link to={`/problems/${record.identifier}/edit`}>编辑</Link>
</Button>
</span>
),
}
const columns = [
{
title: '标题',
dataIndex: 'name',
render: (name, record) => <Link style={{ color: '#459be5' }} to={`/myproblems/${record.identifier}`}>{name}</Link>
},
{
title: '分类',
dataIndex: 'category',
width: '20%',
align: 'center',
render: (category) => <span>{category ? testMaps['category'][+category] : '-'}</span>
},
{
title: '难度',
dataIndex: 'difficult',
align: 'center',
width: '15%',
render: (difficult) => {
if (difficult) {
return <Tag color={tagBackground[+difficult]}>{diffText[+difficult]}</Tag>
} else {
return '-';
class DeveloperHome extends React.PureComponent {
/**
* 表格列
*/
options = {
title: '操作',
key: 'action',
fixed: 'right',
width: 100,
render: (text, record) => (
<span>
<Button type="primary">
<Link to={`/problems/${record.identifier}/edit`}>编辑</Link>
</Button>
</span>
),
}
columns = [
{
title: '标题',
dataIndex: 'name',
render: (name, record) => <Button type="link" onClick={() => this.handleNameClick(record)} className={'oj_item_name'}>{name}</Button>
},
{
title: '分类',
dataIndex: 'category',
width: '20%',
align: 'center',
render: (category) => <span>{category ? testMaps['category'][+category] : '-'}</span>
},
{
title: '难度',
dataIndex: 'difficult',
align: 'center',
width: '15%',
render: (difficult) => {
if (difficult) {
return <Tag color={tagBackground[+difficult]}>{diffText[+difficult]}</Tag>
} else {
return '-';
}
}
}
},
{
title: '热度',
dataIndex: 'hack_user_lastest_codes_count',
sorter: true,
align: 'center',
width: '10%'
},
{
title: '通过率',
dataIndex: 'passed_rate',
sorter: true,
align:'right',
width: '10%',
render: val => <span>{`${val}%`}</span>
},
];
},
{
title: '热度',
dataIndex: 'hack_user_lastest_codes_count',
sorter: true,
align: 'center',
width: '10%'
},
{
title: '通过率',
dataIndex: 'passed_rate',
sorter: true,
align:'right',
width: '10%',
render: val => <span>{`${val}%`}</span>
},
];
class DeveloperHome extends React.PureComponent {
state = {
data: [],
loading: false,
@ -170,7 +172,7 @@ class DeveloperHome extends React.PureComponent {
page: 1, // 当前页数
limit: 10 // 每页显示条件
},
columns: columns,
columns: this.columns,
searchInfo: []
};
@ -179,7 +181,7 @@ class DeveloperHome extends React.PureComponent {
const { isMySource } = this.props;
if (isMySource) {
this.handleFilterSearch({come_from: 'mine'});
let _columns = columns.concat([options]);
let _columns = this.columns.concat([this.options]);
this.setState({
columns: _columns
});
@ -309,13 +311,13 @@ class DeveloperHome extends React.PureComponent {
this.handleFilterSearch({come_from: item.key === 'all' ? '' : item.key});
if (item.key !== 'all') {
let _columns = columns.concat([options]);
let _columns = this.columns.concat([this.options]);
this.setState({
columns: _columns
});
} else {
this.setState({
columns: columns
columns: this.columns
})
}
}
@ -333,10 +335,19 @@ class DeveloperHome extends React.PureComponent {
});
if (info.type === 'come_from' && info.key === 'mine') {
this.setState({
columns: columns
columns: this.columns
});
}
}
// 点击name
handleNameClick = (record) => {
console.log('name has click', record);
// 先调用start接口获取返回的 identifier, 再跳转到开启编辑
this.props.startProgramQuestion(record.identifier, this.props);
}
render () {
// const { testReducer, handleClick } = this.props;
const {
@ -453,10 +464,11 @@ const mapDispatchToProps = (dispatch) => ({
handleClick: () => dispatch(actions.toggleTodo()),
fetchOJList: (params) => dispatch(actions.getOJList(params)),
changePaginationInfo: (obj) => dispatch(actions.changePaginationInfo(obj)),
startProgramQuestion: (id, props) => dispatch(actions.startProgramQuestion(id, props))
});
export default connect(
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(DeveloperHome);
)(DeveloperHome));
// export default DeveloperHome;

@ -72,4 +72,8 @@
color: #fff;
}
}
.oj_item_name{
color: #459be5;
cursor: pointer;
}
}

@ -4,7 +4,7 @@
* @Github:
* @Date: 2019-11-25 09:46:03
* @LastEditors: tangjiang
* @LastEditTime: 2019-11-27 19:28:50
* @LastEditTime: 2019-11-29 15:04:12
*/
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.bubble.css';
@ -38,7 +38,6 @@ const defaultOptions = [
* @description 抽取一个React编辑器组件基于Quill
* @class QuillEditor类
* @param [object] props 接收的属性
*
* props: {
* options: {} // 编辑器配置信息, 不传使用 defaultOptions, 传了的话 使用用户自定义的,
* placeholder: '' // 编辑器提示信息
@ -71,7 +70,7 @@ class QuillEditor extends React.Component {
toolbar: renderOptions
},
readOnly,
theme: 'snow',
theme: readOnly ? 'bubble' : 'snow',
}
// 实例化 Quill 编辑器
quillEditor = new Quill(this.editorRef.current, editorOption);
@ -122,12 +121,15 @@ class QuillEditor extends React.Component {
render () {
const styles = this.props.style || {}
return (
<div
id="quill_editor"
style={styles}
className={'quill_editor_area'}
ref={this.editorRef}>
<div>
<div
id="quill_editor"
style={styles}
className={'quill_editor_area'}
ref={this.editorRef}>
</div>
</div>
);
}
}

@ -1,3 +1,4 @@
.quill_editor_area{
height: 300px;
overflow-y: auto;
}

@ -4,7 +4,7 @@
* @Github:
* @Date: 2019-11-23 10:53:19
* @LastEditors: tangjiang
* @LastEditTime: 2019-11-29 08:56:18
* @LastEditTime: 2019-11-29 20:00:34
*/
import './index.scss';
import React, { useEffect } from 'react';
@ -20,9 +20,10 @@ import actions from '../../../redux/actions';
const StudentStudy = (props) => {
useEffect(() => {
const { match: { params }, startProgramQuestion } = props;
const { match: { params }, getUserProgramDetail } = props;
let { id } = params;
startProgramQuestion(id);
// startProgramQuestion(id);
getUserProgramDetail(id);
}, []);
return (
<div className={'student_study_warp'}>
@ -61,7 +62,9 @@ const mapStateToProps = (state) => ({});
const mapDispatchToProps = (dispatch) => ({
// 调用开启编辑
startProgramQuestion: (id) => dispatch(actions.startProgramQuestion(id))
// startProgramQuestion: (id) => dispatch(actions.startProgramQuestion(id))
// 调用编程题详情
getUserProgramDetail: (id) => dispatch(actions.getUserProgramDetail(id))
});
export default connect(

@ -4,7 +4,7 @@
* @Github:
* @Date: 2019-11-27 09:49:30
* @LastEditors: tangjiang
* @LastEditTime: 2019-11-27 19:36:41
* @LastEditTime: 2019-11-29 13:46:11
*/
import '../index.scss';
import React from 'react';

@ -33,13 +33,15 @@ function getModeByMirrorName(mirror_name) {
return mode;
}
const _extraKeys = {"Alt-/": "autocomplete"};
function createCMOptions(mirror_name) {
function createCMOptions(mirror_name, theme) {
let mode = getModeByMirrorName(mirror_name)
let cmOptions = {
lineNumbers: true,
mode: mode,
theme: "railscasts",
// theme: "railscasts",
// theme: "vs-dark",
theme: theme,
indentUnit:4,
matchBrackets: true,
autoRefresh: true,
@ -97,6 +99,7 @@ class TPICodeMirror extends Component {
super(props)
this.state = {
cmFontSize: fromStore('cmFontSize', 16),
cmCodeMode: fromStore('cmCodeMode', 'vs-dark'),
autoCompleteSwitch: fromStore('autoCompleteSwitch', true),
}
}
@ -114,7 +117,7 @@ class TPICodeMirror extends Component {
}
}
componentDidMount() {
let cmOptions = createCMOptions(this.props.mirror_name)
let cmOptions = createCMOptions(this.props.mirror_name, this.state.cmCodeMode)
extend_editor = window.CodeMirror.fromTextArea(window.$('#extend-challenge-file-edit')[0]
, cmOptions);
@ -241,6 +244,12 @@ class TPICodeMirror extends Component {
this.setState({ cmFontSize: value });
}
onCodeModeChange = (value) => {
toStore('cmCodeMode', value);
this.setState({ cmCodeMode: value });
window.monaco.editor.setTheme(value);
}
render() {
const { repositoryCode, showSettingDrawer, settingDrawerOpen } = this.props;
const { cmFontSize } = this.state;
@ -259,6 +268,7 @@ class TPICodeMirror extends Component {
>
<TPICodeSetting {...this.props} {...this.state}
onFontSizeChange={this.onFontSizeChange}
onCodeModeChange={this.onCodeModeChange}
onAutoCompleteSwitchChange={this.onAutoCompleteSwitchChange}
></TPICodeSetting>
</Drawer>

@ -18,12 +18,12 @@ class TPICodeSetting extends Component {
render() {
const { autoCompleteSwitch, onAutoCompleteSwitchChange, onFontSizeChange
, cmFontSize,
, cmFontSize, cmCodeMode,
onCodeModeChange,
shixun } = this.props;
const task_pass = shixun.task_pass
const forbid_copy = shixun.forbid_copy
const test_set_permission = shixun.test_set_permission
return (
<div className="ide-settings--content">
<style>{`
@ -54,6 +54,25 @@ class TPICodeSetting extends Component {
</div>
</div>
</div>*/}
<div className="-layout-h -center -justify-between">
<div className="ide-settings--item-key">显示模式</div>
<div className="ide-settings--item-value">
<div className="select -view-flat -value">
<div className="-layout-v -start">
<div className="select--wrapper -layout-h -center -justify" >
<Select
style={{ width: '120px' }}
value={cmCodeMode}
onChange={onCodeModeChange}
>
<Option value={'vs'}>白色背景</Option>
<Option value={'vs-dark'}>黑色背景</Option>
</Select>
</div>
</div>
</div>
</div>
</div>
<div className="-layout-h -center -justify-between">
<div className="ide-settings--item-key">字体大小</div>
<div className="ide-settings--item-value">
@ -61,6 +80,7 @@ class TPICodeSetting extends Component {
<div className="-layout-v -start">
<div className="select--wrapper -layout-h -center -justify" >
<Select
style={{ width: '120px' }}
value={cmFontSize}
onChange={onFontSizeChange}>
<Option value={12}>12px</Option>

@ -93,7 +93,7 @@
.monaco-editor .monaco-editor-hover code { background-color: rgba(10, 10, 10, 0.4); }
.monaco-editor .goto-definition-link { color: #4e94ce !important; }
.mtk1 { color: #d4d4d4 !important; }
/* .mtk1 { color: #d4d4d4 !important; }
.mtk2 { color: #1e1e1e !important; }
.mtk3 { color: #cc6666 !important; }
.mtk4 { color: #9cdcfe !important; }
@ -116,7 +116,7 @@
.mtk21 { color: #4f76ac !important; }
.mtk22 { color: #3dc9b0 !important; }
.mtk23 { color: #74b0df !important; }
.mtk24 { color: #4864aa !important; }
.mtk24 { color: #4864aa !important; } */
.mtki { font-style: italic; }
.mtkb { font-weight: bold; }
.mtku { text-decoration: underline; text-underline-position: under; }

@ -17,10 +17,11 @@ import * as monaco from 'monaco-editor'
import { fromStore, toStore } from 'educoder'
import './TPIMonacoConfig'
import { isThisSecond } from 'date-fns';
// https://microsoft.github.io/monaco-editor/playground.html#customizing-the-appearence-exposed-colors
monaco.editor.defineTheme('myCoolTheme', {
base: 'vs-dark',
base: 'vs', // vs、vs-dark、hc-black
inherit: true,
rules: [
{ token: 'green', background: 'FF0000', foreground: '00FF00', fontStyle: 'italic'},
@ -213,8 +214,9 @@ class TPIMonaco extends Component {
loadMonacoResouce();
this.state = {
cmFontSize: fromStore('cmFontSize', 16),
cmCodeMode: fromStore('cmCodeMode', 'vs-dark'),
autoCompleteSwitch: fromStore('autoCompleteSwitch', true),
}
}
}
componentDidUpdate(prevProps, prevState, snapshot) {
@ -243,7 +245,6 @@ class TPIMonaco extends Component {
editor_monaco.setValue(this.props.repositoryCode)
}
// 代码没变也需要layout可能从命令行自动切回了代码tab
editor_monaco.layout();
// Clears the editor's undo history.
// TODO
@ -290,11 +291,12 @@ class TPIMonaco extends Component {
language: lang,
// language: 'css',
// theme: "vs-dark",
theme: "myCoolTheme",
// theme: "vs",
theme: this.state.cmCodeMode,
// theme: 'myCoolTheme',
insertSpaces: false,
fontSize: this.state.cmFontSize
fontSize: this.state.cmFontSize,
// theme: this.state.cdCodeMode
});
window.editor_monaco = editor;
@ -368,10 +370,17 @@ class TPIMonaco extends Component {
}
onFontSizeChange = (value) => {
toStore('cmFontSize', value)
this.setState({ cmFontSize: value });
this.editor_monaco.updateOptions({fontSize: value})
}
this.setState({ cmFontSize: value });
onCodeModeChange = (value) => {
toStore('cmCodeMode', value);
this.setState({ cmCodeMode: value });
window.monaco.editor.setTheme(value);
}
onAutoCompleteSwitchChange = () => {
}
@ -393,6 +402,7 @@ class TPIMonaco extends Component {
>
<TPICodeSetting {...this.props} {...this.state}
onFontSizeChange={this.onFontSizeChange}
onCodeModeChange={this.onCodeModeChange}
onAutoCompleteSwitchChange={this.onAutoCompleteSwitchChange}
></TPICodeSetting>
</Drawer>

@ -20,6 +20,7 @@ import Trialapplication from "../login/Trialapplication";
const $ = window.$;
const versionNum = '0001';
const timestamp = Date.parse(new Date());
// let _url_origin = getUrl()
let _url_origin='';
if(window.location.port === "3007"){
@ -35,14 +36,14 @@ if (!window['indexHOCLoaded']) {
// $('head').append($('<link rel="stylesheet" type="text/css" />')
// .attr('href', `${_url_origin}/stylesheets/educoder/antd.min.css?1525440977`));
$('head').append($('<link rel="stylesheet" type="text/css" />')
.attr('href', `${_url_origin}/stylesheets/css/edu-common.css?8`));
.attr('href', `${_url_origin}/stylesheets/css/edu-common.css?${timestamp}`));
$('head').append($('<link rel="stylesheet" type="text/css" />')
.attr('href', `${_url_origin}/stylesheets/educoder/edu-main.css?8`));
.attr('href', `${_url_origin}/stylesheets/educoder/edu-main.css?${timestamp}`));
// index.html有加载
$('head').append($('<link rel="stylesheet" type="text/css" />')
.attr('href', `${_url_origin}/stylesheets/educoder/edu-all.css?8`));
.attr('href', `${_url_origin}/stylesheets/educoder/edu-all.css?${timestamp}`));
// $('head').append($('<link rel="stylesheet" type="text/css" />')

@ -345,7 +345,7 @@ class InfosCourse extends Component{
</p>
<span><img alt="用户" className="radius mt15" height="60" src={getImageUrl('images/'+`${item.teacher && item.teacher.avatar_url}`)} width="60"/></span>
<p className="font-14 mt10 task-hide"><span>{item.teacher && item.teacher.real_name}</span></p>
<p className="font-16 mb15 task-hide mt10"><span className="color-grey-98">{item.teacher && item.teacher.school_name}</span></p>
<p className="font-16 mb15 task-hide mt10"><span className="color-grey-98">{item&&item.school}</span></p>
</div>
<div className="edu-txt-center course-bottom">
<div className="inline color-grey-6">

@ -36,6 +36,7 @@ import {
saveUserInputCode,
changeUserCodeTab,
submitUserCode,
getUserProgramDetail
// isUpdateCodeCtx
} from './ojForUser';
@ -79,6 +80,7 @@ export default {
changeSubmitLoadingStatus,
submitUserCode,
changePublishLoadingStatus,
isMyPublish
isMyPublish,
getUserProgramDetail
// isUpdateCodeCtx
}

@ -4,7 +4,7 @@
* @Github:
* @Date: 2019-11-27 13:42:11
* @LastEditors: tangjiang
* @LastEditTime: 2019-11-29 12:03:51
* @LastEditTime: 2019-11-29 20:07:09
*/
import types from "./actionTypes";
import { Base64 } from 'js-base64';
@ -19,7 +19,7 @@ import {
} from "../../services/ojService";
// 进入编程页面时,首先调用开启编程题接口
export const startProgramQuestion = (id) => {
export const startProgramQuestion = (id, props) => {
return (dispatch) => {
fetchStartProgram(id).then(res => {
const { status, data } = res;
@ -29,21 +29,30 @@ export const startProgramQuestion = (id) => {
type: types.SAVE_USER_PROGRAM_ID,
payload: identifier
});
// 调用用户编程详情接口
fetchUserProgramDetail(identifier).then(res => {
const { status, data = {} } = res;
if (status === 200) {
dispatch({
type: types.USER_PROGRAM_DETAIL,
payload: data
});
}
})
// 跳转至开启编程
props.history.push(`/myproblems/${identifier}`);
// Redirect.to
}
})
}
}
// 获取用户编程题详情
export const getUserProgramDetail = (identifier) => {
// 调用用户编程详情接口
return (dispatch) => {
fetchUserProgramDetail(identifier).then(res => {
const { status, data = {} } = res;
if (status === 200) {
dispatch({
type: types.USER_PROGRAM_DETAIL,
payload: data
});
}
});
}
}
/**
* @description 更新代码
* @param {*} identifier

@ -4,7 +4,7 @@
* @Github:
* @Date: 2019-11-20 16:35:46
* @LastEditors: tangjiang
* @LastEditTime: 2019-11-28 21:21:56
* @LastEditTime: 2019-11-29 18:55:43
*/
import types from './actionTypes';
import CONST from '../../constants';
@ -204,7 +204,7 @@ export const validateOjForm = (props, type) => {
payload: true
});
setTimeout(() => {
props.history.push('/developer');
props.history.push('/problems');
}, 1000);
}

@ -4,7 +4,7 @@
* @Github:
* @Date: 2019-11-27 13:41:48
* @LastEditors: tangjiang
* @LastEditTime: 2019-11-28 17:34:13
* @LastEditTime: 2019-11-29 20:07:57
*/
import types from "../actions/actionTypes";
import { Base64 } from 'js-base64';

@ -20,6 +20,7 @@ import Trialapplication from "../login/Trialapplication";
const $ = window.$;
const versionNum = '0001';
const timestamp = Date.parse(new Date());
// let _url_origin = getUrl()
let _url_origin='';
if(window.location.port === "3007"){
@ -35,14 +36,14 @@ if (!window['indexHOCLoaded']) {
// $('head').append($('<link rel="stylesheet" type="text/css" />')
// .attr('href', `${_url_origin}/stylesheets/educoder/antd.min.css?1525440977`));
$('head').append($('<link rel="stylesheet" type="text/css" />')
.attr('href', `${_url_origin}/stylesheets/css/edu-common.css?8`));
.attr('href', `${_url_origin}/stylesheets/css/edu-common.css?${timestamp}`));
$('head').append($('<link rel="stylesheet" type="text/css" />')
.attr('href', `${_url_origin}/stylesheets/educoder/edu-main.css?8`));
.attr('href', `${_url_origin}/stylesheets/educoder/edu-main.css?${timestamp}`));
// index.html有加载
$('head').append($('<link rel="stylesheet" type="text/css" />')
.attr('href', `${_url_origin}/stylesheets/educoder/edu-all.css?8`));
.attr('href', `${_url_origin}/stylesheets/educoder/edu-all.css?${timestamp}`));
// $('head').append($('<link rel="stylesheet" type="text/css" />')

@ -3795,3 +3795,7 @@ a.singlepublishtwo{
.fontweightbold{
font-weight: bold !important;
}
.ant-drawer{
z-index: 10000 !important;
}
Loading…
Cancel
Save