Commit 42fa6994 authored by Juan Segarra Montesinos's avatar Juan Segarra Montesinos
Browse files

MDL-68944 mod_workshop: Workshop skips scheduled allocation

parent 16a5169a
......@@ -81,4 +81,41 @@ class observer {
}
return true;
}
/**
* Called when the '\mod_workshop\event\phase_automatically_switched' event is triggered.
*
* This observer handles the phase_automatically_switched event triggered when phaseswithassesment is active
* and the phase is automatically switched.
*
* When this happens, this situation can occur:
*
* * cron_task transition the workshop to PHASE_ASESSMENT.
* * scheduled_allocator task executes.
* * scheduled_allocator task cannot allocate parcipants because workshop is not
* in PHASE_SUBMISSION state (it's in PHASE_ASSESMENT).
*
* @param \mod_workshop\event\phase_automatically_switched $event
*/
public static function phase_automatically_switched(\mod_workshop\event\phase_automatically_switched $event) {
if ($event->other['previousworkshopphase'] != \workshop::PHASE_SUBMISSION) {
return;
}
if ($event->other['targetworkshopphase'] != \workshop::PHASE_ASSESSMENT) {
return;
}
$workshop = $event->get_record_snapshot('workshop', $event->objectid);
$course = $event->get_record_snapshot('course', $event->courseid);
$cm = $event->get_record_snapshot('course_modules', $event->contextinstanceid);
$workshop = new \workshop($workshop, $cm, $course);
if ($workshop->phase != \workshop::PHASE_ASSESSMENT) {
return;
}
$allocator = $workshop->allocator_instance('scheduled');
// We know that we come from PHASE_SUBMISSION so we tell the allocator not to test for the PHASE_SUBMISSION state.
$allocator->execute(false);
}
}
......@@ -31,5 +31,10 @@ $observers = array(
array(
'eventname' => '\mod_workshop\event\course_module_viewed',
'callback' => '\workshopallocation_scheduled\observer::workshop_viewed',
),
array(
'eventname' => '\mod_workshop\event\phase_automatically_switched',
'callback' => '\workshopallocation_scheduled\observer::phase_automatically_switched'
)
);
......@@ -128,71 +128,97 @@ class workshop_scheduled_allocator implements workshop_allocator {
/**
* Executes the allocation
*
* @param bool $checksubmissionphase Check that the workshop is in submission phase before doing anything else.
* @return workshop_allocation_result
*/
public function execute() {
public function execute(bool $checksubmissionphase = true) {
global $DB;
$result = new workshop_allocation_result($this);
// make sure the workshop itself is at the expected state
if ($this->workshop->phase != workshop::PHASE_SUBMISSION) {
// Execution can occur in multiple places. Ensure we only allocate one at a time.
$lockfactory = \core\lock\lock_config::get_lock_factory('mod_workshop_allocation_scheduled_execution');
$executionlock = $lockfactory->get_lock($this->workshop->id, 1, 30);
if (!$executionlock) {
$result->set_status(workshop_allocation_result::STATUS_FAILED,
get_string('resultfailedphase', 'workshopallocation_scheduled'));
return $result;
get_string('resultfailed', 'workshopallocation_scheduled'));
}
if (empty($this->workshop->submissionend)) {
$result->set_status(workshop_allocation_result::STATUS_FAILED,
get_string('resultfaileddeadline', 'workshopallocation_scheduled'));
return $result;
}
try {
// Make sure the workshop itself is at the expected state.
if ($this->workshop->submissionend > time()) {
$result->set_status(workshop_allocation_result::STATUS_VOID,
get_string('resultvoiddeadline', 'workshopallocation_scheduled'));
return $result;
}
if ($checksubmissionphase && $this->workshop->phase != workshop::PHASE_SUBMISSION) {
$executionlock->release();
$result->set_status(workshop_allocation_result::STATUS_FAILED,
get_string('resultfailedphase', 'workshopallocation_scheduled'));
return $result;
}
$current = $DB->get_record('workshopallocation_scheduled',
array('workshopid' => $this->workshop->id, 'enabled' => 1), '*', IGNORE_MISSING);
if (empty($this->workshop->submissionend)) {
$executionlock->release();
$result->set_status(workshop_allocation_result::STATUS_FAILED,
get_string('resultfaileddeadline', 'workshopallocation_scheduled'));
return $result;
}
if ($current === false) {
$result->set_status(workshop_allocation_result::STATUS_FAILED,
get_string('resultfailedconfig', 'workshopallocation_scheduled'));
return $result;
}
if ($this->workshop->submissionend > time()) {
$executionlock->release();
$result->set_status(workshop_allocation_result::STATUS_VOID,
get_string('resultvoiddeadline', 'workshopallocation_scheduled'));
return $result;
}
if (!$current->enabled) {
$result->set_status(workshop_allocation_result::STATUS_VOID,
get_string('resultdisabled', 'workshopallocation_scheduled'));
return $result;
}
$current = $DB->get_record('workshopallocation_scheduled',
array('workshopid' => $this->workshop->id, 'enabled' => 1), '*', IGNORE_MISSING);
if (!is_null($current->timeallocated) and $current->timeallocated >= $this->workshop->submissionend) {
$result->set_status(workshop_allocation_result::STATUS_VOID,
get_string('resultvoidexecuted', 'workshopallocation_scheduled'));
return $result;
}
if ($current === false) {
$executionlock->release();
$result->set_status(workshop_allocation_result::STATUS_FAILED,
get_string('resultfailedconfig', 'workshopallocation_scheduled'));
return $result;
}
if (!$current->enabled) {
$executionlock->release();
$result->set_status(workshop_allocation_result::STATUS_VOID,
get_string('resultdisabled', 'workshopallocation_scheduled'));
return $result;
}
// so now we know that we are after the submissions deadline and either the scheduled allocation was not
// executed yet or it was but the submissions deadline has been prolonged (and hence we should repeat the
// allocations)
if (!is_null($current->timeallocated) and $current->timeallocated >= $this->workshop->submissionend) {
$executionlock->release();
$result->set_status(workshop_allocation_result::STATUS_VOID,
get_string('resultvoidexecuted', 'workshopallocation_scheduled'));
return $result;
}
// So now we know that we are after the submissions deadline and either the scheduled allocation was not
// executed yet or it was but the submissions deadline has been prolonged (and hence we should repeat the
// allocations).
$settings = workshop_random_allocator_setting::instance_from_text($current->settings);
$randomallocator = $this->workshop->allocator_instance('random');
$randomallocator->execute($settings, $result);
// Store the result in the instance's table.
$update = new stdClass();
$update->id = $current->id;
$update->timeallocated = $result->get_timeend();
$update->resultstatus = $result->get_status();
$update->resultmessage = $result->get_message();
$update->resultlog = json_encode($result->get_logs());
$settings = workshop_random_allocator_setting::instance_from_text($current->settings);
$randomallocator = $this->workshop->allocator_instance('random');
$randomallocator->execute($settings, $result);
$DB->update_record('workshopallocation_scheduled', $update);
// store the result in the instance's table
$update = new stdClass();
$update->id = $current->id;
$update->timeallocated = $result->get_timeend();
$update->resultstatus = $result->get_status();
$update->resultmessage = $result->get_message();
$update->resultlog = json_encode($result->get_logs());
} catch (\Exception $e) {
$executionlock->release();
$result->set_status(workshop_allocation_result::STATUS_FAILED,
get_string('resultfailed', 'workshopallocation_scheduled'));
throw $e;
}
$DB->update_record('workshopallocation_scheduled', $update);
$executionlock->release();
return $result;
}
......
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace workshopallocation_scheduled;
/**
* Test for the scheduled allocator.
*
* @package workshopallocation_scheduled
* @copyright 2020 Jaume I University <https://www.uji.es/>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class scheduled_allocator_test extends \advanced_testcase {
/** @var \stdClass $course The course where the tests will be run */
private $course;
/** @var \workshop $workshop The workshop where the tests will be run */
private $workshop;
/** @var \stdClass $workshopcm The workshop course module instance */
private $workshopcm;
/** @var \stdClass[] $students An array of student enrolled in $course */
private $students;
/**
* Tests that student submissions get automatically alocated after the submission deadline and when the workshop
* "Switch to the next phase after the submissions deadline" checkbox is active.
*/
public function test_that_allocator_in_executed_on_submission_end_when_phaseswitchassessment_is_active(): void {
global $DB;
$this->resetAfterTest();
$this->setup_test_course_and_workshop();
$this->activate_switch_to_the_next_phase_after_submission_deadline();
$this->set_the_submission_deadline_in_the_past();
$this->activate_the_scheduled_allocator();
$workshopgenerator = $this->getDataGenerator()->get_plugin_generator('mod_workshop');
cron_setup_user();
// Let the students add submissions.
$this->workshop->switch_phase(\workshop::PHASE_SUBMISSION);
// Create some submissions.
foreach ($this->students as $student) {
$workshopgenerator->create_submission($this->workshop->id, $student->id);
}
// No allocations yet.
$this->assertEmpty($this->workshop->get_allocations());
/* Execute the tasks that will do the transition and allocation thing.
* We expect the workshop cron to do the whole work: change the phase and
* allocate the submissions.
*/
$this->execute_workshop_cron_task();
$workshopdb = $DB->get_record('workshop', ['id' => $this->workshop->id]);
$workshop = new \workshop($workshopdb, $this->workshopcm, $this->course);
$this->assertEquals(\workshop::PHASE_ASSESSMENT, $workshop->phase);
$this->assertNotEmpty($workshop->get_allocations());
}
/**
* No allocations are performed if the allocator is not enabled.
*/
public function test_that_allocator_is_not_executed_when_its_not_active(): void {
global $DB;
$this->resetAfterTest();
$this->setup_test_course_and_workshop();
$this->activate_switch_to_the_next_phase_after_submission_deadline();
$this->set_the_submission_deadline_in_the_past();
$workshopgenerator = $this->getDataGenerator()->get_plugin_generator('mod_workshop');
cron_setup_user();
// Let the students add submissions.
$this->workshop->switch_phase(\workshop::PHASE_SUBMISSION);
// Create some submissions.
foreach ($this->students as $student) {
$workshopgenerator->create_submission($this->workshop->id, $student->id);
}
// No allocations yet.
$this->assertEmpty($this->workshop->get_allocations());
// Transition to the assessment phase.
$this->execute_workshop_cron_task();
$workshopdb = $DB->get_record('workshop', ['id' => $this->workshop->id]);
$workshop = new \workshop($workshopdb, $this->workshopcm, $this->course);
// No allocations too.
$this->assertEquals(\workshop::PHASE_ASSESSMENT, $workshop->phase);
$this->assertEmpty($workshop->get_allocations());
}
/**
* Activates and configures the scheduled allocator for the workshop.
*/
private function activate_the_scheduled_allocator(): void {
$settings = \workshop_random_allocator_setting::instance_from_object((object)[
'numofreviews' => count($this->students),
'numper' => 1,
'removecurrentuser' => true,
'excludesamegroup' => false,
'assesswosubmission' => true,
'addselfassessment' => false
]);
$allocator = new \workshop_scheduled_allocator($this->workshop);
$storesettingsmethod = new \ReflectionMethod('workshop_scheduled_allocator', 'store_settings');
$storesettingsmethod->setAccessible(true);
$storesettingsmethod->invoke($allocator, true, true, $settings, new \workshop_allocation_result($allocator));
}
/**
* Creates a minimum common setup to execute tests:
*/
protected function setup_test_course_and_workshop(): void {
$this->setAdminUser();
$datagenerator = $this->getDataGenerator();
$this->course = $datagenerator->create_course();
$this->students = [];
for ($i = 0; $i < 10; $i++) {
$this->students[] = $datagenerator->create_and_enrol($this->course);
}
$workshopdb = $datagenerator->create_module('workshop', [
'course' => $this->course,
'name' => 'Test Workshop',
]);
$this->workshopcm = get_coursemodule_from_instance('workshop', $workshopdb->id, $this->course->id, false, MUST_EXIST);
$this->workshop = new \workshop($workshopdb, $this->workshopcm, $this->course);
}
/**
* Executes the workshop cron task.
*/
protected function execute_workshop_cron_task(): void {
ob_start();
$cron = new \mod_workshop\task\cron_task();
$cron->execute();
ob_end_clean();
}
/**
* Executes the scheduled allocator cron task.
*/
protected function execute_allocator_cron_task(): void {
ob_start();
$cron = new \workshopallocation_scheduled\task\cron_task();
$cron->execute();
ob_end_clean();
}
/**
* Activates the "Switch to the next phase after the submissions deadline" flag in the workshop.
*/
protected function activate_switch_to_the_next_phase_after_submission_deadline(): void {
global $DB;
$DB->set_field('workshop', 'phaseswitchassessment', 1, ['id' => $this->workshop->id]);
}
/**
* Sets the submission deadline in a past time.
*/
protected function set_the_submission_deadline_in_the_past(): void {
global $DB;
$DB->set_field('workshop', 'submissionend', time() - 1, ['id' => $this->workshop->id]);
}
}
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace mod_workshop\event;
/**
* This event is triggered when a phase is automatically switched, usually from cron_task.
*
* @property-read array $other {
* Extra information about the event.
*
* - int previousworkshopphase: Previous workshop phase.
* - int targetworkshopphase: Target workshop phase.
* }
*
* @package mod_workshop
* @copyright 2020 Universitat Jaume I <https://www.uji.es/>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class phase_automatically_switched extends \core\event\base {
/**
* Init method.
*
* @return void
*/
protected function init() {
$this->data['crud'] = 'u';
$this->data['edulevel'] = self::LEVEL_TEACHING;
$this->data['objecttable'] = 'workshop';
}
/**
* Returns description of what happened.
*
* @return string
*/
public function get_description() {
return "The phase of the workshop with course module id " .
"'$this->contextinstanceid' has been automatically switched from " .
"'{$this->other['previousworkshopphase']} to '{$this->other['currentworkshopphase']}'.";
}
/**
* Return localised event name.
*
* @return string
*/
public static function get_name() {
return get_string('eventphaseautomaticallyswitched', 'mod_workshop');
}
/**
* Get URL related to the action.
*
* @return \moodle_url
*/
public function get_url() {
return new \moodle_url('/mod/workshop/view.php', array('id' => $this->contextinstanceid));
}
/**
* Custom validation.
*
* @return void
* @throws \coding_exception
*/
protected function validate_data() {
parent::validate_data();
if (!isset($this->other['previousworkshopphase'])) {
throw new \coding_exception('The \'previousworkshopphase\' value must be set in other.');
}
if (!isset($this->other['targetworkshopphase'])) {
throw new \coding_exception('The \'targetworkshopphase\' value must be set in other.');
}
}
/**
* Map the objectid information in order to restore the event accurately. In this event
* objectid is the workshop id.
*
* @return array
*/
public static function get_objectid_mapping() {
return array('db' => 'workshop', 'restore' => 'workshop');
}
/**
* No need to map the 'other' field as it only stores phases and they don't need to be mapped.
*
* @return bool
*/
public static function get_other_mapping() {
return false;
}
}
......@@ -53,7 +53,6 @@ class cron_task extends \core\task\scheduled_task {
mtrace(' processing workshop subplugins ...');
// Now when the scheduled allocator had a chance to do its job.
// Check if there are some workshops to switch into the assessment phase.
$workshops = $DB->get_records_select("workshop",
"phase = 20 AND phaseswitchassessment = 1 AND submissionend > 0 AND submissionend < ?", [$now]);
......@@ -72,10 +71,11 @@ class cron_task extends \core\task\scheduled_task {
'context' => $workshop->context,
'courseid' => $workshop->course->id,
'other' => [
'workshopphase' => $workshop->phase
'targetworkshopphase' => $workshop->phase,
'previousworkshopphase' => \workshop::PHASE_SUBMISSION,
]
];
$event = \mod_workshop\event\phase_switched::create($params);
$event = \mod_workshop\event\phase_automatically_switched::create($params);
$event->trigger();
// Disable the automatic switching now so that it is not executed again by accident.
......
......@@ -73,4 +73,48 @@ class mod_workshop_cron_task_testcase extends advanced_testcase {
$this->assertStringContainsString('Processing automatic assessment phase switch', $output);
$this->assertEquals(workshop::PHASE_ASSESSMENT, $DB->get_field('workshop', 'phase', ['id' => $workshop->id]));
}
public function test_that_phase_automatically_switched_event_is_triggerd_when_phase_switchassesment_is_active(): void {
global $DB;
$this->resetAfterTest();
$this->setAdminUser();
// Set up a test workshop with 'Switch to the next phase after the submissions deadline' enabled.
$generator = $this->getDataGenerator();
$course = $generator->create_course();
$workshop = $generator->create_module('workshop', [
'course' => $course,
'name' => 'Test Workshop',
]);
$DB->update_record('workshop', [
'id' => $workshop->id,
'phase' => workshop::PHASE_SUBMISSION,
'phaseswitchassessment' => 1,
'submissionend' => time() - 1,
]);
// Execute the cron.
$eventsink = $this->redirectEvents();
ob_start();
cron_setup_user();
$cron = new \mod_workshop\task\cron_task();
$cron->execute();
ob_end_clean();
$events = array_filter($eventsink->get_events(), function ($event) {
return $event instanceof \mod_workshop\event\phase_automatically_switched;
});
$this->assertCount(1, $events);
$phaseswitchedevent = array_pop($events);
$this->assertArrayHasKey('previousworkshopphase', $phaseswitchedevent->other);
$this->assertArrayHasKey('targetworkshopphase', $phaseswitchedevent->other);
$this->assertEquals($phaseswitchedevent->other['previousworkshopphase'], \workshop::PHASE_SUBMISSION);
$this->assertEquals($phaseswitchedevent->other['targetworkshopphase'], \workshop::PHASE_ASSESSMENT);
}
}
This files describes API changes in /mod/workshop - activity modules,
information provided here is intended especially for developers.
=== 4.0 ===
* \mod_workshop\event\phase_automatically_switched event is triggered when the phase is automatically switched within
the cron task.
* A new method \workshopallocation_scheduled::phase_automatically_switched added to handle the
\mod_workshop\event\phase_automatically_switched event.
* A new boolean parameter, $checksubmissionphase, has been added to the workshop_scheduled_allocator::execute() method
in order to allow (or not) the allocation of submissions to be done in phases other than the SUBMISSION_PHASE.