diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..3fd9f6fd1 --- /dev/null +++ b/Procfile @@ -0,0 +1,2 @@ +web: cd client && npm start +api: bundle exec rails s -p 3001 diff --git a/app/assets/javascripts/admins/ajaxform.js b/app/assets/javascripts/admins/ajaxform.js new file mode 100644 index 000000000..20a88247a --- /dev/null +++ b/app/assets/javascripts/admins/ajaxform.js @@ -0,0 +1,1312 @@ +/*! + * jQuery Form Plugin + * version: 3.51.0-2014.06.20 + * Requires jQuery v1.5 or later + * Copyright (c) 2014 M. Alsup + * Examples and documentation at: http://malsup.com/jquery/form/ + * Project repository: https://github.com/malsup/form + * Dual licensed under the MIT and GPL licenses. + * https://github.com/malsup/form#copyright-and-license + */ +/*global ActiveXObject */ + +// AMD support +(function(factory) { + "use strict"; + if (typeof define === 'function' && define.amd) { + // using AMD; register as anon module + define(['jquery'], factory); + } else { + // no AMD; invoke directly + factory((typeof(jQuery) != 'undefined') ? jQuery : window.Zepto); + } + } + + (function($) { + "use strict"; + + /* + Usage Note: + ----------- + Do not use both ajaxSubmit and ajaxForm on the same form. These + functions are mutually exclusive. Use ajaxSubmit if you want + to bind your own submit handler to the form. For example, + + $(document).ready(function() { + $('#myForm').on('submit', function(e) { + e.preventDefault(); // <-- important + $(this).ajaxSubmit({ + target: '#output' + }); + }); + }); + + Use ajaxForm when you want the plugin to manage all the event binding + for you. For example, + + $(document).ready(function() { + $('#myForm').ajaxForm({ + target: '#output' + }); + }); + + You can also use ajaxForm with delegation (requires jQuery v1.7+), so the + form does not have to exist when you invoke ajaxForm: + + $('#myForm').ajaxForm({ + delegation: true, + target: '#output' + }); + + When using ajaxForm, the ajaxSubmit function will be invoked for you + at the appropriate time. + */ + + /** + * Feature detection + */ + var feature = {}; + feature.fileapi = $("").get(0).files !== undefined; + feature.formdata = window.FormData !== undefined; + + var hasProp = !!$.fn.prop; + + // attr2 uses prop when it can but checks the return type for + // an expected string. this accounts for the case where a form + // contains inputs with names like "action" or "method"; in those + // cases "prop" returns the element + $.fn.attr2 = function() { + if (!hasProp) { + return this.attr.apply(this, arguments); + } + var val = this.prop.apply(this, arguments); + if ((val && val.jquery) || typeof val === 'string') { + return val; + } + return this.attr.apply(this, arguments); + }; + + /** + * ajaxSubmit() provides a mechanism for immediately submitting + * an HTML form using AJAX. + */ + $.fn.ajaxSubmit = function(options) { + /*jshint scripturl:true */ + + // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) + if (!this.length) { + log('ajaxSubmit: skipping submit process - no element selected'); + return this; + } + + var method, action, url, $form = this; + + if (typeof options == 'function') { + options = { + success: options + }; + } else if (options === undefined) { + options = {}; + } + + method = options.type || this.attr2('method'); + action = options.url || this.attr2('action'); + + url = (typeof action === 'string') ? $.trim(action) : ''; + url = url || window.location.href || ''; + if (url) { + // clean url (don't include hash vaue) + url = (url.match(/^([^#]+)/) || [])[1]; + } + + options = $.extend(true, { + url: url, + success: $.ajaxSettings.success, + type: method || $.ajaxSettings.type, + iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' + }, options); + + // hook for manipulating the form data before it is extracted; + // convenient for use with rich editors like tinyMCE or FCKEditor + var veto = {}; + this.trigger('form-pre-serialize', [this, options, veto]); + if (veto.veto) { + log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); + return this; + } + + // provide opportunity to alter form data before it is serialized + if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { + log('ajaxSubmit: submit aborted via beforeSerialize callback'); + return this; + } + + var traditional = options.traditional; + if (traditional === undefined) { + traditional = $.ajaxSettings.traditional; + } + + var elements = []; + var qx, a = this.formToArray(options.semantic, elements); + if (options.data) { + options.extraData = options.data; + qx = $.param(options.data, traditional); + } + + // give pre-submit callback an opportunity to abort the submit + if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { + log('ajaxSubmit: submit aborted via beforeSubmit callback'); + return this; + } + + // fire vetoable 'validate' event + this.trigger('form-submit-validate', [a, this, options, veto]); + if (veto.veto) { + log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); + return this; + } + + var q = $.param(a, traditional); + if (qx) { + q = (q ? (q + '&' + qx) : qx); + } + if (options.type.toUpperCase() == 'GET') { + options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; + options.data = null; // data is null for 'get' + } else { + options.data = q; // data is the query string for 'post' + } + + var callbacks = []; + if (options.resetForm) { + callbacks.push(function() { + $form.resetForm(); + }); + } + if (options.clearForm) { + callbacks.push(function() { + $form.clearForm(options.includeHidden); + }); + } + + // perform a load on the target only if dataType is not provided + if (!options.dataType && options.target) { + var oldSuccess = options.success || function() {}; + callbacks.push(function(data) { + var fn = options.replaceTarget ? 'replaceWith' : 'html'; + $(options.target)[fn](data).each(oldSuccess, arguments); + }); + } else if (options.success) { + callbacks.push(options.success); + } + + options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg + var context = options.context || this; // jQuery 1.4+ supports scope context + for (var i = 0, max = callbacks.length; i < max; i++) { + callbacks[i].apply(context, [data, status, xhr || $form, $form]); + } + }; + + if (options.error) { + var oldError = options.error; + options.error = function(xhr, status, error) { + var context = options.context || this; + oldError.apply(context, [xhr, status, error, $form]); + }; + } + + if (options.complete) { + var oldComplete = options.complete; + options.complete = function(xhr, status) { + var context = options.context || this; + oldComplete.apply(context, [xhr, status, $form]); + }; + } + + // are there files to upload? + + // [value] (issue #113), also see comment: + // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 + var fileInputs = $('input[type=file]:enabled', this).filter(function() { + return $(this).val() !== ''; + }); + + var hasFileInputs = fileInputs.length > 0; + var mp = 'multipart/form-data'; + var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); + + var fileAPI = feature.fileapi && feature.formdata; + log("fileAPI :" + fileAPI); + var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; + + var jqxhr; + + // options.iframe allows user to force iframe mode + // 06-NOV-09: now defaulting to iframe mode if file input is detected + if (options.iframe !== false && (options.iframe || shouldUseFrame)) { + // hack to fix Safari hang (thanks to Tim Molendijk for this) + // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d + if (options.closeKeepAlive) { + $.get(options.closeKeepAlive, function() { + jqxhr = fileUploadIframe(a); + }); + } else { + jqxhr = fileUploadIframe(a); + } + } else if ((hasFileInputs || multipart) && fileAPI) { + jqxhr = fileUploadXhr(a); + } else { + jqxhr = $.ajax(options); + } + + $form.removeData('jqxhr').data('jqxhr', jqxhr); + + // clear element array + for (var k = 0; k < elements.length; k++) { + elements[k] = null; + } + + // fire 'notify' event + this.trigger('form-submit-notify', [this, options]); + return this; + + // utility fn for deep serialization + function deepSerialize(extraData) { + var serialized = $.param(extraData, options.traditional).split('&'); + var len = serialized.length; + var result = []; + var i, part; + for (i = 0; i < len; i++) { + // #252; undo param space replacement + serialized[i] = serialized[i].replace(/\+/g, ' '); + part = serialized[i].split('='); + // #278; use array instead of object storage, favoring array serializations + result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); + } + return result; + } + + // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) + function fileUploadXhr(a) { + var formdata = new FormData(); + + for (var i = 0; i < a.length; i++) { + formdata.append(a[i].name, a[i].value); + } + + if (options.extraData) { + var serializedData = deepSerialize(options.extraData); + for (i = 0; i < serializedData.length; i++) { + if (serializedData[i]) { + formdata.append(serializedData[i][0], serializedData[i][1]); + } + } + } + + options.data = null; + + var s = $.extend(true, {}, $.ajaxSettings, options, { + contentType: false, + processData: false, + cache: false, + type: method || 'POST' + }); + + if (options.uploadProgress) { + // workaround because jqXHR does not expose upload property + s.xhr = function() { + var xhr = $.ajaxSettings.xhr(); + if (xhr.upload) { + xhr.upload.addEventListener('progress', function(event) { + var percent = 0; + var position = event.loaded || event.position; /*event.position is deprecated*/ + var total = event.total; + if (event.lengthComputable) { + percent = Math.ceil(position / total * 100); + } + options.uploadProgress(event, position, total, percent); + }, false); + } + return xhr; + }; + } + + s.data = null; + var beforeSend = s.beforeSend; + s.beforeSend = function(xhr, o) { + //Send FormData() provided by user + if (options.formData) { + o.data = options.formData; + } else { + o.data = formdata; + } + if (beforeSend) { + beforeSend.call(this, xhr, o); + } + }; + return $.ajax(s); + } + + // private function for handling file uploads (hat tip to YAHOO!) + function fileUploadIframe(a) { + var form = $form[0], + el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; + var deferred = $.Deferred(); + + // #341 + deferred.abort = function(status) { + xhr.abort(status); + }; + + if (a) { + // ensure that every serialized input is still enabled + for (i = 0; i < elements.length; i++) { + el = $(elements[i]); + if (hasProp) { + el.prop('disabled', false); + } else { + el.removeAttr('disabled'); + } + } + } + + s = $.extend(true, {}, $.ajaxSettings, options); + s.context = s.context || s; + id = 'jqFormIO' + (new Date().getTime()); + if (s.iframeTarget) { + $io = $(s.iframeTarget); + n = $io.attr2('name'); + if (!n) { + $io.attr2('name', id); + } else { + id = n; + } + } else { + $io = $(''); + $io.css({ + position: 'absolute', + top: '-1000px', + left: '-1000px' + }); + } + io = $io[0]; + + + xhr = { // mock object + aborted: 0, + responseText: null, + responseXML: null, + status: 0, + statusText: 'n/a', + getAllResponseHeaders: function() {}, + getResponseHeader: function() {}, + setRequestHeader: function() {}, + abort: function(status) { + var e = (status === 'timeout' ? 'timeout' : 'aborted'); + log('aborting upload... ' + e); + this.aborted = 1; + + try { // #214, #257 + if (io.contentWindow.document.execCommand) { + io.contentWindow.document.execCommand('Stop'); + } + } catch (ignore) {} + + $io.attr('src', s.iframeSrc); // abort op in progress + xhr.error = e; + if (s.error) { + s.error.call(s.context, xhr, e, status); + } + if (g) { + $.event.trigger("ajaxError", [xhr, s, e]); + } + if (s.complete) { + s.complete.call(s.context, xhr, e); + } + } + }; + + g = s.global; + // trigger ajax global events so that activity/block indicators work like normal + if (g && 0 === $.active++) { + $.event.trigger("ajaxStart"); + } + if (g) { + $.event.trigger("ajaxSend", [xhr, s]); + } + + if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { + if (s.global) { + $.active--; + } + deferred.reject(); + return deferred; + } + if (xhr.aborted) { + deferred.reject(); + return deferred; + } + + // add submitting element to data if we know it + sub = form.clk; + if (sub) { + n = sub.name; + if (n && !sub.disabled) { + s.extraData = s.extraData || {}; + s.extraData[n] = sub.value; + if (sub.type == "image") { + s.extraData[n + '.x'] = form.clk_x; + s.extraData[n + '.y'] = form.clk_y; + } + } + } + + var CLIENT_TIMEOUT_ABORT = 1; + var SERVER_ABORT = 2; + + function getDoc(frame) { + /* it looks like contentWindow or contentDocument do not + * carry the protocol property in ie8, when running under ssl + * frame.document is the only valid response document, since + * the protocol is know but not on the other two objects. strange? + * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy + */ + + var doc = null; + + // IE8 cascading access check + try { + if (frame.contentWindow) { + doc = frame.contentWindow.document; + } + } catch (err) { + // IE8 access denied under ssl & missing protocol + log('cannot get iframe.contentWindow document: ' + err); + } + + if (doc) { // successful getting content + return doc; + } + + try { // simply checking may throw in ie8 under ssl or mismatched protocol + doc = frame.contentDocument ? frame.contentDocument : frame.document; + } catch (err) { + // last attempt + log('cannot get iframe.contentDocument: ' + err); + doc = frame.document; + } + return doc; + } + + // Rails CSRF hack (thanks to Yvan Barthelemy) + var csrf_token = $('meta[name=csrf-token]').attr('content'); + var csrf_param = $('meta[name=csrf-param]').attr('content'); + if (csrf_param && csrf_token) { + s.extraData = s.extraData || {}; + s.extraData[csrf_param] = csrf_token; + } + + // take a breath so that pending repaints get some cpu time before the upload starts + function doSubmit() { + // make sure form attrs are set + var t = $form.attr2('target'), + a = $form.attr2('action'), + mp = 'multipart/form-data', + et = $form.attr('enctype') || $form.attr('encoding') || mp; + + // update form attrs in IE friendly way + form.setAttribute('target', id); + if (!method || /post/i.test(method)) { + form.setAttribute('method', 'POST'); + } + if (a != s.url) { + form.setAttribute('action', s.url); + } + + // ie borks in some cases when setting encoding + if (!s.skipEncodingOverride && (!method || /post/i.test(method))) { + $form.attr({ + encoding: 'multipart/form-data', + enctype: 'multipart/form-data' + }); + } + + // support timout + if (s.timeout) { + timeoutHandle = setTimeout(function() { + timedOut = true; + cb(CLIENT_TIMEOUT_ABORT); + }, s.timeout); + } + + // look for server aborts + function checkState() { + try { + var state = getDoc(io).readyState; + log('state = ' + state); + if (state && state.toLowerCase() == 'uninitialized') { + setTimeout(checkState, 50); + } + } catch (e) { + log('Server abort: ', e, ' (', e.name, ')'); + cb(SERVER_ABORT); + if (timeoutHandle) { + clearTimeout(timeoutHandle); + } + timeoutHandle = undefined; + } + } + + // add "extra" data to form if provided in options + var extraInputs = []; + try { + if (s.extraData) { + for (var n in s.extraData) { + if (s.extraData.hasOwnProperty(n)) { + // if using the $.param format that allows for multiple values with the same name + if ($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) { + extraInputs.push( + $('').val(s.extraData[n].value) + .appendTo(form)[0]); + } else { + extraInputs.push( + $('').val(s.extraData[n]) + .appendTo(form)[0]); + } + } + } + } + + if (!s.iframeTarget) { + // add iframe to doc and submit the form + $io.appendTo('body'); + } + if (io.attachEvent) { + io.attachEvent('onload', cb); + } else { + io.addEventListener('load', cb, false); + } + setTimeout(checkState, 15); + + try { + form.submit(); + } catch (err) { + // just in case form has element with name/id of 'submit' + var submitFn = document.createElement('form').submit; + submitFn.apply(form); + } + } finally { + // reset attrs and remove "extra" input elements + form.setAttribute('action', a); + form.setAttribute('enctype', et); // #380 + if (t) { + form.setAttribute('target', t); + } else { + $form.removeAttr('target'); + } + $(extraInputs).remove(); + } + } + + if (s.forceSync) { + doSubmit(); + } else { + setTimeout(doSubmit, 10); // this lets dom updates render + } + + var data, doc, domCheckCount = 50, + callbackProcessed; + + function cb(e) { + if (xhr.aborted || callbackProcessed) { + return; + } + + doc = getDoc(io); + if (!doc) { + log('cannot access response document'); + e = SERVER_ABORT; + } + if (e === CLIENT_TIMEOUT_ABORT && xhr) { + xhr.abort('timeout'); + deferred.reject(xhr, 'timeout'); + return; + } else if (e == SERVER_ABORT && xhr) { + xhr.abort('server abort'); + deferred.reject(xhr, 'error', 'server abort'); + return; + } + + if (!doc || doc.location.href == s.iframeSrc) { + // response not received yet + if (!timedOut) { + return; + } + } + if (io.detachEvent) { + io.detachEvent('onload', cb); + } else { + io.removeEventListener('load', cb, false); + } + + var status = 'success', + errMsg; + try { + if (timedOut) { + throw 'timeout'; + } + + var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); + log('isXml=' + isXml); + if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { + if (--domCheckCount) { + // in some browsers (Opera) the iframe DOM is not always traversable when + // the onload callback fires, so we loop a bit to accommodate + log('requeing onLoad callback, DOM not available'); + setTimeout(cb, 250); + return; + } + // let this fall through because server response could be an empty document + //log('Could not access iframe DOM after mutiple tries.'); + //throw 'DOMException: not available'; + } + + //log('response detected'); + var docRoot = doc.body ? doc.body : doc.documentElement; + xhr.responseText = docRoot ? docRoot.innerHTML : null; + xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; + if (isXml) { + s.dataType = 'xml'; + } + xhr.getResponseHeader = function(header) { + var headers = { + 'content-type': s.dataType + }; + return headers[header.toLowerCase()]; + }; + // support for XHR 'status' & 'statusText' emulation : + if (docRoot) { + xhr.status = Number(docRoot.getAttribute('status')) || xhr.status; + xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; + } + + var dt = (s.dataType || '').toLowerCase(); + var scr = /(json|script|text)/.test(dt); + if (scr || s.textarea) { + // see if user embedded response in textarea + var ta = doc.getElementsByTagName('textarea')[0]; + if (ta) { + xhr.responseText = ta.value; + // support for XHR 'status' & 'statusText' emulation : + xhr.status = Number(ta.getAttribute('status')) || xhr.status; + xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; + } else if (scr) { + // account for browsers injecting pre around json response + var pre = doc.getElementsByTagName('pre')[0]; + var b = doc.getElementsByTagName('body')[0]; + if (pre) { + xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; + } else if (b) { + xhr.responseText = b.textContent ? b.textContent : b.innerText; + } + } + } else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) { + xhr.responseXML = toXml(xhr.responseText); + } + + try { + data = httpData(xhr, dt, s); + } catch (err) { + status = 'parsererror'; + xhr.error = errMsg = (err || status); + } + } catch (err) { + log('error caught: ', err); + status = 'error'; + xhr.error = errMsg = (err || status); + } + + if (xhr.aborted) { + log('upload aborted'); + status = null; + } + + if (xhr.status) { // we've set xhr.status + status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; + } + + // ordering of these callbacks/triggers is odd, but that's how $.ajax does it + if (status === 'success') { + if (s.success) { + s.success.call(s.context, data, 'success', xhr); + } + deferred.resolve(xhr.responseText, 'success', xhr); + if (g) { + $.event.trigger("ajaxSuccess", [xhr, s]); + } + } else if (status) { + if (errMsg === undefined) { + errMsg = xhr.statusText; + } + if (s.error) { + s.error.call(s.context, xhr, status, errMsg); + } + deferred.reject(xhr, 'error', errMsg); + if (g) { + $.event.trigger("ajaxError", [xhr, s, errMsg]); + } + } + + if (g) { + $.event.trigger("ajaxComplete", [xhr, s]); + } + + if (g && !--$.active) { + $.event.trigger("ajaxStop"); + } + + if (s.complete) { + s.complete.call(s.context, xhr, status); + } + + callbackProcessed = true; + if (s.timeout) { + clearTimeout(timeoutHandle); + } + + // clean up + setTimeout(function() { + if (!s.iframeTarget) { + $io.remove(); + } else { //adding else to clean up existing iframe response. + $io.attr('src', s.iframeSrc); + } + xhr.responseXML = null; + }, 100); + } + + var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) + if (window.ActiveXObject) { + doc = new ActiveXObject('Microsoft.XMLDOM'); + doc.async = 'false'; + doc.loadXML(s); + } else { + doc = (new DOMParser()).parseFromString(s, 'text/xml'); + } + return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; + }; + var parseJSON = $.parseJSON || function(s) { + /*jslint evil:true */ + return window['eval']('(' + s + ')'); + }; + + var httpData = function(xhr, type, s) { // mostly lifted from jq1.4.4 + + var ct = xhr.getResponseHeader('content-type') || '', + xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, + data = xml ? xhr.responseXML : xhr.responseText; + + if (xml && data.documentElement.nodeName === 'parsererror') { + if ($.error) { + $.error('parsererror'); + } + } + if (s && s.dataFilter) { + data = s.dataFilter(data, type); + } + if (typeof data === 'string') { + if (type === 'json' || !type && ct.indexOf('json') >= 0) { + data = parseJSON(data); + } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { + $.globalEval(data); + } + } + return data; + }; + + return deferred; + } + }; + + /** + * ajaxForm() provides a mechanism for fully automating form submission. + * + * The advantages of using this method instead of ajaxSubmit() are: + * + * 1: This method will include coordinates for elements (if the element + * is used to submit the form). + * 2. This method will include the submit element's name/value data (for the element that was + * used to submit the form). + * 3. This method binds the submit() method to the form for you. + * + * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely + * passes the options argument along after properly binding events for submit elements and + * the form itself. + */ + $.fn.ajaxForm = function(options) { + options = options || {}; + options.delegation = options.delegation && $.isFunction($.fn.on); + + // in jQuery 1.3+ we can fix mistakes with the ready state + if (!options.delegation && this.length === 0) { + var o = { + s: this.selector, + c: this.context + }; + if (!$.isReady && o.s) { + log('DOM not ready, queuing ajaxForm'); + $(function() { + $(o.s, o.c).ajaxForm(options); + }); + return this; + } + // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() + log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); + return this; + } + + if (options.delegation) { + $(document) + .off('submit.form-plugin', this.selector, doAjaxSubmit) + .off('click.form-plugin', this.selector, captureSubmittingElement) + .on('submit.form-plugin', this.selector, options, doAjaxSubmit) + .on('click.form-plugin', this.selector, options, captureSubmittingElement); + return this; + } + + return this.ajaxFormUnbind() + .bind('submit.form-plugin', options, doAjaxSubmit) + .bind('click.form-plugin', options, captureSubmittingElement); + }; + + // private event handlers + function doAjaxSubmit(e) { + /*jshint validthis:true */ + var options = e.data; + if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed + e.preventDefault(); + $(e.target).ajaxSubmit(options); // #365 + } + } + + function captureSubmittingElement(e) { + /*jshint validthis:true */ + var target = e.target; + var $el = $(target); + if (!($el.is("[type=submit],[type=image]"))) { + // is this a child element of the submit el? (ex: a span within a button) + var t = $el.closest('[type=submit]'); + if (t.length === 0) { + return; + } + target = t[0]; + } + var form = this; + form.clk = target; + if (target.type == 'image') { + if (e.offsetX !== undefined) { + form.clk_x = e.offsetX; + form.clk_y = e.offsetY; + } else if (typeof $.fn.offset == 'function') { + var offset = $el.offset(); + form.clk_x = e.pageX - offset.left; + form.clk_y = e.pageY - offset.top; + } else { + form.clk_x = e.pageX - target.offsetLeft; + form.clk_y = e.pageY - target.offsetTop; + } + } + // clear form vars + setTimeout(function() { + form.clk = form.clk_x = form.clk_y = null; + }, 100); + } + + + // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm + $.fn.ajaxFormUnbind = function() { + return this.unbind('submit.form-plugin click.form-plugin'); + }; + + /** + * formToArray() gathers form element data into an array of objects that can + * be passed to any of the following ajax functions: $.get, $.post, or load. + * Each object in the array has both a 'name' and 'value' property. An example of + * an array for a simple login form might be: + * + * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] + * + * It is this array that is passed to pre-submit callback functions provided to the + * ajaxSubmit() and ajaxForm() methods. + */ + $.fn.formToArray = function(semantic, elements) { + var a = []; + if (this.length === 0) { + return a; + } + + var form = this[0]; + var formId = this.attr('id'); + var els = semantic ? form.getElementsByTagName('*') : form.elements; + var els2; + + if (els && !/MSIE [678]/.test(navigator.userAgent)) { // #390 + els = $(els).get(); // convert to standard array + } + + // #386; account for inputs outside the form which use the 'form' attribute + if (formId) { + els2 = $(':input[form="' + formId + '"]').get(); // hat tip @thet + if (els2.length) { + els = (els || []).concat(els2); + } + } + + if (!els || !els.length) { + return a; + } + + var i, j, n, v, el, max, jmax; + for (i = 0, max = els.length; i < max; i++) { + el = els[i]; + n = el.name; + if (!n || el.disabled) { + continue; + } + + if (semantic && form.clk && el.type == "image") { + // handle image inputs on the fly when semantic == true + if (form.clk == el) { + a.push({ + name: n, + value: $(el).val(), + type: el.type + }); + a.push({ + name: n + '.x', + value: form.clk_x + }, { + name: n + '.y', + value: form.clk_y + }); + } + continue; + } + + v = $.fieldValue(el, true); + if (v && v.constructor == Array) { + if (elements) { + elements.push(el); + } + for (j = 0, jmax = v.length; j < jmax; j++) { + a.push({ + name: n, + value: v[j] + }); + } + } else if (feature.fileapi && el.type == 'file') { + if (elements) { + elements.push(el); + } + var files = el.files; + if (files.length) { + for (j = 0; j < files.length; j++) { + a.push({ + name: n, + value: files[j], + type: el.type + }); + } + } else { + // #180 + a.push({ + name: n, + value: '', + type: el.type + }); + } + } else if (v !== null && typeof v != 'undefined') { + if (elements) { + elements.push(el); + } + a.push({ + name: n, + value: v, + type: el.type, + required: el.required + }); + } + } + + if (!semantic && form.clk) { + // input type=='image' are not found in elements array! handle it here + var $input = $(form.clk), + input = $input[0]; + n = input.name; + if (n && !input.disabled && input.type == 'image') { + a.push({ + name: n, + value: $input.val() + }); + a.push({ + name: n + '.x', + value: form.clk_x + }, { + name: n + '.y', + value: form.clk_y + }); + } + } + return a; + }; + + /** + * Serializes form data into a 'submittable' string. This method will return a string + * in the format: name1=value1&name2=value2 + */ + $.fn.formSerialize = function(semantic) { + //hand off to jQuery.param for proper encoding + return $.param(this.formToArray(semantic)); + }; + + /** + * Serializes all field elements in the jQuery object into a query string. + * This method will return a string in the format: name1=value1&name2=value2 + */ + $.fn.fieldSerialize = function(successful) { + var a = []; + this.each(function() { + var n = this.name; + if (!n) { + return; + } + var v = $.fieldValue(this, successful); + if (v && v.constructor == Array) { + for (var i = 0, max = v.length; i < max; i++) { + a.push({ + name: n, + value: v[i] + }); + } + } else if (v !== null && typeof v != 'undefined') { + a.push({ + name: this.name, + value: v + }); + } + }); + //hand off to jQuery.param for proper encoding + return $.param(a); + }; + + /** + * Returns the value(s) of the element in the matched set. For example, consider the following form: + * + *
+ * + * var v = $('input[type=text]').fieldValue(); + * // if no values are entered into the text inputs + * v == ['',''] + * // if values entered into the text inputs are 'foo' and 'bar' + * v == ['foo','bar'] + * + * var v = $('input[type=checkbox]').fieldValue(); + * // if neither checkbox is checked + * v === undefined + * // if both checkboxes are checked + * v == ['B1', 'B2'] + * + * var v = $('input[type=radio]').fieldValue(); + * // if neither radio is checked + * v === undefined + * // if first radio is checked + * v == ['C1'] + * + * The successful argument controls whether or not the field element must be 'successful' + * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). + * The default value of the successful argument is true. If this value is false the value(s) + * for each element is returned. + * + * Note: This method *always* returns an array. If no valid value can be determined the + * array will be empty, otherwise it will contain one or more values. + */ + $.fn.fieldValue = function(successful) { + for (var val = [], i = 0, max = this.length; i < max; i++) { + var el = this[i]; + var v = $.fieldValue(el, successful); + if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { + continue; + } + if (v.constructor == Array) { + $.merge(val, v); + } else { + val.push(v); + } + } + return val; + }; + + /** + * Returns the value of the field element. + */ + $.fieldValue = function(el, successful) { + var n = el.name, + t = el.type, + tag = el.tagName.toLowerCase(); + if (successful === undefined) { + successful = true; + } + + if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || + (t == 'checkbox' || t == 'radio') && !el.checked || + (t == 'submit' || t == 'image') && el.form && el.form.clk != el || + tag == 'select' && el.selectedIndex == -1)) { + return null; + } + + if (tag == 'select') { + var index = el.selectedIndex; + if (index < 0) { + return null; + } + var a = [], + ops = el.options; + var one = (t == 'select-one'); + var max = (one ? index + 1 : ops.length); + for (var i = (one ? index : 0); i < max; i++) { + var op = ops[i]; + if (op.selected) { + var v = op.value; + if (!v) { // extra pain for IE... + v = (op.attributes && op.attributes.value && !(op.attributes.value.specified)) ? op.text : op.value; + } + if (one) { + return v; + } + a.push(v); + } + } + return a; + } + return $(el).val(); + }; + + /** + * Clears the form data. Takes the following actions on the form's input fields: + * - input text fields will have their 'value' property set to the empty string + * - select elements will have their 'selectedIndex' property set to -1 + * - checkbox and radio inputs will have their 'checked' property set to false + * - inputs of type submit, button, reset, and hidden will *not* be effected + * - button elements will *not* be effected + */ + $.fn.clearForm = function(includeHidden) { + return this.each(function() { + $('input,select,textarea', this).clearFields(includeHidden); + }); + }; + + /** + * Clears the selected form elements. + */ + $.fn.clearFields = $.fn.clearInputs = function(includeHidden) { + var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list + return this.each(function() { + var t = this.type, + tag = this.tagName.toLowerCase(); + if (re.test(t) || tag == 'textarea') { + this.value = ''; + } else if (t == 'checkbox' || t == 'radio') { + this.checked = false; + } else if (tag == 'select') { + this.selectedIndex = -1; + } else if (t == "file") { + if (/MSIE/.test(navigator.userAgent)) { + $(this).replaceWith($(this).clone(true)); + } else { + $(this).val(''); + } + } else if (includeHidden) { + // includeHidden can be the value true, or it can be a selector string + // indicating a special test; for example: + // $('#myForm').clearForm('.special:hidden') + // the above would clean hidden inputs that have the class of 'special' + if ((includeHidden === true && /hidden/.test(t)) || + (typeof includeHidden == 'string' && $(this).is(includeHidden))) { + this.value = ''; + } + } + }); + }; + + /** + * Resets the form data. Causes all form elements to be reset to their original value. + */ + $.fn.resetForm = function() { + return this.each(function() { + // guard against an input with the name of 'reset' + // note that IE reports the reset function as an 'object' + if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { + this.reset(); + } + }); + }; + + /** + * Enables or disables any matching elements. + */ + $.fn.enable = function(b) { + if (b === undefined) { + b = true; + } + return this.each(function() { + this.disabled = !b; + }); + }; + + /** + * Checks/unchecks any matching checkboxes or radio buttons and + * selects/deselects and matching option elements. + */ + $.fn.selected = function(select) { + if (select === undefined) { + select = true; + } + return this.each(function() { + var t = this.type; + if (t == 'checkbox' || t == 'radio') { + this.checked = select; + } else if (this.tagName.toLowerCase() == 'option') { + var $sel = $(this).parent('select'); + if (select && $sel[0] && $sel[0].type == 'select-one') { + // deselect all other options + $sel.find('option').selected(false); + } + this.selected = select; + } + }); + }; + + // expose debug var + $.fn.ajaxSubmit.debug = false; + + // helper fn for console logging + function log() { + if (!$.fn.ajaxSubmit.debug) { + return; + } + var msg = '[jquery.form] ' + Array.prototype.join.call(arguments, ''); + if (window.console && window.console.log) { + window.console.log(msg); + } else if (window.opera && window.opera.postError) { + window.opera.postError(msg); + } + } + + })); \ No newline at end of file diff --git a/app/assets/javascripts/admins/user_schools_statistics/index.js b/app/assets/javascripts/admins/user_schools_statistics/index.js new file mode 100644 index 000000000..1d084ff25 --- /dev/null +++ b/app/assets/javascripts/admins/user_schools_statistics/index.js @@ -0,0 +1,81 @@ +$(document).on('turbolinks:load', function() { + if ($('body.admins-user-schools-statistics-index-page').length > 0) { + var $form = $('.user-schools-statistic-list-form'); + + // ************** 学校选择 ************* + var matcherFunc = function(params, data){ + if ($.trim(params.term) === '') { + return data; + } + if (typeof data.text === 'undefined') { + return null; + } + + if (data.name && data.name.indexOf(params.term) > -1) { + var modifiedData = $.extend({}, data, true); + return modifiedData; + } + + // Return `null` if the term should not be displayed + return null; + } + + + var defineSchoolSelect = function (schools) { + $form.find('.school-select').select2({ + theme: 'bootstrap4', + placeholder: '选择学校/单位', + minimumInputLength: 1, + data: schools, + templateResult: function (item) { + if(!item.id || item.id === '') return item.text; + return item.name; + }, + templateSelection: function(item){ + if (item.id) { + $form.find('#school_id').val(item.id); + } + return item.name || item.text; + }, + matcher: matcherFunc + }); + }; + + + // 初始化学校选择器 + $.ajax({ + url: '/api/schools/for_option.json', + dataType: 'json', + type: 'GET', + success: function(data) { + defineSchoolSelect(data.schools); + } + }); + + // 清空 + $form.on('click', '.clear-btn', function(){ + $form.find('select[name="date"]').val(''); + $form.find('select[name="province"]').val(''); + $form.find('.school-select').val('').trigger('change'); + $form.find('input[type="submit"]').trigger('click'); + }) + + + // 导出 + $('.export-action').on('click', function(){ + var form = $(".user-schools-statistic-list-form") + var exportLink = $(this); + var date = form.find("select[name='date']").val(); + var schoolId = form.find('input[name="school_id"]').val(); + var province = form.find('input[name="province"]').val(); + console.log(province) + if(province == "" || province == null){ + alert("只能按省份导出"); + return; + } + + var url = exportLink.data("url").split('?')[0] + "?date=" + date + "&school_id=" + schoolId + "&province=" + province; + window.open(url); + }); + } +}); \ No newline at end of file diff --git a/app/assets/javascripts/admins/webapp_banners/index.js b/app/assets/javascripts/admins/webapp_banners/index.js new file mode 100644 index 000000000..c1ecf6693 --- /dev/null +++ b/app/assets/javascripts/admins/webapp_banners/index.js @@ -0,0 +1,25 @@ +$(document).on('turbolinks:load', function() { + if ($('.weapp-banner-setting-container').length > 0) { + var $form = $('#course_form'); + + $('.course.banner-item-bottom').on("change", 'input[type="file"]', function() { + var $fileInput = $(this); + var file = this.files[0]; + var imageType = /image.*/; + if (file && file.type.match(imageType)) { + $form.ajaxSubmit() + } + }); + + var $shixunform = $('#shixun_form'); + + $('.shixun.banner-item-bottom').on("change", 'input[type="file"]', function() { + var $fileInput = $(this); + var file = this.files[0]; + var imageType = /image.*/; + if (file && file.type.match(imageType)) { + $shixunform.ajaxSubmit() + } + }); + } +}) \ No newline at end of file diff --git a/app/assets/stylesheets/admins/laboratories.scss b/app/assets/stylesheets/admins/laboratories.scss index 9dc219f6a..28e616c94 100644 --- a/app/assets/stylesheets/admins/laboratories.scss +++ b/app/assets/stylesheets/admins/laboratories.scss @@ -1,171 +1,154 @@ .admins-laboratories-index-page { - .laboratory-list-table { - .member-container { - .laboratory-user { - display: flex; - justify-content: center; - flex-wrap: wrap; - - .laboratory-user-item { - display: flex; - align-items: center; - height: 22px; - line-height: 22px; - padding: 2px 5px; - margin: 2px 2px; - border: 1px solid #91D5FF; - background-color: #E6F7FF; - color: #91D5FF; - border-radius: 4px; + .laboratory-list-table { + .member-container { + .laboratory-user { + display: flex; + justify-content: center; + flex-wrap: wrap; + .laboratory-user-item { + display: flex; + align-items: center; + height: 22px; + line-height: 22px; + padding: 2px 5px; + margin: 2px 2px; + border: 1px solid #91D5FF; + background-color: #E6F7FF; + color: #91D5FF; + border-radius: 4px; + } + } } - } } - } } -.admins-laboratory-settings-show-page, .admins-laboratory-settings-update-page { - .edit-laboratory-setting-container { - .logo-item { - display: flex; - - &-img { - display: block; - width: 80px; - height: 80px; - background: #f0f0f0; - } - - &-upload { - cursor: pointer; - position: absolute; - top: 0; - width: 80px; - height: 80px; - background: #F5F5F5; - border: 1px solid #E5E5E5; - - &::before { - content: ''; - position: absolute; - top: 27px; - left: 39px; - width: 2px; - height: 26px; - background: #E5E5E5; - } - - &::after { - content: ''; - position: absolute; - top: 39px; - left: 27px; - width: 26px; - height: 2px; - background: #E5E5E5; - } - } - - &-left { - position: relative; - width: 80px; - height: 80px; - &.has-img { - .logo-item-upload { - display: none; - } - - &:hover { - .logo-item-upload { - display: block; - background: rgba(145, 145, 145, 0.8); +.admins-laboratory-settings-show-page, +.admins-laboratory-settings-update-page, +.weapp-banner-setting-container { + .edit-laboratory-setting-container { + .logo-item { + display: flex; + &-img { + display: block; + width: 80px; + height: 80px; + background: #f0f0f0; + } + &-upload { + cursor: pointer; + position: absolute; + top: 0; + width: 80px; + height: 80px; + background: #F5F5F5; + border: 1px solid #E5E5E5; + &::before { + content: ''; + position: absolute; + top: 27px; + left: 39px; + width: 2px; + height: 26px; + background: #E5E5E5; + } + &::after { + content: ''; + position: absolute; + top: 39px; + left: 27px; + width: 26px; + height: 2px; + background: #E5E5E5; + } + } + &-left { + position: relative; + width: 80px; + height: 80px; + &.has-img { + .logo-item-upload { + display: none; + } + &:hover { + .logo-item-upload { + display: block; + background: rgba(145, 145, 145, 0.8); + } + } + } + } + &-right { + display: flex; + flex-direction: column; + justify-content: space-between; + color: #777777; + font-size: 12px; + } + &-title { + color: #23272B; + font-size: 14px; } - } - } - } - - &-right { - display: flex; - flex-direction: column; - justify-content: space-between; - color: #777777; - font-size: 12px; - } - - &-title { - color: #23272B; - font-size: 14px; - } - } - - .banner-item { - margin-bottom: 15px; - display: flex; - flex-direction: column; - - &-img { - display: block; - width: 300px; - height: 80px; - background: #f0f0f0; - } - - &-upload { - cursor: pointer; - position: absolute; - top: 0; - width: 300px; - height: 80px; - background: #F5F5F5; - border: 1px solid #E5E5E5; - - &::before { - content: ''; - position: absolute; - top: 27px; - left: 149px; - width: 2px; - height: 26px; - background: #E5E5E5; - } - - &::after { - content: ''; - position: absolute; - top: 39px; - left: 137px; - width: 26px; - height: 2px; - background: #E5E5E5; } - } - - &-top { - margin-bottom: 10px; - } - - &-bottom { - position: relative; - width: 300px; - height: 80px; - - &.has-img { - .banner-item-upload { - display: none; - } - - &:hover { - .banner-item-upload { - display: block; - background: rgba(145, 145, 145, 0.8); + .banner-item { + margin-bottom: 15px; + display: flex; + flex-direction: column; + &-img { + display: block; + width: 300px; + height: 80px; + background: #f0f0f0; + } + &-upload { + cursor: pointer; + position: absolute; + top: 0; + width: 300px; + height: 80px; + background: #F5F5F5; + border: 1px solid #E5E5E5; + &::before { + content: ''; + position: absolute; + top: 27px; + left: 149px; + width: 2px; + height: 26px; + background: #E5E5E5; + } + &::after { + content: ''; + position: absolute; + top: 39px; + left: 137px; + width: 26px; + height: 2px; + background: #E5E5E5; + } + } + &-top { + margin-bottom: 10px; + } + &-bottom { + position: relative; + width: 300px; + height: 80px; + &.has-img { + .banner-item-upload { + display: none; + } + &:hover { + .banner-item-upload { + display: block; + background: rgba(145, 145, 145, 0.8); + } + } + } + } + &-title { + color: #23272B; + font-size: 14px; } - } } - } - - &-title { - color: #23272B; - font-size: 14px; - } } - } } \ No newline at end of file diff --git a/app/controllers/admins/dashboards_controller.rb b/app/controllers/admins/dashboards_controller.rb index 3971971ff..5a85d5a0e 100644 --- a/app/controllers/admins/dashboards_controller.rb +++ b/app/controllers/admins/dashboards_controller.rb @@ -5,6 +5,16 @@ class Admins::DashboardsController < Admins::BaseController @month_active_user_count = User.where(last_login_on: current_month).count @new_user_count = User.where(created_on: current_month).count + + unless Rails.env.development? + shixun_tomcat = edu_setting('cloud_bridge') + + uri = "#{shixun_tomcat}/bridge/monitor/getPodsInfo" + res = interface_get uri, 502, "数据接口延迟" + if res['code'] == 0 + @pod_num = res['sum'] || 0 + end + end end def month_active_user diff --git a/app/controllers/admins/laboratory_settings_controller.rb b/app/controllers/admins/laboratory_settings_controller.rb index 283afc175..b22122831 100644 --- a/app/controllers/admins/laboratory_settings_controller.rb +++ b/app/controllers/admins/laboratory_settings_controller.rb @@ -16,7 +16,7 @@ class Admins::LaboratorySettingsController < Admins::BaseController def form_params params.permit(:identifier, :name, - :nav_logo, :login_logo, :tab_logo, :oj_banner, + :nav_logo, :login_logo, :tab_logo, :oj_banner, :shixun_banner, :subject_banner, :course_banner, :competition_banner, :moop_cases_banner, :footer, navbar: %i[name link hidden]) end diff --git a/app/controllers/admins/user_schools_statistics_controller.rb b/app/controllers/admins/user_schools_statistics_controller.rb new file mode 100644 index 000000000..a4680d5a2 --- /dev/null +++ b/app/controllers/admins/user_schools_statistics_controller.rb @@ -0,0 +1,18 @@ +class Admins::UserSchoolsStatisticsController < Admins::BaseController + + def export + params[:per_page] = 500 + _count, @schools = Admins::UserSchoolsStatisticQuery.call(params) + + filename = ['用户运营统计', Time.zone.now.strftime('%Y%m%d%H%M%S')].join('-') << '.xlsx' + render xlsx: 'export', filename: filename + end + + def index + default_sort('cnt', 'desc') + total_count, schools = Admins::UserSchoolsStatisticQuery.call(params) + + @schools = paginate schools, total_count: total_count + + end +end \ No newline at end of file diff --git a/app/controllers/admins/weapp_banners_controller.rb b/app/controllers/admins/weapp_banners_controller.rb new file mode 100644 index 000000000..d8e5aedf9 --- /dev/null +++ b/app/controllers/admins/weapp_banners_controller.rb @@ -0,0 +1,52 @@ +class Admins::WeappBannersController < Admins::BaseController + + def index + @shixun = WeappSettings::ShixunBanner.first + @course = WeappSettings::CourseBanner.first + end + + def create + ActiveRecord::Base.transaction do + old_carouse = WeappSettings::CourseBanner.first + + if old_carouse.present? + old_carouse.destroy! + file_path = Util::FileManage.source_disk_filename(old_carouse) + File.delete(file_path) if File.exist?(file_path) # 删除之前的文件 + end + + @course = WeappSettings::CourseBanner.create! + save_image_file(params[:course_banner], @course) + end + end + + + def shixun_banner + ActiveRecord::Base.transaction do + old_shixun = WeappSettings::ShixunBanner.first + + if old_shixun.present? + old_shixun.destroy! + file_path = Util::FileManage.source_disk_filename(old_shixun) + File.delete(file_path) if File.exist?(file_path) # 删除之前的文件 + end + + @shixun = WeappSettings::ShixunBanner.create! + save_image_file(params[:shixun_banner], @shixun) + end + end + + + + + private + + def save_image_file(file, model) + return unless file.present? && file.is_a?(ActionDispatch::Http::UploadedFile) + + file_path = Util::FileManage.source_disk_filename(model) + File.delete(file_path) if File.exist?(file_path) # 删除之前的文件 + Util.write_file(file, file_path) + end + +end \ No newline at end of file diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 15f918c01..59ec88fc7 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -72,6 +72,15 @@ class ApplicationController < ActionController::Base if !current_user.shixun_permission(@shixun) tip_exception(403, "..") end + # if !current_user.shixun_permission(@shixun) + # if @shixun.user_scope == 1 + # school_id = @shixun.shixun_schools.first&.school_id + # name = School.find_by(id: school_id)&.name + # tip_exception(-5, "当前实训只对#{name}等单位开放") + # else + # tip_exception(403, "..") + # end + # end end def admin_or_business? @@ -448,6 +457,25 @@ class ApplicationController < ActionController::Base end end + # 无参类型处理 + def interface_get(uri, status, message) + begin + uid_logger_dubug("--uri_exec: url is #{uri}") + uri = URI.parse(URI.encode(uri.strip)) + res = Net::HTTP.get(uri) + uid_logger_dubug("--uri_exec: .....res is #{res}") + res = JSON.parse(res) + if (res && res['code'] != 0) + tip_exception(status, message) + else + res + end + rescue Exception => e + uid_logger("--uri_exec: exception #{e.message}") + raise Educoder::TipException.new(message) + end + end + # json格式请求 def interface_json_post(uri, params, status, message) begin diff --git a/app/controllers/challenges_controller.rb b/app/controllers/challenges_controller.rb index c7fcb4423..103c33aab 100644 --- a/app/controllers/challenges_controller.rb +++ b/app/controllers/challenges_controller.rb @@ -230,7 +230,7 @@ class ChallengesController < ApplicationController 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) + @shixun.shixun_info.update_column(:evaluate_script, script) if script.present? end # TODO: # if path != params[:challenge][:path] diff --git a/app/controllers/concerns/controller_rescue_handler.rb b/app/controllers/concerns/controller_rescue_handler.rb index 6ff15cfbc..4ab5d3276 100644 --- a/app/controllers/concerns/controller_rescue_handler.rb +++ b/app/controllers/concerns/controller_rescue_handler.rb @@ -6,10 +6,12 @@ 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: "接口方法异常"} @@ -18,6 +20,7 @@ module ControllerRescueHandler 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 @@ -32,6 +35,7 @@ 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) diff --git a/app/controllers/concerns/git_helper.rb b/app/controllers/concerns/git_helper.rb index d8479d458..db99f9da5 100644 --- a/app/controllers/concerns/git_helper.rb +++ b/app/controllers/concerns/git_helper.rb @@ -13,7 +13,7 @@ module GitHelper content = GitService.file_content(repo_path: repo_path, path: path) - Rails.logger.info("git file content: content is #{content}") + #Rails.logger.info("git file content: content is #{content}") decode_content = nil if content.present? content = content["content"] #6.24 -hs 这个为新增,因为当实训题里含有选择题时,这里会报错,undefined method `[]' for nil:NilClass @@ -25,6 +25,8 @@ module GitHelper decode_content = if cd["encoding"] == 'GB18030' && cd['confidence'] > 0.8 content.encode('UTF-8', 'GBK', {:invalid => :replace, :undef => :replace, :replace => ' '}) + elsif cd['encoding'].blank? + raise("ERROR_UTF8") else content.force_encoding('UTF-8') end @@ -34,7 +36,9 @@ module GitHelper rescue Exception => e Rails.logger.error(e.message) - raise Educoder::TipException.new("文档内容获取异常") + error_msg = e.message == "ERROR_UTF8" ? "文件无法预览" : "文档内容获取异常" + error_status = e.message == "ERROR_UTF8" ? -2 : -1 + raise Educoder::TipException.new(error_status, error_msg) end end @@ -53,13 +57,17 @@ module GitHelper end # 添加目录 - def git_add_folder(folder_path, author_name, author_email, message) - GitService.add_tree(file_path: folder_path, message: message, author_name: author_name, author_email: author_email) + def git_add_folder(repo_path, tree_path, author_name, author_email, message) + Rails.logger.info("#####repo_path:#{repo_path}, tree_path: #{tree_path}") + GitService.add_tree(repo_path: repo_path, tree_path: tree_path, message: message, author_name: author_name, + author_email: author_email) end # 删除文件 - def git_delete_file(file_path, author_name, author_email, message) - GitService.delete_file(file_path: file_path, message: message, author_name: author_name, author_email: author_email) + def git_delete_file(repo_path, tree_path, author_name, author_email, message) + Rails.logger.info("#####repo_path:#{repo_path}, tree_path: #{tree_path}") + GitService.delete_file(repo_path: repo_path, tree_path: tree_path, message: message, author_name: author_name, + author_email: author_email) end # 版本库Fork功能 diff --git a/app/controllers/concerns/login_helper.rb b/app/controllers/concerns/login_helper.rb index b85b17a22..e3ef0480c 100644 --- a/app/controllers/concerns/login_helper.rb +++ b/app/controllers/concerns/login_helper.rb @@ -35,6 +35,7 @@ module LoginHelper UserAction.create(action_id: user&.id, action_type: 'Login', user_id: user&.id, ip: request.remote_ip) user.update_column(:last_login_on, Time.now) + # 注册完成后有一天的试用申请(先去掉) # UserDayCertification.create(user_id: user.id, status: 1) end @@ -44,6 +45,8 @@ module LoginHelper if autologin = cookies.delete(autologin_cookie_name) User.current.delete_autologin_token(autologin) end + + UserOnline.logout(User.current.id) User.current.delete_session_token(session[:tk]) self.logged_user = nil end @@ -52,6 +55,7 @@ module LoginHelper default_yun_session = "#{laboratory.try(:identifier).split('.').first}_user_id" # end session[:"#{default_yun_session}"] = nil + session[:request_user_id] = nil end # Sets the logged in user @@ -78,6 +82,8 @@ module LoginHelper # # end # session[:user_id] = user.id + UserOnline.login(user.id) + session[:request_user_id] = user.id session[:"#{default_yun_session}"] = user.id session[:ctime] = Time.now.utc.to_i session[:atime] = Time.now.utc.to_i diff --git a/app/controllers/courses_controller.rb b/app/controllers/courses_controller.rb index fd2d25dd5..f82775235 100644 --- a/app/controllers/courses_controller.rb +++ b/app/controllers/courses_controller.rb @@ -106,7 +106,7 @@ class CoursesController < ApplicationController videos = @course.videos videos = custom_sort(videos, params[:sort_by], params[:sort_direction]) @count = videos.count - @videos = paginate videos + @videos = paginate videos.includes(user: :user_extension) end def delete_course_video @@ -747,6 +747,12 @@ class CoursesController < ApplicationController ActiveRecord::Base.transaction do course_student.destroy! course_teacher.update!(is_active: 1) + teacher_course_record = @course.teacher_group_records.find_by(user_id: current_user.id) + if teacher_course_record.present? + teacher_course_record.update!(group_id: course_student.course_group_id) + else + TeacherGroupRecord.create!(user_id: current_user.id, course_id: @course.id, group_id: course_student.course_group_id) + end CourseDeleteStudentDeleteWorksJob.perform_later(@course.id, [current_user.id]) end normal_status(0, "切换成功") @@ -766,6 +772,12 @@ class CoursesController < ApplicationController ActiveRecord::Base.transaction do course_student.destroy! course_teacher.update!(is_active: 1) + teacher_course_record = @course.teacher_group_records.find_by(user_id: current_user.id) + if teacher_course_record.present? + teacher_course_record.update!(group_id: course_student.course_group_id) + else + TeacherGroupRecord.create!(user_id: current_user.id, course_id: @course.id, group_id: course_student.course_group_id) + end CourseDeleteStudentDeleteWorksJob.perform_later(@course.id, [current_user.id]) end normal_status(0, "切换成功") @@ -788,7 +800,9 @@ class CoursesController < ApplicationController course_student.update_attributes!(is_active: 1) else # 学生身份不存在则创建 - CourseMember.create!(user_id: current_user.id, role: 4, course_id: @course.id) + course_group_id = @course.teacher_group_records.find_by(user_id: current_user.id)&.group_id.to_i + course_group_id = @course.course_groups.find_by(id: course_group_id)&.id.to_i + CourseMember.create!(user_id: current_user.id, role: 4, course_id: @course.id, course_group_id: course_group_id) CourseAddStudentCreateWorksJob.perform_later(@course.id, [current_user.id]) end normal_status(0, "切换成功") diff --git a/app/controllers/discusses_controller.rb b/app/controllers/discusses_controller.rb index 3b1dff96b..c1850559d 100644 --- a/app/controllers/discusses_controller.rb +++ b/app/controllers/discusses_controller.rb @@ -46,7 +46,7 @@ class DiscussesController < ApplicationController end sql = "select d.id from discusses d join shixuns s on d.dis_id = s.id where s.status = 2 and s.hidden = false and d.root_id is null - and d.hidden = false #{sql1} #{sql2} order by d.created_at desc" + and d.hidden = false and d.dis_type = 'Shixun' #{sql1} #{sql2} order by d.created_at desc" memo_ids = Discuss.find_by_sql(sql).pluck(:id) @memo_count = memo_ids.size @@ -81,8 +81,7 @@ class DiscussesController < ApplicationController begin @discuss = Discuss.create!(:dis_id => params[:container_id], :dis_type => params[:container_type], :content => params[:content].gsub(" \;", "").strip, :user_id => current_user.id, - :praise_count => 0, :position => params[:position], :challenge_id => params[:challenge_id], - :hidden => !current_user.admin?) # 管理员回复的能够显示 + :praise_count => 0, :position => params[:position], :challenge_id => params[:challenge_id]) rescue Exception => e uid_logger_error("create discuss failed : #{e.message}") raise Educoder::TipException.new("评论异常,原因:#{e.message}") diff --git a/app/controllers/ecloud_controller.rb b/app/controllers/ecloud_controller.rb index 8e29e5409..c3421215d 100644 --- a/app/controllers/ecloud_controller.rb +++ b/app/controllers/ecloud_controller.rb @@ -16,8 +16,8 @@ require 'digest' class EcloudController < ApplicationController - before_filter :save_para - before_filter :check_sign_key, only: [:ps_new, :ps_update, :bs_new, :bs_update] + before_action :save_para + before_action :check_sign_key, only: [:ps_new, :ps_update, :bs_new, :bs_update] def index @@ -239,57 +239,60 @@ class EcloudController < ApplicationController end def ecloud_login_callback + if params[:test] + user_info = decode '{"userid":2147,"custid":2104,"custcode":"E0002018042810010054","custtype":2,"status":2,"username":"15111030087@QW_er","useralias":"15111030087","isadmin":true,"entprise":"04**004","departments":"","departmentnames":"","mobile":"15365386520","email":"15111030087@139.com"}' + else + res = request_ecloud_authorization - unless params["test"] == 'true' - #获取code - logger.info "oauth2 login_callback: #{params}" - - raise "没有code" unless params[:code] - - url = "#{SERVER_URL}/oauth2/authorization?grant_type=authorization_code" + - "&client_id=#{CLIENT_ID}&scope=&redirect_uri=&code=#{params[:code]}" - - res = post(url) logger.info "oauth2 authorization resp: #{res}" - # {"access_token":"ae673b2d-88b4-46cc-aa74-0b031f24b76f","expires":6,"refresh_token":"7380cc67-a59c-4c21-9000-70e12a58d175","username":"15111030087@QW_er","uid":2147} + raise '登录失败' unless res["access_token"] - body = decode(res) - - raise '登录失败' unless body["access_token"] + user_info = decode get_ecloud_user(res) + logger.info "oauth2 get user info: #{user_info}" + end - #获取此用户信息 - res = get("#{SERVER_URL}/user/info?access_token=#{body['access_token']}&userid=#{body['uid']}") - logger.info "oauth2 get user info: #{res}" - # {"userid":2147,"custid":2104,"custcode":"E0002018042810010054","custtype":2,"status":2,"username":"15111030087@QW_er","useralias":"15111030087","isadmin":true,"entprise":"04**004","departments":"","departmentnames":"","mobile":"15365386520","email":"15111030087@139.com"} - else - res = '{"userid":2147,"custid":2104,"custcode":"E0002018042810010054","custtype":2,"status":2,"username":"15111030087@QW_er","useralias":"15111030087","isadmin":true,"entprise":"04**004","departments":"","departmentnames":"","mobile":"15365386520","email":"15111030087@139.com"}' + open_user = OpenUsers::Ecloud.find_or_initialize_by(uid: user_info['userid']) do |u| + u.extra = user_info end + redirect_to "/users/#{open_user.user.login}/courses" and return if open_user.persisted? + + ActiveRecord::Base.transaction do + user = User.find_or_initialize_by(phone: user_info["mobile"]) do |u| + u.login = "ecoder_#{user_info['mobile']}" + u.type ='User' + u.status = User::STATUS_ACTIVE + u.nickname = user_info['username'] + u.lastname = user_info['username'] + end + + if !user.persisted? + user.mail = user_info["email"] unless user_info["email"].blank? || User.find_by_mail(user_info["email"]) + user.save! + user.create_user_extension! + end - # 同步用户 - info = decode(res) + open_user.user = user + open_user.save! + successful_authentication(user) - user = User.find_by_ecoder_user_id(info["userid"]) - unless user - #新建用户 - user = User.create_with_ecoder!(info) + redirect_to "/users/#{user.login}/courses" end + rescue Exception => e + render :json => {code: 500, msg: "#{e.message}"} + end - self.logged_user = user - - user = UserExtension.where(:user_id => User.current.id).first - # if user.gender.nil? || user.school_id.nil? || User.current.lastname.nil? - # redirect_to my_account_path - # elsif user.identity == 3 && user.school_id.nil? - # redirect_to my_account_path - # else - # redirect_to User.current - # end - redirect_to User.current + private + + def request_ecloud_authorization + url = "#{SERVER_URL}/oauth2/authorization?grant_type=authorization_code&client_id=#{CLIENT_ID}&scope=&redirect_uri=&code=#{params[:code]}" + decode post(url) end + def get_ecloud_user(body) + res = get("#{SERVER_URL}/user/info?access_token=#{body['access_token']}&userid=#{body['uid']}") + end - private def get(url) uri = URI(url) diff --git a/app/controllers/games_controller.rb b/app/controllers/games_controller.rb index 1649e3eb9..7015cca40 100644 --- a/app/controllers/games_controller.rb +++ b/app/controllers/games_controller.rb @@ -749,6 +749,8 @@ class GamesController < ApplicationController # 针对web类型的实训 web_route = game_challenge.try(:web_route) + server_url = @game.get_server_url if web_route.present? + mirror_name = @shixun.mirror_name e_record = EvaluateRecord.where(:identifier => sec_key).first @@ -776,7 +778,7 @@ class GamesController < ApplicationController @base_date = {grade: grade, gold: score, experience: experience, status: game_status, had_done: had_done, position: game_challenge.position, port: port, record_consume_time: record_consume_time, mirror_name: mirror_name, picture: picture, web_route: web_route, star: @game.star, - next_game: next_game, prev_game: prev_game, max_mem: max_mem} + next_game: next_game, prev_game: prev_game, max_mem: max_mem, server_url: server_url} end # 记录实训花费的时间 @@ -971,6 +973,7 @@ class GamesController < ApplicationController if res && res['code'].to_i != 0 raise("实训云平台繁忙(繁忙等级:99)") end + # @vnc_url = res['showServer'] @vnc_url = if request.subdomain == "pre-newweb" || request.subdomain == "test-newweb" # 无域名版本 diff --git a/app/controllers/homework_commons_controller.rb b/app/controllers/homework_commons_controller.rb index 83bcaf37a..d4e7ae4a3 100644 --- a/app/controllers/homework_commons_controller.rb +++ b/app/controllers/homework_commons_controller.rb @@ -1210,7 +1210,7 @@ class HomeworkCommonsController < ApplicationController rescue Exception => e uid_logger(e.message) - tip_exception("删除失败") + tip_exception(e.message) raise ActiveRecord::Rollback end end @@ -1433,7 +1433,7 @@ class HomeworkCommonsController < ApplicationController def require_id_params tip_exception("请至少选择一个作业") if params[:homework_ids].blank? - tip_exception("批量设置不能超过15个") if params[:homework_ids].length > 15 + tip_exception("批量设置不能超过15个") if params[:homework_ids].length > 15 && params[:type].blank? end def validate_min_max_num diff --git a/app/controllers/main_controller.rb b/app/controllers/main_controller.rb index 69323bf49..3d2383573 100644 --- a/app/controllers/main_controller.rb +++ b/app/controllers/main_controller.rb @@ -4,6 +4,7 @@ class MainController < ApplicationController skip_before_action :setup_laboratory def first_stamp + UserOnline.login(session[:request_user_id]) if session[:request_user_id] render :json => { status: 0, message: Time.now.to_i } end diff --git a/app/controllers/myshixuns_controller.rb b/app/controllers/myshixuns_controller.rb index 893bf28d7..29a9a9730 100644 --- a/app/controllers/myshixuns_controller.rb +++ b/app/controllers/myshixuns_controller.rb @@ -99,6 +99,7 @@ class MyshixunsController < ApplicationController status = jsonTestDetails['status'] game_id = jsonTestDetails['buildID'] 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")}") resubmit = jsonTestDetails['resubmit'] @@ -117,6 +118,10 @@ class MyshixunsController < ApplicationController pics = params[:tpiRepoPath] game.update_column(:picture_path, pics) end + # 如果启动了服务,则存在redis中,供前端访问 + if server_url.present? + game.set_server_key(server_url) + end max_query_index = game.outputs ? (game.outputs.first.try(:query_index).to_i + 1) : 1 test_set_score = 0 unless jenkins_testsets.blank? diff --git a/app/controllers/shixuns_controller.rb b/app/controllers/shixuns_controller.rb index a5cc27967..8f74f0474 100644 --- a/app/controllers/shixuns_controller.rb +++ b/app/controllers/shixuns_controller.rb @@ -3,6 +3,7 @@ class ShixunsController < ApplicationController include ApplicationHelper include ElasticsearchAble include CoursesHelper + include GitCommon before_action :require_login, :check_auth, except: [:download_file, :index, :menus, :show, :show_right, :ranking_list, :discusses, :collaborators, :fork_list, :propaedeutics] @@ -16,7 +17,7 @@ class ShixunsController < ApplicationController :propaedeutics, :departments, :apply_shixun_mirror, :jupyter_exec, :get_mirror_script, :download_file, :shixun_list, :batch_send_to_course] before_action :find_repo_name, only: [:repository, :commits, :file_content, :update_file, :shixun_exec, :copy, - :add_file, :jupyter_exec] + :add_file, :jupyter_exec, :upload_git_file, :delete_git_file, :upload_git_folder] before_action :allowed, only: [:update, :close, :update_propaedeutics, :settings, :publish, :apply_public, :upload_git_folder, :shixun_members_added, :change_manager, :collaborators_delete, :upload_git_file, @@ -417,8 +418,8 @@ class ShixunsController < ApplicationController logger.info("#########service_update_params: #{service_update_params}") begin ActiveRecord::Base.transaction do - @shixun.update_attributes(shixun_params) - @shixun.shixun_info.update_attributes(shixun_info_params) + @shixun.update_attributes!(shixun_params) + @shixun.shixun_info.update_attributes!(shixun_info_params) # 镜像变动 @shixun.shixun_mirror_repositories.where.not(mirror_repository_id: old_mirror_ids).destroy_all @shixun.shixun_mirror_repositories.create!(new_mirror_id) if new_mirror_id.present? @@ -878,7 +879,7 @@ class ShixunsController < ApplicationController end end - include GitCommon + def update_file content = params[:content] @@ -897,7 +898,8 @@ class ShixunsController < ApplicationController author_email = current_user.git_mail message = params[:message] || "upload file by browser" uid_logger("-----author_email: #{author_email}") - update_file_base64_content(content, @repo_path, @path, author_email, author_name, message) + path = @path.present? ? "#{@path}/#{upload_file.original_filename}" : "#{upload_file.original_filename}" + update_file_base64_content(content, @repo_path, path, author_email, author_name, message) render_ok end @@ -906,7 +908,7 @@ class ShixunsController < ApplicationController author_name = current_user.real_name author_email = current_user.git_mail message = params[:message] || "upload folder by browser" - git_add_folder(@path, author_name, author_email, message) + git_add_folder(@repo_path, @path, author_name, author_email, message) render_ok end @@ -914,7 +916,7 @@ class ShixunsController < ApplicationController author_name = current_user.real_name author_email = current_user.git_mail message = params[:message] || "delete file by browser" - git_delete_file(@path, author_name, author_email, message) + git_delete_file(@repo_path, @path, author_name, author_email, message) render_ok end @@ -1096,9 +1098,8 @@ private @repo_path = if params[:secret_repository] @shixun.shixun_secret_repository&.repo_path else - @shixun.try(:repo_path) + @shixun.repo_path end - logger.info("######{@repo_path}") @path = params[:path] end diff --git a/app/controllers/student_works_controller.rb b/app/controllers/student_works_controller.rb index 59da73703..8c2c4fda1 100644 --- a/app/controllers/student_works_controller.rb +++ b/app/controllers/student_works_controller.rb @@ -360,6 +360,7 @@ class StudentWorksController < ApplicationController # 给作品评分 def add_score tip_exception("该学生的分数已经过调整,不能再评阅") if @work.ultimate_score + tip_exception("学生匿评时分数为必填") if params[:score].blank? && @user_course_identity == Course::STUDENT tip_exception("分数和评语不能都为空") if params[:score].blank? && params[:comment].blank? tip_exception("分数不能超过0-100") if params[:score] && (params[:score].to_f < 0 || params[:score].to_f > 100) diff --git a/app/controllers/weapps/attendances_controller.rb b/app/controllers/weapps/attendances_controller.rb new file mode 100644 index 000000000..d584072c2 --- /dev/null +++ b/app/controllers/weapps/attendances_controller.rb @@ -0,0 +1,144 @@ +class Weapps::AttendancesController < ApplicationController + before_action :require_login + before_action :find_course, only: [:create, :index, :student_attendances, :history_attendances] + before_action :find_attendance, except: [:create, :index, :student_attendances, :history_attendances] + before_action :user_course_identity + before_action :teacher_allowed, only: [:create] + before_action :edit_auth, only: [:update, :destroy, :end] + + def create + ActiveRecord::Base.transaction do + attendance = @course.course_attendances.create!(create_params.merge(user_id: current_user.id)) + unless params[:group_ids].blank? || @course.course_groups.where(id: params[:group_ids]).count == @course.course_groups.count + group_ids = @course.charge_group_ids(current_user) & params[:group_ids].map(&:to_i) + group_ids.each do |group_id| + @course.course_attendance_groups.create!(course_group_id: group_id, course_attendance: attendance) + end + CreateStudentAttendanceRecordJob.perform_now(attendance.id, group_ids) + else + @course.course_attendance_groups.create!(course_group_id: 0, course_attendance: attendance) + CreateStudentAttendanceRecordJob.perform_now(attendance.id, [0]) + end + render_ok({attendance_id: attendance.id}) + end + end + + def index + tip_exception(403) if @user_course_identity >= Course::STUDENT + current_date = Date.current + current_end_time = Time.current.strftime("%H:%M:%S") + @current_attendance = @course.course_attendances.where("attendance_date = '#{current_date}' and end_time > '#{current_end_time}'") + .order("attendance_date asc, start_time asc") + + all_attendances = @course.course_attendances.where("attendance_date < '#{current_date}' or (attendance_date = '#{current_date}' and end_time < '#{current_end_time}')") + @all_member_attendances = CourseMemberAttendance.where(course_attendance_id: all_attendances) + if params[:group_id].present? + all_attendances = all_attendances.joins(:course_attendance_groups).where(course_attendance_groups: {course_group_id: [params[:group_id], 0]}) + @all_member_attendances = @all_member_attendances.joins(:course_member).where(course_members: {course_group_id: params[:group_id]}) + end + + @history_attendances = all_attendances.order("id asc") + @all_history_count = @history_attendances.size + end + + def student_attendances + # tip_exception("学生身份的签到列表") if @user_course_identity != Course::STUDENT + member = @course.students.find_by(user_id: current_user.id) + if member.present? + current_date = Date.current + current_end_time = Time.current.strftime("%H:%M:%S") + + # 先算出该学生所在分班的签到id + # 分班id为0 表示签到不限制分班 + group_ids = [member&.course_group_id.to_i, 0] + all_attendance_ids = @course.course_attendance_groups.where(course_group_id: group_ids).pluck(:course_attendance_id) + + # 学生的历史签到只统计加入课堂后创建的签到 + history_attendance_ids = member.course_member_attendances.where(course_id: @course.id).pluck(:course_attendance_id) + + @history_attendances = @course.course_attendances.where(id: history_attendance_ids.uniq). + where("attendance_date < '#{current_date}' or (attendance_date = '#{current_date}' and end_time < '#{current_end_time}')").order("id desc") + @current_attendance = @course.course_attendances.where(id: all_attendance_ids.uniq). + where("attendance_date = '#{current_date}' and start_time <= '#{current_end_time}' and end_time > '#{current_end_time}'") + @history_count = @history_attendances.size + + student_attendance_ids = @history_attendances.pluck(:id) + student_attendance_ids += @current_attendance.present? ? @current_attendance.pluck(:id) : [] + + if student_attendance_ids.uniq.blank? + @normal_count = 0 + @leave_count = 0 + @absence_count = 0 + else + @normal_count = @course.course_member_attendances.where(course_member_id: member&.id, course_attendance_id: student_attendance_ids, attendance_status: "NORMAL").size + @leave_count = @course.course_member_attendances.where(course_member_id: member&.id, course_attendance_id: student_attendance_ids, attendance_status: "LEAVE").size + # 旷课只统计历史签到的 + @absence_count = @course.course_member_attendances.where(course_member_id: member&.id, course_attendance_id: @history_attendances.pluck(:id), attendance_status: "ABSENCE").size + end + + @all_history_count = @history_attendances.size + @history_attendances = paginate @history_attendances.includes(:course_member_attendances) + end + end + + def show + @normal_count = @attendance.normal_count + @leave_count = @attendance.leave_count + @absence_count = @attendance.absence_count + @all_count = @attendance.course_member_attendances.size + + @_is_current_attendance = @attendance.current_attendance? + + if @attendance.course_attendance_groups.first&.course_group_id.to_i == 0 + @group_ids = @course.course_groups.pluck(:id) + [0] + else + @group_ids = @attendance.course_attendance_groups.pluck(:course_group_id) + end + + @groups = @course.course_groups.where(id: @group_ids) + @course_members = @course.students if @_is_current_attendance + + @all_attendances = @attendance.course_member_attendances + end + + def update + @attendance.update!(name: params[:name]) + render_ok + end + + def destroy + @attendance.destroy! + render_ok + end + + def history_attendances + current_date = Date.current + current_end_time = Time.current.strftime("%H:%M:%S") + + @history_attendances = @course.course_attendances.where("attendance_date < '#{current_date}' or + (attendance_date = '#{current_date}' and end_time < '#{current_end_time}')").order("id desc") + @all_history_count = @history_attendances.size + @history_attendances = paginate @history_attendances.includes(:course_member_attendances) + end + + def end + a_end_time = "#{@attendance.attendance_date} #{@attendance.end_time}".to_time + tip_exception("该签到已截止") unless @attendance.current_attendance? + @attendance.update!(end_time: Time.current) + render_ok + end + + private + def create_params + params.permit(:name, :mode, :attendance_date, :start_time, :end_time) + end + + def find_attendance + @attendance = CourseAttendance.find params[:id] + @course = @attendance.course + end + + def edit_auth + tip_exception(403, "") unless @user_course_identity < Course::PROFESSOR || @attendance.user_id == current_user.id + end +end \ No newline at end of file diff --git a/app/controllers/weapps/banners_controller.rb b/app/controllers/weapps/banners_controller.rb new file mode 100644 index 000000000..84a31caa2 --- /dev/null +++ b/app/controllers/weapps/banners_controller.rb @@ -0,0 +1,12 @@ +class Weapps::BannersController < Weapps::BaseController + + def index + shixun = WeappSettings::ShixunBanner.first + course = WeappSettings::CourseBanner.first + + render json: { + shixun_img: shixun ? Util::FileManage.source_disk_file_url(shixun) : '', + course_img: course ? Util::FileManage.source_disk_file_url(course) : '' + } + end +end \ No newline at end of file diff --git a/app/controllers/weapps/course_member_attendances_controller.rb b/app/controllers/weapps/course_member_attendances_controller.rb new file mode 100644 index 000000000..7e315fc85 --- /dev/null +++ b/app/controllers/weapps/course_member_attendances_controller.rb @@ -0,0 +1,76 @@ +class Weapps::CourseMemberAttendancesController < ApplicationController + before_action :require_login + before_action :find_course, :user_course_identity, only: [:update_status] + + def index + attendance = CourseAttendance.find params[:attendance_id] + if attendance.course_attendance_groups.first&.course_group_id.to_i == 0 + @members = attendance.course.students + else + @members = attendance.course.students.where(course_group_id: attendance.course_attendance_groups.pluck(:course_group_id)) + end + @member_attendances = attendance.course_member_attendances + if params[:group_ids].present? + @members = @members.where(course_group_id: params[:group_ids]) + end + + if params[:attendance_status].present? + @members = @members.joins(:course_member_attendances).where(course_member_attendances: {course_attendance_id: attendance.id, attendance_status: params[:attendance_status]}) + end + + @members = @members.joins(:course_member_attendances).order("attendance_status=1 desc, course_member_attendances.updated_at desc") + @members_count = @members.uniq.count + @members = paginate @members.preload(user: :user_extension).uniq + + # @member_attendances = @member_attendances.where(attendance_status: params[:attendance_status]) if params[:attendance_status].present? + # @member_attendances = @member_attendances.joins(user: :user_extension).order("attendance_status=1 desc, course_member_attendances.updated_at desc, user_extensions.student_id asc") + # @member_attendances = paginate @member_attendances.preload(user: :user_extension) + end + + def create + tip_exception("签到码不能为空") if params[:code].blank? + tip_exception("attendance_mode参数不对") unless ["NUMBER", "QRCODE"].include?(params[:attendance_mode]) + + attendance = CourseAttendance.find_by(attendance_code: params[:code]) + tip_exception("签到码输入有误") if attendance.blank? || attendance.course.blank? + + member = attendance.course.students.find_by(user_id: current_user.id) + tip_exception("签到码输入有误") if member.blank? + + tip_exception("不在签到时间内") unless attendance.current_attendance? + + tip_exception("只支持数字签到") if attendance.mode != "ALL" && attendance.mode == "NUMBER" && params[:attendance_mode] == "QRCODE" + tip_exception("只支持二维码签到") if attendance.mode != "ALL" && attendance.mode == "QRCODE" && params[:attendance_mode] == "NUMBER" + + current_attendance = attendance.course_member_attendances.find_by(user_id: current_user.id) + if current_attendance.present? + tip_exception("请勿重复签到") if current_attendance.attendance_status == "NORMAL" + tip_exception("您当前是请假状态,无法签到") if current_attendance.attendance_status == "LEAVE" + tip_exception("您当前是旷课状态,无法签到") if current_attendance.attendance_status == "ABSENCE" && current_attendance.attendance_mode == "TEACHER" + current_attendance.update!(attendance_status: "NORMAL", attendance_mode: params[:attendance_mode]) + else + attendance.course_member_attendances.create!(course_member_id: member.id, user_id: current_user.id, course_id: attendance.course_id, + course_group_id: member.course_group_id, attendance_status: "NORMAL", attendance_mode: params[:attendance_mode]) + end + + render_ok + end + + def update_status + tip_exception("user_id不能为空") if params[:user_id].blank? + tip_exception(403, "无权限调整签到状态") if @user_course_identity > Course::ASSISTANT_PROFESSOR + tip_exception("attendance_status参数不对") unless ["NORMAL", "LEAVE", "ABSENCE"].include?(params[:attendance_status]) + attendance = @course.course_attendances.find_by!(id: params[:attendance_id]) + current_attendance = attendance.course_member_attendances.find_by(user_id: params[:user_id]) + if current_attendance.present? + current_attendance.update!(attendance_status: params[:attendance_status], attendance_mode: "TEACHER") + else + member = attendance.course.students.find_by(user_id: params[:user_id]) + tip_exception( "该用户非课堂学生") if member.blank? + attendance.course_member_attendances.create!(course_member_id: member.id, user_id: params[:user_id], course_id: attendance.course_id, + course_group_id: member.course_group_id, attendance_status: params[:attendance_status], attendance_mode: "TEACHER") + end + render_ok + end + +end \ No newline at end of file diff --git a/app/controllers/weapps/courses_controller.rb b/app/controllers/weapps/courses_controller.rb index a0ee59971..e1ceb6fd3 100644 --- a/app/controllers/weapps/courses_controller.rb +++ b/app/controllers/weapps/courses_controller.rb @@ -8,18 +8,32 @@ class Weapps::CoursesController < Weapps::BaseController 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) + + # 签到数据 + attendances = @course.course_attendances + current_date = Date.current + current_end_time = Time.current.strftime("%H:%M:%S") + if @user_course_identity == Course::STUDENT + attendances = attendances.joins(:course_attendance_groups).where(course_attendance_groups: {course_group_id: [member.try(:course_group_id).to_i, 0]}) + .where("attendance_date < '#{current_date}' or (attendance_date = '#{current_date}' and start_time < '#{current_end_time}')") + end + attendance_ids = attendances.blank? ? "(-1)" : "(" + attendances.pluck(:id).join(",") + ")" + + homework_commons = @course.homework_commons.where(homework_type: ["practice", "normal"]).homework_published 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) + 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") + (course_act_type = 'HomeworkCommon' and course_act_id in #{homework_ids}) or + (course_act_type = 'CourseAttendance' and course_act_id in #{attendance_ids})").order("id desc") @activities_count = activities.size @activities = paginate activities.includes(:course_act, user: :user_extension) end diff --git a/app/helpers/weapps/attendances_helper.rb b/app/helpers/weapps/attendances_helper.rb new file mode 100644 index 000000000..e0223ad74 --- /dev/null +++ b/app/helpers/weapps/attendances_helper.rb @@ -0,0 +1,20 @@ +module Weapps::AttendancesHelper + + def student_attendance_status attendance, user + st_attendance = attendance.course_member_attendances.find_by(user_id: user.id) + st_attendance.present? ? st_attendance.attendance_status : "ABSENCE" + end + + def group_attendance_count attendances, member_ids + # course_member_ids = group.course_members.pluck(:id) + attendances.select{|attendance| member_ids.include?(attendance.course_member_id) && attendance.attendance_status == "NORMAL"}.size + end + + def history_member_count member_attendances, status, attendance_id + member_attendances.select{|member_attendance| member_attendance.attendance_status == status && member_attendance.course_attendance_id == attendance_id}.size + end + + def cal_rate base, sum + sum == 0 ? 0 : (base.to_f / sum) + end +end \ No newline at end of file diff --git a/app/jobs/create_student_attendance_record_job.rb b/app/jobs/create_student_attendance_record_job.rb new file mode 100644 index 000000000..83a353565 --- /dev/null +++ b/app/jobs/create_student_attendance_record_job.rb @@ -0,0 +1,26 @@ +class CreateStudentAttendanceRecordJob < ApplicationJob + queue_as :default + + def perform(attendance_id, group_ids) + attendance = CourseAttendance.find_by(id: attendance_id) + course = attendance.course + return if attendance.blank? || course.blank? + + if group_ids.include?(0) + students = course.students + else + students = course.students.where(course_group_id: group_ids) + end + + attrs = %i[course_attendance_id user_id course_member_id course_id course_group_id created_at updated_at] + + same_attrs = {course_attendance_id: attendance.id, course_id: course.id} + + CourseMemberAttendance.bulk_insert(*attrs) do |worker| + + students.each do |student| + worker.add same_attrs.merge(user_id: student.user_id, course_member_id: student.id, course_group_id: student.course_group_id) + end + end + end +end diff --git a/app/jobs/create_student_work_job.rb b/app/jobs/create_student_work_job.rb index 1fd9a9b00..18e472b3a 100644 --- a/app/jobs/create_student_work_job.rb +++ b/app/jobs/create_student_work_job.rb @@ -14,7 +14,9 @@ class CreateStudentWorkJob < ApplicationJob student_ids = course.students.pluck(:user_id) student_ids.each do |user_id| - worker.add same_attrs.merge(user_id: user_id) + unless StudentWork.where(user_id: user_id, homework_common_id: homework.id).exists? + worker.add same_attrs.merge(user_id: user_id) + end end end end diff --git a/app/jobs/homework_end_update_score_job.rb b/app/jobs/homework_end_update_score_job.rb index 4ba4502fc..dec13cc36 100644 --- a/app/jobs/homework_end_update_score_job.rb +++ b/app/jobs/homework_end_update_score_job.rb @@ -22,7 +22,7 @@ class HomeworkEndUpdateScoreJob < ApplicationJob challenge_settings = homework.homework_challenge_settings myshixuns.find_each(batch_size: 100) do |myshixun| work = student_works.select{|work| work.user_id == myshixun.user_id}.first - if work && myshixun && (work.update_time.nil? || work.update_time < myshixun.updated_at) + if work.present? && myshixun games = myshixun.games.where(challenge_id: challenge_settings.pluck(:challenge_id)) HomeworksService.new.update_myshixun_work_score work, myshixun, games, homework, challenge_settings end diff --git a/app/jobs/student_join_attendance_record_job.rb b/app/jobs/student_join_attendance_record_job.rb new file mode 100644 index 000000000..32807bbec --- /dev/null +++ b/app/jobs/student_join_attendance_record_job.rb @@ -0,0 +1,32 @@ +class StudentJoinAttendanceRecordJob < ApplicationJob + queue_as :default + + def perform(member_id) + member = CourseMember.find_by(id: member_id) + course = member&.course + return if member.blank? || course.blank? + + current_date = Date.current + current_end_time = Time.current.strftime("%H:%M:%S") + group_ids = member.course_group_id == 0 ? [0] : [member.course_group_id, 0] + + current_attendance_ids = course.course_attendances.joins(:course_attendance_groups).where(course_attendance_groups: {course_group_id: group_ids}). + where("(attendance_date = '#{current_date}' and start_time <= '#{current_end_time}' and end_time > '#{current_end_time}') or (attendance_date > '#{current_date}')").pluck(:id) + + all_group_attendance_ids = course.course_attendances.joins(:course_attendance_groups).where(course_attendance_groups: {course_group_id: 0}).pluck(:id) + member.course_member_attendances.where.not(course_attendance_id: all_group_attendance_ids+current_attendance_ids).delete_all + + attrs = %i[course_attendance_id user_id course_member_id course_id course_group_id created_at updated_at] + + same_attrs = {course_member_id: member_id, course_id: course.id, user_id: member.user_id, course_group_id: member.course_group_id} + + CourseMemberAttendance.bulk_insert(*attrs) do |worker| + + current_attendance_ids.each do |attendance_id| + unless course.course_member_attendances.where(course_member_id: member_id, course_attendance_id: attendance_id).exists? + worker.add same_attrs.merge(course_attendance_id: attendance_id) + end + end + end + end +end diff --git a/app/libs/user_online.rb b/app/libs/user_online.rb new file mode 100644 index 000000000..8db5754f3 --- /dev/null +++ b/app/libs/user_online.rb @@ -0,0 +1,41 @@ +module UserOnline + class << self + def login(user_id) + set_bit(user_id, 1) + end + + def logout(user_id) + set_bit(user_id, 0) + end + + def set_bit(user_id, flag) + if !Rails.cache.data.exists(cache_key) + Rails.cache.data.setbit(cache_key, user_id, flag) + Rails.cache.data.expire(cache_key, 20 * 60 + 10) + else + Rails.cache.data.setbit(cache_key, user_id, flag) + end + end + + def count + if Rails.cache.is_a?(ActiveSupport::Cache::RedisStore) + Rails.cache.data.bitcount(cache_key) + else + 0 + end + end + + def cache_key + if Rails.cache.is_a?(ActiveSupport::Cache::RedisStore) + # 10分钟为一段记录用户在线, 统计范围为20分钟内的线用户 + # TODO 更精确时长 + begin_hour = Time.now.beginning_of_hour + minutes_piece = (Time.now - begin_hour) / 600 + time = begin_hour.since((minutes_piece.to_i - 1) * 600).strftime("%H-%M") + "online_user_#{time}" + else + raise '请配置config.cache_store = redis_store' + end + end + end +end diff --git a/app/models/course.rb b/app/models/course.rb index 14c17cf39..2c76f9579 100644 --- a/app/models/course.rb +++ b/app/models/course.rb @@ -90,6 +90,13 @@ class Course < ApplicationRecord # 直播 has_many :live_links, dependent: :destroy + # 签到 + has_many :course_attendances, dependent: :destroy + has_many :course_attendance_groups + has_many :course_member_attendances + + has_many :teacher_group_records, dependent: :destroy + validate :validate_sensitive_string scope :hidden, ->(is_hidden = true) { where(is_hidden: is_hidden) } diff --git a/app/models/course_activity.rb b/app/models/course_activity.rb index d9930596c..e31da31a8 100644 --- a/app/models/course_activity.rb +++ b/app/models/course_activity.rb @@ -2,10 +2,11 @@ class CourseActivity < ApplicationRecord belongs_to :course_act, polymorphic: true belongs_to :course belongs_to :user - belongs_to :exercise - belongs_to :poll - belongs_to :course_message - belongs_to :homework_common + belongs_to :exercise, optional: true + belongs_to :poll, optional: true + belongs_to :course_message, optional: true + belongs_to :homework_common, optional: true + belongs_to :course_attendance, optional: true # after_create :add_course_lead diff --git a/app/models/course_attendance.rb b/app/models/course_attendance.rb new file mode 100644 index 000000000..1bd96fc29 --- /dev/null +++ b/app/models/course_attendance.rb @@ -0,0 +1,69 @@ +class CourseAttendance < ApplicationRecord + # status: 0: 未开启,1:已开启,2:已截止 + # mode: 0 两种签到,1 二维码签到,2 数字签到 + enum mode: { ALL: 0, QRCODE: 1, NUMBER: 2 } + + belongs_to :course + belongs_to :user + + has_many :course_attendance_groups, dependent: :destroy + has_many :course_member_attendances, dependent: :destroy + + has_one :course_act, class_name: 'CourseActivity', as: :course_act, dependent: :destroy + + validates :name, presence: true, length: { maximum: 60, too_long: "不能超过60个字符" } + validates :mode, presence: true + validates :attendance_date, presence: true + validates :start_time, presence: true + validates :end_time, presence: true + + after_create :generate_attendance_code, :act_as_course_activity + + # 正常签到人数 + def normal_count + course_member_attendances.select{|member_attendance| member_attendance.attendance_status == "NORMAL"}.size + end + + # 请假人数 + def leave_count + course_member_attendances.select{|member_attendance| member_attendance.attendance_status == "LEAVE"}.size + end + + # 旷课人数 + def absence_count + course_member_attendances.select{|member_attendance| member_attendance.attendance_status == "ABSENCE"}.size + end + + # 总人数 + def all_count + course_member_attendances.size + end + + def current_attendance? + a_start_time = "#{attendance_date} #{start_time}".to_time + a_end_time = "#{attendance_date} #{end_time}".to_time + a_start_time < Time.current && Time.current < a_end_time + end + + #课程动态公共表记录 + def act_as_course_activity + CourseActivity.create(user_id: user_id, course_id: course_id, course_act: self) + end + + # 延迟生成邀请码 + def attendance_code + return generate_attendance_code + end + + # 生成邀请码 + CODES = %W(2 3 4 5 6 7 8 9 A B C D E F G H J K L N M O P Q R S T U V W X Y Z) + def generate_attendance_code + code = read_attribute(:attendance_code) + if !code || code.size < 4 + code = CODES.sample(4).join + return generate_attendance_code if CourseAttendance.where(attendance_code: code).present? + update_attribute(:attendance_code, code) + end + code + end +end diff --git a/app/models/course_attendance_group.rb b/app/models/course_attendance_group.rb new file mode 100644 index 000000000..02c2f6fb9 --- /dev/null +++ b/app/models/course_attendance_group.rb @@ -0,0 +1,5 @@ +class CourseAttendanceGroup < ApplicationRecord + belongs_to :course + belongs_to :course_attendance + belongs_to :course_group, optional: true +end diff --git a/app/models/course_group.rb b/app/models/course_group.rb index 5bd27804f..79bc6fcab 100644 --- a/app/models/course_group.rb +++ b/app/models/course_group.rb @@ -9,6 +9,8 @@ class CourseGroup < ApplicationRecord has_many :homework_group_settings, :dependent => :destroy scope :by_group_ids, lambda { |ids| where(id: ids)} + has_many :course_attendance_groups, dependent: :destroy + validates :name, length: { maximum: 60, too_long: "不能超过60个字符" } validates_uniqueness_of :name, scope: :course_id, message: "不能创建相同名称的分班" diff --git a/app/models/course_member.rb b/app/models/course_member.rb index 65849e5de..21221e7e9 100644 --- a/app/models/course_member.rb +++ b/app/models/course_member.rb @@ -8,6 +8,7 @@ class CourseMember < ApplicationRecord belongs_to :course_group, counter_cache: true, optional: true belongs_to :graduation_group, optional: true has_many :teacher_course_groups, dependent: :destroy + has_many :course_member_attendances, dependent: :destroy scope :teachers_and_admin, -> { where(role: %i[CREATOR PROFESSOR ASSISTANT_PROFESSOR]) } scope :students, ->(course) { where(course_id: course.id, role: %i[STUDENT])} @@ -22,6 +23,10 @@ class CourseMember < ApplicationRecord # after_destroy :delete_works # after_create :work_operation + after_create :create_attendance_record + after_commit :create_attendance_record + + def delete_works if self.role == "STUDENT" course = self.course @@ -156,4 +161,11 @@ class CourseMember < ApplicationRecord end teachers end + + private + + def create_attendance_record + StudentJoinAttendanceRecordJob.perform_later(id) + end + end diff --git a/app/models/course_member_attendance.rb b/app/models/course_member_attendance.rb new file mode 100644 index 000000000..152bb48b6 --- /dev/null +++ b/app/models/course_member_attendance.rb @@ -0,0 +1,11 @@ +class CourseMemberAttendance < ApplicationRecord + # attendance_mode :0 初始数据,1 二维码签到,2 数字签到,3 老师签到 + enum attendance_mode: { DEFAULT: 0, QRCODE: 1, NUMBER: 2, TEACHER: 3} + # attendance_status :1 正常签到,2 请假,0 旷课 + enum attendance_status: { NORMAL: 1, LEAVE: 2, ABSENCE: 0 } + belongs_to :course_member + belongs_to :user + belongs_to :course + belongs_to :course_attendance + belongs_to :course_group +end diff --git a/app/models/ecloud.rb b/app/models/ecloud.rb index 293948f3d..f2648093c 100644 --- a/app/models/ecloud.rb +++ b/app/models/ecloud.rb @@ -1,8 +1,8 @@ #encoding=utf-8 class Ecloud < ActiveRecord::Base - attr_accessible :applyno, :begintime, :bossorderid, :custcode, :custid, :custname, :custtype, :ecordercode, :endtime, - :mobile, :opttype, :productcode, :registersource, :string, :trial, :useralias, :userid, :username, :email, - :effecttime, :operatime + # attr_accessible :applyno, :begintime, :bossorderid, :custcode, :custid, :custname, :custtype, :ecordercode, :endtime, + # :mobile, :opttype, :productcode, :registersource, :string, :trial, :useralias, :userid, :username, :email, + # :effecttime, :operatime has_many :ecloud_services, :dependent => :destroy # 业务列表 has_many :ecloud_productparas, :dependent => :destroy # 开通参数列表 diff --git a/app/models/ecloud_productpara.rb b/app/models/ecloud_productpara.rb index ec1b94bc5..a88fc9d6c 100644 --- a/app/models/ecloud_productpara.rb +++ b/app/models/ecloud_productpara.rb @@ -1,4 +1,4 @@ class EcloudProductpara < ActiveRecord::Base - attr_accessible :key, :value, :ecloud_id + # attr_accessible :key, :value, :ecloud_id belongs_to :ecloud end diff --git a/app/models/ecloud_service.rb b/app/models/ecloud_service.rb index dba4a7b20..cb171b297 100644 --- a/app/models/ecloud_service.rb +++ b/app/models/ecloud_service.rb @@ -1,6 +1,6 @@ # 操作代码 0:新增业务,1:注销业务2:修改业务 class EcloudService < ActiveRecord::Base - attr_accessible :begintime, :code, :endtime, :opttype, :ecloud_id, :packagecode, :bossorderid + # attr_accessible :begintime, :code, :endtime, :opttype, :ecloud_id, :packagecode, :bossorderid belongs_to :ecloud has_many :ecloud_serviece_serviceparas end diff --git a/app/models/ecloud_serviece_servicepara.rb b/app/models/ecloud_serviece_servicepara.rb index 5dbff71f5..f73a3f712 100644 --- a/app/models/ecloud_serviece_servicepara.rb +++ b/app/models/ecloud_serviece_servicepara.rb @@ -1,5 +1,5 @@ # ket值,license表示人数,对应企业版;duration表示月数,对应个人版; class EcloudServieceServicepara < ActiveRecord::Base - attr_accessible :key, :value, :ecloud_service_id + # attr_accessible :key, :value, :ecloud_service_id belongs_to :ecloud_service end diff --git a/app/models/ecloud_users.rb b/app/models/ecloud_users.rb index 99da0df24..8f29c8e2d 100644 --- a/app/models/ecloud_users.rb +++ b/app/models/ecloud_users.rb @@ -1,4 +1,4 @@ class EcloudUser < ActiveRecord::Base # opttype: # user['opttype']: 操作类型0:开通;1:变更;3: 取消授权;4:暂停;5:恢复; - attr_accessible :begintime, :email, :endtime, :mobile, :opttype, :paras, :useralias, :userid, :username, :custid + # attr_accessible :begintime, :email, :endtime, :mobile, :opttype, :paras, :useralias, :userid, :username, :custid end diff --git a/app/models/game.rb b/app/models/game.rb index 062ad15cc..144dbced2 100644 --- a/app/models/game.rb +++ b/app/models/game.rb @@ -29,6 +29,19 @@ class Game < ApplicationRecord validates :identifier, uniqueness: true + # 服务器uri+port的redis的key + def server_key + "game_server_url_#{id}" + end + + def set_server_key(server_url) + Rails.cache.write("#{server_key}", server_url, expires_in: 5.minute) + end + + def get_server_url + Rails.cache.read(server_key) + end + # 根据得分比例来算实际得分(试卷、实训作业) def real_score score ((final_score < 0 ? 0 : final_score).to_f / challenge.score) * score diff --git a/app/models/homework_bank.rb b/app/models/homework_bank.rb index 7e13891d3..2fdfc613e 100644 --- a/app/models/homework_bank.rb +++ b/app/models/homework_bank.rb @@ -12,5 +12,5 @@ class HomeworkBank < ApplicationRecord validates :name, length: { maximum: 60, too_long: "不能超过60个字符" } validates :description, length: { maximum: 15000, too_long: "不能超过15000个字符" } - validates :reference_answer, length: { maximum: 15000, too_long: "不能超过15000个字符" } + validates :reference_answer, length: { maximum: 25000, too_long: "不能超过25000个字符" } end diff --git a/app/models/homework_common.rb b/app/models/homework_common.rb index 65c2e6f21..7da7a177d 100644 --- a/app/models/homework_common.rb +++ b/app/models/homework_common.rb @@ -38,7 +38,7 @@ class HomeworkCommon < ApplicationRecord 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个字符" } + validates :reference_answer, length: { maximum: 25000, too_long: "不能超过25000个字符" } # after_update :update_activity before_destroy :update_homework_bank_quotes @@ -104,7 +104,7 @@ class HomeworkCommon < ApplicationRecord end def user_work user_id - work = self.student_works.find_by_user_id(user_id) || StudentWork.create!(homework_common_id: id, user_id: user_id) + work = StudentWork.find_by(homework_common_id: id, user_id: user_id) || StudentWork.create!(homework_common_id: id, user_id: user_id) end # 是否在补交阶段内 diff --git a/app/models/laboratory_setting.rb b/app/models/laboratory_setting.rb index e53b54cd3..63949f4ef 100644 --- a/app/models/laboratory_setting.rb +++ b/app/models/laboratory_setting.rb @@ -30,6 +30,10 @@ class LaboratorySetting < ApplicationRecord image_url('_subject_banner') end + def shixun_banner_url + image_url('_shixun_banner') + end + def course_banner_url image_url('_course_banner') end @@ -62,7 +66,7 @@ class LaboratorySetting < ApplicationRecord name: nil, navbar: [ { 'name' => '实践课程', 'link' => '/paths', 'hidden' => false }, - { 'name' => '翻转课堂', 'link' => '/courses', 'hidden' => false }, + { 'name' => '教学课堂', 'link' => '/courses', 'hidden' => false }, { 'name' => '实训项目', 'link' => '/shixuns', 'hidden' => false }, { 'name' => '在线竞赛', 'link' => '/competitions', 'hidden' => false }, { 'name' => '教学案例', 'link' => '/moop_cases', 'hidden' => false }, diff --git a/app/models/shixun_info.rb b/app/models/shixun_info.rb index c2498067f..a8522f81c 100644 --- a/app/models/shixun_info.rb +++ b/app/models/shixun_info.rb @@ -2,9 +2,11 @@ class ShixunInfo < ApplicationRecord belongs_to :shixun validates_uniqueness_of :shixun_id validates_length_of :fork_reason, maximum: 60, message: "不能超过60个字符" + # validates_presence_of :evaluate_script, message: "实训脚本不能为空" after_commit :create_diff_record - validates :description, length: { maximum: 5000, too_long: "不能超过5000个字符" } + validates :description, length: { maximum: 10000, too_long: "不能超过10000个字符" } + private diff --git a/app/models/sta_all.rb b/app/models/sta_all.rb new file mode 100644 index 000000000..e9d64b368 --- /dev/null +++ b/app/models/sta_all.rb @@ -0,0 +1,20 @@ +class StaAll < ApplicationRecord + # t.integer :school_id 学校ID + # t.integer :tea_count 老师数 + # t.integer :stu_count 学生数 + # t.integer :active_users_count 活跃用户数(3个月内有登录) + # t.integer :courses_count 总课堂数 + # t.integer :curr_courses_count 正在进行的课堂数 + # t.integer :homw_shixuns_count 实训作业数 + # t.integer :homw_other_count 其它类型作业数 + # t.integer :sources_count 资源数 + # t.integer :videos_count 视频总个数 + # t.integer :shixuns_count 制作实训总数 + # t.integer :myshixuns_count 挑战实训总数 + # t.integer :mys_passed_count 通关的实训总数 + # t.integer :games_count 挑战的总关卡数 + # t.integer :games_passed_count 通关的总关卡数 + # t.integer :build_count 评测总数 + + belongs_to :school +end diff --git a/app/models/teacher_group_record.rb b/app/models/teacher_group_record.rb new file mode 100644 index 000000000..2dc9a392d --- /dev/null +++ b/app/models/teacher_group_record.rb @@ -0,0 +1,4 @@ +class TeacherGroupRecord < ApplicationRecord + belongs_to :user + belongs_to :course +end diff --git a/app/models/user.rb b/app/models/user.rb index b3a1da84d..7e60983d1 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -160,6 +160,8 @@ class User < ApplicationRecord has_many :examination_banks, dependent: :destroy has_many :examination_intelligent_settings, dependent: :destroy + has_many :teacher_group_records, dependent: :destroy + # Groups and active users scope :active, lambda { where(status: STATUS_ACTIVE) } diff --git a/app/models/weapp_settings/course_banner.rb b/app/models/weapp_settings/course_banner.rb new file mode 100644 index 000000000..bbf2af499 --- /dev/null +++ b/app/models/weapp_settings/course_banner.rb @@ -0,0 +1,3 @@ +class WeappSettings::CourseBanner < WeappSetting + default_scope { order(position: :asc) } +end \ No newline at end of file diff --git a/app/models/weapp_settings/shixun_banner.rb b/app/models/weapp_settings/shixun_banner.rb new file mode 100644 index 000000000..72237d688 --- /dev/null +++ b/app/models/weapp_settings/shixun_banner.rb @@ -0,0 +1,3 @@ +class WeappSettings::ShixunBanner < WeappSetting + default_scope { order(position: :asc) } +end \ No newline at end of file diff --git a/app/queries/admins/user_schools_statistic_query.rb b/app/queries/admins/user_schools_statistic_query.rb new file mode 100644 index 000000000..d68c0b825 --- /dev/null +++ b/app/queries/admins/user_schools_statistic_query.rb @@ -0,0 +1,114 @@ +class Admins::UserSchoolsStatisticQuery < ApplicationQuery + include CustomSortable + + attr_reader :params + + sort_columns :cnt, + default_by: :cnt, default_direction: :desc + + def initialize(params) + @params = params + end + + def call + schools = School + if params[:province].present? + schools = schools.where("province like ?", "%#{params[:province]}%") + end + + if params[:school_id].present? + schools = schools.where(id: params[:school_id]) + end + + total = schools.count + # 根据排序字段进行查询 + schools = query_by_sort_column(schools.group(:id), params[:sort_by]) + #schools = custom_sort(schools, params[:sort_by], params[:sort_direction]) + schools = schools.limit(page_size).offset(offset).to_a + # 查询并组装其它数据 + schools = package_other_data(schools) + [total, schools] + + end + + private + + def package_other_data(schools) + ids = schools.map(&:id) + user_e = UserExtension.where(school_id: schools.map(&:id)) + #study_myshixun = Myshixun.joins("join user_extensions ue on ue.user_id = myshixuns.user_id").where(ue: {school_id: ids}) + #finish_myshixun = Myshixun.joins("join user_extensions ue on ue.user_id = myshixuns.user_id") + # .where(ue: {school_id: ids}, myshixuns: {status: 1}) + study_challenge = Game.joins("join user_extensions ue on ue.user_id = games.user_id") + .where(ue: {school_id: ids},).where( games:{status: [0, 1, 2]}) + finish_challenge = Game.joins("join user_extensions ue on ue.user_id = games.user_id") + .where(ue: {school_id: ids}).where(games: {status: 2}) + reg_teacher = user_e.where(identity: 'teacher') + reg_student = user_e.where.not(identity: 'teacher') + + if time_range.present? + #study_myshixun = study_myshixun.where(updated_at: time_range) + #finish_myshixun = finish_myshixun.where(updated_at: time_range) + study_challenge = study_challenge.where(updated_at: time_range) + finish_challenge = finish_challenge.where(updated_at: time_range) + reg_teacher = reg_teacher.where(created_at: time_range) + reg_student = reg_student.where(created_at: time_range) + user_e = user_e.joins(:user).where(users: {last_login_on: time_range}) + end + + #study_myshixun_map = study_myshixun.reorder(nil).group(:school_id).count + #finish_myshixun_map = finish_myshixun.reorder(nil).group(:school_id).count + study_challenge_map = study_challenge.reorder(nil).group(:school_id).count + finish_challenge_map = finish_challenge.reorder(nil).group(:school_id).count + evaluate_count_map = study_challenge.reorder(nil).group(:school_id).sum(:evaluate_count) + reg_teacher_map = reg_teacher.reorder(nil).group(:school_id).count + reg_student_map = reg_student.reorder(nil).group(:school_id).count + user_e_map = user_e.reorder(nil).group(:school_id).count + + schools.each do |school| + school._extra_data = { + #study_shixun_count: study_myshixun_map.fetch(schools.id, 0), + #finish_shixun_count: finish_myshixun_map.fetch(schools.id, 0), + study_challenge_count: study_challenge_map.fetch(school.id, 0), + finish_challenge_count: finish_challenge_map.fetch(school.id, 0), + evaluate_count: evaluate_count_map.fetch(school.id, 0), + reg_teacher_count: reg_teacher_map.fetch(school.id, 0), + reg_student_count: reg_student_map.fetch(school.id, 0), + user_active_count: user_e_map.fetch(school.id, 0) + } + end + schools + end + + def query_by_sort_column(schools, sort_by_column) + #base_query_column = 'schools.*' + + case sort_by_column.to_s + when 'cnt' then + schools.left_joins(:user_extensions).select("schools.*, count(*) cnt").order("cnt desc") + else + schools + end + end + + def time_range + @_time_range ||= begin + case params[:date] + when 'dayly' then 1.days.ago..Time.now + when 'weekly' then 1.weeks.ago..Time.now + when 'monthly' then 1.months.ago..Time.now + when 'quarterly' then 3.months.ago..Time.now + when 'yearly' then 1.years.ago..Time.now + else '' + end + end + end + + def page_size + params[:per_page].to_i.zero? ? 20 : params[:per_page].to_i + end + + def offset + (params[:page].to_i.zero? ? 0 : params[:page].to_i - 1) * page_size + end +end diff --git a/app/queries/weapps/subject_query.rb b/app/queries/weapps/subject_query.rb index b50c2a104..0a3c9beb2 100644 --- a/app/queries/weapps/subject_query.rb +++ b/app/queries/weapps/subject_query.rb @@ -19,6 +19,11 @@ class Weapps::SubjectQuery < ApplicationQuery subjects = subjects.joins(:sub_discipline_containers).where(sub_discipline_containers: {container_type: "Subject"}) end + # 搜索 + if params[:keyword].present? + subjects = subjects.where("subjects.name like '%#{params[:keyword]}%'") + end + subjects = subjects.left_joins(:shixuns, :repertoire).select('subjects.id, subjects.name, subjects.excellent, subjects.stages_count, subjects.status, subjects.homepage_show, subjects.shixuns_count, subjects.repertoire_id, subjects.updated_at, IFNULL(sum(shixuns.myshixuns_count), 0) myshixuns_count') .group('subjects.id').order("subjects.homepage_show #{sort_type}, #{order_type} #{sort_type}") diff --git a/app/services/admins/save_laboratory_setting_service.rb b/app/services/admins/save_laboratory_setting_service.rb index c29e374bd..89dfbb0e0 100644 --- a/app/services/admins/save_laboratory_setting_service.rb +++ b/app/services/admins/save_laboratory_setting_service.rb @@ -40,6 +40,7 @@ class Admins::SaveLaboratorySettingService < ApplicationService save_image_file(params[:login_logo], 'login') save_image_file(params[:tab_logo], 'tab') save_image_file(params[:subject_banner], '_subject_banner') + save_image_file(params[:shixun_banner], '_shixun_banner') save_image_file(params[:course_banner], '_course_banner') save_image_file(params[:competition_banner], '_competition_banner') save_image_file(params[:moop_cases_banner], '_moop_cases_banner') diff --git a/app/services/application_service.rb b/app/services/application_service.rb index 81c48de95..6bf1c807a 100644 --- a/app/services/application_service.rb +++ b/app/services/application_service.rb @@ -9,6 +9,10 @@ class ApplicationService content.gsub(regex, '') end + def convert_https content + content.gsub("http:", "https:") + end + private def strip(str) diff --git a/app/services/schools/school_statistic_service.rb b/app/services/schools/school_statistic_service.rb new file mode 100644 index 000000000..a5082108d --- /dev/null +++ b/app/services/schools/school_statistic_service.rb @@ -0,0 +1,100 @@ +class Schools::SchoolStatisticService < ApplicationService + attr_reader :school + + def initialize(school) + @school = school.includes(:courses, user_extensions: :user) + @user_extensions = school.user_extensions + end + + # 学校老师数量 + def teacher_count + @user_extensions.map{|ue| ue.identity == 0 }.size + end + + # 学校学生数 + def student_count + @user_extensions.map{|ue| ue.identity == 1 }.size + end + + # 活跃用户(近1天有登录) + def acitve_user_1_day_count + @user_extensions.map{|ue| ue.user.last_login_on&.between?(1.days.ago, Time.now)}.size + end + + # 活跃用户(近1个周有登录) + def acitve_user_1_week_count + @user_extensions.map{|ue| ue.user.last_login_on&.between?(1.weeks.ago, Time.now)}.size + end + + # 活跃用户(近3个月有登录) + def acitve_user_1_months_count + @user_extensions.map{|ue| ue.user.last_login_on&.between?(1.months.ago, Time.now)}.size + end + + # 活跃用户(近3个月有登录) + def acitve_user_3_months_count + @user_extensions.map{|ue| ue.user.last_login_on&.between?(3.months.ago, Time.now)}.size + end + + # 活跃用户(进半年有登录记录) + def acitve_user_6_months_count + @user_extensions.map{|ue| ue.user.last_login_on&.between?(6.months.ago, Time.now)}.size + end + + # 课堂总数(上层记得Include) + def courses_count + @school.courses.size + end + + # 正在进行的课堂数 + def curr_courses_count + @school.courses.map{|c| c.is_end == false && c.is_delete != 0}.size + end + + # 实训作业数目 + def hom_shixuns_count + @school.courses.joins(:homework_commons).where(homework_commons: {homework_type: 'practice'}).size + end + + # 资源数 + def sources_count + @school.courses.joins(:attachments).size + end + + # 视频总数 + def videos_count + @school.courses.joins(:course_videos).size + end + + # 制作实训数 + def shixun_count + @user_extensions.joins(user: :shixuns).size + end + + # 挑战实训总数 + def myshixuns_count + @user_extensions.joins("join myshixuns on myshixuns.user_id = user_extensions.user_id").size + end + + # 通过的实训总数 + def pass_myshixun_count + @user_extensions.joins("join myshixuns on myshixuns.user_id = user_extensions.user_id").where(myshixuns: {status: 1}).size + end + + # 挑战的关卡数 + def games_count + @user_extensions.joins("join games on games.user_id = user_extensions.user_id").where(games: {status: 0..2}) + end + + # 通关的关卡数 + def pass_games_count + @user_extensions.joins("join games on games.user_id = user_extensions.user_id").where(games: {status: 2}) + end + + # 评测总数 + def evalute_count + @user_extensions.joins("join games on games.user_id = user_extensions.user_id").sum(:evalute_count) + end + + +end \ No newline at end of file diff --git a/app/services/videos/dispatch_callback_service.rb b/app/services/videos/dispatch_callback_service.rb index b32c87c4e..5adebea73 100644 --- a/app/services/videos/dispatch_callback_service.rb +++ b/app/services/videos/dispatch_callback_service.rb @@ -12,7 +12,7 @@ class Videos::DispatchCallbackService < ApplicationService # TODO:: 拆分事件分发 case params['EventType'] when 'FileUploadComplete' then # 视频上传完成 - video.file_url = params['FileUrl'] + video.file_url = convert_https(params['FileUrl']) video.filesize = params['Size'] video.upload_success video.save! diff --git a/app/tasks/statistic_school_report_task.rb b/app/tasks/statistic_school_report_task.rb index a72c57830..3371ce527 100644 --- a/app/tasks/statistic_school_report_task.rb +++ b/app/tasks/statistic_school_report_task.rb @@ -1,20 +1,20 @@ class StatisticSchoolReportTask def call - School.find_each do |school| - evaluate_count = Game.joins(:challenge) - .joins('LEFT JOIN course_members ON course_members.user_id = games.user_id') - .joins('LEFT JOIN homework_commons_shixuns hcs ON hcs.shixun_id = challenges.shixun_id') - .joins('LEFT JOIN homework_commons hc ON hcs.homework_common_id = hc.id AND hc.homework_type = 4') - .joins('LEFT JOIN courses ON hc.course_id = courses.id AND course_members.course_id = courses.id') - .where(courses: { school_id: school.id }) - .sum(:evaluate_count) - - report = SchoolReport.find_or_initialize_by(school_id: school.id) - - report.school_name = school.name - report.shixun_evaluate_count = evaluate_count - - report.save - end + # School.find_each do |school| + # evaluate_count = Game.joins(:challenge) + # .joins('LEFT JOIN course_members ON course_members.user_id = games.user_id') + # .joins('LEFT JOIN homework_commons_shixuns hcs ON hcs.shixun_id = challenges.shixun_id') + # .joins('LEFT JOIN homework_commons hc ON hcs.homework_common_id = hc.id AND hc.homework_type = 4') + # .joins('LEFT JOIN courses ON hc.course_id = courses.id AND course_members.course_id = courses.id') + # .where(courses: { school_id: school.id }) + # .sum(:evaluate_count) + # + # report = SchoolReport.find_or_initialize_by(school_id: school.id) + # + # report.school_name = school.name + # report.shixun_evaluate_count = evaluate_count + # + # report.save + # end end end diff --git a/app/views/admins/daily_school_statistics/shared/_list.html.erb b/app/views/admins/daily_school_statistics/shared/_list.html.erb index 6982891ee..1ec80de21 100644 --- a/app/views/admins/daily_school_statistics/shared/_list.html.erb +++ b/app/views/admins/daily_school_statistics/shared/_list.html.erb @@ -11,7 +11,7 @@