Commit 230ee7e6 authored by Artem Baranovskyi's avatar Artem Baranovskyi
Browse files

Few JS coding style fixes.

parent 67087bbd
// Local/asystgrade/amd/src/marks.js
define(['core/ajax', 'core/log'], function(ajax, log) {
return {
init: function() {
window.addEventListener('load', function() {
const params = new URLSearchParams(window.location.search);
const qid = params.get('qid');
const slot = params.get('slot');
window.console.log('marks.js initialized');
console.log('Request about to be sent'); // До AJAX вызова
// Выполняем AJAX запрос через core/ajax
let request = ajax.call([{
methodname: 'local_asystgrade_update_grade', // Имя вашего PHP метода
args: {qid: qid, slot: slot},
}]);
// console.log('Request completed', response); // После получения ответа
request[0].done(function(response) {
window.console.log('Response received:', response); // Печатает весь ответ
if (response.status === 'success') {
updateMarks(response.grades, response.inputNames, response.maxmark);
} else {
log.error(response.message);
}
}).fail(function(ex) {
window.console.error('Ошибка AJAX запроса: ', ex);
});
});
}
};
/**
* Обновляет оценки на странице.
*
* @param {Array} grades - Массив оценок.
* @param {Array} inputNames - Массив имен input элементов.
* @param {number} maxmark - Максимальная оценка.
*/
function updateMarks(grades, inputNames, maxmark) {
// Обновляем DOM элемент на странице с оценками
grades.forEach(function(grade, index) {
const predictedGrade = grade.predicted_grade === 'correct' ? maxmark : 0;
const inputName = inputNames[index];
const inputElement = document.querySelector(`input[name="${inputName}"]`);
if (inputElement) {
inputElement.value = predictedGrade;
// Console.log(`Updated input: ${inputName} with grade: ${predictedGrade}`);
} else {
// Console.warn(`Input not found: ${inputName}`);
}
});
}
});
......@@ -92,4 +92,14 @@ class quizquery implements quizquery_interface
]
);
}
public function get_attempts_and_steps($qid, $slot) {
return $this->db->get_records_sql("
SELECT qa.*, qs.*, qasd.*
FROM {question_attempts} qa
JOIN {question_attempt_steps} qs ON qa.id = qs.questionattemptid
LEFT JOIN {question_attempt_step_data} qasd ON qs.id = qasd.attemptstepid
WHERE qa.questionid = :qid AND qa.slot = :slot
AND qasd.name = 'answer' AND qs.state = 'complete'", ['qid' => $qid, 'slot' => $slot]);
}
}
<?php
namespace local_asystgrade\output;
defined('MOODLE_INTERNAL') || die();
class ajax_controller {
public static function get_marks(): string | false {
global $PAGE;
// Получаем параметры из URL.
$qid = optional_param('qid', null, PARAM_INT);
$slot = optional_param('slot', false, PARAM_INT);
$quizQuery = new \local_asystgrade\db\quizquery();
if ($quizQuery->gradesExist($qid, $slot)) {
return json_encode(['status' => 'error', 'message' => 'Grades already exist in the database.']);
}
var_dump('AJAX');
$question_attempts = $quizQuery->get_question_attempts($qid, $slot);
$referenceAnswer = $quizQuery->get_reference_answer($qid);
$maxmark = (float)$question_attempts->current()->maxmark;
$data = prepare_api_data($quizQuery, $question_attempts, $referenceAnswer);
$studentData = $data['studentData'];
$inputNames = array_column($studentData, 'inputName');
var_dump('Entering AJAX function...');
error_log('Before fetching question attempts');
// API вызов для получения оценок
try {
$apiendpoint = get_config('local_asystgrade', 'apiendpoint') ?: 'http://flask:5000/api/autograde';
$httpClient = new \local_asystgrade\api\http_client();
$apiClient = \local_asystgrade\api\client::getInstance($apiendpoint, $httpClient);
$response = $apiClient->send_data([
'referenceAnswer' => $data['referenceAnswer'],
'studentAnswers' => array_column($studentData, 'studentAnswer')
]);
$grades = json_decode($response, true);
error_log('After fetching question attempts');
} catch (Exception $e) {
return json_encode(['status' => 'error', 'message' => 'API Error: ' . $e->getMessage()]);
}
// Возвращаем JSON с оценками и другими данными
return json_encode([
'status' => 'success',
'grades' => $grades,
'inputNames' => $inputNames,
'maxmark' => $maxmark
]);
}
}
<?php
$functions = [
'local_asystgrade_update_grade' => [
'classname' => 'local_asystgrade\output\ajax_controller', // Контроллерный класс
'methodname' => 'get_marks', // Имя метода
'classpath' => 'local/asystgrade/classes/output/ajax_controller.php', // Путь к файлу
'description' => 'Gets the marks for students.',
'type' => 'read',
'ajax' => true, // Разрешить вызов через AJAX
'capabilities'=> ''
],
];
\ No newline at end of file
......@@ -26,6 +26,30 @@ use local_asystgrade\db\quizquery;
defined('MOODLE_INTERNAL') || die();
//global $PAGE;
//require_once(__DIR__ . '/../../config.php');
//require_login();
//$PAGE->set_url('/local/asystgrade/index.php');
//$PAGE->set_context(context_system::instance());
//$PAGE->set_title('Your Page Title');
//$PAGE->set_heading('Your Page Heading');
//$slot = optional_param('slot', false, PARAM_INT);
//$PAGE->requires->js_call_amd('local_asystgrade/marks', 'init');
//function local_asystgrade_page_init() {
// global $PAGE;
// $slot = optional_param('slot', false, PARAM_INT);
// echo "Calling js_call_amd..."; // Добавьте перед вызовом js_call_amd
// $PAGE->requires->js_call_amd('local_asystgrade/marks', 'init');
//
//
// if ($PAGE->url->compare(new moodle_url('/mod/quiz/report.php'), URL_MATCH_BASE) && $slot) {
// echo "Calling js_call_amd..."; // Добавьте перед вызовом js_call_amd
// $PAGE->requires->js_call_amd('local_asystgrade/marks', 'init');
// }
//}
/**
* A hook function that will process the data and insert the rating value.
* The function must be called on the desired page like https://www.moodle.loc/mod/quiz/report.php?id=2&mode=grading&slot=1&qid=1&grade=needsgrading&includeauto=1
......@@ -37,10 +61,12 @@ function local_asystgrade_before_footer()
{
global $PAGE;
// Obtaining parameters from URL
$qid = optional_param('qid', null, PARAM_INT);
$qid = optional_param('qid', null, PARAM_INT);
$slot = optional_param('slot', false, PARAM_INT);
if ($PAGE->url->compare(new moodle_url('/mod/quiz/report.php'), URL_MATCH_BASE) && $slot) {
$PAGE->requires->js_call_amd('local_asystgrade/marks', 'init');
/*if ($PAGE->url->compare(new moodle_url('/mod/quiz/report.php'), URL_MATCH_BASE) && $slot) {
$quizQuery = new quizquery();
if ($quizQuery->gradesExist($qid, $slot)) {
......@@ -94,7 +120,7 @@ function local_asystgrade_before_footer()
pasteGradedMarks($grades, $inputNames, $maxmark);
error_log('URL matches /mod/quiz/report.php in page_init');
}
}*/
}
/**
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment