Merge branches 'dev_aliyun' and 'dev_new_shixunsrepository' of https://bdgit.educoder.net/Hjqreturn/educoder into dev_new_shixunsrepository

 Conflicts:
	public/react/src/modules/tpm/TPMIndex.js
dev_new_shixunsrepository
杨树明 5 years ago
commit f022a8139e

2
.gitignore vendored

@ -43,7 +43,7 @@
/public/react/config/stats.json
/public/react/stats.json
/public/react/.idea/*
/public/h5build
/public/npm-debug.log
# avatars

@ -49,6 +49,8 @@ gem 'rqrcode_png'
gem 'acts-as-taggable-on', '~> 6.0'
gem 'omniauth-cas'
group :development, :test do
gem 'rspec-rails', '~> 3.8'
end

@ -120,5 +120,19 @@ $(document).on('turbolinks:load', function() {
});
}
});
// ------------ 上移/下移 -------------
$('.discipline-list-container').on('click', ".move-action", function () {
var $doAction = $(this);
var disciplineId = $doAction.data('id');
var opr = $doAction.data('opr');
$.ajax({
url: '/admins/disciplines/' + disciplineId + '/adjust_position',
method: 'POST',
dataType: 'script',
data: {opr: opr}
});
});
}
});

@ -1,5 +1,5 @@
$(document).on('turbolinks:load', function() {
$('.admin-modal-container').on('show.bs.modal', '.modal.admin-edit-discipline-modal', function(){
$(document).on('turbolinks:load', function () {
$('.admin-modal-container').on('show.bs.modal', '.modal.admin-edit-discipline-modal', function () {
var $modal = $('.modal.admin-edit-discipline-modal');
var $form = $modal.find('form.admin-edit-discipline-form');
@ -14,7 +14,18 @@ $(document).on('turbolinks:load', function() {
}
});
$modal.on('click', '.submit-btn', function(){
$modal.on('click', '.submit-btn', submit_edit_form);
$form.find("#discipline_name").keydown(function (e) {
var ev = e || event;
var keycode = ev.which || ev.keyCode;
if (keycode == 13) {
submit_edit_form();
return false;
}
});
function submit_edit_form() {
$form.find('.error').html('');
var url = $form.attr('action');
@ -26,6 +37,6 @@ $(document).on('turbolinks:load', function() {
data: $form.serialize()
});
}
});
}
});
});

@ -0,0 +1,31 @@
$(document).on('turbolinks:load', function() {
$('.admin-modal-container').on('show.bs.modal', '.modal.admin-edit-repertoire-modal', function(){
var $modal = $('.modal.admin-edit-repertoire-modal');
var $form = $modal.find('form.admin-edit-repertoire-form');
$form.validate({
errorElement: 'span',
errorClass: 'danger text-danger',
rules: {
'repertoire[name]': {
required: true,
maxlength: 20
}
}
});
$modal.on('click', '.submit-btn', function(){
$form.find('.error').html('');
var url = $form.attr('action');
if ($form.valid()) {
$.ajax({
method: 'PATCH',
dataType: 'script',
url: url,
data: $form.serialize()
});
}
});
});
});

@ -1,5 +1,5 @@
$(document).on('turbolinks:load', function() {
$('.admin-modal-container').on('show.bs.modal', '.modal.admin-edit-sub-discipline-modal', function(){
$(document).on('turbolinks:load', function () {
$('.admin-modal-container').on('show.bs.modal', '.modal.admin-edit-sub-discipline-modal', function () {
var $modal = $('.modal.admin-edit-sub-discipline-modal');
var $form = $modal.find('form.admin-edit-sub-discipline-form');
@ -14,7 +14,18 @@ $(document).on('turbolinks:load', function() {
}
});
$modal.on('click', '.submit-btn', function(){
$modal.on('click', '.submit-btn', submit_edit_form);
$form.find("#sub_discipline_name").keydown(function (e) {
var ev = e || event;
var keycode = ev.which || ev.keyCode;
if (keycode == 13) {
submit_edit_form();
return false;
}
});
function submit_edit_form() {
$form.find('.error').html('');
var url = $form.attr('action');
@ -26,6 +37,7 @@ $(document).on('turbolinks:load', function() {
data: $form.serialize()
});
}
});
}
});
});

@ -0,0 +1,31 @@
$(document).on('turbolinks:load', function() {
$('.admin-modal-container').on('show.bs.modal', '.modal.admin-edit-sub-repertoire-modal', function(){
var $modal = $('.modal.admin-edit-sub-repertoire-modal');
var $form = $modal.find('form.admin-edit-sub-repertoire-form');
$form.validate({
errorElement: 'span',
errorClass: 'danger text-danger',
rules: {
'sub_repertoire[name]': {
required: true,
maxlength: 20
}
}
});
$modal.on('click', '.submit-btn', function(){
$form.find('.error').html('');
var url = $form.attr('action');
if ($form.valid()) {
$.ajax({
method: 'PATCH',
dataType: 'script',
url: url,
data: $form.serialize()
});
}
});
});
});

@ -1,5 +1,5 @@
$(document).on('turbolinks:load', function() {
$('.admin-modal-container').on('show.bs.modal', '.modal.admin-edit-tag-discipline-modal', function(){
$(document).on('turbolinks:load', function () {
$('.admin-modal-container').on('show.bs.modal', '.modal.admin-edit-tag-discipline-modal', function () {
var $modal = $('.modal.admin-edit-tag-discipline-modal');
var $form = $modal.find('form.admin-edit-tag-discipline-form');
@ -14,7 +14,18 @@ $(document).on('turbolinks:load', function() {
}
});
$modal.on('click', '.submit-btn', function(){
$modal.on('click', '.submit-btn', submit_edit_form);
$form.find("#tag_discipline_name").keydown(function (e) {
var ev = e || event;
var keycode = ev.which || ev.keyCode;
if (keycode == 13) {
submit_edit_form();
return false;
}
});
function submit_edit_form() {
$form.find('.error').html('');
var url = $form.attr('action');
@ -26,6 +37,6 @@ $(document).on('turbolinks:load', function() {
data: $form.serialize()
});
}
});
}
});
});

@ -0,0 +1,31 @@
$(document).on('turbolinks:load', function() {
$('.admin-modal-container').on('show.bs.modal', '.modal.admin-edit-tag-repertoire-modal', function(){
var $modal = $('.modal.admin-edit-tag-repertoire-modal');
var $form = $modal.find('form.admin-edit-tag-repertoire-form');
$form.validate({
errorElement: 'span',
errorClass: 'danger text-danger',
rules: {
'tag_repertoire[name]': {
required: true,
maxlength: 20
}
}
});
$modal.on('click', '.submit-btn', function(){
$form.find('.error').html('');
var url = $form.attr('action');
if ($form.valid()) {
$.ajax({
method: 'PATCH',
dataType: 'script',
url: url,
data: $form.serialize()
});
}
});
});
});

@ -0,0 +1,65 @@
$(document).on('turbolinks:load', function() {
if ($('body.admins-repertoires-index-page').length > 0) {
// ============== 新建 ===============
var $modal = $('.modal.admin-create-repertoire-modal');
var $form = $modal.find('form.admin-create-repertoire-form');
var $nameInput = $form.find('input[name="name"]');
$form.validate({
errorElement: 'span',
errorClass: 'danger text-danger',
rules: {
name: {
required: true
}
}
});
// modal ready fire
$modal.on('show.bs.modal', function () {
$nameInput.val('');
});
$modal.on('click', '.submit-btn', function(){
$form.find('.error').html('');
if ($form.valid()) {
var url = $form.data('url');
$.ajax({
method: 'POST',
dataType: 'json',
url: url,
data: $form.serialize(),
success: function(){
$.notify({ message: '创建成功' });
$modal.modal('hide');
setTimeout(function(){
window.location.reload();
}, 500);
},
error: function(res){
var data = res.responseJSON;
$form.find('.error').html(data.message);
}
});
}
});
$(".repertoire-list-container").on("change", '.repertoire-source-form', function () {
var s_id = $(this).attr("data-id");
var s_value = $(this).val();
var s_name = $(this).attr("name");
var json = {};
json[s_name] = s_value;
$.ajax({
url: "/admins/repertoires/" + s_id,
type: "PUT",
dataType:'script',
data: json
});
});
}
});

@ -0,0 +1,119 @@
$(document).on('turbolinks:load', function() {
if ($('body.admins-salesman-channels-index-page').length > 0) {
// ============= 添加销售人员 ==============
var $addMemberModal = $('.admin-add-salesman-channel-user-modal');
var $addMemberForm = $addMemberModal.find('.admin-add-salesman-channel-user-form');
var $memberSelect = $addMemberModal.find('.salesman-channel-user-select');
var $form = $addMemberModal.find('form.admin-add-salesman-user-form');
// 搜索
var searchscForm = $(".saleman-channel-list-form .search-form");
$addMemberModal.on('show.bs.modal', function(event){
$memberSelect.select2('val', ' ');
});
$memberSelect.select2({
theme: 'bootstrap4',
placeholder: '请输入要添加的单位',
multiple: true,
minimumInputLength: 1,
ajax: {
delay: 500,
url: '/admins/schools',
dataType: 'json',
data: function(params){
return { keyword: params.term };
},
processResults: function(data){
return { results: data.schools }
}
},
templateResult: function (item) {
if(!item.id || item.id === '') return '';
return $("<span>" + item.name + "</span>");
},
templateSelection: function(item){
if (item.id) {
}
return item.name || '';
}
});
$addMemberModal.on('click', '.submit-btn', function(){
$addMemberForm.find('.error').html('');
// var salesmanId = $salesmanIdInput.val();
var memberIds = $memberSelect.val();
if (memberIds && memberIds.length > 0) {
var url = $form.data('url');
$.ajax({
method: 'POST',
dataType: 'json',
url: url,
data: $form.serialize(),
success: function(){
$.notify({ message: '创建成功' });
$addMemberModal.modal('hide');
searchscForm.find('input[name="keyword"]').val('');
setTimeout(function(){
submitForm();
}, 500);
},
error: function(res){
var data = res.responseJSON;
$addMemberForm.find('.error').html(data.message);
}
});
} else {
$addMemberModal.modal('hide');
}
});
// 清空
searchscForm.on('click', '.clear-btn', function () {
searchscForm.find('.start_date').val('');
searchscForm.find('.end_date').val('').trigger('change');
searchscForm.find('input[name="keyword"]').val('');
});
// 时间跨度
var baseOptions = {
autoclose: true,
language: 'zh-CN',
format: 'yyyy-mm-dd',
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');
// 区间搜索
searchscForm.on('click', ".search-btn", function(){
submitForm();
});
var submitForm = function(){
var url = searchscForm.data('search-form-url');
var form = searchscForm;
$.ajax({
url: url,
data: form.serialize(),
dataType: "script"
})
};
}
});

@ -0,0 +1,82 @@
$(document).on('turbolinks:load', function() {
if ($('body.admins-salesman-customers-index-page').length > 0) {
// ============= 添加销售人员 ==============
var $addMemberModal = $('.admin-add-salesman-customer-user-modal');
var $addMemberForm = $addMemberModal.find('.admin-add-salesman-customer-user-form');
var $memberSelect = $addMemberModal.find('.salesman-customer-user-select');
var $salesmanIdInput = $('.salesman-customer-list-form').find(".btn-primary");
$addMemberModal.on('show.bs.modal', function(event){
var $link = $(event.relatedTarget);
// var salesmanId = $link.data('salesman_id');
// $salesmanIdInput.val(salesmanId);
$memberSelect.select2('val', ' ');
});
$memberSelect.select2({
theme: 'bootstrap4',
placeholder: '请输入要添加的销售姓名',
multiple: true,
minimumInputLength: 1,
ajax: {
delay: 500,
url: '/admins/users',
dataType: 'json',
data: function(params){
return { name: params.term };
},
processResults: function(data){
return { results: data.users }
}
},
templateResult: function (item) {
if(!item.id || item.id === '') return item.text;
return $("<span>" + item.real_name + " <span class='font-12'>" + item.school_name + ' ' + item.hidden_phone + "</span></span>");
},
templateSelection: function(item){
if (item.id) {
}
return item.real_name || item.text;
}
});
$addMemberModal.on('click', '.submit-btn', function(){
$addMemberForm.find('.error').html('');
// var salesmanId = $salesmanIdInput.val();
var memberIds = $memberSelect.val();
if (memberIds && memberIds.length > 0) {
$.ajax({
method: 'POST',
dataType: 'json',
url: '/admins/salesman_customers/batch_add',
data: { salesman_id: $salesmanIdInput.data("salesman-id"), user_ids: memberIds },
success: function(){
$.notify({ message: '创建成功' });
$addMemberModal.modal('hide');
setTimeout(function(){
listForm();
}, 500);
},
error: function(res){
var data = res.responseJSON;
$form.find('.error').html(data.message);
}
});
} else {
$addMemberModal.modal('hide');
}
});
var listForm = function(){
$.ajax({
url: '/admins/salesman_customers?salesman_id='+ $salesmanIdInput.data("salesman-id"),
dataType: "script"
});
};
}
});

@ -0,0 +1,99 @@
$(document).on('turbolinks:load', function() {
if ($('body.admins-salesmans-index-page').length > 0) {
// ============= 添加销售人员 ==============
var $addMemberModal = $('.admin-add-salesman-user-modal');
var $addMemberForm = $addMemberModal.find('.admin-add-salesman-user-form');
var $memberSelect = $addMemberModal.find('.salesman-user-select');
// var $salesmanIdInput = $addMemberForm.find('input[name="salesman_id"]')
$addMemberModal.on('show.bs.modal', function(event){
var $link = $(event.relatedTarget);
// var salesmanId = $link.data('salesman-id');
// $salesmanIdInput.val(salesmanId);
$memberSelect.select2('val', ' ');
});
$memberSelect.select2({
theme: 'bootstrap4',
placeholder: '请输入要添加的销售姓名',
multiple: true,
minimumInputLength: 1,
ajax: {
delay: 500,
url: '/admins/users',
dataType: 'json',
data: function(params){
return { name: params.term };
},
processResults: function(data){
return { results: data.users }
}
},
templateResult: function (item) {
if(!item.id || item.id === '') return item.text;
return $("<span>" + item.real_name + " <span class='font-12'>" + item.school_name + ' ' + item.hidden_phone + "</span></span>");
},
templateSelection: function(item){
if (item.id) {
}
return item.real_name || item.text;
}
});
$addMemberModal.on('click', '.submit-btn', function(){
$addMemberForm.find('.error').html('');
// var salesmanId = $salesmanIdInput.val();
var memberIds = $memberSelect.val();
if (memberIds && memberIds.length > 0) {
$.ajax({
method: 'POST',
dataType: 'json',
url: '/admins/salesmans/batch_add',
data: { user_ids: memberIds },
success: function(){
$.notify({ message: '创建成功' });
$addMemberModal.modal('hide');
setTimeout(function(){
window.location.reload();
}, 500);
},
error: function(res){
var data = res.responseJSON;
$form.find('.error').html(data.message);
}
});
} else {
$addMemberModal.modal('hide');
}
});
$(".salesman-list-container").on("change", '.salesman-sync-course', function () {
var s_id = $(this).attr("data-id");
var json = {};
$.ajax({
url: "/admins/salesmans/" + s_id + "/update_sync_course",
type: "POST",
dataType:'script',
data: json
})
});
$(".salesman-list-container").on("change", '.salesman-sync-form', function () {
var s_id = $(this).attr("data-id");
var s_value = $(this).val();
var s_name = $(this).attr("name");
var json = {};
json[s_name] = s_value;
$.ajax({
url: "/admins/salesmans/" + s_id,
type: "PUT",
dataType:'script',
data: json
});
});
}
});

@ -30,7 +30,21 @@ $(document).on('turbolinks:load', function() {
type: "PUT",
dataType:'script',
data: json
})
});
});
$(".shixun-settings-list-container").on("change", '.repertoire-setting-form', function () {
var s_id = $(this).attr("data-id");
var s_value = $(this).val();
var s_name = $(this).attr("name");
var json = {};
json[s_name] = s_value;
$.ajax({
url: "/admins/shixun_settings/" + s_id + "/update_tag_repertoires",
type: "POST",
dataType:'script',
data: json
});
});
$("select#settings-tag-choosed").select2({

@ -1,4 +1,4 @@
$(document).on('turbolinks:load', function() {
$(document).on('turbolinks:load', function () {
if ($('body.admins-sub-disciplines-index-page').length > 0) {
// ============== 新建 ===============
@ -21,7 +21,18 @@ $(document).on('turbolinks:load', function() {
$nameInput.val('');
});
$modal.on('click', '.submit-btn', function(){
$modal.on('click', '.submit-btn', submit_create_form);
$nameInput.keydown(function (e) {
var ev = e || event;
var keycode = ev.which || ev.keyCode;
if (keycode == 13) {
submit_create_form();
return false;
}
});
function submit_create_form() {
$form.find('.error').html('');
if ($form.valid()) {
@ -32,21 +43,21 @@ $(document).on('turbolinks:load', function() {
dataType: 'json',
url: url,
data: $form.serialize(),
success: function(){
$.notify({ message: '创建成功' });
success: function () {
$.notify({message: '创建成功'});
$modal.modal('hide');
setTimeout(function(){
setTimeout(function () {
window.location.reload();
}, 500);
},
error: function(res){
error: function (res) {
var data = res.responseJSON;
$form.find('.error').html(data.message);
}
});
}
});
}
$(".sub-discipline-list-container").on("change", '.sub-discipline-source-form', function () {
var s_id = $(this).attr("data-id");
@ -57,9 +68,22 @@ $(document).on('turbolinks:load', function() {
$.ajax({
url: "/admins/sub_disciplines/" + s_id,
type: "PUT",
dataType:'script',
dataType: 'script',
data: json
});
});
// ------------ 上移/下移 -------------
$('.sub-discipline-list-container').on('click', ".move-action", function () {
var $doAction = $(this);
var objectId = $doAction.data('id');
var opr = $doAction.data('opr');
$.ajax({
url: '/admins/sub_disciplines/' + objectId + '/adjust_position',
method: 'POST',
dataType: 'script',
data: {opr: opr}
});
});
}
});

@ -0,0 +1,65 @@
$(document).on('turbolinks:load', function() {
if ($('body.admins-sub-repertoires-index-page').length > 0) {
// ============== 新建 ===============
var $modal = $('.modal.admin-create-sub-repertoire-modal');
var $form = $modal.find('form.admin-create-sub-repertoire-form');
var $nameInput = $form.find('input[name="name"]');
$form.validate({
errorElement: 'span',
errorClass: 'danger text-danger',
rules: {
name: {
required: true
}
}
});
// modal ready fire
$modal.on('show.bs.modal', function () {
$nameInput.val('');
});
$modal.on('click', '.submit-btn', function(){
$form.find('.error').html('');
if ($form.valid()) {
var url = $form.data('url');
$.ajax({
method: 'POST',
dataType: 'json',
url: url,
data: $form.serialize(),
success: function(){
$.notify({ message: '创建成功' });
$modal.modal('hide');
setTimeout(function(){
window.location.reload();
}, 500);
},
error: function(res){
var data = res.responseJSON;
$form.find('.error').html(data.message);
}
});
}
});
$(".sub-repertoire-list-container").on("change", '.sub-repertoire-source-form', function () {
var s_id = $(this).attr("data-id");
var s_value = $(this).val();
var s_name = $(this).attr("name");
var json = {};
json[s_name] = s_value;
$.ajax({
url: "/admins/sub_repertoires/" + s_id,
type: "PUT",
dataType:'script',
data: json
});
});
}
});

@ -0,0 +1,72 @@
$(document).on('turbolinks:load', function () {
if ($('body.admins-subject-settings-index-page').length > 0) {
var $form = $('.subject-setting-list-form');
// ************** 学校选择 *************
$form.find('.school-select').select2({
theme: 'bootstrap4',
placeholder: '请选择创建者单位',
minimumInputLength: 1,
ajax: {
delay: 500,
url: '/api/schools/search.json',
dataType: 'json',
data: function (params) {
return {keyword: params.term};
},
processResults: function (data) {
return {results: data.schools}
}
},
templateResult: function (item) {
if (!item.id || item.id === '') return item.text;
return item.name;
},
templateSelection: function (item) {
if (item.id) {
}
return item.name || item.text;
}
});
$(".subject-setting-list-container").on("change", '.subject-setting-form', function () {
var s_id = $(this).attr("data-id");
var s_value = $(this).val();
var s_name = $(this).attr("name");
var json = {};
json[s_name] = s_value;
$.ajax({
url: "/admins/subject_settings/" + s_id,
type: "PUT",
dataType:'script',
data: json
})
});
// 清空
$form.on('click', '.clear-btn', function () {
$form.find('select[name="status"]').val('');
$form.find('.school-select').val('').trigger('change');
$form.find('input[name="keyword"]').val('');
$form.find('#homepage_show').attr('checked', false);
$form.find('#excellent').attr('checked', false);
$form.find('input[type="submit"]').trigger('click');
});
// 上传图片
$('.modal.admin-upload-file-modal').on('upload:success', function (e, data) {
if(data.suffix == '_qrcode'){
var $imageElement = $('.subject-weapp-image-' + data.source_id);
$imageElement.attr('src', data.url);
$imageElement.show();
$imageElement.next().html('重新上传');
} else {
var $imageElement = $('.subject-image-' + data.source_id);
$imageElement.attr('src', data.url);
$imageElement.show();
$imageElement.next().html('重新上传');
}
});
}
});

@ -37,22 +37,8 @@ $(document).on('turbolinks:load', function () {
$form.find('#homepage_show').attr('checked', false);
$form.find('#excellent').attr('checked', false);
$form.find('input[type="submit"]').trigger('click');
})
// 上传图片
$('.modal.admin-upload-file-modal').on('upload:success', function (e, data) {
if(data.suffix == '_qrcode'){
var $imageElement = $('.subject-weapp-image-' + data.source_id);
$imageElement.attr('src', data.url);
$imageElement.show();
$imageElement.next().html('重新上传');
} else {
var $imageElement = $('.subject-image-' + data.source_id);
$imageElement.attr('src', data.url);
$imageElement.show();
$imageElement.next().html('重新上传');
}
});
// 定义状态切换监听事件
var defineStatusChangeFunc = function (doElement, undoElement, url, callback) {
$('.subject-list-container').on('click', doElement, function () {

@ -1,4 +1,4 @@
$(document).on('turbolinks:load', function() {
$(document).on('turbolinks:load', function () {
if ($('body.admins-tag-disciplines-index-page').length > 0) {
// ============== 新建 ===============
@ -21,7 +21,18 @@ $(document).on('turbolinks:load', function() {
$nameInput.val('');
});
$modal.on('click', '.submit-btn', function(){
$modal.on('click', '.submit-btn', submit_create_form);
$nameInput.keydown(function (e) {
var ev = e || event;
var keycode = ev.which || ev.keyCode;
if (keycode == 13) {
submit_create_form();
return false;
}
});
function submit_create_form() {
$form.find('.error').html('');
if ($form.valid()) {
@ -32,21 +43,21 @@ $(document).on('turbolinks:load', function() {
dataType: 'json',
url: url,
data: $form.serialize(),
success: function(){
$.notify({ message: '创建成功' });
success: function () {
$.notify({message: '创建成功'});
$modal.modal('hide');
setTimeout(function(){
setTimeout(function () {
window.location.reload();
}, 500);
},
error: function(res){
error: function (res) {
var data = res.responseJSON;
$form.find('.error').html(data.message);
}
});
}
});
}
$(".tag-discipline-list-container").on("change", '.tag-discipline-source-form', function () {
var s_id = $(this).attr("data-id");
@ -57,9 +68,23 @@ $(document).on('turbolinks:load', function() {
$.ajax({
url: "/admins/tag_disciplines/" + s_id,
type: "PUT",
dataType:'script',
dataType: 'script',
data: json
});
});
// ------------ 上移/下移 -------------
$('.tag-discipline-list-container').on('click', ".move-action", function () {
var $doAction = $(this);
var objectId = $doAction.data('id');
var opr = $doAction.data('opr');
$.ajax({
url: '/admins/tag_disciplines/' + objectId + '/adjust_position',
method: 'POST',
dataType: 'script',
data: {opr: opr}
});
});
}
});

@ -0,0 +1,65 @@
$(document).on('turbolinks:load', function() {
if ($('body.admins-tag-repertoires-index-page').length > 0) {
// ============== 新建 ===============
var $modal = $('.modal.admin-create-tag-repertoire-modal');
var $form = $modal.find('form.admin-create-tag-repertoire-form');
var $nameInput = $form.find('input[name="name"]');
$form.validate({
errorElement: 'span',
errorClass: 'danger text-danger',
rules: {
name: {
required: true
}
}
});
// modal ready fire
$modal.on('show.bs.modal', function () {
$nameInput.val('');
});
$modal.on('click', '.submit-btn', function(){
$form.find('.error').html('');
if ($form.valid()) {
var url = $form.data('url');
$.ajax({
method: 'POST',
dataType: 'json',
url: url,
data: $form.serialize(),
success: function(){
$.notify({ message: '创建成功' });
$modal.modal('hide');
setTimeout(function(){
window.location.reload();
}, 500);
},
error: function(res){
var data = res.responseJSON;
$form.find('.error').html(data.message);
}
});
}
});
$(".tag-repertoire-list-container").on("change", '.tag-repertoire-source-form', function () {
var s_id = $(this).attr("data-id");
var s_value = $(this).val();
var s_name = $(this).attr("name");
var json = {};
json[s_name] = s_value;
$.ajax({
url: "/admins/tag_repertoires/" + s_id,
type: "PUT",
dataType:'script',
data: json
});
});
}
});

@ -51,12 +51,12 @@ class AccountsController < ApplicationController
# todo user_extension
UserExtension.create!(user_id: @user.id)
# 注册完成手机号或邮箱想可以奖励500金币
RewardGradeService.call(
@user,
container_id: @user.id,
container_type: pre == 'p' ? 'Phone' : 'Mail',
score: 500
)
# RewardGradeService.call(
# @user,
# container_id: @user.id,
# container_type: pre == 'p' ? 'Phone' : 'Mail',
# score: 500
# )
# 注册时,记录是否是引流用户
ip = request.remote_ip
ua = UserAgent.find_by_ip(ip)
@ -167,7 +167,7 @@ class AccountsController < ApplicationController
end
# 检验邮箱是否已被注册及邮箱或者手机号是否合法
# 参数type为事件类型 1注册2忘记密码
# 参数type为事件类型 1注册2忘记密码3绑定
def valid_email_and_phone
check_mail_and_phone_valid(params[:login], params[:type])
end

@ -7,7 +7,7 @@ class Admins::DisciplinesController < Admins::BaseController
def create
name = params[:name].to_s.strip
return render_error('名称重复') if Discipline.where(name: name).exists?
Discipline.create!(name: name)
Discipline.create!(name: name, position: Discipline.all.pluck(:position).max + 1)
render_ok
end
@ -16,7 +16,8 @@ class Admins::DisciplinesController < Admins::BaseController
end
def update
if params[:discipline] && params[:discipline][:name].present?
begin
if params[:discipline] && params[:discipline][:name]
name = params[:discipline][:name].to_s.strip
current_discipline.update_attributes!(name: name)
else
@ -30,13 +31,40 @@ class Admins::DisciplinesController < Admins::BaseController
end
end
end
rescue Exception => e
@message = e.message
end
@disciplines = Discipline.all
end
def destroy
@discipline_id = params[:id]
ActiveRecord::Base.transaction do
Discipline.where("position > #{current_discipline.position}").update_all("position=position-1")
current_discipline.destroy!
end
end
def adjust_position
max_position = Discipline.all.pluck(:position).max
opr = params[:opr] || "down"
if (params[:opr] == "up" && current_discipline.position == 1) || (params[:opr] == "down" && current_discipline.position == max_position)
@message = "超出范围"
else
ActiveRecord::Base.transaction do
if opr == "up"
Discipline.find_by("position = #{current_discipline.position - 1}")&.update!(position: current_discipline.position)
current_discipline.update!(position: current_discipline.position - 1)
else
Discipline.find_by("position = #{current_discipline.position + 1}")&.update!(position: current_discipline.position)
current_discipline.update!(position: current_discipline.position + 1)
end
end
end
@disciplines = Discipline.all
rescue Exception => e
@message = e.message
end
private
def current_discipline

@ -0,0 +1,36 @@
class Admins::RepertoiresController < Admins::BaseController
def index
@repertoires = Repertoire.all
end
def edit
@repertoire = current_repertoire
end
def update
Rails.logger.info("#################--------")
if params[:repertoire] && params[:repertoire][:name].present?
name = params[:repertoire][:name].to_s.strip
current_repertoire.update_attributes!(name: name)
end
@repertoires = Repertoire.all
end
def create
name = params[:name].to_s.strip
return render_error('名称重复') if Repertoire.where(name: name).exists?
Repertoire.create!(name: name)
render_ok
end
def destroy
@repertoire_id = params[:id]
current_repertoire.destroy!
end
private
def current_repertoire
@_current_repertoire = Repertoire.find params[:id]
end
end

@ -0,0 +1,35 @@
class Admins::SalesmanChannelsController < Admins::BaseController
before_action :set_salesman
def index
@channels = @salesman.salesman_channels
if params[:keyword].present?
@channels = @channels.joins(:school).where("schools.name like ?", "%#{params[:keyword]}%")
end
@start_time = params[:start_date]
@end_time = params[:end_date].blank? ? Time.now : params[:end_date]
end
def batch_add
channel_ids = @salesman.salesman_channels.pluck(:school_id)
school_ids = params[:school_ids] - channel_ids
school_ids.each do |school_id|
school = School.find_by(id: school_id)
next if school.blank? || @salesman.salesman_channels.where(school_id: school.id).exists?
@salesman.salesman_channels.create!(school_id: school.id)
end
render_ok
rescue Exception => ex
render_error(ex.message)
end
def destroy
@salesman.salesman_channels.find_by!(id: params[:id]).destroy
end
private
def set_salesman
@salesman = Salesman.find params[:salesman_id]
end
end

@ -0,0 +1,28 @@
class Admins::SalesmanCustomersController < Admins::BaseController
before_action :set_salesman
def index
@customers = @salesman.salesman_customers.includes(:user, :school)
end
def batch_add
customer_ids = @salesman.salesman_customers.pluck(:user_id)
user_ids = params[:user_ids] - customer_ids
user_ids.each do |user_id|
user = UserExtension.find_by(user_id: user_id)
next if user.blank? || @salesman.salesman_customers.where(user_id: user.user_id).exists?
@salesman.salesman_customers.create!(user_id: user.user_id, school_id: user.school_id)
end
render_ok
end
def destroy
@salesman.salesman_customers.find_by!(id: params[:id]).destroy
end
private
def set_salesman
@salesman = Salesman.find params[:salesman_id]
end
end

@ -0,0 +1,29 @@
class Admins::SalesmansController < Admins::BaseController
before_action :set_salesman, except: [:index, :batch_add]
def index
@salesmans = Salesman.all
end
def destroy
@salesman.destroy!
end
# 批量增加销售人员
def batch_add
salesman_user_ids = Salesman.where(id: params[:user_ids]).pluck(:user_id)
user_ids = params[:user_ids] - salesman_user_ids
user_ids.each do |user_id|
user = User.find_by(id: user_id)
next if user.blank?
Salesman.create!(user_id: user.id, name: user.real_name)
end
render_ok
end
private
def set_salesman
@salesman = Salesman.find params[:id]
end
end

@ -4,7 +4,7 @@ class Admins::SchoolsController < Admins::BaseController
params[:sort_direction] ||= 'desc'
schools = Admins::SchoolQuery.call(params)
@total_count = schools.map(&:id).count
@schools = paginate schools
school_ids = @schools.map(&:id)

@ -18,7 +18,7 @@ class Admins::ShixunSettingsController < Admins::BaseController
task_pass: params[:task_pass].present? ? params[:task_pass] : false,
code_hidden: params[:code_hidden].present? ? params[:code_hidden] : false,
vip: params[:vip].present? ? params[:vip] : false,
is_wechat_support: params[:is_wechat_support].present? ? params[:is_wechat_support] : false
no_subject: params[:no_subject].present? ? params[:no_subject] : false
}
@shixuns_type_check = MirrorRepository.pluck(:type_name,:id)
@ -47,22 +47,24 @@ class Admins::ShixunSettingsController < Admins::BaseController
@shixun = Shixun.find_by(id:params[:id])
@page_no = params[:page_no] || "1"
@shixun_tags = TagRepertoire.order("name asc").pluck(:name,:id)
tag_ids = params[:tag_repertoires]
if tag_ids.present?
@shixun&.shixun_tag_repertoires.delete_all
tag_repertoire_ids = @shixun&.tag_repertoires&.pluck(:id)
tag_ids.each do |id|
unless tag_repertoire_ids.include?(id)
tag_repertoire = @shixun.shixun_tag_repertoires.new(shixun_id:@shixun.id,tag_repertoire_id:id)
tag_repertoire.save!
end
end
else
unless @shixun.update_attributes(setting_params)
redirect_to admins_shixun_settings_path
flash[:danger] = "更新失败"
end
end
def update_tag_repertoires
shixun = Shixun.find_by(id:params[:id])
tag_repertoire_ids = params[:tag_repertoires] || []
tag_ids = tag_repertoire_ids.reject(&:blank?).map(&:to_i)
old_tag_ids = shixun.shixun_tag_repertoires.pluck(:tag_repertoire_id)
new_ids = tag_ids - old_tag_ids
delete_ids = old_tag_ids - tag_ids
tag_params = new_ids.map{|sub| {tag_repertoire_id: sub}}
ActiveRecord::Base.transaction do
shixun.shixun_tag_repertoires.where(tag_repertoire_id: delete_ids).destroy_all
shixun.shixun_tag_repertoires.create!(tag_params)
end
end
private
@ -133,6 +135,6 @@ class Admins::ShixunSettingsController < Admins::BaseController
def setting_params
params.permit(:use_scope,:excute_time,:close,:status,:can_copy,:webssh,:hidden,:homepage_show,:task_pass,
:code_hidden,:vip,:page_no,:id, :is_wechat_support, tag_repertoires:[])
:code_hidden,:vip,:page_no,:id, :no_subject)
end
end

@ -7,8 +7,9 @@ class Admins::SubDisciplinesController < Admins::BaseController
def create
name = params[:name].to_s.strip
return render_error('名称不能为空') if name.blank?
return render_error('名称重复') if current_discipline.sub_disciplines.where(name: name).exists?
SubDiscipline.create!(name: name, discipline_id: current_discipline.id)
SubDiscipline.create!(name: name, discipline_id: current_discipline.id, position: current_discipline.sub_disciplines.pluck(:position).max + 1)
render_ok
end
@ -17,7 +18,8 @@ class Admins::SubDisciplinesController < Admins::BaseController
end
def update
if params[:sub_discipline] && params[:sub_discipline][:name].present?
begin
if params[:sub_discipline] && params[:sub_discipline][:name]
name = params[:sub_discipline][:name].to_s.strip
current_sub_discipline.update_attributes!(name: name)
else
@ -28,13 +30,43 @@ class Admins::SubDisciplinesController < Admins::BaseController
end
end
end
rescue Exception => e
@message = e.message
end
@sub_disciplines = current_sub_discipline.discipline&.sub_disciplines
end
def destroy
@sub_discipline_id = params[:id]
ActiveRecord::Base.transaction do
discipline = current_sub_discipline.discipline
discipline.sub_disciplines.where("position > #{current_sub_discipline.position}").update_all("position=position-1")
current_sub_discipline.destroy!
end
end
def adjust_position
discipline = current_sub_discipline.discipline
max_position = discipline.sub_disciplines.pluck(:position).max
opr = params[:opr] || "down"
if (params[:opr] == "up" && current_sub_discipline.position == 1) || (params[:opr] == "down" && current_sub_discipline.position == max_position)
@message = "超出范围"
else
ActiveRecord::Base.transaction do
if opr == "up"
discipline.sub_disciplines.find_by("position = #{current_sub_discipline.position - 1}")&.update!(position: current_sub_discipline.position)
current_sub_discipline.update!(position: current_sub_discipline.position - 1)
else
discipline.sub_disciplines.find_by("position = #{current_sub_discipline.position + 1}")&.update!(position: current_sub_discipline.position)
current_sub_discipline.update!(position: current_sub_discipline.position + 1)
end
end
end
@sub_disciplines = discipline&.sub_disciplines
rescue Exception => e
@message = e.message
end
private

@ -0,0 +1,45 @@
class Admins::SubRepertoiresController < Admins::BaseController
def index
@repertoire = current_repertoire
@sub_repertoires = current_repertoire.sub_repertoires
end
def create
name = params[:name].to_s.strip
return render_error('名称重复') if current_repertoire.sub_repertoires.where(name: name).exists?
SubRepertoire.create!(name: name, repertoire_id: current_repertoire.id)
render_ok
end
def edit
@sub_repertoire = current_sub_repertoire
end
def update
if params[:sub_repertoire] && params[:sub_repertoire][:name].present?
name = params[:sub_repertoire][:name].to_s.strip
current_sub_repertoire.update_attributes!(name: name)
end
@sub_repertoires = current_sub_repertoire.repertoire&.sub_repertoires
end
def destroy
@sub_repertoire_id = params[:id]
current_sub_repertoire.destroy!
end
private
def current_sub_repertoire
@_current_sub_repertoire = SubRepertoire.find params[:id]
end
def current_repertoire
@_current_repertoire = Repertoire.find params[:repertoire_id]
end
def setting_params
params.permit(:shixun, :subject, :question)
end
end

@ -0,0 +1,34 @@
class Admins::SubjectSettingsController < Admins::BaseController
def index
default_sort('created_at', 'desc')
subjects = Admins::SubjectQuery.call(params)
@sub_disciplines = SubDiscipline.where(subject: 1).pluck(:name,:id)
@subjects = paginate subjects.includes(:repertoire, :subject_level_system, :sub_disciplines)
end
def update
sub_discipline_ids = params[:sub_disciplines] || []
sub_ids = sub_discipline_ids.reject(&:blank?).map(&:to_i)
old_sub_ids = current_subject.sub_discipline_containers.pluck(:sub_discipline_id)
new_ids = sub_ids - old_sub_ids
delete_ids = old_sub_ids - sub_ids
sub_params = new_ids.map{|sub| {sub_discipline_id: sub}}
ActiveRecord::Base.transaction do
current_subject.sub_discipline_containers.where(sub_discipline_id: delete_ids).destroy_all
current_subject.sub_discipline_containers.create!(sub_params)
end
end
def update_mobile_show
subject = Subject.find(params[:subject_id])
subject.update_attributes(:show_mobile => params[:show_mobile])
end
private
def current_subject
@_current_subject ||= Subject.find(params[:id])
end
end

@ -3,7 +3,7 @@ class Admins::SubjectsController < Admins::BaseController
default_sort('created_at', 'desc')
subjects = Admins::SubjectQuery.call(params)
@subjects = paginate subjects.includes(:repertoire, :subject_level_system, user: { user_extension: :school })
@subjects = paginate subjects.includes(user: { user_extension: :school })
end
def edit
@ -14,7 +14,7 @@ class Admins::SubjectsController < Admins::BaseController
current_subject.update!(update_params)
flash[:success] = '保存成功'
redirect_to admins_subjects_path
redirect_to admins_subject_settings_path
end
def destroy
@ -49,7 +49,7 @@ class Admins::SubjectsController < Admins::BaseController
# 设为金课
def excellent
current_subject.update!(excellent: true)
current_subject.update!(excellent: true, public: 2)
render_ok
end

@ -8,7 +8,8 @@ class Admins::TagDisciplinesController < Admins::BaseController
def create
name = params[:name].to_s.strip
return render_error('名称重复') if current_sub_discipline.tag_disciplines.where(name: name).exists?
TagDiscipline.create!(name: name, sub_discipline_id: current_sub_discipline.id, user_id: current_user.id)
TagDiscipline.create!(name: name, sub_discipline_id: current_sub_discipline.id, user_id: current_user.id,
position: current_sub_discipline.tag_disciplines.pluck(:position).max + 1)
render_ok
end
@ -17,19 +18,50 @@ class Admins::TagDisciplinesController < Admins::BaseController
end
def update
if params[:tag_discipline] && params[:tag_discipline][:name].present?
begin
if params[:tag_discipline] && params[:tag_discipline][:name]
name = params[:tag_discipline][:name].to_s.strip
current_tag_discipline.update_attributes!(name: name)
else
current_tag_discipline.update_attributes!(setting_params)
end
rescue Exception => e
@message = e.message
end
@tag_disciplines = current_tag_discipline.sub_discipline&.tag_disciplines
end
def destroy
@tag_discipline_id = params[:id]
ActiveRecord::Base.transaction do
sub_discipline = current_tag_discipline.sub_discipline
sub_discipline.tag_disciplines.where("position > #{current_tag_discipline.position}").update_all("position=position-1")
current_tag_discipline.destroy!
end
end
def adjust_position
sub_discipline = current_tag_discipline.sub_discipline
max_position = sub_discipline.tag_disciplines.pluck(:position).max
opr = params[:opr] || "down"
if (params[:opr] == "up" && current_tag_discipline.position == 1) || (params[:opr] == "down" && current_tag_discipline.position == max_position)
@message = "超出范围"
else
ActiveRecord::Base.transaction do
if opr == "up"
sub_discipline.tag_disciplines.find_by("position = #{current_tag_discipline.position - 1}")&.update!(position: current_tag_discipline.position)
current_tag_discipline.update!(position: current_tag_discipline.position - 1)
else
sub_discipline.tag_disciplines.find_by("position = #{current_tag_discipline.position + 1}")&.update!(position: current_tag_discipline.position)
current_tag_discipline.update!(position: current_tag_discipline.position + 1)
end
end
end
@tag_disciplines = sub_discipline&.tag_disciplines
rescue Exception => e
@message = e.message
end
private

@ -0,0 +1,43 @@
class Admins::TagRepertoiresController < Admins::BaseController
def index
@sub_repertoire = current_sub_repertoire
@tag_repertoires = current_sub_repertoire.tag_repertoires
end
def create
name = params[:name].to_s.strip
return render_error('名称重复') if current_sub_repertoire.tag_repertoires.where(name: name).exists?
TagRepertoire.create!(name: name, sub_repertoire_id: current_sub_repertoire.id)
render_ok
end
def edit
@tag_repertoire = current_tag_repertoire
end
def update
if params[:tag_repertoire] && params[:tag_repertoire][:name].present?
name = params[:tag_repertoire][:name].to_s.strip
current_tag_repertoire.update_attributes!(name: name)
end
@tag_repertoires = current_tag_repertoire.sub_repertoire&.tag_repertoires
end
def destroy
@tag_repertoire_id = params[:id]
current_tag_repertoire.destroy!
end
private
def current_sub_repertoire
@_current_sub_repertoire = SubRepertoire.find params[:sub_repertoire_id]
end
def current_tag_repertoire
@_current_tag_repertoire = TagRepertoire.find params[:id]
end
end

@ -48,6 +48,19 @@ class ApplicationController < ActionController::Base
EduSetting.get(name)
end
# 平台身份权限判断(学生用户无权限)
def identity_auth
ue = current_user.user_extension
tip_exception(403, "..") unless current_user.admin_or_business? || ue.teacher? || ue.professional?
end
# 平台已认证身份判断(已认证的老师和专业人士)
def certi_identity_auth
ue = current_user.user_extension
tip_exception(403, "..") unless current_user.admin_or_business? ||
(current_user.professional_certification && (ue.teacher? || ue.professional?))
end
def shixun_marker
unless current_user.is_shixun_marker? || current_user.admin_or_business?
tip_exception(403, "..")
@ -73,7 +86,7 @@ class ApplicationController < ActionController::Base
check_account
tip_exception(@course.excellent ? 410 : 409, "您没有权限进入")
end
if @user_course_identity > Course::CREATOR && @user_course_identity <= Course::STUDENT
if @user_course_identity > Course::CREATOR && @user_course_identity <= Course::STUDENT && @course.tea_id != current_user.id
# 实名认证和职业认证的身份判断
tip_exception(411, "你的实名认证和职业认证审核未通过") if @course.authentication &&
@course.professional_certification && (!current_user.authentication && !current_user.professional_certification)
@ -92,7 +105,7 @@ class ApplicationController < ActionController::Base
# 判断用户的邮箱或者手机是否可用
# params[:type] 1: 注册2忘记密码
# params[:type] 1: 注册2忘记密码3绑定
def check_mail_and_phone_valid login, type
unless login =~ /^[a-zA-Z0-9]+([._\\]*[a-zA-Z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/ || login =~ /^1\d{10}$/ ||
login =~ /^[a-zA-Z0-9]+([._\\]*[a-zA-Z0-9])$/
@ -104,6 +117,8 @@ class ApplicationController < ActionController::Base
tip_exception(-2, "该手机号码或邮箱已被注册")
elsif type.to_i == 2 && user.nil?
tip_exception(-2, "该手机号码或邮箱未注册")
elsif type.to_i == 3 && user.present?
tip_exception(-2, "该手机号码或邮箱已绑定")
end
sucess_status
end
@ -218,7 +233,7 @@ class ApplicationController < ActionController::Base
# 未授权的捕捉407弹试用申请弹框
def require_login
#6.13 -hs
tip_exception(401, "..") unless User.current.logged?
tip_exception(401, "请登录后再操作") unless User.current.logged?
end
# 异常提醒
@ -632,7 +647,8 @@ class ApplicationController < ActionController::Base
end
def paginate(relation)
limit = (params[:limit].to_i.zero? || params[:limit].to_i > 20) ? 20 : params[:limit].to_i
limit = params[:limit] || params[:per_page]
limit = (limit.to_i.zero? || limit.to_i > 20) ? 20 : limit.to_i
page = params[:page].to_i.zero? ? 1 : params[:page].to_i
offset = (page - 1) * limit
@ -643,6 +659,8 @@ class ApplicationController < ActionController::Base
end
end
def strf_time(time)
time.blank? ? '' : time.strftime("%Y-%m-%d %H:%M:%S")
end

@ -17,9 +17,11 @@ class AttachmentsController < ApplicationController
redirect_to @file.cloud_url and return
end
pdf_attachment = params[:disposition] || "attachment"
if pdf_attachment == "inline"
type_attachment = params[:disposition] || "attachment"
if type_attachment == "inline"
send_file absolute_path(local_path(@file)),filename: @file.title, disposition: 'inline',type: 'application/pdf'
elsif type_attachment == "MP4"
send_file_with_range absolute_path(local_path(@file)), disposition: 'inline', type: "video/mp4", range: true
else
send_file(absolute_path(local_path(@file)), filename: @file.title,stream:false, type: @file.content_type.presence || 'application/octet-stream')
end
@ -202,4 +204,31 @@ class AttachmentsController < ApplicationController
end
end
def send_file_with_range(path, options = {})
logger.info("########request.headers: #{request.headers}")
logger.info("########request.headers: #{File.exist?(path)}")
if File.exist?(path)
size = File.size(path)
logger.info("########request.headers: #{request.headers}")
if !request.headers["Range"]
status_code = 200 # 200 OK
offset = 0
length = File.size(path)
else
status_code = 206 # 206 Partial Content
bytes = Rack::Utils.byte_ranges(request.headers, size)[0]
offset = bytes.begin
length = bytes.end - bytes.begin
end
response.header["Accept-Ranges"] = "bytes"
response.header["Content-Range"] = "bytes #{bytes.begin}-#{bytes.end}/#{size}" if bytes
response.header["status"] = status_code
send_data IO.binread(path, length, offset), options
else
raise ActionController::MissingFile, "Cannot read file #{path}."
end
end
end

@ -1,7 +1,11 @@
class BindUsersController < ApplicationController
before_action :require_login
# before_action :require_login
def create
# user = CreateBindUserService.call(create_params)
#
if params[:type] == "qq"
begin
user = CreateBindUserService.call(current_user, create_params)
successful_authentication(user) if user.id != current_user.id
@ -9,6 +13,24 @@ class BindUsersController < ApplicationController
rescue ApplicationService::Error => ex
render_error(ex.message)
end
else
begin
tip_exception '系统错误' if session[:unionid].blank?
bind_user = User.try_to_login(params[:username], params[:password])
tip_exception '用户名或者密码错误' if bind_user.blank?
tip_exception '用户名或者密码错误' unless bind_user.check_password?(params[:password].to_s)
tip_exception '该账号已被绑定,请更换其他账号进行绑定' if bind_user.bind_open_user?(params[:type].to_s)
OpenUsers::Wechat.create!(user: bind_user, uid: session[:unionid])
successful_authentication(bind_user)
render_ok
rescue Exception => e
render_error(e.message)
end
end
end
def new_user
current_user

@ -181,7 +181,7 @@ class ChallengesController < ApplicationController
begin
ActiveRecord::Base.transaction do
tab = params[:tab].to_i
@challenge.update_attributes(challenge_params)
@challenge.update_attributes!(challenge_params)
if tab == 0 && @challenge.st == 0
@challenge.challenge_tags.delete_all
if params[:challenge_tag].present?
@ -211,7 +211,7 @@ class ChallengesController < ApplicationController
# last 末尾匹配, full: 全完匹配
logger.info("set: #{set}; match_rule : #{set[:match_rule]}")
match_rule = set[:match_rule] == 'last' ? 'last' : 'full'
TestSet.create(:challenge_id => @challenge.id,
TestSet.create!(:challenge_id => @challenge.id,
:input => "#{set[:input]}",
:output => "#{set[:output]}",
:is_public => params_hidden[index],
@ -227,8 +227,11 @@ class ChallengesController < ApplicationController
@challenge.update_attributes(picture_path: nil, web_route: nil, expect_picture_path: nil, original_picture_path: nil)
end
# 关卡评测执行文件如果被修改,需要修改脚本内容
logger.info("############shixun_publiced:#{@shixun.public == 0}")
if @shixun.public == 0
script = modify_shixun_script @shixun, @shixun.evaluate_script
@shixun.shixun_info.update_column(:evaluate_script, script)
end
# TODO:
# if path != params[:challenge][:path]
# shixun_modify_status_without_publish(@shixun, 1)
@ -237,9 +240,9 @@ class ChallengesController < ApplicationController
end
end
rescue => e
logger_error("##update_challenges: ##{e.message}")
tip_exception("更新失败!")
rescue Exception => e
logger.error("##update_challenges: ##{e.message}")
tip_exception("#{e.message}")
end
end
@ -262,7 +265,7 @@ class ChallengesController < ApplicationController
params[:challenge_answer].each_with_index do |answer, index|
# 内容为空不保存
next if answer[:contents].blank?
ChallengeAnswer.create(name: answer[:name], contents: answer[:contents],
ChallengeAnswer.create!(name: answer[:name], contents: answer[:contents],
level: index+1, score: answer[:score], challenge_id: @challenge.id)
end
end

@ -136,22 +136,22 @@ class CollegesController < ApplicationController
private
def require_login
return if User.current.logged?
redirect_to "/login?back_url=#{CGI::escape(request.fullpath)}"
end
# def require_login
# return if User.current.logged?
#
# redirect_to "/login?back_url=#{CGI::escape(request.fullpath)}"
# end
def check_college_present!
return if current_college.present?
redirect_to '/404'
tip_exception(404, "")
end
def check_manage_permission!
return if can_manage_college?
redirect_to '/403'
tip_exception(403, "")
end
def can_manage_college?
@ -160,7 +160,7 @@ class CollegesController < ApplicationController
return true if current_user.is_teacher? && current_user.school_id == current_school.id # 学校老师
# return true if current_school.customers.exists? && current_user.partner&.partner_customers&.exists?(customer_id: current_school.customer_id)
false
tip_exception(403, "")
end
def current_school

@ -6,12 +6,25 @@ module ControllerRescueHandler
Util.logger_error e
render json: {status: -1, message: e.message}
end
rescue_from ActiveRecord::StatementInvalid do |e|
Util.logger_error e
render json: {status: -1, message: "接口数据异常"}
end
rescue_from NoMethodError do |e|
Util.logger_error e
render json: {status: -1, message: "接口方法异常"}
end
rescue_from ActionController::UnknownFormat do |e|
render json: {status: -1, message: "接口调用非JSON格式"}
end
# rescue_from ActionView::MissingTemplate, with: :object_not_found
# rescue_from ActiveRecord::RecordNotFound, with: :object_not_found
rescue_from Educoder::TipException, with: :tip_show
rescue_from ::ActionView::MissingTemplate, with: :missing_template
rescue_from ActiveRecord::RecordNotFound, with: :object_not_found
rescue_from ActionController::ParameterMissing, with: :render_parameter_missing
# form validation error
rescue_from ActiveModel::ValidationError do |ex|
render_error(ex.model.errors.full_messages.join(','))
@ -19,5 +32,9 @@ module ControllerRescueHandler
rescue_from ActiveRecord::RecordInvalid do |ex|
render_error(ex.record.errors.full_messages.join(','))
end
# rescue_from RuntimeError do |ex|
# Util.logger_error "#######ex:#{ex}"
# render_error(ex.message)
# end
end
end

@ -16,7 +16,7 @@ module LoginHelper
:expires => 1.month.from_now,
:path => '/',
:secure => false,
:httponly => true
:httponly => false
}
if edu_setting('cookie_domain').present?
cookie_options = cookie_options.merge(domain: edu_setting('cookie_domain'))

@ -16,5 +16,25 @@ module RenderExpand
send_data kit.to_pdf, filename: options[:filename], disposition: options[:disposition] || 'attachment', type: 'application/pdf'
end
ActionController.add_renderer :exam_pdf do |template, options|
file = File.open(Rails.root.join('app/templates', template << '.html.erb'))
html = ERB.new(file.read).result(binding)
kit = PDFKit.new(html)
# PDFKit初始化后再添加样式文件到stylesheets会出现在页面的<!DOCTYPE>定义不起作用文档模式为默认为BackCompat从而导致katex不起作用
# 而测试发现通过配置添加css样式文件不会有影响
PDFKit.configure do |config|
config.default_options = {
:"user-style-sheet" => Rails.root.join('app/templates', options[:stylesheets])
}
end
send_data kit.to_pdf, filename: options[:filename], disposition: options[:disposition] || 'attachment', type: 'application/pdf'
end
end
end

@ -2,7 +2,7 @@ class CourseGroupsController < ApplicationController
before_action :require_login, :check_auth
before_action :set_group, except: [:create]
before_action :find_course, only: [:create]
before_action :teacher_allowed
before_action :teacher_allowed, except: [:set_invite_code_halt]
def create
tip_exception("分班名称不能为空") if params[:name].blank?
@ -55,6 +55,15 @@ class CourseGroupsController < ApplicationController
end
end
# 邀请码停用/启用
def set_invite_code_halt
teacher = @course.teachers.find_by(user_id: current_user.id)
tip_exception(403, "无权限") unless current_user.admin_or_business? ||
(teacher.present? && (teacher.teacher_course_groups.pluck(:course_group_id).include?(@group.id) || teacher.teacher_course_groups.size == 0))
@group.update!(invite_code_halt: !@group.invite_code_halt)
normal_status(0, "成功")
end
private
def set_group

@ -1,6 +1,7 @@
class CoursesController < ApplicationController
include MessagesHelper
include ExportHelper
include CustomSortable
# model validation error
rescue_from ActiveRecord::RecordInvalid do |ex|
@ -12,7 +13,7 @@ class CoursesController < ApplicationController
end
before_action :require_login, except: [:index, :show, :students, :teachers, :board_list, :mine, :all_course_groups,
:left_banner, :top_banner, :informs, :online_learning, :course_groups]
:left_banner, :top_banner, :informs, :online_learning, :course_groups, :search_slim]
before_action :check_account, only: [:new, :create, :apply_to_join_course, :join_excellent_course]
before_action :check_auth, except: [:index, :show, :students, :teachers, :board_list, :mine, :all_course_groups,
:left_banner, :top_banner, :apply_to_join_course, :exit_course, :course_groups]
@ -23,8 +24,8 @@ class CoursesController < ApplicationController
:course_group_list, :set_course_group, :change_course_admin, :change_course_teacher,
:delete_course_teacher, :teacher_application_review, :students, :all_course_groups,
:transfer_to_course_group, :delete_from_course, :search_users, :add_students_by_search,
:base_info, :get_historical_courses, :create_group_by_importing_file,
:attahcment_category_list,:export_member_scores_excel, :duplicate_course,
:base_info, :get_historical_courses, :create_group_by_importing_file, :course_videos,
:attahcment_category_list,:export_member_scores_excel, :duplicate_course, :delete_course_video,
:switch_to_teacher, :switch_to_assistant, :switch_to_student, :exit_course,
:informs, :update_informs, :online_learning, :update_task_position, :tasks_list,
:join_excellent_course, :export_couser_info, :export_member_act_score, :new_informs,
@ -100,6 +101,23 @@ class CoursesController < ApplicationController
@courses = @courses.preload(:school, :none_hidden_course_modules, teacher: :user_extension)
end
def course_videos
logger.info("########[#{@course}")
videos = @course.videos
videos = custom_sort(videos, params[:sort_by], params[:sort_direction])
@count = videos.count
@videos = paginate videos
end
def delete_course_video
video = Video.find_by(id: params[:video_id])
tip_exception(404, "找不到资源") if video.blank?
tip_exception(403, "...") unless (video.user_id == current_user.id || current_user.admin_or_business?)
video.destroy!
AliyunVod::Service.delete_video([video.uuid]) rescue nil
render_ok
end
def visits_plus_one
new_visits = @course.visits + 1
@course.update_visits(new_visits)
@ -377,8 +395,7 @@ class CoursesController < ApplicationController
def destroy
if @course.is_delete == 0
@course.delete!
Tiding.create!(user_id: current_user.id, trigger_user_id: current_user.id, container_id: @course.id,
container_type: 'DeleteCourse', tiding_type: 'System', belong_container: @course, extra: @course.name)
DeleteCourseNotifyJob.perform_later(@course.id, current_user.id)
normal_status(0, "成功")
else
normal_status(-1, "课堂已删除,无需重复操作")
@ -723,12 +740,15 @@ class CoursesController < ApplicationController
# 切换为教师
def switch_to_teacher
begin
course_member = @course.course_members.find_by!(user_id: current_user.id, is_active: 1)
tip_exception("切换失败") unless course_member.STUDENT?
course_student = @course.students.find_by!(user_id: current_user.id, is_active: 1)
tip_exception("切换失败") unless course_student.present?
course_teacher = CourseMember.find_by!(user_id: current_user.id, role: %i[CREATOR PROFESSOR], course_id: @course.id)
course_member.update!(is_active: 0)
ActiveRecord::Base.transaction do
course_student.destroy!
course_teacher.update!(is_active: 1)
CourseDeleteStudentDeleteWorksJob.perform_later(@course.id, [current_user.id])
end
normal_status(0, "切换成功")
rescue => e
uid_logger_error(e.message)
@ -739,12 +759,15 @@ class CoursesController < ApplicationController
# 切换为助教
def switch_to_assistant
begin
course_member = @course.course_members.find_by!(user_id: current_user.id, is_active: 1)
tip_exception("切换失败") unless course_member.STUDENT?
course_student = @course.course_members.find_by!(user_id: current_user.id, is_active: 1)
tip_exception("切换失败") unless course_student.present?
course_teacher = CourseMember.find_by!(user_id: current_user.id, role: %i[ASSISTANT_PROFESSOR], course_id: @course.id)
course_member.update!(is_active: 0)
ActiveRecord::Base.transaction do
course_student.destroy!
course_teacher.update!(is_active: 1)
CourseDeleteStudentDeleteWorksJob.perform_later(@course.id, [current_user.id])
end
normal_status(0, "切换成功")
rescue => e
uid_logger_error(e.message)
@ -1109,11 +1132,11 @@ class CoursesController < ApplicationController
return normal_status(-1, "邀请码不能为空") if params[:invite_code].blank?
invite_code = params[:invite_code]
course = Course.find_by(invite_code: invite_code, is_delete: 0, invite_code_halt: 0, laboratory_id: current_laboratory.id)
course_group = CourseGroup.find_by(invite_code: invite_code)
course_group = CourseGroup.find_by(invite_code: invite_code, invite_code_halt: 0)
if course.blank?
return normal_status(-1, "邀请码无效") if course_group.blank?
course = Course.find_by(id: course_group.course_id, is_delete: 0, invite_code_halt: 0, laboratory_id: current_laboratory.id)
course = Course.find_by(id: course_group.course_id, is_delete: 0, laboratory_id: current_laboratory.id)
return normal_status(-1, "邀请码无效") if course.blank?
end
@ -1146,6 +1169,7 @@ class CoursesController < ApplicationController
if existing_student.present?
# 如果在该课堂已经存在学生身份,且邀请码为分班邀请码,则将其直接加入分班
existing_student.update!(course_group_id: course_group.id) if course_group.present?
message = "您已是课堂成员"
else
correspond_teacher_exist = current_user.none_admin_teacher_of_course? course
new_student = CourseMember.new(user_id: current_user.id, course_id: course.id, role: 4)
@ -1156,9 +1180,9 @@ class CoursesController < ApplicationController
CourseAddStudentCreateWorksJob.perform_later(course.id, [current_user.id])
StudentJoinCourseNotifyJob.perform_later(current_user.id, course.id)
end
student_role = 1
end
end
# 创建教师身份
if (params[:professor].present? && params[:professor].to_i == 1) || (params[:assistant_professor].present? && params[:assistant_professor].to_i == 1)
@ -1194,9 +1218,9 @@ class CoursesController < ApplicationController
teacher_role = 1
end
if teacher_role && student_role
if (teacher_role && student_role) || message.to_s == "您已是课堂成员"
render json: { status: 0, message: message, course_id: course.id}
elsif student_role
elsif student_role.to_i == 1
render json: { status: 0, message: "加入成功", course_id: course.id}
else
normal_status(message)

@ -1,8 +1,10 @@
class ExaminationBanksController < ApplicationController
include PaginateHelper
before_action :require_login
before_action :certi_identity_auth, only: [:create, :edit, :update, :destroy, :set_public, :revoke_item]
before_action :find_exam, except: [:index, :create]
before_action :edit_auth, only: [:update, :destroy, :set_public, :revoke_item]
before_action :identity_auth, only: [:index]
def index
exams = ExaminationBankQuery.call(params)
@ -59,7 +61,7 @@ class ExaminationBanksController < ApplicationController
def set_public
tip_exception(-1, "该试卷已公开") if @exam.public?
tip_exception(-1, "请勿重复提交申请") if ApplyAction.where(container_id: @exam.id, container_type: "ExaminationBank").exists?
tip_exception(-1, "请勿重复提交申请") if ApplyAction.where(container_id: @exam.id, container_type: "ExaminationBank", status: 0).exists?
ApplyAction.create!(container_id: @exam.id, container_type: "ExaminationBank", user_id: current_user.id)
# @exam.update_attributes!(public: 1)
render_ok

@ -1,5 +1,6 @@
class ExaminationIntelligentSettingsController < ApplicationController
before_action :require_login
before_action :certi_identity_auth, only: [:create, :optinal_items, :save_exam, :exchange_one_item, :exchange_items]
before_action :find_exam, only: [:exchange_one_item, :exchange_items, :save_exam]
def optinal_items
@ -36,16 +37,19 @@ class ExaminationIntelligentSettingsController < ApplicationController
end
def exchange_one_item
item = @exam.item_baskets.find_by!(id: params[:item_id])
item = @exam.item_baskets.find_by!(item_bank_id: params[:item_id])
exam_type_setting = @exam.examination_type_settings.find_by!(item_type: item.item_type)
# 获取可选的题
items = OptionalItemQuery.call(@exam.sub_discipline_id, @exam.tag_discipline_containers.pluck(:tag_discipline_id), @exam.difficulty, @exam.public)
# 可选题中去掉已组卷的试题
type_items = items.select{ |t_item| t_item.item_type == item.item_type }
# 如果可选的题数小于等于设置的题数则提示无可换的题
tip_exception("无可换的题") if type_items.size <= exam_type_setting.count
# 可选题中去掉已组卷的同题型试题
optional_item_ids = type_items.pluck(:id) - @exam.item_baskets.where(item_type: item.item_type).pluck(:item_bank_id)
optional_item_ids = (type_items.pluck(:id) - @exam.item_baskets.where(item_type: item.item_type).pluck(:item_bank_id)).uniq
# 如果可选的题数等于0则提示无可换的题
tip_exception("无可换的题") if optional_item_ids.size == 0
new_item = ItemBank.find optional_item_ids.sample(1).first
ActiveRecord::Base.transaction do
@exam.item_baskets << ItemBasket.new(item_bank_id: new_item.id, position: item.position, score: item.score, item_type: new_item.item_type)
@ -61,13 +65,15 @@ class ExaminationIntelligentSettingsController < ApplicationController
# 获取可选的题
items = OptionalItemQuery.call(@exam.sub_discipline_id, @exam.tag_discipline_containers.pluck(:tag_discipline_id), @exam.difficulty, @exam.public)
type_items = items.select{ |t_item| t_item.item_type == params[:item_type] }
# 如果可选的题数小于等于设置的题数则提示无可换的题
tip_exception("无可换的题") if type_items.size <= exam_type_setting.count
# 可选题中去掉已组卷的同题型试题
# 可选题中去掉已组卷的试题
choosed_item_ids = choosed_items.pluck(:item_bank_id)
optional_item_ids = type_items.pluck(:id) - choosed_item_ids
optional_item_ids = (type_items.pluck(:id) - choosed_item_ids).uniq
# 如果可选的题数等于0则提示无可换的题
tip_exception("无可换的题") if optional_item_ids.size == 0
# 如果可选题数小于设置的题数n则在原来的选题中随机选n个确保换题时能选到新的题
# 如果可选题数小于设置的题数n则在原来的选题中随机选n个确保换题时能选到新的题
if optional_item_ids.size < exam_type_setting.count
absence_count = exam_type_setting.count - optional_item_ids.size
optional_item_ids = optional_item_ids + choosed_item_ids.sample(absence_count)

@ -1,5 +1,6 @@
class ExaminationItemsController < ApplicationController
before_action :require_login
before_action :certi_identity_auth, only: [:create, :destroy, :delete_item_type, :set_score, :batch_set_score, :adjust_position]
before_action :validate_score, only: [:set_score, :batch_set_score]
before_action :find_exam, only: [:create, :batch_set_score, :delete_item_type]
before_action :find_item, except: [:create, :batch_set_score, :delete_item_type]

@ -1,12 +1,12 @@
class ExerciseQuestionsController < ApplicationController
before_action :require_login, :check_auth #用户需登陆
before_action :get_exercise,only:[:new,:create] #获取试卷
before_action :get_exercise_question,except: [:new,:create] #获取试卷的问题及试卷
before_action :get_exercise, only: [:new, :create] #获取试卷
before_action :get_exercise_question, except: [:new, :create] #获取试卷的问题及试卷
before_action :is_course_teacher #是否为老师
before_action :validate_params,only: [:create,:update] #传入参数的验证
before_action :check_exercise_status,only: [:new,:create,:delete_answer,:destroy] #除未发布状态之外,其余状态不能进行增删操作
before_action :cannot_change_column,only: [:update] #更新时不能更改的内容
before_action :check_adjust_score,only: [:adjust_score]
before_action :validate_params, only: [:create, :update] #传入参数的验证
before_action :check_exercise_status, only: [:new, :create, :delete_answer, :destroy] #除未发布状态之外,其余状态不能进行增删操作
before_action :cannot_change_column, only: [:update] #更新时不能更改的内容
before_action :check_adjust_score, only: [:adjust_score]
include ExercisesHelper
def new
@ -24,7 +24,6 @@ class ExerciseQuestionsController < ApplicationController
#question_type 0为单选题1为多选题2为判断题3为填空题单空和多空4为简答题5为实训题
def create
ActiveRecord::Base.transaction do
begin
question_options = {
:question_title => params[:question_title],
:question_type => params[:question_type].present? ? params[:question_type].to_i : 0, #默认为单选题
@ -49,11 +48,11 @@ class ExerciseQuestionsController < ApplicationController
ques_type = @exercise_question.question_type
if ques_type <= Exercise::MULTIPLE
choices_array = params[:question_choices]
choices_count= choices_array.count
choices_count = choices_array.count
standard_answer = params[:standard_answers] #为数组格式,因为可能会有单选和多选,标准答案,已提前判断不能为空,
standard_answer = standard_answer.uniq.reject(&:blank?)
(1..choices_count).each do |c|
choice = choices_array[c-1] #每一个选项的内容
choice = choices_array[c - 1] #每一个选项的内容
choice_option = {
:choice_position => c,
:choice_text => choice.strip
@ -71,16 +70,16 @@ class ExerciseQuestionsController < ApplicationController
question_standard_answer = ExerciseStandardAnswer.new(standard_option)
question_standard_answer.save!
if standard_answer.count > 1 && ques_type == Exercise::SINGLE #当标准答案数大于1且不为多选时修改为多选
@exercise_question.update_attribute("question_type",Exercise::MULTIPLE)
@exercise_question.update_attribute("question_type", Exercise::MULTIPLE)
elsif standard_answer.count == 1 && ques_type == Exercise::MULTIPLE
@exercise_question.update_attribute("question_type",Exercise::SINGLE)
@exercise_question.update_attribute("question_type", Exercise::SINGLE)
end
end
elsif ques_type == Exercise::JUDGMENT #这个为判断题
choices_array = params[:question_choices] #判断的选项,对/错等等
choices_count= choices_array.count
choices_count = choices_array.count
(1..choices_count).each do |c|
choice = choices_array[c-1] #每一个选项的内容
choice = choices_array[c - 1] #每一个选项的内容
choice_option = {
:choice_position => c,
:choice_text => choice.strip
@ -127,7 +126,7 @@ class ExerciseQuestionsController < ApplicationController
shixun_scores = params[:question_scores] #试卷有多个的分值有多个分数表,所以为分数的数组
shixun_name = params[:shixun_name] || shixun.name
question_score = 0
shixun.challenges.try(:each_with_index) do |challenge,index|
shixun.challenges.try(:each_with_index) do |challenge, index|
shixun_option = {
:challenge_id => challenge.id,
:shixun_id => shixun.id,
@ -138,13 +137,8 @@ class ExerciseQuestionsController < ApplicationController
ex_shixun_challenge = ExerciseShixunChallenge.create!(shixun_option)
question_score += ex_shixun_challenge.question_score # 问题的分数,为各个关卡分数的总和
end
@exercise_question.update!(:question_score => question_score,:shixun_name=> shixun_name)
end
@exercise_question.update!(:question_score => question_score, :shixun_name => shixun_name)
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception("试卷问题创建失败!")
raise ActiveRecord::Rollback
end
end
end
@ -164,20 +158,13 @@ class ExerciseQuestionsController < ApplicationController
def edit
ActiveRecord::Base.transaction do
begin
@exercise_choices = @exercise_question.exercise_choices
@exercise_question_shixun = @exercise_question.exercise_shixun_challenges
rescue Exception => e
uid_logger_error(e.message)
tip_exception("页面调用失败!")
raise ActiveRecord::Rollback
end
end
end
def update
ActiveRecord::Base.transaction do
begin
standard_answer_change = false
# 更新试卷题目的内容
question_options = {
@ -198,24 +185,24 @@ class ExerciseQuestionsController < ApplicationController
choice_array_count_array = (1..choice_array_count).to_a
if ex_choice_count > choice_array_count #如果选项有减少的,那么只更新传入的,删除以前的
choice_array_count_array.each do |c|
choice = choices_array[c-1] #每一个选项的内容
exercise_choice = @exercise_question.exercise_choices.find_choice_custom("choice_position",(c))
exercise_choice.update(choice_text:choice)
choice = choices_array[c - 1] #每一个选项的内容
exercise_choice = @exercise_question.exercise_choices.find_choice_custom("choice_position", (c))
exercise_choice.update(choice_text: choice)
end
drop_ex_choice = @exercise_question.exercise_choices.left_choice_choose("choice_position",(choice_array_count))
drop_ex_choice = @exercise_question.exercise_choices.left_choice_choose("choice_position", (choice_array_count))
drop_ex_choice.destroy_all
else
ex_choice_count_array.each do |c|
choice = choices_array[c-1] #每一个选项的内容
exercise_choice = @exercise_question.exercise_choices.find_choice_custom("choice_position",(c))
exercise_choice.update(choice_text:choice)
choice = choices_array[c - 1] #每一个选项的内容
exercise_choice = @exercise_question.exercise_choices.find_choice_custom("choice_position", (c))
exercise_choice.update(choice_text: choice)
end
new_add_choice = choice_array_count_array - ex_choice_count_array #新传入的需新增
if new_add_choice.count > 0
new_add_choice.each do |i|
choice_option = {
:choice_position => i,
:choice_text => choices_array[i-1].strip
:choice_text => choices_array[i - 1].strip
}
question_choices = @exercise_question.exercise_choices.new(choice_option)
question_choices.save!
@ -248,9 +235,9 @@ class ExerciseQuestionsController < ApplicationController
end
if standard_answer.count > 1 && @exercise_question.question_type == Exercise::SINGLE #当标准答案数大于1且不为多选时修改为多选
@exercise_question.update_attribute("question_type",Exercise::MULTIPLE)
@exercise_question.update_attribute("question_type", Exercise::MULTIPLE)
elsif standard_answer.count == 1 && @exercise_question.question_type == Exercise::MULTIPLE
@exercise_question.update_attribute("question_type",Exercise::SINGLE)
@exercise_question.update_attribute("question_type", Exercise::SINGLE)
end
end
elsif @exercise_question.question_type == Exercise::COMPLETION #填空题
@ -286,14 +273,14 @@ class ExerciseQuestionsController < ApplicationController
:answer_text => null_choice_text[n - 1]
}
standard_option = @hash_symbol_null_
ex_answer_pre[n-1].update(standard_option)
ex_answer_pre[n - 1].update(standard_option)
end
if new_add_choice.count > 0 #表示有新增的
new_add_choice.each do |i|
standard_option = {
:exercise_question_id => @exercise_question.id,
:exercise_choice_id => null_choice_id,
:answer_text => null_choice_text[i-1]
:answer_text => null_choice_text[i - 1]
}
question_standard_answer = ExerciseStandardAnswer.new(standard_option)
question_standard_answer.save!
@ -301,7 +288,7 @@ class ExerciseQuestionsController < ApplicationController
end
else
new_delete_choice = ex_answer_pre_count_array - null_choice_text_count_array
null_choice_text.each_with_index do |n,index|
null_choice_text.each_with_index do |n, index|
standard_option = {
:exercise_question_id => @exercise_question.id,
:exercise_choice_id => null_choice_id,
@ -311,7 +298,7 @@ class ExerciseQuestionsController < ApplicationController
end
if new_delete_choice.count > 0 #表示填空题的答案有删减的
new_delete_choice.each do |d|
ex_answer_pre[d-1].destroy
ex_answer_pre[d - 1].destroy
end
end
end
@ -333,7 +320,7 @@ class ExerciseQuestionsController < ApplicationController
if @exercise_question.question_type == Exercise::SUBJECTIVE #主观题
main_standard_answer = standard_answer.present? ? standard_answer.first : nil
if @exercise_answers_array.present?
@exercise_answers_array.first.update_attribute("answer_text",main_standard_answer)
@exercise_answers_array.first.update_attribute("answer_text", main_standard_answer)
else
standard_option = {
:exercise_question_id => @exercise_question.id,
@ -371,15 +358,9 @@ class ExerciseQuestionsController < ApplicationController
# end
# end
# end
normal_status(3,"修改了标准答案\n是否重新计算学生答题的成绩?")
normal_status(3, "修改了标准答案\n是否重新计算学生答题的成绩?")
else
normal_status(0,"试卷更新成功!")
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception("页面调用失败!")
raise ActiveRecord::Rollback
normal_status(0, "试卷更新成功!")
end
end
end
@ -391,17 +372,17 @@ class ExerciseQuestionsController < ApplicationController
ex_users_committed = @exercise.exercise_users.exercise_user_committed
if ex_users_committed.size > 0
ex_users_committed.each do |ex_user|
update_objective_score = update_single_score(@exercise_question,ex_user.user_id,standard_answer)
update_objective_score = update_single_score(@exercise_question, ex_user.user_id, standard_answer)
if update_objective_score != 0
objective_score = ex_user.objective_score
new_objective_score = objective_score + update_objective_score
total_score = ex_user.score + update_objective_score
total_score = total_score < 0.0 ? 0.0 : total_score
ex_user.update!(objective_score:new_objective_score,score:total_score)
ex_user.update!(objective_score: new_objective_score, score: total_score)
end
end
end
normal_status(0,"学生成绩更新成功")
normal_status(0, "学生成绩更新成功")
rescue Exception => e
uid_logger_error(e.message)
tip_exception("答案删除失败!")
@ -456,7 +437,7 @@ class ExerciseQuestionsController < ApplicationController
choice_d_id = params[:choice_no].to_i # 选项的当前位置
question_choices = @exercise_question.exercise_choices
delete_answer = question_choices.find_by(choice_position: choice_d_id)
left_choices = question_choices.where("choice_position > ? ",choice_d_id)
left_choices = question_choices.where("choice_position > ? ", choice_d_id)
left_choices.update_all("choice_position = choice_position - 1") if left_choices
if delete_answer.destroy
normal_status(0, "答案删除成功!")
@ -493,11 +474,10 @@ class ExerciseQuestionsController < ApplicationController
#老师调分窗口
def adjust_score
ActiveRecord::Base.transaction do
begin
ex_all_scores = @exercise.exercise_questions.pluck(:question_score).sum
ex_obj_score = @exercise_current_user.objective_score #全部客观题得分
ex_subj_score = @exercise_current_user.subjective_score < 0.0 ? 0.0 : @exercise_current_user.subjective_score #全部主观题得分
ex_answers = @exercise_question.exercise_answers.search_answer_users("user_id",@user_id) #当前用户答案的得分
ex_answers = @exercise_question.exercise_answers.search_answer_users("user_id", @user_id) #当前用户答案的得分
if @exercise_question.question_type == Exercise::MULTIPLE
if ex_answers.present? #学生有回答时 取学生的答题得分否则0分
answer_choice_array = []
@ -580,7 +560,7 @@ class ExerciseQuestionsController < ApplicationController
if ex_answers.exists?
ex_answers_old_score = ex_answers.first.score > 0.0 ? ex_answers.first.score : 0.0 #原分数小于0取0
new_sub_score = ex_subj_score - ex_answers_old_score + @c_score #原全部主观题总分减去原该主观题得分再加调分后的分数,即为当前全部主观题得分
ex_answers.first.update_attribute("score",@c_score)
ex_answers.first.update_attribute("score", @c_score)
else #如果学生未答,则创建新的答题记录
answer_option = {
:user_id => @user_id,
@ -604,14 +584,14 @@ class ExerciseQuestionsController < ApplicationController
@exercise_current_user.update!(ex_scores)
elsif @exercise_question.question_type == Exercise::PRACTICAL
ex_answers = @exercise_question.exercise_shixun_answers.where(user_id:@user_id,exercise_shixun_challenge_id:@shixun_a_id)
ex_answers = @exercise_question.exercise_shixun_answers.where(user_id: @user_id, exercise_shixun_challenge_id: @shixun_a_id)
if ex_answers.present? #当为实训题时
ex_shixun_old_score = ex_answers.first.score > 0.0 ? ex_answers.first.score : 0.0
new_obj_score = ex_obj_score - ex_shixun_old_score + @c_score
ex_answers.first.update_attribute("score",@c_score)
ex_answers.first.update_attribute("score", @c_score)
else
ex_shixun_option ={
ex_shixun_option = {
:exercise_question_id => @exercise_question.id,
:user_id => @user_id,
:exercise_shixun_challenge_id => @shixun_a_id,
@ -668,30 +648,25 @@ class ExerciseQuestionsController < ApplicationController
end
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception(e.message)
raise ActiveRecord::Rollback
end
end
end
private
def questions_params
params.require(:exercise_question).permit(:question_title,:question_type,
:question_number,:exercise_id,
:question_score,:shixun_id,:is_ordered)
params.require(:exercise_question).permit(:question_title, :question_type,
:question_number, :exercise_id,
:question_score, :shixun_id, :is_ordered)
end
def get_exercise
@exercise = Exercise.find_by(id:params[:exercise_id])
@exercise = Exercise.find_by(id: params[:exercise_id])
if @exercise.blank?
tip_exception(404,"试卷不存在")
tip_exception(404, "试卷不存在")
else
@course = @exercise.course
if @course.blank?
tip_exception(404,"课堂不存在")
tip_exception(404, "课堂不存在")
end
end
end
@ -708,51 +683,51 @@ class ExerciseQuestionsController < ApplicationController
if @exercise_question.present?
@exercise = @exercise_question.exercise
if @exercise.blank?
tip_exception(404,"试卷不存在")
tip_exception(404, "试卷不存在")
else
@course = @exercise.course
if @course.blank?
tip_exception(404,"课堂不存在")
tip_exception(404, "课堂不存在")
end
end
else
tip_exception(404,"试卷问题不存在")
tip_exception(404, "试卷问题不存在")
end
end
def validate_params
normal_status(-1,"题目不允许为空!") if (params[:question_title].blank? && params[:question_type].to_i != Exercise::PRACTICAL ) #除了实训题,其余题目必需有题干
normal_status(-1,"问题类型不允许为空!" ) if params[:question_type].blank?
normal_status(-1,"分值不允许为空!" ) if params[:question_score].blank? && params[:question_scores].blank? #分值的数组或参数必需存在一个
normal_status(-1, "题目不允许为空!") if (params[:question_title].blank? && params[:question_type].to_i != Exercise::PRACTICAL) #除了实训题,其余题目必需有题干
normal_status(-1, "问题类型不允许为空!") if params[:question_type].blank?
normal_status(-1, "分值不允许为空!") if params[:question_score].blank? && params[:question_scores].blank? #分值的数组或参数必需存在一个
if params[:question_score].present? && params[:question_score].to_f <= 0.0 #问题类型存在,则分值不能为空,且必需大于0
normal_status(-1,"分值必需大于0")
elsif (params[:question_score].present? && params[:question_score].to_f.round(1) > 100.0) || (params[:question_scores].present? && (params[:question_scores].map{|a| a.to_f.round(1)}.max > 100.0))
normal_status(-1,"分值不能超过100分")
normal_status(-1, "分值必需大于0")
elsif (params[:question_score].present? && params[:question_score].to_f.round(1) > 100.0) || (params[:question_scores].present? && (params[:question_scores].map {|a| a.to_f.round(1)}.max > 100.0))
normal_status(-1, "分值不能超过100分")
elsif params[:question_scores].present? && params[:question_scores].include?(0.0) #如果有负数,则自动取绝对值,#多个分数值,针对实训题的
normal_status(-1,"分值必需大于0")
normal_status(-1, "分值必需大于0")
elsif params[:standard_answers].present? && params[:question_choices].present? && (params[:standard_answers].count > params[:question_choices].count)
normal_status(-1,"标准答案数不能大于选项数!")
elsif [0,1,2,3].include?(params[:question_type].to_i) && (params[:standard_answers].blank? || params[:standard_answers].include?("")) #选择题/判断题/填空题 问题选项/标准答案不能为空,也不能包含空的内容
normal_status(-1,"标准答案不能为空!")
normal_status(-1, "标准答案数不能大于选项数!")
elsif [0, 1, 2, 3].include?(params[:question_type].to_i) && (params[:standard_answers].blank? || params[:standard_answers].include?("")) #选择题/判断题/填空题 问题选项/标准答案不能为空,也不能包含空的内容
normal_status(-1, "标准答案不能为空!")
elsif params[:question_type].to_i == 2 && (params[:standard_answers].count > 1 || params[:question_choices].blank? || params[:question_choices].include?("")) #判断题的标准答案不能大于1个选项不能为空
normal_status(-1,"判断题选项不能为空/标准答案不能大于1个")
normal_status(-1, "判断题选项不能为空/标准答案不能大于1个")
elsif params[:question_type].to_i <= 1 && (params[:question_choices].blank? || params[:question_choices].include?("") || params[:question_choices].count < 2) #选择题选项不能为空,且不能小于2
normal_status(-1,"选择题选项内容不能为空且不能少于2个")
elsif params[:question_type].to_i == 3 && (params[:standard_answers].blank? || params[:standard_answers].count > 5 ) #填空题选项最多为5个,且如果为1个的话不允许修改is_ordered
normal_status(-1,"填空题标准答案不能为空/不能超过5个")
normal_status(-1, "选择题选项内容不能为空且不能少于2个")
elsif params[:question_type].to_i == 3 && (params[:standard_answers].blank? || params[:standard_answers].count > 5) #填空题选项最多为5个,且如果为1个的话不允许修改is_ordered
normal_status(-1, "填空题标准答案不能为空/不能超过5个")
elsif params[:question_type].to_i == 4 && params[:standard_answers].count > 2 #简单题参考答案最多为1个
normal_status(-1,"简答题的参考答案不能大于2个")
normal_status(-1, "简答题的参考答案不能大于2个")
elsif params[:question_type].to_i == 5
if params[:shixun_id].blank? #实训题的id不能为空
normal_status(-1,"实训题id不能为空")
normal_status(-1, "实训题id不能为空")
elsif params[:shixun_name].blank?
normal_status(-1,"实训题名称不能为空!")
normal_status(-1, "实训题名称不能为空!")
end
end
end
def check_exercise_status
normal_status(-1,"不能更改试卷问题!") if @exercise.exercise_status != Exercise::UNPUBLISHED
normal_status(-1, "不能更改试卷问题!") if @exercise.exercise_status != Exercise::UNPUBLISHED
end
#更新时不能修改的内容
@ -767,19 +742,19 @@ class ExerciseQuestionsController < ApplicationController
update_choices_count = params[:question_choices].present? ? params[:question_choices].count : choices_count #传入的选项个数
standard_answer = params[:standard_answers] #传参数是怎么传的?能不能传空值?
if update_question_score.present? && question_score != update_question_score #分数有更改
normal_status(-1,"已发布/已截止,分数不允许修改!")
normal_status(-1, "已发布/已截止,分数不允许修改!")
elsif update_choices_count != choices_count #选项个数有修改
normal_status(-1,"已发布/已截止,不允许增删答案!")
normal_status(-1, "已发布/已截止,不允许增删答案!")
elsif standard_answer.present?
if @exercise_question.question_type == Exercise::COMPLETION
# exercise_answers_text = standard_answer.map{|a| a[:answer_text]}.sum.uniq
# unless (standard_answer.count == exercise_choice_ids.count) && (standard_answers_text.count == exercise_answers_text.count)
unless standard_answer.count == exercise_choice_ids.count
normal_status(-1,"已发布/已截止,不允许增删标准答案!")
normal_status(-1, "已发布/已截止,不允许增删标准答案!")
end
elsif @exercise_question.question_type == Exercise::SUBJECTIVE
unless standard_answers_text.count == standard_answer.count
normal_status(-1,"已发布/已截止,不允许增删标准答案!")
normal_status(-1, "已发布/已截止,不允许增删标准答案!")
end
end
end
@ -791,13 +766,13 @@ class ExerciseQuestionsController < ApplicationController
@user_id = params[:user_id]
@exercise_current_user = @exercise.exercise_users.exercise_commit_users(@user_id).first #当前试卷用户的答案内容
if @exercise_current_user.blank?
normal_status(-1,"用户不存在!")
normal_status(-1, "用户不存在!")
elsif @c_score.blank?
normal_status(-1,"分数不能为空!")
normal_status(-1, "分数不能为空!")
elsif @exercise_question.question_type == Exercise::SINGLE || @exercise_question.question_type == Exercise::JUDGMENT
normal_status(-1,"单选题/判断题不能调分!")
normal_status(-1, "单选题/判断题不能调分!")
elsif params[:comment].present? && params[:comment].length > 100
normal_status(-1,"评语不能超过100个字符!")
normal_status(-1, "评语不能超过100个字符!")
else
@shixun_a_id = params[:shixun_challenge_id]
if @exercise_question.question_type == Exercise::PRACTICAL #当为实训题时,为关卡的分数
@ -806,13 +781,13 @@ class ExerciseQuestionsController < ApplicationController
@old_ques_score = @shixun_challenge.first.question_score
else
@old_ques_score = nil
normal_status(-1,"实训答案id不能为空!")
normal_status(-1, "实训答案id不能为空!")
end
else
@old_ques_score = @exercise_question.question_score #当不为实训题时,为各问题的分数
end
if @old_ques_score.present? && (@c_score > @old_ques_score)
normal_status(-1,"分数不能大于题目分数!")
normal_status(-1, "分数不能大于题目分数!")
end
end
end

@ -1235,7 +1235,7 @@ class ExercisesController < ApplicationController
normal_status(0, "正在下载中")
else
set_export_cookies
render pdf: 'exercise_export/blank_exercise', filename: filename_, stylesheets: stylesheets, disposition: 'inline', type: "pdf_attachment.content_type", stream: false
render exam_pdf: 'exercise_export/blank_exercise', filename: filename_, stylesheets: stylesheets, disposition: 'inline', type: "pdf_attachment.content_type", stream: false
end
end

@ -524,11 +524,11 @@ class GamesController < ApplicationController
else
{updated_at: Time.now}
end
logger.info("#############myshixuns_update: ##{myshixuns_update}")
#logger.info("#############myshixuns_update: ##{myshixuns_update}")
@myshixun.update_attributes!(myshixuns_update)
gitUrl = repo_ip_url @myshixun.repo_path
logger.info("#############giturl: ##{gitUrl}")
#logger.info("#############giturl: ##{gitUrl}")
gitUrl = Base64.urlsafe_encode64(gitUrl)
shixun_tomcat = edu_setting('cloud_bridge')
@ -554,7 +554,7 @@ class GamesController < ApplicationController
testSet << test_cases
end
logger.info("##############testSet: #{testSet}")
#logger.info("##############testSet: #{testSet}")
testCases = Base64.urlsafe_encode64(testSet.to_json) unless testSet.blank?
# 评测类型: 012 用于webssh的评测 3用于vnc
@ -581,7 +581,7 @@ class GamesController < ApplicationController
if secret_rep&.repo_name
secretGitUrl = repo_ip_url secret_rep.repo_path
br_params.merge!({secretGitUrl: Base64.urlsafe_encode64(secretGitUrl), secretDir: secret_rep.secret_dir_path})
logger.info("#######br_params:#{br_params}")
#logger.info("#######br_params:#{br_params}")
end
# 中间层交互
@ -700,10 +700,10 @@ class GamesController < ApplicationController
resubmit_identifier = @game.resubmit_identifier
# 如果没有超时并且正在评测中
# 判断评测中的状态有两种1、如果之前没有通关的只需判断status为1即可如果通过关则判断game的resubmit_identifier是否更新
uid_logger("################game_status: #{@game.status}")
uid_logger("################params[:resubmit]: #{params[:resubmit]}")
uid_logger("################resubmit_identifier: #{resubmit_identifier}")
uid_logger("################time_out: #{params[:time_out]}")
#uid_logger("################game_status: #{@game.status}")
#uid_logger("################params[:resubmit]: #{params[:resubmit]}")
#uid_logger("################resubmit_identifier: #{resubmit_identifier}")
#uid_logger("################time_out: #{params[:time_out]}")
sec_key = params[:sec_key]
if (params[:time_out] == "false") && ((params[:resubmit].blank? && @game.status == 1) || (params[:resubmit].present? &&
(params[:resubmit] != resubmit_identifier)))
@ -764,7 +764,7 @@ class GamesController < ApplicationController
end
end
uid_logger("game is #{@game.id}, record id is #{e_record.try(:id)}, time is**** #{Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")}")
#uid_logger("game is #{@game.id}, record id is #{e_record.try(:id)}, time is**** #{Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")}")
# 记录前端总耗时
record_consume_time = e_record.try(:pod_execute)
max_mem = e_record.try(:max_mem)
@ -850,7 +850,7 @@ class GamesController < ApplicationController
@allowed_hidden_testset = @identity < User::EDU_GAME_MANAGER || @game.test_sets_view #解锁的用户
if max_query_index > 0
uid_logger("max_query_index is #{max_query_index} game id is #{@game.id}, challenge_id is #{challenge.id}")
#uid_logger("max_query_index is #{max_query_index} game id is #{@game.id}, challenge_id is #{challenge.id}")
@qurey_test_sets = TestSet.find_by_sql("SELECT o.code, o.actual_output, o.out_put, o.result, o.test_set_position, o.ts_time, o.ts_mem,
o.query_index, t.is_public, t.input, t.output, o.compile_success FROM outputs o, games g, challenges c,
test_sets t where g.id=#{@game.id} and c.id=#{challenge.id} and o.query_index=#{max_query_index}

@ -368,6 +368,7 @@ class HomeworkCommonsController < ApplicationController
ActiveRecord::Base.transaction do
begin
@homework = HomeworkCommon.new(homework_params)
@homework.reference_answer = params[:reference_answer].to_s.strip
@homework.homework_type = @homework_type
@homework.user_id = current_user.id
@homework.course_id = @course.id
@ -417,6 +418,7 @@ class HomeworkCommonsController < ApplicationController
ActiveRecord::Base.transaction do
begin
@homework.update_attributes!(homework_params)
@homework.reference_answer = params[:reference_answer].to_s.strip
if @homework.homework_type == "group"
homework_detail_group = @homework.homework_detail_group
@ -497,7 +499,7 @@ 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
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)
@ -874,10 +876,12 @@ class HomeworkCommonsController < ApplicationController
subjects = Subject.where(id: params[:subject_ids], status: 2).includes(stages: :shixuns).reorder("id desc")
@homework_ids = []
none_shixun_ids = ShixunSchool.where("school_id != #{current_user.school_id}").pluck(:shixun_id)
# none_shixun_ids = ShixunSchool.where("school_id != #{current_user.school_id}").pluck(:shixun_id)
course_module = @course.course_modules.find_by(module_type: "shixun_homework")
subjects.each do |subject|
shixun_ids = subject.shixuns.where(use_scope: 0).pluck(:id) +
subject.shixuns.joins(:shixun_schools).where("school_id = #{current_user.try(:school_id).to_i} and use_scope = 1").pluck(:id)
subject.stages.each do |stage|
@ -887,7 +891,7 @@ class HomeworkCommonsController < ApplicationController
course_module_id: course_module.id, position: course_module.course_second_categories.count + 1)
# 去掉不对当前用户的单位公开的实训,已发布的实训
stage.shixuns.no_jupyter.where.not(shixuns: {id: none_shixun_ids}).unhidden.each do |shixun|
stage.shixuns.no_jupyter.where(id: shixun_ids).unhidden.each do |shixun|
homework = HomeworksService.new.create_homework shixun, @course, category, current_user
@homework_ids << homework.id
CreateStudentWorkJob.perform_later(homework.id)
@ -910,7 +914,7 @@ class HomeworkCommonsController < ApplicationController
def publish_homework
tip_exception("请至少选择一个分班") if params[:group_ids].blank? && @course.course_groups.size != 0
group_ids = params[:group_ids]&.reject(&:blank?).map(&:to_i)
group_ids = params[:group_ids]&.reject(&:blank?)&.map(&:to_i)
if params[:detail].blank?
tip_exception("缺少截止时间参数") if params[:end_time].blank?
tip_exception("截止时间不能早于当前时间") if params[:end_time] <= strf_time(Time.now)
@ -918,7 +922,7 @@ class HomeworkCommonsController < ApplicationController
@course.end_date.present? && params[:end_time] > strf_time(@course.end_date.end_of_day)
else
tip_exception("缺少分班截止时间参数") if params[:group_end_times].blank?
group_end_times = params[:group_end_times].reject(&:blank?).map{|time| time.to_time}
group_end_times = params[:group_end_times].reject(&:blank?)&.map{|time| time.to_time}
tip_exception("截止时间和分班参数的个数不一致") if group_end_times.length != group_ids.length
group_end_times.each do |time|
tip_exception("分班截止时间不能早于当前时间") if time <= Time.now
@ -979,8 +983,8 @@ class HomeworkCommonsController < ApplicationController
end
homework.homework_detail_manual.update_attributes!(comment_status: 1)
if homework.course_acts.size == 0
homework.course_acts << CourseActivity.new(user_id: homework.user_id, course_id: homework.course_id)
if homework.course_act.blank?
homework.course_act << CourseActivity.new(user_id: homework.user_id, course_id: homework.course_id)
end
# 发消息
HomeworkCommonPushNotifyJob.perform_later(homework.id, tiding_group_ids)
@ -1041,7 +1045,7 @@ class HomeworkCommonsController < ApplicationController
def end_homework
tip_exception("请至少选择一个分班") if params[:group_ids].blank? && @course.course_groups.size != 0
time = Time.now.strftime("%Y-%m-%d %H:%M:%S")
time = Time.now
# 已发布且未截止的作业才能立即截止
@ -1049,7 +1053,7 @@ class HomeworkCommonsController < ApplicationController
homeworks = homeworks.published_no_end.includes(:homework_group_settings, :homework_detail_manual, :homework_challenge_settings)
course_students = @course.students
charge_group_ids = @course.charge_group_ids(current_user)
group_ids = params[:group_ids]&.reject(&:blank?).map(&:to_i)
group_ids = params[:group_ids]&.reject(&:blank?)&.map(&:to_i)
end_groups = charge_group_ids & group_ids if group_ids
begin
@ -1082,7 +1086,7 @@ class HomeworkCommonsController < ApplicationController
homework.end_time = time
end
homework_detail_manual.update_attributes!(comment_status: 2) if homework.end_time <= time
# homework_detail_manual.update_attributes!(comment_status: 2) if homework.end_time <= time
# 实训作业的作品需要计算是否迟交
if homework.homework_type == "practice"
@ -1404,8 +1408,8 @@ class HomeworkCommonsController < ApplicationController
end
def homework_params
tip_exception("name参数不能为空") if params[:name].blank?
tip_exception("description参数不能为空") if params[:description].blank?
tip_exception("标题不能为空") if params[:name].blank?
tip_exception("内容不能为空") if params[:description].blank?
params.require(:homework_common).permit(:name, :description, :reference_answer)
end

@ -1,8 +1,10 @@
class ItemBanksController < ApplicationController
include PaginateHelper
before_action :require_login
before_action :certi_identity_auth, only: [:create, :edit, :update, :destroy, :set_public]
before_action :find_item, except: [:index, :create]
before_action :edit_auth, only: [:update, :destroy, :set_public]
before_action :identity_auth, only: [:index]
def index
items = ItemBankQuery.call(params)
@ -52,7 +54,7 @@ class ItemBanksController < ApplicationController
def set_public
tip_exception(-1, "该试题已公开") if @item.public?
tip_exception(-1, "请勿重复提交申请") if ApplyAction.where(container_id: @item.id, container_type: 'ItemBank').exists?
tip_exception(-1, "请勿重复提交申请") if ApplyAction.where(container_id: @item.id, container_type: 'ItemBank', status: 0).exists?
ApplyAction.create!(container_id: @item.id, container_type: 'ItemBank', user_id: current_user.id)
# @item.update_attributes!(public: 1)
render_ok

@ -1,5 +1,6 @@
class ItemBasketsController < ApplicationController
before_action :require_login
before_action :certi_identity_auth, only: [:create, :delete_item_type, :destroy, :set_score, :batch_set_score, :adjust_position]
before_action :validate_score, only: [:set_score, :batch_set_score]
helper_method :current_basket

@ -0,0 +1,69 @@
class LiveLinksController < ApplicationController
before_action :require_login
before_action :find_course, only: [:index, :create]
before_action :user_course_identity, :teacher_allowed, only: [:create]
before_action :edit_auth, only: [:edit, :update]
before_action :delete_auth, only: [:destroy]
def index
lives = @course.live_links
order_str = "on_status desc, live_time desc"
@total_count = lives.size
@my_live_id = @course.live_links.find_by(user_id: current_user.id)&.id
# order_str = "live_links.id = #{@my_live_id} desc, #{order_str}" if @my_live_id.present?
lives = lives.order("#{order_str}")
@lives = paginate lives.includes(user: :user_extension)
end
def create
on_status = params[:live_time].present? && params[:live_time].to_time <= Time.now ? 1 : 0
@course.live_links.create!(create_params.merge(user_id: current_user.id, on_status: on_status))
render_ok
end
def edit
@live = current_live
end
def update
if params[:on_status]
tip_exception("请勿重复开启") if current_live.on_status && params[:on_status].to_i == 1
ActiveRecord::Base.transaction do
current_live.update!(on_status: params[:on_status])
# 开启时发送消息,关闭直播时删除对应的消息
if params[:on_status].to_i == 1
LivePublishJob.perform_later(current_live.id)
end
end
else
on_status = params[:live_time].present? && params[:live_time].to_time <= Time.now ? 1 : 0
current_live.update!(create_params.merge(on_status: on_status))
end
render_ok
end
def destroy
current_live.destroy!
render_ok
end
private
def create_params
params.permit(:url, :description, :course_name, :platform, :live_time, :duration)
end
def current_live
@_current_live = LiveLink.find params[:id]
end
def edit_auth
tip_exception(403, "无权限操作") unless current_user.id == current_live.user_id || current_user.admin_or_business?
end
def delete_auth
tip_exception(403, "无权限操作") unless current_user.id == current_live.user_id || current_user.admin?
end
end

@ -8,6 +8,24 @@ class MainController < ApplicationController
end
def index
domain_session = params[:_educoder_session]
if domain_session
uid_logger("main start domain_session is #{domain_session}")
if cookies[:_educoder_session] != domain_session
cookies[:_educoder_session] = nil
cookies[:_educoder_session] = domain_session
end
uid_logger("main start is #{cookies[:_educoder_session]}")
end
# TODO: 这块之后需要整合者架构重新变化统一跳转到index后再路由分发
if params[:path] && params[:path]&.include?("h5educoderbuild") && params[:path].split("/").first == "h5educoderbuild"
render file: 'public/h5educoderbuild/index.html', :layout => false
else
render file: 'public/react/build/index.html', :layout => false
end
end
end

@ -91,7 +91,7 @@ class MyshixunsController < ApplicationController
ActiveRecord::Base.transaction do
begin
t1 = Time.now
uid_logger_dubug("@@@222222#{params[:jsonTestDetails]}")
#uid_logger_dubug("@@@222222#{params[:jsonTestDetails]}")
jsonTestDetails = JSON.parse(params[:jsonTestDetails])
timeCost = JSON.parse(params[:timeCost])
brige_end_time = Time.parse(timeCost['evaluateEnd']) if timeCost['evaluateEnd'].present?
@ -101,7 +101,7 @@ class MyshixunsController < ApplicationController
sec_key = jsonTestDetails['sec_key']
server_url = jsonTestDetails['showServer']
uid_logger_dubug("training_task_status start-#{game_id}-1#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")}")
#uid_logger_dubug("training_task_status start-#{game_id}-1#{Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")}")
resubmit = jsonTestDetails['resubmit']
outPut = tran_base64_decode64(jsonTestDetails['outPut'])
@ -267,10 +267,12 @@ class MyshixunsController < ApplicationController
@sec_key = generate_identifier(EvaluateRecord, 12)
record = EvaluateRecord.create!(:user_id => current_user.id, :shixun_id => @myshixun.shixun_id, :game_id => game_id,
:identifier => @sec_key, :exec_time => exec_time)
uid_logger_dubug("-- game build: file update #{@sec_key}, record id is #{record.id}, time is **** #{Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")}")
#uid_logger_dubug("-- game build: file update #{@sec_key}, record id is #{record.id}, time is **** #{Time.now.strftime("%Y-%m-%d %H:%M:%S.%L")}")
end
# 隐藏代码文件 和 VNC的都不需要走版本库
unless @hide_code || (@myshixun.shixun&.vnc_evaluate && params[:evaluate].present?)
vnc = @myshixun.shixun&.vnc
unless @hide_code || (vnc && params[:evaluate].present?)
# 远程版本库文件内容
last_content = GitService.file_content(repo_path: @repo_path, path: path)["content"]
@ -280,8 +282,6 @@ class MyshixunsController < ApplicationController
else
params[:content]
end
uid_logger_dubug("###11222333####{content}")
uid_logger_dubug("###222333####{last_content}")
if content != last_content
@content_modified = 1
@ -289,8 +289,6 @@ class MyshixunsController < ApplicationController
author_name = current_user.real_name
author_email = current_user.git_mail
message = params[:evaluate] == 0 ? "System automatically submitted" : "User submitted"
uid_logger_dubug("112233#{author_name}")
uid_logger_dubug("112233#{author_email}")
@content = GitService.update_file(repo_path: @repo_path,
file_path: path,
message: message,

@ -30,4 +30,22 @@ class Oauth::BaseController < ActionController::Base
@_default_yun_session = "#{request.subdomain.split('.').first}_user_id"
# @_default_yun_session = "#{current_laboratory.try(:identifier).split('.').first}_user_id"
end
def session_openid
session[:openid]
end
def set_session_openid(openid)
Rails.logger.info("[wechat] set session openid: #{openid}")
session[:openid] = openid
end
def session_unionid
session[:unionid]
end
def set_session_unionid(unionid)
Rails.logger.info("[wechat] set session unionid: #{unionid}")
session[:unionid] = unionid
end
end

@ -0,0 +1,13 @@
class Oauth::CasController < Oauth::BaseController
def create
user, is_new_user = Oauth::CreateORFindCasUserService.call(current_user, auth_hash)
successful_authentication(user)
redirect_to root_url
end
def auth_hash
JSON.parse(CGI.unescape(request.env['omniauth.auth'].extra.to_json))
end
end

@ -1,11 +1,32 @@
class Oauth::WechatController < Oauth::BaseController
def create
user, new_user = Oauth::CreateOrFindWechatAccountService.call(current_user ,params)
# user, new_user = Oauth::CreateOrFindWechatAccountService.call(current_user ,params)
successful_authentication(user)
begin
code = params['code'].to_s.strip
tip_exception("code不能为空") if code.blank?
new_user = false
result = WechatOauth::Service.access_token(code)
result = WechatOauth::Service.user_info(result['access_token'], result['openid'])
# 存在该用户
open_user = OpenUsers::Wechat.find_by(uid: result['unionid'])
if open_user.present? && open_user.user.present?
successful_authentication(open_user.user)
else
if current_user.blank? || !current_user.logged?
new_user = true
set_session_openid(result['openid'])
set_session_unionid(result['unionid'])
else
OpenUsers::Wechat.create!(user: current_user, uid: result['unionid'])
end
end
render_ok(new_user: new_user)
rescue Oauth::CreateOrFindWechatAccountService::Error => ex
rescue WechatOauth::Error => ex
render_error(ex.message)
end
end
end

@ -1,13 +1,13 @@
class PollQuestionsController < ApplicationController
before_action :require_login, :check_auth
before_action :get_poll,only:[:new,:create]
before_action :get_poll_question,except: [:new,:create]
before_action :get_poll, only: [:new, :create]
before_action :get_poll_question, except: [:new, :create]
before_action :is_course_teacher
before_action :get_poll_questions_count,only:[:create]
before_action :get_poll_question_answers,only:[:edit,:update]
before_action :check_poll_status,only: [:new,:create,:delete_answer,:destroy]
before_action :validates_params,only:[:create,:update]
before_action :validates_update_params,only: [:update]
before_action :get_poll_questions_count, only: [:create]
before_action :get_poll_question_answers, only: [:edit, :update]
before_action :check_poll_status, only: [:new, :create, :delete_answer, :destroy]
before_action :validates_params, only: [:create, :update]
before_action :validates_update_params, only: [:update]
def new
@ -25,7 +25,6 @@ class PollQuestionsController < ApplicationController
# 创建题目和选择的答案
def create
ActiveRecord::Base.transaction do
begin
poll_options = {
:question_title => params[:question_title],
:question_type => params[:question_type],
@ -50,7 +49,7 @@ class PollQuestionsController < ApplicationController
p_other_answer = params[:question_other_answer]
# 新增选择题答案选择的选项
(1..p_answer.count).each do |i|
answer = p_answer[i-1] # 传入的答案的内容
answer = p_answer[i - 1] # 传入的答案的内容
question_option = {
:answer_position => i,
:answer_text => answer
@ -69,11 +68,6 @@ class PollQuestionsController < ApplicationController
end
end
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception("问卷的问题创建失败!")
raise ActiveRecord::Rollback
end
end
end
@ -103,7 +97,6 @@ class PollQuestionsController < ApplicationController
def update
ActiveRecord::Base.transaction do
begin
if @poll_question.question_type < 3 #当为单选题或多选题时
p_answer = params[:question_answers]
p_other_answer = params[:question_other_answer]
@ -114,21 +107,21 @@ class PollQuestionsController < ApplicationController
end
end
(1..p_answer_count).each do |i|
answer = @poll_question.poll_answers.find_answer_by_custom("answer_position",i).first
answer = @poll_question.poll_answers.find_answer_by_custom("answer_position", i).first
if answer # 判断该位置的answer是否存在存在则更新.不存在则跳到下一步
answer.answer_text = p_answer[i-1]
answer.answer_text = p_answer[i - 1]
answer.answer_position = i
answer.save!
else
answer_options = {
:answer_position => i,
:answer_text => p_answer[i-1]
:answer_text => p_answer[i - 1]
}
@poll_question.poll_answers.new answer_options
end
end
if p_other_answer #判断答案的其他选项是否存在
other_answer = @poll_question.poll_answers.find_answer_by_custom("answer_text","").first
other_answer = @poll_question.poll_answers.find_answer_by_custom("answer_text", "").first
if other_answer.blank?
question_option = {
:answer_position => p_answer_count + 1,
@ -143,11 +136,6 @@ class PollQuestionsController < ApplicationController
end
@poll_question.update!(poll_questions_params)
rescue Exception => e
uid_logger_error(e.message)
tip_exception("更新失败")
raise ActiveRecord::Rollback
end
end
end
@ -157,7 +145,7 @@ class PollQuestionsController < ApplicationController
answer_d_id = params[:answer_no].to_i # 答案的当前位置
poll_answers = @poll_question.poll_answers
delete_answer = poll_answers.find_by(answer_position: answer_d_id)
left_answers = poll_answers.where("answer_position > ?",answer_d_id)
left_answers = poll_answers.where("answer_position > ?", answer_d_id)
left_answers.update_all("answer_position = answer_position - 1") if left_answers
if delete_answer.destroy
@ -196,7 +184,7 @@ class PollQuestionsController < ApplicationController
if @poll.polls_status.to_i == 1
if opr.present?
if opr.to_s == "up"
last_q_p = @poll.poll_questions.find_by(question_number: (current_q_p-1)) #当前问题的前一个问题
last_q_p = @poll.poll_questions.find_by(question_number: (current_q_p - 1)) #当前问题的前一个问题
if last_q_p.present?
@poll_question.update!(question_number: (current_q_p - 1))
last_q_p.update!(question_number: current_q_p) # 重新获取当前问题的位置
@ -205,7 +193,7 @@ class PollQuestionsController < ApplicationController
normal_status(-1, "移动失败,已经是第一个问题了!")
end
elsif opr.to_s == "down"
next_q_p = @poll.poll_questions.find_by(question_number: (current_q_p+1)) #当前问题的后一个问题
next_q_p = @poll.poll_questions.find_by(question_number: (current_q_p + 1)) #当前问题的后一个问题
if next_q_p.present?
@poll_question.update!(question_number: (current_q_p + 1))
next_q_p.update!(question_number: current_q_p)
@ -219,7 +207,7 @@ class PollQuestionsController < ApplicationController
normal_status(-1, "移动失败,请输入参数")
end
else
normal_status(-1,"已发布的不能移动问题")
normal_status(-1, "已发布的不能移动问题")
end
rescue Exception => e
uid_logger_error(e.message)
@ -231,7 +219,7 @@ class PollQuestionsController < ApplicationController
private
def poll_questions_params
params.require(:poll_question).permit(:question_title,:question_type,:is_necessary,:question_number,:max_choices,:min_choices)
params.require(:poll_question).permit(:question_title, :question_type, :is_necessary, :question_number, :max_choices, :min_choices)
end
def validates_params
@ -242,12 +230,12 @@ class PollQuestionsController < ApplicationController
normal_status(-1, "最小可选不能大于最大可选!")
elsif params[:question_answers].present? && (params[:max_choices].to_i > params[:question_answers].count)
normal_status(-1, "选择题的最大可选项不能大于答案数!")
elsif [1,3].include?(params[:question_type]) && (params[:max_choices].to_i > 0 || params[:min_choices].to_i > 0)
elsif [1, 3].include?(params[:question_type]) && (params[:max_choices].to_i > 0 || params[:min_choices].to_i > 0)
normal_status(-1, "单选题或主观题不能有最大或最小选择数!")
elsif params[:question_type] == 3 && (params[:question_answers] || params[:question_other_answer])
normal_status(-1, "主观问题不需要可选答案!")
elsif params[:question_type] != 3
if params[:question_answers].present? && params[:question_answers].select{|answer| answer.blank?}.count > 0
if params[:question_answers].present? && params[:question_answers].select {|answer| answer.blank?}.count > 0
normal_status(-1, "选项不能有空值!")
elsif params[:question_other_answer].present? && !params[:question_other_answer].blank?
normal_status(-1, "其他选项不能有值!")
@ -262,11 +250,11 @@ class PollQuestionsController < ApplicationController
def validates_update_params
question_a_count = params[:question_answers].present? ? params[:question_answers].count : 0
question_o_count = params[:question_other_answer].present? ? params[:question_other_answer].count : 0
normal_status(-1, "已发布的问卷不允许增删答案!") if (((question_a_count+question_o_count) != @poll_current_answers) && (@poll.polls_status.to_i != 1))
normal_status(-1, "已发布的问卷不允许增删答案!") if (((question_a_count + question_o_count) != @poll_current_answers) && (@poll.polls_status.to_i != 1))
end
def get_poll
@poll = Poll.find_by(id:params[:poll_id])
@poll = Poll.find_by(id: params[:poll_id])
if @poll.blank?
tip_exception(404)
end
@ -283,7 +271,7 @@ class PollQuestionsController < ApplicationController
def get_poll_question
@poll_question = PollQuestion.find_by(id: params[:id])
if @poll_question.present?
@poll = Poll.find_by(id:@poll_question.poll_id)
@poll = Poll.find_by(id: @poll_question.poll_id)
else
tip_exception(404)
end
@ -305,7 +293,7 @@ class PollQuestionsController < ApplicationController
tip_exception(404)
else
@identity = current_user.course_identity(@course)
normal_status(-1, "权限不够") unless(@course.present? && @identity < Course::STUDENT) #课堂存在,且当前用户为教师/管理员
normal_status(-1, "权限不够") unless (@course.present? && @identity < Course::STUDENT) #课堂存在,且当前用户为教师/管理员
end
end
end

@ -6,12 +6,11 @@ class PollVotesController < ApplicationController
def create #每一次答案的点击,请求一次
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) #当前用户的答案,可能有多个
user_votes = question_votes.find_current_vote("user_id", current_user.id) #当前用户的答案,可能有多个
# 当前用户的当前答案,如果已存在,当再次点击的时候,取消答案,即删除该答案
current_vote_text = nil
@ -58,7 +57,7 @@ class PollVotesController < ApplicationController
}
PollVote.create!(answer_option)
# 重新取一次poll_votes
user_votes = @poll_question.poll_votes.find_current_vote("user_id",current_user.id)
user_votes = @poll_question.poll_votes.find_current_vote("user_id", current_user.id)
end
# if current_vote_text.present? #已有其他输入文字的选项
# current_vote_text.update_attribute("vote_text", question_answer_text)
@ -84,7 +83,7 @@ class PollVotesController < ApplicationController
end
end
if old_ids.size > 0
ea_answer = user_votes.find_current_vote("poll_answer_id",old_ids)
ea_answer = user_votes.find_current_vote("poll_answer_id", old_ids)
ea_answer.destroy_all
end
else
@ -115,11 +114,6 @@ class PollVotesController < ApplicationController
@current_question_status = 1
end
end
rescue Exception => e
uid_logger_error(e.message)
tip_exception("页面调用失败!")
raise ActiveRecord::Rollback
end
end
@ -128,14 +122,14 @@ class PollVotesController < ApplicationController
def get_poll_question
@poll_question = PollQuestion.find_by_id(params[:poll_question_id])
if @poll_question.blank?
normal_status(-1,"问卷试题不存在!")
normal_status(-1, "问卷试题不存在!")
else
@poll = @poll_question.poll
@course = @poll.course
if @poll.blank?
normal_status(-1,"问卷不存在!")
normal_status(-1, "问卷不存在!")
elsif @course.blank?
normal_status(-1,"课堂不存在!")
normal_status(-1, "课堂不存在!")
end
end
end
@ -146,7 +140,7 @@ class PollVotesController < ApplicationController
question_type = @poll_question&.question_type
if (question_type == 1) && params[:poll_answer_id].blank?
normal_status(-1,"答案ID错误!")
normal_status(-1, "答案ID错误!")
elsif question_type == 2
user_vote_count = params[:poll_answer_id].size
if @poll_question.max_choices.present?
@ -155,10 +149,10 @@ class PollVotesController < ApplicationController
question_max_choices = 0
end
if question_max_choices > 0 && (user_vote_count > question_max_choices)
normal_status(-1,"多选题答案超过最大限制!")
normal_status(-1, "多选题答案超过最大限制!")
end
elsif (poll_user.present? && poll_user.commit_status == 1) || poll_user_status == 3
normal_status(-1,"已提交/已结束的问卷不允许修改!")
normal_status(-1, "已提交/已结束的问卷不允许修改!")
end
end

@ -1,25 +1,25 @@
class PollsController < ApplicationController
# before_action :check_poll_status 问卷的发消息和定时任务没有做
before_action :require_login, :check_auth,except: [:index]
before_action :find_course, except: [:show,:poll_setting,:commit_setting,:edit,:update,:start_answer,:commit_poll,
:commit_result,:poll_lists,:cancel_publish,:cancel_publish_modal,:common_header,:publish_groups]
before_action :get_poll_and_course, only: [:show,:poll_setting,:commit_setting,:edit,:update,:start_answer,
:commit_poll,:commit_result,:poll_lists,:cancel_publish,
:cancel_publish_modal,:common_header, :publish_groups]
before_action :require_login, :check_auth, except: [:index]
before_action :find_course, except: [:show, :poll_setting, :commit_setting, :edit, :update, :start_answer, :commit_poll,
:commit_result, :poll_lists, :cancel_publish, :cancel_publish_modal, :common_header, :publish_groups]
before_action :get_poll_and_course, only: [:show, :poll_setting, :commit_setting, :edit, :update, :start_answer,
:commit_poll, :commit_result, :poll_lists, :cancel_publish,
:cancel_publish_modal, :common_header, :publish_groups]
before_action :user_course_identity
before_action :is_course_teacher, except: [:index,:start_answer,:poll_setting,:commit_poll,:commit_result,:poll_lists,:common_header] #判断是否为课堂老师
before_action :is_course_teacher, except: [:index, :start_answer, :poll_setting, :commit_poll, :commit_result, :poll_lists, :common_header] #判断是否为课堂老师
before_action :check_user_status
before_action :is_course_public, only: [:set_public]
before_action :check_user_on_answer, only: [:show,:start_answer,:commit_poll,:poll_lists] #判断当前用户在问卷的权限/老师是否属于分班的权限
before_action :validate_params, only: [:create,:update]
before_action :validates_multi_ids, only: [:publish,:end_poll,:destroys,:set_public,:join_poll_banks]
before_action :check_poll_setting_status,only: [:commit_setting]
before_action :get_questions_count ,only: [:start_answer,:show,:commit_result,:edit]
before_action :check_user_id_start_answer,only: [:start_answer]
before_action :check_poll_question_complete,only: [:commit_poll] #问卷提交前来判断问题是否完成
before_action :check_poll_commit_result,only: [:commit_result]
before_action :check_user_on_answer, only: [:show, :start_answer, :commit_poll, :poll_lists] #判断当前用户在问卷的权限/老师是否属于分班的权限
before_action :validate_params, only: [:create, :update]
before_action :validates_multi_ids, only: [:publish, :end_poll, :destroys, :set_public, :join_poll_banks]
before_action :check_poll_setting_status, only: [:commit_setting]
before_action :get_questions_count, only: [:start_answer, :show, :commit_result, :edit]
before_action :check_user_id_start_answer, only: [:start_answer]
before_action :check_poll_question_complete, only: [:commit_poll] #问卷提交前来判断问题是否完成
before_action :check_poll_commit_result, only: [:commit_result]
# before_action :get_all_polls_commit, only: [:commit_result] #该问卷全部的用户
before_action :get_left_banner_id, only:[:common_header,:start_answer,:new,:edit,:index]
before_action :get_left_banner_id, only: [:common_header, :start_answer, :new, :edit, :index]
include PollsHelper
def index
@ -66,7 +66,7 @@ class PollsController < ApplicationController
poll_setting_ids = @course.poll_group_settings.where("course_group_id = #{@member_group_id}").poll_group_not_published.pluck(:poll_id)
when 2
poll_setting_ids = @course.poll_group_settings.where("course_group_id = #{@member_group_id}")
.where("publish_time is not null and publish_time <= ? and end_time > ?",Time.now,Time.now).pluck(:poll_id)
.where("publish_time is not null and publish_time <= ? and end_time > ?", Time.now, Time.now).pluck(:poll_id)
when 3
poll_setting_ids = @course.poll_group_settings.where("course_group_id = #{@member_group_id}").poll_group_ended.pluck(:poll_id)
end
@ -83,7 +83,7 @@ class PollsController < ApplicationController
# 分页
@polls_select_count = @polls.size
@polls = @polls.order( "IF(ISNULL(publish_time),0,1), publish_time DESC,created_at DESC")
@polls = @polls.order("IF(ISNULL(publish_time),0,1), publish_time DESC,created_at DESC")
@page = params[:page] || 1
@limit = params[:limit] || 15
@ -126,7 +126,6 @@ class PollsController < ApplicationController
# un_anonymous 是否实名默认为false即不公开
def create
ActiveRecord::Base.transaction do
begin
poll_name = params[:polls_name]
poll_desc = params[:polls_description]
poll_options = {
@ -138,11 +137,6 @@ class PollsController < ApplicationController
:polls_type => "Course",
}
@poll = Poll.create!(poll_options)
rescue Exception => e
uid_logger_error(e.message)
tip_exception("问卷创建失败!")
raise ActiveRecord::Rollback
end
end
end
@ -160,7 +154,6 @@ class PollsController < ApplicationController
def update
ActiveRecord::Base.transaction do
begin
poll_name = params[:polls_name]
poll_des = params[:polls_description]
poll_params = {
@ -168,12 +161,7 @@ class PollsController < ApplicationController
:polls_description => poll_des
}
@poll.update!(poll_params)
normal_status(0,"问卷更新成功!")
rescue Exception => e
uid_logger_error(e.message)
tip_exception("没有权限")
raise ActiveRecord::Rollback
end
normal_status(0, "问卷更新成功!")
end
end
@ -207,8 +195,8 @@ class PollsController < ApplicationController
@user_poll_answer = 3 #教师页面
end
poll_id_array = [@poll.id]
@poll_publish_count = get_user_permission_course(poll_id_array,2).count #是否存在已发布的
@poll_unpublish_count = get_user_permission_course(poll_id_array,1).count #是否存在未发布的
@poll_publish_count = get_user_permission_course(poll_id_array, 2).count #是否存在已发布的
@poll_unpublish_count = get_user_permission_course(poll_id_array, 1).count #是否存在未发布的
if (@poll_publish_count == 0) && (@poll_unpublish_count == 0) #即表示没有分班
if @poll_status == 1
@ -231,7 +219,7 @@ class PollsController < ApplicationController
begin
poll_ids = params[:check_ids]
if poll_ids.count > 0
@course_groups = get_user_permission_course(poll_ids,1)
@course_groups = get_user_permission_course(poll_ids, 1)
else
@course_groups = []
end
@ -258,23 +246,21 @@ class PollsController < ApplicationController
if params[:detail].blank?
tip_exception("缺少截止时间参数") if params[:end_time].blank?
tip_exception("截止时间不能早于当前时间") if params[:end_time] <= strf_time(Time.now)
tip_exception("截止时间不能晚于课堂结束时间(#{@course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}") if
@course.end_date.present? && params[:end_time] > strf_time(@course.end_date.end_of_day)
tip_exception("截止时间不能晚于课堂结束时间(#{@course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}") if @course.end_date.present? && params[:end_time] > strf_time(@course.end_date.end_of_day)
else
group_end_times = params[:group_end_times].reject(&:blank?).map{|time| time.to_time}
group_end_times = params[:group_end_times].reject(&:blank?).map {|time| time.to_time}
tip_exception("缺少截止时间参数") if group_end_times.blank?
tip_exception("截止时间和分班参数的个数不一致") if group_end_times.length != group_ids.length
group_end_times.each do |time|
tip_exception("分班截止时间不能早于当前时间") if time <= Time.now
tip_exception("分班截止时间不能晚于课堂结束时间(#{@course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}") if
@course.end_date.present? && time > @course.end_date.end_of_day
tip_exception("分班截止时间不能晚于课堂结束时间(#{@course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}") if @course.end_date.present? && time > @course.end_date.end_of_day
end
end
ActiveRecord::Base.transaction do
begin
check_ids = Poll.where(id: params[:check_ids])
ex_end_time = params[:end_time].blank? ? Time.at(((1.month.since.to_i)/3600.0).ceil * 3600) : params[:end_time].to_time
ex_end_time = params[:end_time].blank? ? Time.at(((1.month.since.to_i) / 3600.0).ceil * 3600) : params[:end_time].to_time
check_ids.each do |poll|
if poll.unified_setting
pl_status = poll.polls_status #则为试卷的状态
@ -294,7 +280,7 @@ class PollsController < ApplicationController
else
poll_unified = false
g_course.each_with_index do |i, index|
poll_group_setting = poll.poll_group_settings.find_in_poll_group("course_group_id",i).first #根据课堂分班的id寻找问卷所在的班级
poll_group_setting = poll.poll_group_settings.find_in_poll_group("course_group_id", i).first #根据课堂分班的id寻找问卷所在的班级
group_end_time = params[:detail] ? group_end_times[index] : ex_end_time
if poll_group_setting.present? #如果该问卷分组存在,则更新,否则新建
poll_group_setting.update!(publish_time: Time.now, end_time: group_end_time)
@ -318,7 +304,7 @@ class PollsController < ApplicationController
poll_unified = true
e_time = ex_end_time
end
poll_status = set_poll_status(Time.now,e_time)
poll_status = set_poll_status(Time.now, e_time)
poll_params = {
:publish_time => Time.now,
@ -328,7 +314,7 @@ class PollsController < ApplicationController
}
poll.update!(poll_params)
if poll.course_acts.size == 0
poll.course_acts << CourseActivity.new(:user_id => poll.user_id,:course_id => poll.course_id)
poll.course_acts << CourseActivity.new(:user_id => poll.user_id, :course_id => poll.course_id)
end
PollPublishNotifyJob.perform_later(poll.id, g_course)
end
@ -350,7 +336,7 @@ class PollsController < ApplicationController
begin
poll_ids = params[:check_ids]
if poll_ids.count > 0
@course_groups = get_user_permission_course(poll_ids,3)
@course_groups = get_user_permission_course(poll_ids, 3)
else
@course_groups = []
end
@ -385,12 +371,12 @@ class PollsController < ApplicationController
poll_users = poll_unified ? poll.poll_users :
poll.poll_users.joins("join course_members on poll_users.user_id = course_members.user_id").where(course_members: {course_group_id: g_course, role: 4})
poll_group_setting = poll.poll_group_settings
old_poll_groups = poll_group_setting.find_in_poll_group("course_group_id",g_course) #问卷分组的截止时间更改
old_poll_groups = poll_group_setting.find_in_poll_group("course_group_id", g_course) #问卷分组的截止时间更改
old_poll_groups.update_all(:end_time => Time.now)
new_end_time = poll_group_setting.end_time_present.map(&:end_time) # 问卷结束时间不为空的
new_end_time_s = new_end_time.size > 0 ? new_end_time.max : Time.now
new_poll_status = set_poll_status(poll.publish_time,new_end_time_s)
poll.update!(:end_time => new_end_time_s,:polls_status => new_poll_status,:unified_setting => poll_unified)
new_poll_status = set_poll_status(poll.publish_time, new_end_time_s)
poll.update!(:end_time => new_end_time_s, :polls_status => new_poll_status, :unified_setting => poll_unified)
elsif poll.unified_setting
poll_users = poll.poll_users
poll.update!(:polls_status => 3, :end_time => Time.now)
@ -414,7 +400,7 @@ class PollsController < ApplicationController
begin
poll_ids = [@poll.id]
if poll_ids.count > 0
@course_groups = get_user_permission_course(poll_ids,2)
@course_groups = get_user_permission_course(poll_ids, 2)
else
@course_groups = []
end
@ -433,12 +419,12 @@ class PollsController < ApplicationController
g_course = params[:group_ids]
if !@poll.unified_setting #如果问卷为分班设置且传入的班级id存在
if g_course.present?
course_group_ids = @course.course_members.course_find_by_ids("course_group_id",g_course).pluck(:user_id).uniq #传入班级的全部学生人数
all_poll_settings = @poll.poll_group_settings.find_in_poll_group("course_group_id",g_course) #根据传入的班级id来获取问卷的分组设置
course_group_ids = @course.course_members.course_find_by_ids("course_group_id", g_course).pluck(:user_id).uniq #传入班级的全部学生人数
all_poll_settings = @poll.poll_group_settings.find_in_poll_group("course_group_id", g_course) #根据传入的班级id来获取问卷的分组设置
all_poll_settings.destroy_all #问卷的设置文件全部删除
# @poll.poll_users.find_by_group_ids(course_group_ids).destroy_all #问卷的提交信息
poll_question_ids = @poll.poll_questions.pluck(:id) #问卷的全部问卷
PollVote.find_current_vote("user_id",course_group_ids).find_current_vote("poll_question_id",poll_question_ids).destroy_all
PollVote.find_current_vote("user_id", course_group_ids).find_current_vote("poll_question_id", poll_question_ids).destroy_all
poll_user_options = {
:commit_status => 0,
:start_at => nil,
@ -456,7 +442,7 @@ class PollsController < ApplicationController
if p_time.nil? #发布时间为空,则表示问卷未发布
poll_status = 1
elsif p_time.present? && e_time.present?
poll_status = set_poll_status(p_time,e_time)
poll_status = set_poll_status(p_time, e_time)
end
else
unified_setting = true
@ -471,9 +457,9 @@ class PollsController < ApplicationController
:end_time => e_time
}
@poll.update!(poll_options)
normal_status(0,"分班问卷撤销发布成功!")
normal_status(0, "分班问卷撤销发布成功!")
else
normal_status(-1,"请选择撤销发布班级!")
normal_status(-1, "请选择撤销发布班级!")
end
else
poll_user_options = {
@ -483,7 +469,7 @@ class PollsController < ApplicationController
}
@poll.poll_users.update_all(poll_user_options)
poll_question_ids = @poll.poll_questions.pluck(:id)
PollVote.find_current_vote("poll_question_id",poll_question_ids).destroy_all
PollVote.find_current_vote("poll_question_id", poll_question_ids).destroy_all
poll_new_params = {
:polls_status => 1,
:publish_time => nil,
@ -492,7 +478,7 @@ class PollsController < ApplicationController
}
@poll.update!(poll_new_params)
@poll.poll_group_settings.destroy_all
normal_status(0,"问卷撤销发布成功!")
normal_status(0, "问卷撤销发布成功!")
## @poll.tidings.destroy_all 用户的发送消息全部删除,因接口未定,所以先注释
@ -510,7 +496,7 @@ class PollsController < ApplicationController
def destroys
ActiveRecord::Base.transaction do
begin
check_ids = Poll.where(id:params[:check_ids])
check_ids = Poll.where(id: params[:check_ids])
check_ids.each do |poll|
if poll.present?
poll.destroy
@ -529,7 +515,7 @@ class PollsController < ApplicationController
def set_public
ActiveRecord::Base.transaction do
begin
check_ids = Poll.where(id:params[:check_ids])
check_ids = Poll.where(id: params[:check_ids])
check_ids.each do |poll|
poll.update!(is_public: true)
end
@ -548,7 +534,7 @@ class PollsController < ApplicationController
begin
check_ids = Poll.where(id: params[:check_ids])
check_ids.each do |poll|
current_ex_bank = current_user.exercise_banks.find_by_container(poll.id,"Poll").first
current_ex_bank = current_user.exercise_banks.find_by_container(poll.id, "Poll").first
if current_ex_bank.present? #当前用户的选择问卷是否已加入习题库,存在则更新习题库和问题库,否则新建习题库和问题库
ex_params = {
:name => poll.polls_name,
@ -556,7 +542,7 @@ class PollsController < ApplicationController
:course_list_id => poll.course.try(:course_list_id)
}
current_ex_bank.update!(ex_params)
question_bank = QuestionBank.ques_by_container(current_ex_bank.id,current_ex_bank.container_type) #该习题库是否存在于问题库里
question_bank = QuestionBank.ques_by_container(current_ex_bank.id, current_ex_bank.container_type) #该习题库是否存在于问题库里
ques_params = {
:name => current_ex_bank.name,
:course_list_id => current_ex_bank.course_list_id
@ -574,7 +560,7 @@ class PollsController < ApplicationController
:container_type => "Poll",
:quotes => 1
}
current_ex_bank= ExerciseBank.new ex_params
current_ex_bank = ExerciseBank.new ex_params
if current_ex_bank.save! #如果习题库保存成功则会创建问题库question_bank
ques_params = {
:name => current_ex_bank.name,
@ -692,9 +678,9 @@ class PollsController < ApplicationController
@user_permission = 2
@user_course_groups = @course.teacher_group(current_user.id) #当前老师的分班
@being_setting_course_ids = @poll.poll_published_ids(current_user.id) #当前用户已发布的班级的id
@user_published_setting = @poll.poll_group_settings.find_in_poll_group("course_group_id",@being_setting_course_ids)
@user_published_setting = @poll.poll_group_settings.find_in_poll_group("course_group_id", @being_setting_course_ids)
poll_ids = [@poll.id]
@poll_publish_count = get_user_permission_course(poll_ids,2).count
@poll_publish_count = get_user_permission_course(poll_ids, 2).count
rescue Exception => e
uid_logger_error(e.message)
@ -725,19 +711,18 @@ class PollsController < ApplicationController
tip_exception("发布时间不能为空") if params[:publish_time].blank?
tip_exception("截止时间不能为空") if params[:end_time].blank?
tip_exception("截止时间必须晚于发布时间") if params[:publish_time].to_time >= params[:end_time].to_time
tip_exception("截止时间不能晚于课堂结束时间(#{@course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}") if
@course.end_date.present? && params[:end_time].to_time > @course.end_date.end_of_day
tip_exception("截止时间不能晚于课堂结束时间(#{@course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}") if @course.end_date.present? && params[:end_time].to_time > @course.end_date.end_of_day
params_publish_time = params[:publish_time].to_time
params_end_time = params[:end_time].to_time
if poll_status != 1 && @poll.publish_time != params_publish_time
normal_status(-1,"不允许修改发布时间")
normal_status(-1, "不允许修改发布时间")
elsif params_publish_time.present? && params_end_time.present? && params_end_time < params_publish_time
normal_status(-1,"截止时间不能小于发布时间")
normal_status(-1, "截止时间不能小于发布时间")
else
#发布时间小于当前时间则poll显示为未发布,当截止时间大于当前时间,则显示为已截止
poll_status_n = set_poll_status(params_publish_time,params_end_time)
poll_status_n = set_poll_status(params_publish_time, params_end_time)
poll_params = {
:unified_setting => unified_setting,
:show_result => show_result,
@ -752,23 +737,22 @@ class PollsController < ApplicationController
end
else
params_times = params[:publish_time_groups] #分班返回的json数组{"publish_time_groups":[{"course_group_id":["1","2"],"publish_time":"xx","end_time":"xxx"}]}
poll_groups = @poll.poll_group_settings.find_in_poll_group("course_id",@course.id) #当前课堂问卷的班级全部分班信息
poll_groups = @poll.poll_group_settings.find_in_poll_group("course_id", @course.id) #当前课堂问卷的班级全部分班信息
poll_groups_ids = poll_groups.pluck(:course_group_id) #问卷的全部分班id
total_common = params_times.map{|k| k[:course_group_id]}.sum #传入的所有分组的分班id
total_common = params_times.map {|k| k[:course_group_id]}.sum #传入的所有分组的分班id
total_common_group = poll_groups_ids & total_common #传入的分班与问卷已存在的分班的交集
old_poll_groups = poll_groups_ids - total_common_group #后来传入的分班里,没有了的班级,即需要删除
params_times.each do |t|
tip_exception("发布时间不能为空") if t[:publish_time].blank?
tip_exception("截止时间不能为空") if t[:end_time].blank?
tip_exception("截止时间不能早于发布时间") if t[:publish_time].to_time > t[:end_time].to_time
tip_exception("截止时间不能晚于课堂结束时间(#{@course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}") if
@course.end_date.present? && t[:end_time].to_time > @course.end_date.end_of_day
tip_exception("截止时间不能晚于课堂结束时间(#{@course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}") if @course.end_date.present? && t[:end_time].to_time > @course.end_date.end_of_day
course_id = t[:course_group_id]
poll_publish_time = t[:publish_time].to_time
poll_end_time = t[:end_time].to_time
poll_group = poll_groups.find_in_poll_group("course_group_id",course_id) #判断该分班是否存在
poll_group = poll_groups.find_in_poll_group("course_group_id", course_id) #判断该分班是否存在
if poll_group.present? && (poll_group.first.publish_time < Time.now) && (poll_publish_time != poll_group.first.publish_time)
error_count += 1
@ -781,14 +765,14 @@ class PollsController < ApplicationController
common_group = poll_groups_ids & course_id #传入的班级与问卷已存在的班级的交集,即表示已有分班的
new_group_ids = course_id - common_group #新传入的班级id
if common_group.size > 0 #传入的参数存在已发布的分班
poll_group = poll_groups.find_in_poll_group("course_group_id",common_group)
poll_group = poll_groups.find_in_poll_group("course_group_id", common_group)
poll_group.each do |the_group_setting|
poll_group_params = {
:publish_time => poll_publish_time,
:end_time => poll_end_time
}
the_group_setting_status = set_poll_status(the_group_setting.publish_time,the_group_setting.end_time)
the_group_setting_status = set_poll_status(the_group_setting.publish_time, the_group_setting.end_time)
if the_group_setting_status == 2
poll_group_params = {
:publish_time => the_group_setting.publish_time,
@ -821,11 +805,11 @@ class PollsController < ApplicationController
if error_count > 0
error_count == 0
normal_status(-1,"已发布/已截止的问卷不允许修改时间")
normal_status(-1, "已发布/已截止的问卷不允许修改时间")
else
# 未发布的分班设置才能删除
if old_poll_groups.size > 0
old_all_poll_groups = poll_groups.find_in_poll_group("course_group_id",old_poll_groups).poll_group_not_published
old_all_poll_groups = poll_groups.find_in_poll_group("course_group_id", old_poll_groups).poll_group_not_published
old_all_poll_groups.destroy_all
end
#问卷更新为poll_group_setting的发布时间最小截止时间最大
@ -837,7 +821,7 @@ class PollsController < ApplicationController
if p_time.nil? #发布时间为空,则表示问卷未发布
poll_status = 1
elsif p_time.present? && e_time.present?
poll_status = set_poll_status(p_time,e_time)
poll_status = set_poll_status(p_time, e_time)
end
poll_params = {
@ -851,7 +835,7 @@ class PollsController < ApplicationController
@poll.update!(poll_params)
if @poll.polls_status == 2
if @poll.course_acts.size == 0
@poll.course_acts << CourseActivity.new(:user_id => @poll.user_id,:course_id => @poll.course_id)
@poll.course_acts << CourseActivity.new(:user_id => @poll.user_id, :course_id => @poll.course_id)
end
end
normal_status(0, "问卷设置成功!")
@ -870,7 +854,7 @@ class PollsController < ApplicationController
def start_answer
ActiveRecord::Base.transaction do
begin
poll_user_current = PollUser.where(user_id:@poll_current_user_id,poll_id:@poll.id)&.first #查找当前用户是否有过答题
poll_user_current = PollUser.where(user_id: @poll_current_user_id, poll_id: @poll.id)&.first #查找当前用户是否有过答题
@poll_status = @poll.get_poll_status(current_user)
if poll_user_current.blank?
if @user_course_identity > Course::ASSISTANT_PROFESSOR #当为老师的时候不创建poll_user表理论上老师是不能进入答题的
@ -897,7 +881,7 @@ class PollsController < ApplicationController
# 判断是否已经回答还是新建的回答
@poll_questions.each do |q|
ques_vote = q.poll_votes.find_current_vote("user_id",@poll_current_user_id)
ques_vote = q.poll_votes.find_current_vote("user_id", @poll_current_user_id)
ques_type = q.question_type
if ques_type != 3 #非简答题时
@ -941,13 +925,13 @@ class PollsController < ApplicationController
def commit_poll
ActiveRecord::Base.transaction do
begin
@poll_multi_questions = @poll.poll_questions.where(question_type:2).select(:id,:max_choices,:min_choices,:question_number)
@poll_multi_questions = @poll.poll_questions.where(question_type: 2).select(:id, :max_choices, :min_choices, :question_number)
error_question = []
@poll_multi_questions.each do |q|
poll_user_votes = current_user.poll_votes.where(poll_question_id:q.id)&.size
poll_user_votes = current_user.poll_votes.where(poll_question_id: q.id)&.size
if q.max_choices.present? && (q.max_choices > 0) && (poll_user_votes > q.max_choices)
error_messages = "#{q.question_number}题:超过最大选项限制"
elsif q.min_choices.present? && (q.min_choices > 0)&& (poll_user_votes < q.min_choices)
elsif q.min_choices.present? && (q.min_choices > 0) && (poll_user_votes < q.min_choices)
error_messages = "#{q.question_number}题:不得少于最小选项限制"
else
error_messages = nil
@ -980,7 +964,7 @@ class PollsController < ApplicationController
def commit_result
ActiveRecord::Base.transaction do
begin
@poll_users = @poll.all_poll_users(current_user.id).where(commit_status:1) # 问卷已提交的用户
@poll_users = @poll.all_poll_users(current_user.id).where(commit_status: 1) # 问卷已提交的用户
@poll_commit_ids = @poll_users.commit_by_status(1).pluck(:user_id) #问卷提交用户的id
@page = params[:page] || 1
@limit = params[:limit] || 10
@ -988,18 +972,18 @@ class PollsController < ApplicationController
@poll_questions = @poll_questions.page(@page).per(@limit)
if params[:format] == "xlsx"
if @user_course_identity > Course::ASSISTANT_PROFESSOR
tip_exception(403,"无权限操作")
tip_exception(403, "无权限操作")
elsif (@poll.polls_status == 1) || (@poll_export_questions.size == 0) || (@poll_commit_ids.size == 0)
normal_status(-1,"暂无用户提交")
normal_status(-1, "暂无用户提交")
elsif params[:export].present? && params[:export]
normal_status(0,"正在下载中")
normal_status(0, "正在下载中")
else
respond_to do |format|
format.xlsx{
format.xlsx {
set_export_cookies
polls_export_name_ = "#{current_user.real_name}_#{@course.name}_#{@poll.polls_name}_#{Time.now.strftime('%Y%m%d_%H%M%S')}"
polls_user_commit = poll_commit_result(@poll,@poll_export_questions,@poll_users,@poll_commit_ids)
render xlsx: "#{polls_export_name_.strip}",template: "polls/commit_result.xlsx.axlsx",locals: {polls_user_commit:polls_user_commit}
polls_user_commit = poll_commit_result(@poll, @poll_export_questions, @poll_users, @poll_commit_ids)
render xlsx: "#{polls_export_name_.strip}", template: "polls/commit_result.xlsx.axlsx", locals: {polls_user_commit: polls_user_commit}
}
end
end
@ -1018,8 +1002,8 @@ class PollsController < ApplicationController
begin
poll_ids = [@poll.id]
@poll_list_status = @poll.get_poll_status(current_user)
@poll_publish_count = get_user_permission_course(poll_ids,2).count
@poll_unpublish_count = get_user_permission_course(poll_ids,1).count
@poll_publish_count = get_user_permission_course(poll_ids, 2).count
@poll_unpublish_count = get_user_permission_course(poll_ids, 1).count
@course_all_members = @course.students
@poll_group_counts = @course.course_groups_count
@ -1028,7 +1012,7 @@ class PollsController < ApplicationController
@poll_users_list = @poll.all_poll_users(current_user.id) #该老师分班的全部学生
get_poll_answers(@poll_users_list, @poll_list_status)
if @poll_list_status == 1
@poll_course_groups =[]
@poll_course_groups = []
else
poll_common_ids = @poll.poll_published_ids(current_user.id)
@poll_course_groups = @course.get_ex_published_course(poll_common_ids)
@ -1080,7 +1064,7 @@ class PollsController < ApplicationController
#班级的选择
if group_id.present?
poll_students = @course_all_members.course_find_by_ids("course_group_id",group_id) # 问卷所分班的全部人数
poll_students = @course_all_members.course_find_by_ids("course_group_id", group_id) # 问卷所分班的全部人数
user_ids = poll_students.pluck(:user_id).reject(&:blank?)
@poll_users_list = @poll_users_list.find_by_group_ids(user_ids)
end
@ -1134,8 +1118,8 @@ class PollsController < ApplicationController
end
def poll_params
params.require(:poll).permit(:polls_name,:polls_status,:publish_time,:end_time,:polls_description,
:show_result,:exercise_bank_id,:is_public,:unified_setting,:un_anonymous)
params.require(:poll).permit(:polls_name, :polls_status, :publish_time, :end_time, :polls_description,
:show_result, :exercise_bank_id, :is_public, :unified_setting, :un_anonymous)
end
# 获得问卷及课堂
@ -1176,7 +1160,7 @@ class PollsController < ApplicationController
def check_unified_setting?(poll) #问卷是否统一设置,如为分班设置,当前用户是否在班级内
if !poll.unified_setting #如果为分班设置,则需判断用户是否在班级内
poll_group_settings = poll.poll_group_settings.pluck(:course_group_id)
member = @course.course_members.course_find_by_ids("user_id",current_user.id)
member = @course.course_members.course_find_by_ids("user_id", current_user.id)
member_group_id = member.pluck(:course_group_id).uniq
if (member_group_id & poll_group_settings).size > 0 || @user_course_identity < Course::STUDENT
true
@ -1196,7 +1180,7 @@ class PollsController < ApplicationController
end
end
def set_poll_status(publish_time,end_time)
def set_poll_status(publish_time, end_time)
time_now_i = Time.now
if publish_time.present? && end_time.present? && publish_time <= time_now_i && end_time > time_now_i
2
@ -1217,20 +1201,20 @@ class PollsController < ApplicationController
@poll_question_singles = @poll_questions.ques_count(1).size # 单选题
@poll_question_doubles = @poll_questions.ques_count(2).size # 多选题
@poll_question_mains = @poll_questions.ques_count(3).size #主观题
@poll_questions = @poll_questions&.includes(:poll_answers,:poll_votes).distinct
@poll_questions = @poll_questions&.includes(:poll_answers, :poll_votes).distinct
end
def check_poll_question_complete #commit_poll 的权限
poll_user_current = @poll.poll_users.find_by_group_ids(current_user.id).first
poll_status = @poll.get_poll_status(current_user)
if @user_course_identity < Course::STUDENT || (poll_status == 3) || (poll_user_current.present? && poll_user_current.commit_status == 1)
normal_status(-1,"用户没有权限!") #老师/管理员在提交时没有权限
normal_status(-1, "用户没有权限!") #老师/管理员在提交时没有权限
else
necessary_answer = 0
poll_questions = @poll.poll_questions
necessary_question = poll_questions.ques_necessary # 问卷必答的问题
necessary_question.each do |q|
user_vote = q.poll_votes.find_current_vote("user_id",current_user.id)
user_vote = q.poll_votes.find_current_vote("user_id", current_user.id)
vote_answer_id = user_vote.pluck(:poll_answer_id).reject(&:blank?).size
vote_text_count = user_vote.pluck(:vote_text).reject(&:blank?).size
if vote_answer_id == 0 && vote_text_count == 0
@ -1238,7 +1222,7 @@ class PollsController < ApplicationController
end
end
if necessary_answer > 0
normal_status(-1,"问卷提交失败,有#{necessary_answer}个未答的必答题!")
normal_status(-1, "问卷提交失败,有#{necessary_answer}个未答的必答题!")
end
end
end
@ -1247,7 +1231,7 @@ class PollsController < ApplicationController
poll_status = @poll.get_poll_status(current_user)
commit_poll_user = @poll.poll_users.find_by_group_ids(current_user.id).commit_by_status(1) #当前用户已提交问卷的
unless (@user_course_identity < Course::STUDENT) || ((@poll.show_result == 1) && (poll_status == 3) && commit_poll_user.present?)
normal_status(-1,"没有权限!") #当前为老师/问卷公开统计,且问卷已截止,且用户有过回答的
normal_status(-1, "没有权限!") #当前为老师/问卷公开统计,且问卷已截止,且用户有过回答的
end
end
@ -1255,11 +1239,11 @@ class PollsController < ApplicationController
user_login = params[:login]
# @poll_current_user_id = params[:user_id]
if user_login.blank? && @user_course_identity < Course::STUDENT #id不存在且当前为老师/管理员等
normal_status(-1,"请输入学生登陆名!")
normal_status(-1, "请输入学生登陆名!")
else
@answer_user = User.find_by(login:user_login)
@answer_user = User.find_by(login: user_login)
if @answer_user.blank?
normal_status(404,"答题用户不存在")
normal_status(404, "答题用户不存在")
else
@poll_current_user_id = @answer_user.id || current_user.id
end
@ -1273,11 +1257,11 @@ class PollsController < ApplicationController
@poll_questions_count = @poll_questions.size
end
def get_user_permission_course(poll_ids,status) #获取用户权限范围内的已发布/未发布
def get_user_permission_course(poll_ids, status) #获取用户权限范围内的已发布/未发布
poll_status = status.to_i
unpublish_group = []
user_groups_id = @course.charge_group_ids(current_user)
all_polls = Poll.where(id:poll_ids)
all_polls = Poll.where(id: poll_ids)
all_polls.each do |poll|
if poll.present?
if poll.unified_setting
@ -1317,28 +1301,28 @@ class PollsController < ApplicationController
publish_course = params[:publish_time_groups]
unified_setting = params[:unified_setting]
if @course.is_end
normal_status(-1,"课堂已结束不能再修改!")
normal_status(-1, "课堂已结束不能再修改!")
elsif unified_setting
poll_group_settings = @poll.poll_group_settings
if poll_group_settings.present?
p_time_present = poll_group_settings.publish_time_present.map(&:publish_time).min
if p_time_present < Time.now
normal_status(-1,"设置失败,存在已发布的分班!")
normal_status(-1, "设置失败,存在已发布的分班!")
end
elsif params[:publish_time].blank?
normal_status(-1,"发布时间不允许为空")
normal_status(-1, "发布时间不允许为空")
end
elsif unified_setting.present? && !unified_setting #非统一设置,分班不能为空
if publish_course.present?
course_ids = publish_course.map{|a| a[:course_group_id]}.sum
publish_t = publish_course.map{|a| a[:publish_time]}
course_ids = publish_course.map {|a| a[:course_group_id]}.sum
publish_t = publish_course.map {|a| a[:publish_time]}
if course_ids.include?(nil) || course_ids.count == 0
normal_status(-1,"请选择分班!")
normal_status(-1, "请选择分班!")
elsif publish_t.include?(nil) || publish_t.count == 0
normal_status(-1,"发布时间不允许为空")
normal_status(-1, "发布时间不允许为空")
end
else
normal_status(-1,"请选择分班!")
normal_status(-1, "请选择分班!")
end
end
end
@ -1354,7 +1338,7 @@ class PollsController < ApplicationController
end
#问卷的统计结果的导出
def poll_commit_result(poll,poll_questions,poll_users,poll_commit_ids)
def poll_commit_result(poll, poll_questions, poll_users, poll_commit_ids)
sub_commit = []
user_commit = []
poll_users_info = %w(序号)
@ -1368,50 +1352,50 @@ class PollsController < ApplicationController
poll_users_info = poll_users_info + user_info + poll_ques_titles
poll_questions.each do |q|
if q.question_type != 3 #问题不为主观题
question_vote_user = q.poll_votes.find_current_vote("user_id",poll_commit_ids)&.size #该问题的有效填写量
question_vote_user = q.poll_votes.find_current_vote("user_id", poll_commit_ids)&.size #该问题的有效填写量
sheet_row = ["#{q.question_number}"] #选择题答案选项的数组
sheet_answer_row = ["小计"] #选择题回答的答案人数,数组
sheet_answer_percent = ["比例"]
sheet_answer_useful = ["本题有效填写人次",question_vote_user]
sheet_answer_useful = ["本题有效填写人次", question_vote_user]
q.poll_answers.each do |a| #问卷的答案选项
answer_users_count = a.poll_votes.find_current_vote("user_id",poll_commit_ids)&.size
answer_percent = (question_vote_user == 0) ? "0.0%" : "#{((answer_users_count / question_vote_user.to_f)*100).round(1).to_s}%"
answer_users_count = a.poll_votes.find_current_vote("user_id", poll_commit_ids)&.size
answer_percent = (question_vote_user == 0) ? "0.0%" : "#{((answer_users_count / question_vote_user.to_f) * 100).round(1).to_s}%"
sheet_row.push(a.answer_text)
sheet_answer_row.push(answer_users_count)
sheet_answer_percent.push(answer_percent)
end
sheet_sub_commit = {
sub_title: sheet_row,
sub_user_votes:[sheet_answer_row,sheet_answer_percent,sheet_answer_useful]
sub_user_votes: [sheet_answer_row, sheet_answer_percent, sheet_answer_useful]
}
sub_commit.push(sheet_sub_commit)
else #主观题答案
user_votes= []
main_show_row = ["#{q.question_number}", q.question_title ]
q.poll_votes.each_with_index do |v,index| #主观题的答案
q_poll_vote = [(index+1), v.vote_text.present? ? v.vote_text : "--"]
user_votes = []
main_show_row = ["#{q.question_number}", q.question_title]
q.poll_votes.each_with_index do |v, index| #主观题的答案
q_poll_vote = [(index + 1), v.vote_text.present? ? v.vote_text : "--"]
user_votes.push(q_poll_vote)
end
sheet_sub_commit = {
sub_title: main_show_row,
sub_user_votes:user_votes
sub_user_votes: user_votes
}
sub_commit.push(sheet_sub_commit)
end
end #each_with_index
poll_users.includes(user: [:user_extension,:poll_votes]).each_with_index do |u,index|
poll_users.includes(user: [:user_extension, :poll_votes]).each_with_index do |u, index|
u_user = u.user
user_answer_array = []
poll_questions.each do |q|
user_poll_votes = u_user.poll_votes.find_current_vote("poll_question_id",q.id)
user_poll_votes = u_user.poll_votes.find_current_vote("poll_question_id", q.id)
if user_poll_votes.present?
if q.question_type < 3
user_poll_answer_ids = user_poll_votes.pluck(:poll_answer_id).reject(&:blank?)
if user_poll_answer_ids.count > 0
answer_content = q.poll_answers.find_answer_by_custom("id",user_poll_answer_ids)
if user_poll_answer_ids.count >1
answer_content = q.poll_answers.find_answer_by_custom("id", user_poll_answer_ids)
if user_poll_answer_ids.count > 1
u_answer = answer_content.pluck(:answer_text).join(";")
else
u_answer = answer_content.first&.answer_text
@ -1436,23 +1420,23 @@ class PollsController < ApplicationController
end
user_answer_array.push(u_answer)
end
user_cell = [index+1]
user_cell = [index + 1]
if poll_un_anony
user_login = u_user.login
user_name = u_user.real_name.present? ? u_user.real_name : "--"
user_class = poll.course.user_group_name(u_user.id)
user_student_id = u_user.student_id.present? ? u_user.student_id : "--"
user_school_name = u_user.school_name.present? ? u_user.school_name : "--"
user_cell += [user_login,user_name, user_class, u_user.mail, user_student_id, user_school_name]
user_cell += [user_login, user_name, user_class, u_user.mail, user_student_id, user_school_name]
end
all_user_cell = user_cell + user_answer_array
user_commit.push(all_user_cell)
end
{
poll_users_info:poll_users_info,
sub_commit:sub_commit,
user_commit:user_commit
poll_users_info: poll_users_info,
sub_commit: sub_commit,
user_commit: user_commit
}
end

@ -26,7 +26,7 @@ class ShixunsController < ApplicationController
before_action :special_allowed, only: [:send_to_course, :search_user_courses]
before_action :shixun_marker, only: [:new, :create]
before_action :validate_wachat_support, only: [:shixun_exec]
#before_action :validate_wachat_support, only: [:shixun_exec]
skip_before_action :check_sign, only: [:download_file]
## 获取课程列表
@ -475,7 +475,7 @@ class ShixunsController < ApplicationController
if params[:shixun][:vnc]
shixun_params.merge(vnc_evaluate: 1)
else
shixun_params
shixun_params.merge(vnc_evaluate: 0)
end
@shixun.update_attributes!(update_params)
end
@ -1187,11 +1187,11 @@ private
md5.hexdigest
end
def validate_wachat_support
if (params[:wechat].present? && !@shixun.is_wechat_support?)
tip_exception(-5, "..")
end
end
# def validate_wachat_support
#
# if (params[:wechat].present? && !@shixun.is_wechat_support?)
# tip_exception(-5, "..")
# end
# end
end

@ -3,9 +3,10 @@ class SubjectsController < ApplicationController
# before_action :check_auth, except: [:index]
before_action :check_account, except: [:index, :show, :right_banner]
before_action :find_subject, except: [:index, :create, :new, :append_to_stage, :add_shixun_to_stage]
before_action :allowed, only: [:update, :edit, :destroy, :publish, :cancel_publish, :cancel_has_publish,
before_action :allowed, only: [:update, :edit, :destroy, :publish, :cancel_publish, :cancel_has_publish, :apply_public,
:search_members, :add_subject_members, :statistics, :shixun_report, :school_report,
:up_member_position, :down_member_position, :update_team_title, :statistics_info]
:cancel_has_public, :up_member_position, :down_member_position, :update_team_title,
:statistics_info, :cancel_public]
before_action :require_admin, only: [:copy_subject]
before_action :shixun_marker, only: [:add_shixun_to_stage]
@ -33,16 +34,16 @@ class SubjectsController < ApplicationController
laboratory_join = " AND subjects.id in #{subject_ids} "
if select
@subjects = Subject.find_by_sql("SELECT subjects.id, subjects.user_id, subjects.name, subjects.stages_count, subjects.repertoire_id, subjects.status,
@subjects = Subject.find_by_sql("SELECT subjects.id, subjects.user_id, subjects.name, subjects.stages_count, subjects.repertoire_id, subjects.status, subjects.public,
subjects.shixuns_count, subjects.excellent, sum(shixuns.myshixuns_count) AS myshixun_member_count FROM subjects join stage_shixuns
on stage_shixuns.subject_id = subjects.id join shixuns on shixuns.id = stage_shixuns.shixun_id where
subjects.hidden = 0 AND subjects.status = 2 AND subjects.name like '%#{search}%' #{laboratory_join}
subjects.hidden = 0 AND subjects.public = 2 AND subjects.name like '%#{search}%' #{laboratory_join}
AND subjects.repertoire_id = #{select} GROUP BY subjects.id ORDER BY myshixun_member_count DESC")
else
@subjects = Subject.find_by_sql("SELECT subjects.id, subjects.user_id, subjects.name, subjects.stages_count, subjects.repertoire_id, subjects.status,
@subjects = Subject.find_by_sql("SELECT subjects.id, subjects.user_id, subjects.name, subjects.stages_count, subjects.repertoire_id, subjects.status, subjects.public,
subjects.shixuns_count, subjects.excellent, sum(shixuns.myshixuns_count) AS myshixun_member_count FROM subjects join stage_shixuns
on stage_shixuns.subject_id = subjects.id join shixuns on shixuns.id = stage_shixuns.shixun_id where
subjects.hidden = 0 AND subjects.status = 2 AND subjects.name like '%#{search}%' #{laboratory_join}
subjects.hidden = 0 AND subjects.public = 2 AND subjects.name like '%#{search}%' #{laboratory_join}
GROUP BY subjects.id ORDER BY myshixun_member_count DESC")
end
else
@ -59,7 +60,7 @@ class SubjectsController < ApplicationController
elsif reorder == "publish_time"
@subjects = @subjects.unhidden
else
@subjects = @subjects.visible.unhidden
@subjects = @subjects.publiced.unhidden
end
# 类型
@ -72,7 +73,7 @@ class SubjectsController < ApplicationController
end
# 排序
order_str = reorder == "publish_time" ? "status = 2 desc, publish_time asc" : "updated_at desc"
order_str = (reorder == "publish_time" ? "homepage_show desc, excellent desc, public = 2 desc, publish_time asc" : "homepage_show desc, excellent desc, updated_at desc")
@subjects = @subjects.reorder(order_str)
end
@ -242,13 +243,14 @@ class SubjectsController < ApplicationController
## 云上实验室过滤
@courses = @courses.where(id: current_laboratory.all_courses)
@none_shixun_ids = ShixunSchool.where("school_id != #{current_user.user_extension.try(:school_id).to_i}").pluck(:shixun_id)
@all_shixun_ids = @subject.shixuns.where(use_scope: 0).pluck(:id) +
@subject.shixuns.joins(:shixun_schools).where("school_id = #{current_user.user_extension.try(:school_id).to_i} and use_scope = 1").pluck(:id)
end
def send_to_course
@course = Course.find_by!(id: params[:course_id])
stages = @subject.stages.where(id: @subject.stage_shixuns.where(shixun_id: params[:shixun_ids]).pluck(:stage_id))
stages = @subject.stages.where(id: @subject.stage_shixuns.where(shixun_id: params[:shixun_ids]).pluck(:stage_id)).reorder("stages.position DESC")
order_ids = params[:shixun_ids].size > 0 ? params[:shixun_ids].reverse.join(',') : -1
course_module = @course.course_modules.where(module_type: "shixun_homework").first
homework_ids = []
@ -259,7 +261,8 @@ class SubjectsController < ApplicationController
CourseSecondCategory.create!(name: stage.name, course_id: @course.id, category_type: "shixun_homework",
course_module_id: course_module.id, position: course_module.course_second_categories.count + 1)
stage.shixuns.no_jupyter.where(id: params[:shixun_ids], status: 2).each do |shixun|
shixuns = stage.shixuns.no_jupyter.published.where(id: params[:shixun_ids]).reorder("field(shixuns.id, #{order_ids})")
shixuns.each do |shixun|
homework = HomeworksService.new.create_homework shixun, @course, category, current_user
homework_ids << homework.id
end
@ -271,14 +274,44 @@ class SubjectsController < ApplicationController
end
def publish
@subject.update_attributes(status: 2)
end
def cancel_publish
begin
apply = ApplyAction.where(container_type: "ApplySubject", container_id: @subject.id).order("created_at desc").first
if apply && apply.status == 0
apply.update_attributes(status: 3)
apply.tidings.destroy_all
end
@subject.update_attributes(status: 0)
rescue => e
uid_logger_error(e.message)
tip_exception("撤销申请失败")
end
end
def cancel_has_publish
begin
@subject.update_attributes(:status => 0)
rescue => e
uid_logger_error(e.message)
tip_exception("撤销发布失败")
raise ActiveRecord::Rollback
end
end
# 申请公开
def apply_public
tip_exception(-1, "请先发布课程再申请公开") if @subject.status != 2
apply = ApplyAction.where(container_type: "ApplySubject", container_id: @subject.id).order("created_at desc").first
if apply && apply.status == 0
@status = 0
else
@subject.update_attributes(status: 1)
@subject.update_attributes(public: 1)
ApplyAction.create(container_type: "ApplySubject", container_id: @subject.id, user_id: current_user.id, status: 0)
begin
status = Educoder::Sms.send(mobile: '18711011226', send_type:'publish_subject' , name: '管理员')
Educoder::Sms.send(mobile: '18711011226', send_type:'publish_subject' , name: '管理员')
rescue => e
uid_logger_error("发送验证码出错: #{e}")
end
@ -286,28 +319,28 @@ class SubjectsController < ApplicationController
end
end
def cancel_publish
def cancel_public
begin
apply = ApplyAction.where(container_type: "ApplySubject", container_id: @subject.id).order("created_at desc").first
if apply && apply.status == 0
apply.update_attributes(status: 3)
apply.tidings.destroy_all
end
@subject.update_attributes(status: 0)
@subject.update_attributes(public: 0)
render_ok
rescue => e
uid_logger_error(e.message)
tip_exception("撤销申请失败")
raise ActiveRecord::Rollback
end
end
def cancel_has_publish
def cancel_has_public
begin
@subject.update_attributes(:status => 0)
@subject.update_attributes(:public => 0)
render_ok
rescue => e
uid_logger_error(e.message)
tip_exception("撤销发布失败")
raise ActiveRecord::Rollback
tip_exception("撤销公开失败")
end
end

@ -2,11 +2,10 @@ class TagDisciplinesController < ApplicationController
before_action :require_login
def create
tip_exception("请输入知识点") if params[:name].blank?
tip_exception("输入字符长度限制在15个以内") if params[:name].length > 15
sub_discipline = SubDiscipline.find_by!(id: params[:sub_discipline_id])
tip_exception("重复的知识点") if sub_discipline.tag_disciplines.exists?(name: params[:name].to_s.strip)
tag_discipline = TagDiscipline.create!(name: params[:name].to_s.strip, sub_discipline: sub_discipline, user_id: current_user.id)
tag_discipline = TagDiscipline.create!(name: params[:name].to_s.strip, sub_discipline: sub_discipline, user_id: current_user.id,
position: sub_discipline.tag_disciplines.pluck(:position).max + 1)
render_ok({tag_discipline_id: tag_discipline.id})
end
end

@ -5,7 +5,7 @@ class TidingsController < ApplicationController
after_action :update_onclick_time!, only: [:index]
def index
tidings = current_user.tidings
tidings = current_user.tidings.visible
@onclick_time = current_user.click_time
tiding_types =
@ -19,8 +19,9 @@ class TidingsController < ApplicationController
end
tidings = tidings.where(tiding_type: tiding_types) if tiding_types.present?
tidings = tidings.where(container_type: 'JoinCourse') if params[:type] == 'course_apply'
@course_apply_count = tidings.where("created_at > '#{@onclick_time}'").where(container_type: 'JoinCourse').count
tidings = tidings.where(container_type: 'JoinCourse', status: 0) if params[:type] == 'course_apply'
# @course_apply_count = tidings.where("created_at > '#{@onclick_time}'").where(container_type: 'JoinCourse', status: 0).count
@course_apply_count = tidings.where(container_type: 'JoinCourse', status: 0).count
tidings = tidings.where(container_type: 'ProjectPackage') if params[:type] == 'project_package'

@ -13,7 +13,7 @@ class Users::VideosController < Users::BaseController
end
def update
return render_error('该状态下不能编辑视频信息') unless current_video.published?
return render_error('该状态下不能编辑视频信息') unless (current_video.published? || current_video.course_videos.present?)
current_video.update!(title: params[:title])
@ -39,6 +39,13 @@ class Users::VideosController < Users::BaseController
@videos = paginate videos
end
def get_video_data
start_time = params[:start_time].to_time.utc.strftime('%Y-%m-%dT%H:%M:%SZ')
end_time = params[:end_time].to_time.utc.strftime('%Y-%m-%dT%H:%M:%SZ')
result = AliyunVod::Service.video_data(current_video.uuid, start_time, end_time)
render :json => {data: result}
end
def batch_publish
Videos::BatchPublishService.call(observed_user, batch_publish_params)
render_ok
@ -50,6 +57,14 @@ class Users::VideosController < Users::BaseController
def current_video
@_current_video ||= observed_user.videos.find_by(id: params[:id])
if @_current_video.nil?
video = Video.find_by(id: params[:id])
if video.course_videos.present?
video
end
else
@_current_video
end
end
def search_params
@ -57,6 +72,6 @@ class Users::VideosController < Users::BaseController
end
def batch_publish_params
params.permit(videos: %i[video_id title])
params.permit(videos: %i[video_id title course_id])
end
end

@ -52,7 +52,7 @@ class UsersController < ApplicationController
def attachment_show
file_name = params[:file_name]
path = params[:path]
path = params[:path] || edu_setting('attachment_folder')
send_file "#{path}/#{file_name}", :filename => "#{file_name}",
:type => 'game',
:disposition => 'attachment' #inline can open in browser

@ -0,0 +1,26 @@
class Weapps::ChallengesController < Weapps::BaseController
before_action :require_login
before_action :set_challenge
def is_play
# 关卡有展示效果 || 选择题 || jupyter实训 || vnc || 隐藏代码窗口 || html+css实训
# @challenge.show_type != -1 || @challenge.st == 1 || @shixun.is_jupyter? || @shixun.vnc ||
# @shixun.hide_code? || (@shixun.small_mirror_name & ["Css", "Html", "Web"]).present?
play = @shixun.is_jupyter? || @shixun.vnc ||
@shixun.hide_code? || (@shixun.small_mirror_name & ["Css", "Html", "Web"]).present?
if play
normal_status(-5, "该关卡暂不支持小程序")
else
render_ok
end
end
private
def set_challenge
@challenge = Challenge.find_by!(id: params[:id])
@shixun = @challenge.shixun
end
end

@ -1,27 +1,50 @@
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 :set_course, except: [:create, :check_invite_code]
before_action :user_course_identity, except: [:basic_info, :create, :check_invite_code]
before_action :check_account, only: [:create, :check_invite_code]
before_action :teacher_allowed, only: [:edit, :update]
before_action :teacher_or_admin_allowed, only: [:change_member_roles, :delete_course_teachers]
def course_activities
@course = current_course
homework_commons = @course.homework_commons.where(homework_type: ["practice", "normal"]).homework_published
member = @course.course_members.find_by(user_id: current_user.id, is_active: 1)
if (@user_course_identity == Course::STUDENT && member.try(:course_group_id).to_i == 0) || @user_course_identity > Course::STUDENT
homework_commons = homework_commons.unified_setting
elsif @user_course_identity == Course::STUDENT
not_homework_ids = @course.homework_group_settings.none_published.where("course_group_id = #{member.try(:course_group_id)}").pluck(:homework_common_id)
homework_commons = homework_commons.where.not(id: not_homework_ids)
end
homework_ids = homework_commons.blank? ? "(-1)" : "(" + homework_commons.pluck(:id).join(",") + ")"
activities = @course.course_activities.where("course_act_type in ('Course', 'CourseMessage') or
(course_act_type = 'HomeworkCommon' and course_act_id in #{homework_ids})").order("id desc")
@activities_count = activities.size
@activities = paginate activities.includes(:course_act, user: :user_extension)
end
def create
# return render_error("只有老师身份才能创建课堂") unless current_user.is_teacher?
course = Course.new(tea_id: current_user.id)
Weapps::CreateCourseService.call(course, course_params)
render_ok
render_ok(id: course.id)
rescue ApplicationService::Error => ex
render_error(ex.message)
end
def basic_info
@course = current_course
end
def edit
@course = current_course
end
def update
Weapps::UpdateCourseService.call(current_course, update_course_params)
render_ok
course = Weapps::UpdateCourseService.call(current_course, update_course_params)
render_ok(id: course.id)
end
def show
@ -33,6 +56,23 @@ class Weapps::CoursesController < Weapps::BaseController
@categories = current_course.shixun_course_modules.first&.course_second_categories
end
def check_invite_code
tip_exception(-1, "邀请码不能为空") if params[:invite_code].blank?
invite_code = params[:invite_code]
course = Course.find_by(invite_code: invite_code, is_delete: 0, invite_code_halt: 0)
course_group = CourseGroup.find_by(invite_code: invite_code, invite_code_halt: 0)
if course.blank?
tip_exception(-1, "邀请码无效") if course_group.blank?
course = Course.find_by(id: course_group.course_id, is_delete: 0)
tip_exception(-1, "邀请码无效") if course.blank?
end
tip_exception(-1, "课堂已结束,无法加入") if course.is_end
render_ok
end
# 教师列表
def teachers
@course = current_course
@ -179,11 +219,11 @@ class Weapps::CoursesController < Weapps::BaseController
private
def course_params
params.permit(:name, :course_list_name, :credit, course_module_types: [])
params.permit(:name, :course_list_name, :credit, :end_date, course_module_types: [])
end
def update_course_params
params.permit(:name, :course_list_name, :credit)
params.permit(:name, :course_list_name, :credit, :end_date)
end
def current_course

@ -17,7 +17,13 @@ class Weapps::SessionsController < Weapps::BaseController
# session[:wechat_user_extra].delete(:nickName)
# 绑定微信号
OpenUsers::Wechat.create!(user: user, uid: session_unionid) if user.wechat_open_user.blank?
# open_user = OpenUsers::Wechat.find_by(uid: session_unionid)
# if open_user.present? && open_user.user_id.nil?
# open_user.update!(user_id: user.id)
# els
if user.wechat_open_user.blank?
OpenUsers::Wechat.create!(user: user, uid: session_unionid)
end
successful_authentication(user)
end

@ -0,0 +1,14 @@
class Weapps::ShixunListsController < ApplicationController
def index
results = Weapps::ShixunSearchService.call(search_params, current_laboratory)
@total_count = results.size
@results = paginate results
end
private
def search_params
params.permit(:keyword, :type, :page, :limit, :order, :status, :diff, :sort, :no_jupyter)
end
end

@ -0,0 +1,28 @@
class Weapps::SubjectsController < Weapps::BaseController
before_action :require_login, except: [:index, :show]
before_action :find_subject, except: [:index]
# 首页
def index
subjects = Weapps::SubjectQuery.call(current_laboratory, params)
@subject_count = subjects.map(&:id).size
@subjects = paginate subjects
end
# 详情
def show
# 合作团队
Rails.logger.info("##########subject: #{@subject.id}")
@members = @subject.subject_members.includes(:user)
shixuns = @subject.shixuns.published.pluck(:id)
challenge_ids = Challenge.where(shixun_id: shixuns).pluck(:id)
# 实训路径中的所有实训标签
@tags = ChallengeTag.where(challenge_id: challenge_ids).pluck(:name).uniq
end
private
def find_subject
@subject = Subject.find(params[:id])
end
end

@ -0,0 +1,16 @@
class Weapps::UnbindAccountsController < Weapps::BaseController
before_action :require_login
def show
@user = current_user
end
def destroy
open_user = OpenUsers::Wechat.find_by!(user_id: current_user.id)
session[:unionid] = open_user.uid
open_user.destroy!
UserAction.create(action_id: current_user.id, action_type: "UnbindWechat", user_id: current_user.id, :ip => request.remote_ip)
logout_user
render_ok
end
end

@ -321,6 +321,10 @@ module TidingDecorator
I18n.t(locale_format(parent_container_type)) % container&.exercise_name
end
def live_link_content
I18n.t(locale_format) % container&.course_name
end
def student_graduation_topic_content
I18n.t(locale_format) % container&.graduation_topic.try(:name)
end

@ -7,8 +7,6 @@ class ItemBanks::SaveItemForm
validates :sub_discipline_id, presence: true
validates :item_type, presence: true, inclusion: {in: %W(SINGLE MULTIPLE JUDGMENT COMPLETION SUBJECTIVE PRACTICAL PROGRAM)}
validates :difficulty, presence: true, inclusion: {in: 1..3}, numericality: { only_integer: true }
validates :name, presence: true, length: { maximum: 1000, too_long: "不能超过1000个字符" }
validates :analysis, length: { maximum: 1000, too_long: "不能超过1000个字符" }
def validate!
super
@ -27,7 +25,6 @@ class ItemBanks::SaveItemForm
attr_accessor :choice_text, :is_answer
validates :choice_text, presence: true, length: { maximum: 500, too_long: "不能超过500个字符" }
validates :is_answer, presence: true, inclusion: {in: 0..1}, numericality: { only_integer: true }
end
end

@ -2,7 +2,7 @@ class Weapps::CreateCourseForm
include ActiveModel::Model
attr_accessor :course
attr_accessor :name, :course_list_name, :credit, :course_module_types
attr_accessor :name, :course_list_name, :credit, :course_module_types, :end_date
validates :name, presence: true
validates :course_list_name, presence: true

@ -2,7 +2,7 @@ class Weapps::UpdateCourseForm
include ActiveModel::Model
attr_accessor :course
attr_accessor :name, :course_list_name, :credit
attr_accessor :name, :course_list_name, :credit, :end_date
validates :name, presence: true
validates :course_list_name, presence: true

@ -1,11 +1,22 @@
module Admins::SubjectsHelper
def display_subject_status(subject)
style =
case subject.status
case subject.public
when 0 then 'text-secondary'
when 1 then 'text-warning'
when 2 then 'text-success'
end
raw content_tag(:span, t("subject.status.#{subject.status}"), class: style)
status =
if subject.public == 2
"publiced"
elsif subject.public == 1
"pending"
elsif subject.status == 2
"processed"
else
"editing"
end
raw content_tag(:span, t("subject.public.#{status}"), class: style)
end
end

@ -137,7 +137,7 @@ module ApplicationHelper
# 用户图像url如果不存在的话source为匿名用户即默认使用匿名用户图像
def url_to_avatar(source)
if File.exist?(disk_filename(source.class, source.id))
if File.exist?(disk_filename(source&.class, source&.id))
ctime = File.ctime(disk_filename(source.class, source.id)).to_i
if source.class.to_s == 'User'
File.join(relative_path, ["#{source.class}", "#{source.id}"]) + "?t=#{ctime}"
@ -397,6 +397,8 @@ module ApplicationHelper
raw arr.join('')
end
# 导出pdf时转化markdown为html
def to_markdown(text,origin_url)
return nil if text.blank?
@ -406,10 +408,10 @@ module ApplicationHelper
:fenced_code_blocks => true,
:lax_html_blocks => true,
:strikethrough => true,
:superscript => true,
:superscript => false,
:tables => true
}
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML,options)
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, options)
m_t = markdown.render(text)
m_t&.include?("src=\"") ? m_t&.gsub("src=\"","src=\"#{origin_url}") : m_t
end

@ -12,6 +12,12 @@ module CoursesHelper
# end
end
def edit_auth group, teachers
User.current.admin_or_business? ||
teachers.select{|teacher| teacher.user_id == User.current.id &&
(teacher.teacher_course_groups.pluck(:course_group_id).include?(group.id) || teacher.teacher_course_groups.size == 0)}.size > 0
end
# 是否有切换为学生的入口
def switch_student_role is_teacher, course, user
is_teacher && course.course_members.where(user_id: user.id, role: %i(STUDENT)).exists?
@ -65,6 +71,8 @@ module CoursesHelper
"/courses/#{course.id}/course_groups"
when "statistics"
"/courses/#{course.id}/statistics"
when "video"
"/courses/#{course.id}/course_videos"
end
end
@ -126,6 +134,8 @@ module CoursesHelper
course.informs.count
when "online_learning"
course.shixuns.count
when "video"
course.course_videos.count + course.live_links.count
end
end

@ -171,10 +171,21 @@ module HomeworkCommonsHelper
{status: status, time: time}
end
# 作品数统计type 1 已提交 0 未提交
# 作品数统计type 1 已提交 0 未提交 2 所有
def studentwork_count homework_common, type, member
student_works = homework_common.teacher_works(member)
type == 1 ? student_works.where("work_status != 0").size : student_works.where(work_status: 0).size
type == 2 ? student_works.size : (type == 1 ? student_works.where("work_status != 0").size : student_works.where(work_status: 0).size)
end
# 作品数统计
def calculate_work_count homework_common, member
count = {}
student_works = homework_common.teacher_works(member)
count[:commit_count] = student_works.select{|work| work.work_status != 0 }.size
count[:uncommit_count] = student_works.select{|work| work.work_status == 0 }.size
count[:compelete_count] = Myshixun.where(id: student_works.pluck(:myshixun_id).reject(&:blank?), status: 1).size
count[:all_count] = student_works.size
count
end
# 上次查重的时间

@ -152,7 +152,7 @@ module ShixunsHelper
challenge_program_name = []
shixun.challenges.map(&:exec_path).each do |exec_path|
challenge_program_name << "\"#{exec_path}\""
if shixun.main_mirror_name == "Java"
if shixun.main_mirror_name == "Java" || shixun.main_mirror_name == "Openjdk10/VNC" || shixun.main_mirror_name == "JavaWeb"
if exec_path.nil? || exec_path.split("src/")[1].nil?
source = "\"\""
else
@ -169,6 +169,7 @@ module ShixunsHelper
source_class_name << source if source.present?
end
end
logger.info("####source_class_name: #{source_class_name}")
script = if script.include?("sourceClassName") && script.include?("challengeProgramName")
script.gsub(/challengeProgramNames=\(.*\)/,"challengeProgramNames=\(#{challenge_program_name.reject(&:blank?).join(" ")}\)").gsub(/sourceClassNames=\(.*\)/, "sourceClassNames=\(#{source_class_name.reject(&:blank?).join(" ")}\)")
else

@ -1,12 +1,23 @@
module SubjectsHelper
# 实训路径的发布状态
def publish_status subject, is_manager, user
def publish_status subject, is_manager
status = -1
if is_manager
status = 0 if subject.status == 0
status = 1 if subject.status == 1
status = 2 if subject.status == 2 && user.admin?
status = 2 if subject.status == 2
end
status
end
# 实训路径的公开状态
def public_status subject, is_manager, user
status = -1
if is_manager
status = 0 if subject.public == 0
status = 1 if subject.public == 1
status = 2 if subject.public == 2 && user.admin?
end
status
end

@ -1,15 +1,16 @@
module Weapps::CoursesHelper
require 'chinese_pinyin'
def teacher_list teachers
def teacher_list teachers, user_course_identity
data = []
teachers.each do |teacher|
if teacher.user.present?
teacher_user = teacher.user
name = teacher_user.real_name
role = teacher.role == "CREATOR" ? "管理员" : teacher.role == "PROFESSOR" ? "教师" : "助教"
member_roles = user_course_identity < Course::ASSISTANT_PROFESSOR ? teacher_user.course_role(teacher.course) : []
item = {name: name, course_member_id: teacher.id, login: teacher_user.login, user_id: teacher.user_id, role: role,
school: teacher_user.school_name, image_url: url_to_avatar(teacher_user)}
school: teacher_user.school_name, image_url: url_to_avatar(teacher_user), member_roles: member_roles}
pinyin = Pinyin.t(name.strip, splitter: '')
first_char = pinyin[0]
letter = first_letter first_char
@ -28,15 +29,16 @@ module Weapps::CoursesHelper
end
def student_list students, excellent
def student_list students, excellent, user_course_identity
data = []
students.each do |student|
if student.user.present?
student_user = student.user
name = student_user.real_name
phone = excellent ? "" : student_user.hidden_phone
member_roles = user_course_identity < Course::ASSISTANT_PROFESSOR ? student_user.course_role(student.course) : []
item = {name: name, course_member_id: student.id, login: student_user.login, user_id: student.user_id,
student_id: student_user.student_id, image_url: url_to_avatar(student_user), phone: phone}
student_id: student_user.student_id, image_url: url_to_avatar(student_user), phone: phone, member_roles: member_roles}
pinyin = Pinyin.t(name.strip, splitter: '')
first_char = pinyin[0]
letter = first_letter first_char

@ -0,0 +1,13 @@
# 删除课堂时将相应的课堂消息置为删除状态,并给老师发送删除消息
class DeleteCourseNotifyJob < ApplicationJob
queue_as :default
def perform(course_id, user_id)
course = Course.find_by(id: course_id)
return if course.blank?
Tiding.where(belong_container: course).update_all(is_delete: 1)
Tiding.create!(user_id: user_id, trigger_user_id: user_id, container_id: course.id,
container_type: 'DeleteCourse', tiding_type: 'System', belong_container: course, extra: course.name)
end
end

@ -0,0 +1,27 @@
# 直播开启的消息通知
class LivePublishJob < ApplicationJob
queue_as :notify
def perform(live_id)
live = LiveLink.find_by(id: live_id)
return if live.blank? || live.course.blank?
course = live.course
attrs = %i[
user_id trigger_user_id container_id container_type parent_container_id parent_container_type
belong_container_id belong_container_type viewed tiding_type created_at updated_at
]
same_attrs = {
trigger_user_id: live.user_id, container_id: live.id, container_type: 'LiveLink',
parent_container_id: live.id, parent_container_type: 'LiveLink',
belong_container_id: live.course_id, belong_container_type: 'Course',
viewed: 0, tiding_type: 'LiveLink'
}
Tiding.bulk_insert(*attrs) do |worker|
course.students.pluck(:user_id).each do |user_id|
worker.add same_attrs.merge(user_id: user_id)
end
end
end
end

@ -37,4 +37,19 @@ module AliyunVod::Service::VideoManage
result
end
# 视频播放数据
def video_data(video_id, start_time, end_time)
params = {
Action: 'DescribePlayVideoStatis',
VideoId: video_id,
StartTime: start_time,
EndTime: end_time,
}.merge(base_params)
puts params
result = request(:post, params)
result
end
end

@ -4,4 +4,5 @@ module CustomRegexp
LASTNAME = /\A[a-zA-Z0-9\u4e00-\u9fa5]+\z/
NICKNAME = /\A[\u4e00-\u9fa5_a-zA-Z0-9]+\z/
PASSWORD = /\A[a-z_A-Z0-9\-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",'_<>~\·`\?:;|]{8,16}\z/
URL = /\Ahttps?:\/\/[-A-Za-z0-9+&@#\/%?=~_|!:,.;]+[-A-Za-z0-9+&@#\/%=~_|]\z/
end

@ -28,7 +28,7 @@ class Challenge < ApplicationRecord
scope :fields_for_list, -> { select([:id, :subject, :st, :score, :position, :shixun_id]) }
validates :task_pass, length: { maximum: 10000, too_long: "不能超过10000个字符" }
validates :task_pass, length: { maximum: 35000, too_long: "不能超过35000个字符" }
after_commit :create_diff_record

@ -3,7 +3,7 @@ class ChallengeAnswer < ApplicationRecord
belongs_to :challenge
has_many :game_answers, :dependent => :destroy
validates :contents, length: { maximum: 5000 , too_long: "不能超过5000个字符"}
validates :contents, length: { maximum: 25000 , too_long: "不能超过25000个字符"}
def view_answer_time(user_id)
game_answers.where(user_id: user_id).last&.view_time

@ -4,6 +4,6 @@ class ChallengeChoose < ApplicationRecord
has_many :challenge_tags, :dependent => :destroy
has_many :challenge_questions, dependent: :destroy
validates :subject, length: { maximum: 1000, too_long: "不能超过1000个字符" }
validates :subject, length: { maximum: 25000, too_long: "不能超过25000个字符" }
end

@ -70,7 +70,9 @@ class Course < ApplicationRecord
# 课堂动态
has_many :course_acts, class_name: 'CourseActivity', as: :course_act, dependent: :destroy
has_one :course_act, class_name: 'CourseActivity', as: :course_act, dependent: :destroy
has_many :course_activities
has_many :tidings, as: :container, dependent: :destroy
# 开放课堂
@ -81,6 +83,13 @@ class Course < ApplicationRecord
# 老版的members弃用 现用course_members
has_many :members
# 视频
has_many :course_videos, dependent: :destroy
has_many :videos, through: :course_videos
# 直播
has_many :live_links, dependent: :destroy
validate :validate_sensitive_string
scope :hidden, ->(is_hidden = true) { where(is_hidden: is_hidden) }
@ -206,7 +215,7 @@ class Course < ApplicationRecord
end
def all_course_module_types
%w[activity announcement online_learning shixun_homework common_homework group_homework exercise attachment course_group graduation poll board statistics]
%w[activity announcement online_learning shixun_homework common_homework group_homework exercise attachment course_group graduation poll board statistics video]
end
def get_course_module_by_type(type)
@ -293,7 +302,7 @@ class Course < ApplicationRecord
#课程动态公共表记录
def act_as_course_activity
self.course_acts << CourseActivity.new(user_id: tea_id, course_id: id)
self.course_act << CourseActivity.new(user_id: tea_id, course_id: id)
end
# 当前老师分班下的所有学生
@ -406,6 +415,7 @@ class Course < ApplicationRecord
when 'exercise' then '试卷'
when 'poll' then '问卷'
when 'attachment' then '资源'
when 'video' then '视频直播'
when 'board' then '讨论'
when 'course_group' then '分班'
when 'statistics' then '统计'
@ -425,9 +435,10 @@ class Course < ApplicationRecord
when 'exercise' then 8
when 'poll' then 9
when 'attachment' then 10
when 'board' then 11
when 'course_group' then 12
when 'statistics' then 13
when 'video' then 11
when 'board' then 12
when 'course_group' then 13
when 'statistics' then 14
else 100
end
end

@ -4,9 +4,26 @@ class CourseActivity < ApplicationRecord
belongs_to :user
belongs_to :exercise
belongs_to :poll
belongs_to :course_message
belongs_to :homework_common
# after_create :add_course_lead
def container_name
case course_act_type
when "HomeworkCommon"
course_act&.name
when "Exercise"
course_act&.exercise_name
when "Poll"
course_act&.poll_name
when "Message"
course_act&.subject
else
""
end
end
# 发布新课导语
# 导语要放置在课程创建信息之后
def add_course_lead

@ -2,6 +2,7 @@ class CourseMessage < ApplicationRecord
enum status: { UNHANDLED: 0, PASSED: 1, REJECTED: 2 }
belongs_to :course
belongs_to :user
has_one :course_act, class_name: 'CourseActivity', as: :course_act, dependent: :destroy
scope :find_by_course, ->(course) { where(course_id: course.id) }
scope :join_course_requests, -> { where(course_message_type: "JoinCourseRequest") }
@ -9,6 +10,8 @@ class CourseMessage < ApplicationRecord
scope :unhandled_join_course_requests_by_course, ->(course) { find_by_course(course).join_course_requests.unhandled }
after_create :act_as_course_activity
def pass!
update!(status: :PASSED)
send_deal_tiding(1)
@ -25,6 +28,11 @@ class CourseMessage < ApplicationRecord
private
#课程动态公共表记录
def act_as_course_activity
self.course_act << CourseActivity.new(user_id: course_message_id, course_id: course_id)
end
def send_deal_tiding deal_status
# 发送申请处理结果消息
Tiding.create!(

@ -0,0 +1,4 @@
class CourseVideo < ApplicationRecord
belongs_to :course
belongs_to :video
end

@ -1,7 +1,12 @@
class Discipline < ApplicationRecord
has_many :sub_disciplines, dependent: :destroy
default_scope { order(position: :asc) }
has_many :sub_disciplines, -> { order("sub_disciplines.position ASC") }, dependent: :destroy
has_many :shixun_sub_disciplines, -> { where("shixun = 1") }, class_name: "SubDiscipline"
has_many :subject_sub_disciplines, -> { where("subject = 1") }, class_name: "SubDiscipline"
has_many :question_sub_disciplines, -> { where("question = 1") }, class_name: "SubDiscipline"
validates_presence_of :name
end

@ -3,5 +3,5 @@ class ExaminationIntelligentSetting < ApplicationRecord
belongs_to :user
has_many :examination_type_settings, dependent: :destroy
has_many :tag_discipline_containers, as: :container, dependent: :destroy
has_many :item_baskets, dependent: :destroy
has_many :item_baskets, -> { order("item_baskets.position ASC") }, dependent: :destroy
end

@ -1,3 +1,4 @@
class HackCode < ApplicationRecord
# 编程题代码相关
belongs_to :hack
end

@ -28,14 +28,14 @@ class HomeworkCommon < ApplicationRecord
belongs_to :course_second_category, optional: true
# 课堂动态
has_many :course_acts, class_name: 'CourseActivity', as: :course_act, dependent: :destroy
has_one :course_act, class_name: 'CourseActivity', as: :course_act, dependent: :destroy
has_many :tidings, as: :container, dependent: :destroy
# 实训作业的分班查重记录
has_many :homework_group_reviews, :dependent => :destroy
# 学生的查重情况
has_many :homework_review_results, :dependent => :destroy
validates :name, length: { maximum: 60, too_long: "不能超过60个字符" }
validates :name, presence: true, length: { maximum: 60, too_long: "不能超过60个字符" }
validates :description, length: { maximum: 15000, too_long: "不能超过15000个字符" }
validates :explanation, length: { maximum: 5000, too_long: "不能超过5000个字符" }
validates :reference_answer, length: { maximum: 15000, too_long: "不能超过15000个字符" }

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

Loading…
Cancel
Save