MDL-66722 core_grades: Add simple direct grading to gradingpanel
authorAndrew Nicols <andrew@nicols.co.uk>
Wed, 25 Sep 2019 07:28:23 +0000 (15:28 +0800)
committerMathew May <mathewm@hotmail.co.nz>
Wed, 30 Oct 2019 02:23:40 +0000 (10:23 +0800)
Part of MDL-66074

13 files changed:
grade/amd/build/grades/grader/gradingpanel/point.min.js [new file with mode: 0644]
grade/amd/build/grades/grader/gradingpanel/point.min.js.map [new file with mode: 0644]
grade/amd/build/grades/grader/gradingpanel/repository.min.js [new file with mode: 0644]
grade/amd/build/grades/grader/gradingpanel/repository.min.js.map [new file with mode: 0644]
grade/amd/src/grades/grader/gradingpanel/point.js [new file with mode: 0644]
grade/amd/src/grades/grader/gradingpanel/repository.js [new file with mode: 0644]
grade/classes/grades/grader/gradingpanel/point/external/fetch.php [new file with mode: 0644]
grade/classes/grades/grader/gradingpanel/point/external/store.php [new file with mode: 0644]
grade/templates/grades/grader/gradingpanel/point.mustache [new file with mode: 0644]
grade/tests/grades_grader_gradingpanel_point_external_fetch_test.php [new file with mode: 0644]
grade/tests/grades_grader_gradingpanel_point_external_store_test.php [new file with mode: 0644]
lang/en/grades.php
lib/db/services.php

diff --git a/grade/amd/build/grades/grader/gradingpanel/point.min.js b/grade/amd/build/grades/grader/gradingpanel/point.min.js
new file mode 100644 (file)
index 0000000..a4191f0
Binary files /dev/null and b/grade/amd/build/grades/grader/gradingpanel/point.min.js differ
diff --git a/grade/amd/build/grades/grader/gradingpanel/point.min.js.map b/grade/amd/build/grades/grader/gradingpanel/point.min.js.map
new file mode 100644 (file)
index 0000000..6712014
Binary files /dev/null and b/grade/amd/build/grades/grader/gradingpanel/point.min.js.map differ
diff --git a/grade/amd/build/grades/grader/gradingpanel/repository.min.js b/grade/amd/build/grades/grader/gradingpanel/repository.min.js
new file mode 100644 (file)
index 0000000..d019b21
Binary files /dev/null and b/grade/amd/build/grades/grader/gradingpanel/repository.min.js differ
diff --git a/grade/amd/build/grades/grader/gradingpanel/repository.min.js.map b/grade/amd/build/grades/grader/gradingpanel/repository.min.js.map
new file mode 100644 (file)
index 0000000..2d08834
Binary files /dev/null and b/grade/amd/build/grades/grader/gradingpanel/repository.min.js.map differ
diff --git a/grade/amd/src/grades/grader/gradingpanel/point.js b/grade/amd/src/grades/grader/gradingpanel/point.js
new file mode 100644 (file)
index 0000000..29f0e5c
--- /dev/null
@@ -0,0 +1,34 @@
+// 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/>.
+
+/**
+ * Grading panel for simple direct grading.
+ *
+ * @module     core_grades/grades/grader/gradingpanel/point
+ * @package    core_grades
+ * @copyright  2019 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+import {saveGrade, fetchGrade} from './repository';
+// Note: We use jQuery.serializer here until we can rewrite Ajax to use XHR.send()
+import jQuery from 'jquery';
+
+export const fetchCurrentGrade = (...args) => fetchGrade('point')(...args);
+
+export const storeCurrentGrade = (component, context, itemname, userId, rootNode) => {
+    const form = rootNode.querySelector('form');
+    return saveGrade('point')(component, context, itemname, userId, jQuery(form).serialize());
+};
diff --git a/grade/amd/src/grades/grader/gradingpanel/repository.js b/grade/amd/src/grades/grader/gradingpanel/repository.js
new file mode 100644 (file)
index 0000000..65ade57
--- /dev/null
@@ -0,0 +1,49 @@
+// 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/>.
+
+/**
+ * Repository for simple direct grading panel.
+ *
+ * @module     core_grades/grades/grader/gradingpanel/repository
+ * @package    core_grades
+ * @copyright  2019 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+import {call as fetchMany} from 'core/ajax';
+
+export const fetchGrade = type => (component, contextid, itemname, gradeduserid) => {
+    return fetchMany([{
+        methodname: `core_grades_grader_gradingpanel_${type}_fetch`,
+        args: {
+            component,
+            contextid,
+            itemname,
+            gradeduserid,
+        },
+    }])[0];
+};
+
+export const saveGrade = type => (component, contextid, itemname, gradeduserid, formdata) => {
+    return fetchMany([{
+        methodname: `core_grades_grader_gradingpanel_${type}_store`,
+        args: {
+            component,
+            contextid,
+            itemname,
+            gradeduserid,
+            formdata,
+        },
+    }])[0];
+};
diff --git a/grade/classes/grades/grader/gradingpanel/point/external/fetch.php b/grade/classes/grades/grader/gradingpanel/point/external/fetch.php
new file mode 100644 (file)
index 0000000..6326008
--- /dev/null
@@ -0,0 +1,167 @@
+<?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/>.
+
+/**
+ * Web service functions relating to point grades and grading.
+ *
+ * @package    core_grades
+ * @copyright  2019 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+declare(strict_types = 1);
+
+namespace core_grades\grades\grader\gradingpanel\point\external;
+
+use coding_exception;
+use context;
+use core_user;
+use core_grades\component_gradeitem as gradeitem;
+use core_grades\component_gradeitems;
+use external_api;
+use external_function_parameters;
+use external_multiple_structure;
+use external_single_structure;
+use external_value;
+use external_warnings;
+use moodle_exception;
+use required_capability_exception;
+use stdClass;
+
+/**
+ * External grading panel point API
+ *
+ * @package    core_grades
+ * @copyright  2019 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class fetch extends external_api {
+
+    /**
+     * Describes the parameters for fetching the grading panel for a simple grade.
+     *
+     * @return external_function_parameters
+     * @since Moodle 3.8
+     */
+    public static function execute_parameters(): external_function_parameters {
+        return new external_function_parameters ([
+            'component' => new external_value(
+                PARAM_ALPHANUMEXT,
+                'The name of the component',
+                VALUE_REQUIRED
+            ),
+            'contextid' => new external_value(
+                PARAM_INT,
+                'The ID of the context being graded',
+                VALUE_REQUIRED
+            ),
+            'itemname' => new external_value(
+                PARAM_ALPHANUM,
+                'The grade item itemname being graded',
+                VALUE_REQUIRED
+            ),
+            'gradeduserid' => new external_value(
+                PARAM_INT,
+                'The ID of the user show',
+                VALUE_REQUIRED
+            ),
+        ]);
+    }
+
+    /**
+     * Fetch the data required to build a grading panel for a simple grade.
+     *
+     * @param string $component
+     * @param int $contextid
+     * @param string $itemname
+     * @param int $gradeduserid
+     * @return array
+     * @since Moodle 3.8
+     */
+    public static function execute(string $component, int $contextid, string $itemname, int $gradeduserid): array {
+        global $USER;
+
+        [
+            'component' => $component,
+            'contextid' => $contextid,
+            'itemname' => $itemname,
+            'gradeduserid' => $gradeduserid,
+        ] = self::validate_parameters(self::execute_parameters(), [
+            'component' => $component,
+            'contextid' => $contextid,
+            'itemname' => $itemname,
+            'gradeduserid' => $gradeduserid,
+        ]);
+
+        // Validate the context.
+        $context = context::instance_by_id($contextid);
+        self::validate_context($context);
+
+        // Validate that the supplied itemname is a gradable item.
+        if (!component_gradeitems::is_valid_itemname($component, $itemname)) {
+            throw new coding_exception("The '{$itemname}' item is not valid for the '{$component}' component");
+        }
+
+        // Fetch the gradeitem instance.
+        $gradeitem = gradeitem::instance($component, $context, $itemname);
+
+        if (!$gradeitem->is_using_direct_grading()) {
+            throw new moodle_exception("The {$itemname} item in {$component}/{$contextid} is not configured for direct grading");
+        }
+
+        // Fetch the actual data.
+        $gradeduser = \core_user::get_user($gradeduserid);
+        $grade = $gradeitem->get_grade_for_user($gradeduser, $USER);
+
+        return self::get_fetch_data($grade);
+    }
+
+    /**
+     * Get the data to be fetched.
+     *
+     * @param component_gradeitem $gradeitem
+     * @return array
+     */
+    public static function get_fetch_data(stdClass $grade): array {
+        return [
+            'templatename' => 'core_grades/grades/grader/gradingpanel/point',
+            'grade' => [
+                'grade' => $grade->grade,
+                'timecreated' => $grade->timecreated,
+                'timemodified' => $grade->timemodified,
+            ],
+            'warnings' => [],
+        ];
+    }
+
+    /**
+     * Describes the data returned from the external function.
+     *
+     * @return external_single_structure
+     * @since Moodle 3.8
+     */
+    public static function execute_returns(): external_single_structure {
+        return new external_single_structure([
+            'templatename' => new external_value(PARAM_SAFEPATH, 'The template to use when rendering this data'),
+            'grade' => new external_single_structure([
+                'grade' => new external_value(PARAM_FLOAT, 'The numeric grade'),
+                'timecreated' => new external_value(PARAM_INT, 'The time that the grade was created'),
+                'timemodified' => new external_value(PARAM_INT, 'The time that the grade was last updated'),
+            ]),
+            'warnings' => new external_warnings(),
+        ]);
+    }
+}
diff --git a/grade/classes/grades/grader/gradingpanel/point/external/store.php b/grade/classes/grades/grader/gradingpanel/point/external/store.php
new file mode 100644 (file)
index 0000000..4f54a33
--- /dev/null
@@ -0,0 +1,164 @@
+<?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/>.
+
+/**
+ * Web service functions relating to point grades and grading.
+ *
+ * @package    core_grades
+ * @copyright  2019 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+declare(strict_types = 1);
+
+namespace core_grades\grades\grader\gradingpanel\point\external;
+
+use coding_exception;
+use context;
+use core_user;
+use core_grades\component_gradeitem as gradeitem;
+use core_grades\component_gradeitems;
+use external_api;
+use external_function_parameters;
+use external_multiple_structure;
+use external_single_structure;
+use external_value;
+use external_warnings;
+use moodle_exception;
+use required_capability_exception;
+
+/**
+ * External grading panel point API
+ *
+ * @package    core_grades
+ * @copyright  2019 Andrew Nicols <andrew@nicols.co.uk>
+ * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class store extends external_api {
+
+    /**
+     * Describes the parameters for fetching the grading panel for a simple grade.
+     *
+     * @return external_function_parameters
+     * @since Moodle 3.8
+     */
+    public static function execute_parameters(): external_function_parameters {
+        return new external_function_parameters ([
+            'component' => new external_value(
+                PARAM_ALPHANUMEXT,
+                'The name of the component',
+                VALUE_REQUIRED
+            ),
+            'contextid' => new external_value(
+                PARAM_INT,
+                'The ID of the context being graded',
+                VALUE_REQUIRED
+            ),
+            'itemname' => new external_value(
+                PARAM_ALPHANUM,
+                'The grade item itemname being graded',
+                VALUE_REQUIRED
+            ),
+            'gradeduserid' => new external_value(
+                PARAM_INT,
+                'The ID of the user show',
+                VALUE_REQUIRED
+            ),
+            'formdata' => new external_value(
+                PARAM_RAW,
+                'The serialised form data representing the grade',
+                VALUE_REQUIRED
+            ),
+        ]);
+    }
+
+    /**
+     * Fetch the data required to build a grading panel for a simple grade.
+     *
+     * @param string $component
+     * @param int $contextid
+     * @param string $itemname
+     * @param int $gradeduserid
+     * @return array
+     * @since Moodle 3.8
+     */
+    public static function execute(string $component, int $contextid, string $itemname, int $gradeduserid, string $formdata): array {
+        global $USER;
+
+        [
+            'component' => $component,
+            'contextid' => $contextid,
+            'itemname' => $itemname,
+            'gradeduserid' => $gradeduserid,
+            'formdata' => $formdata,
+        ] = self::validate_parameters(self::execute_parameters(), [
+            'component' => $component,
+            'contextid' => $contextid,
+            'itemname' => $itemname,
+            'gradeduserid' => $gradeduserid,
+            'formdata' => $formdata,
+        ]);
+
+        // Validate the context.
+        $context = context::instance_by_id($contextid);
+        self::validate_context($context);
+
+        // Validate that the supplied itemname is a gradable item.
+        if (!component_gradeitems::is_valid_itemname($component, $itemname)) {
+            throw new coding_exception("The '{$itemname}' item is not valid for the '{$component}' component");
+        }
+
+        // Fetch the gradeitem instance.
+        $gradeitem = gradeitem::instance($component, $context, $itemname);
+
+        // Validate that this gradeitem is actually enabled.
+        if (!$gradeitem->is_grading_enabled()) {
+            throw new moodle_exception("Grading is not enabled for {$itemname} in this context");
+        }
+
+        // Fetch the record for the graded user.
+        $gradeduser = \core_user::get_user($gradeduserid);
+
+        // Require that this user can save grades.
+        $gradeitem->require_user_can_grade($gradeduser, $USER);
+
+        if (!$gradeitem->is_using_direct_grading()) {
+            throw new moodle_exception("The {$itemname} item in {$component}/{$contextid} is not configured for direct grading");
+        }
+
+        // Parse the serialised string into an object.
+        $data = [];
+        parse_str($formdata, $data);
+
+        // Grade.
+        $gradeitem->store_grade_from_formdata($gradeduser, $USER, (object) $data);
+
+        // Fetch the updated grade back out.
+        $grade = $gradeitem->get_grade_for_user($gradeduser, $USER);
+
+        return fetch::get_fetch_data($grade);
+    }
+
+    /**
+     * Describes the data returned from the external function.
+     *
+     * @return external_single_structure
+     * @since Moodle 3.8
+     */
+    public static function execute_returns(): external_single_structure {
+        return fetch::execute_returns();
+    }
+}
diff --git a/grade/templates/grades/grader/gradingpanel/point.mustache b/grade/templates/grades/grader/gradingpanel/point.mustache
new file mode 100644 (file)
index 0000000..ebf77c3
--- /dev/null
@@ -0,0 +1,35 @@
+{{!
+    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/>.
+}}
+{{!
+    @template core_grades/grades/grader/gradingpanel/point
+
+    Point-based grading template for use in the grading panel.
+
+    Context variables required for this template:
+
+    Example context (json):
+    {
+      "grade": 47
+    }
+}}
+<form>
+  <div class="form-group">
+    <label for="core_grades-grade-{{uniqid}}">{{#str}}grade, moodle{{/str}}</label>
+    <input class="form-control" type="number" name="grade" value="{{grade}}" id="core_grades-grade-{{uniqid}}" aria-describedby="core_grades-help-{{uniqid}}">
+    <small id="core_grades-help-{{uniqid}}" class="form-text text-muted">{{#str}}grade_help, core_grades{{/str}}</small>
+  </div>
+</form>
diff --git a/grade/tests/grades_grader_gradingpanel_point_external_fetch_test.php b/grade/tests/grades_grader_gradingpanel_point_external_fetch_test.php
new file mode 100644 (file)
index 0000000..66db17e
--- /dev/null
@@ -0,0 +1,200 @@
+<?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/>.
+
+/**
+ * Unit tests for core_grades\component_gradeitems;
+ *
+ * @package   core_grades
+ * @category  test
+ * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU Public License
+ */
+
+declare(strict_types = 1);
+
+namespace core_grades\grades\grader\gradingpanel\point\external;
+
+use advanced_testcase;
+use coding_exception;
+use core_grades\component_gradeitem;
+use external_api;
+use mod_forum\local\entities\forum as forum_entity;
+use moodle_exception;
+
+/**
+ * Unit tests for core_grades\component_gradeitems;
+ *
+ * @package   core_grades
+ * @category  test
+ * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class fetch_test extends advanced_testcase {
+
+    public static function setupBeforeClass(): void {
+        global $CFG;
+        require_once("{$CFG->libdir}/externallib.php");
+    }
+
+    /**
+     * Ensure that an execute with an invalid component is rejected.
+     */
+    public function test_execute_invalid_component(): void {
+        $this->resetAfterTest();
+        $user = $this->getDataGenerator()->create_user();
+        $this->setUser($user);
+
+        $this->expectException(coding_exception::class);
+        $this->expectExceptionMessage("The 'foo' item is not valid for the 'mod_invalid' component");
+        fetch::execute('mod_invalid', 1, 'foo', 2);
+    }
+
+    /**
+     * Ensure that an execute with an invalid itemname on a valid component is rejected.
+     */
+    public function test_execute_invalid_itemname(): void {
+        $this->resetAfterTest();
+        $user = $this->getDataGenerator()->create_user();
+        $this->setUser($user);
+
+        $this->expectException(coding_exception::class);
+        $this->expectExceptionMessage("The 'foo' item is not valid for the 'mod_forum' component");
+        fetch::execute('mod_forum', 1, 'foo', 2);
+    }
+
+    /**
+     * Ensure that an execute against a different grading method is rejected.
+     */
+    public function test_execute_incorrect_type(): void {
+        $this->resetAfterTest();
+
+        $forum = $this->get_forum_instance([
+            // Negative numbers mean a scale.
+            'grade_forum' => -1,
+        ]);
+        $course = $forum->get_course_record();
+        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'teacher');
+        $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+        $this->setUser($teacher);
+
+        $gradeitem = component_gradeitem::instance('mod_forum', $forum->get_context(), 'forum');
+
+        $this->expectException(moodle_exception::class);
+        $this->expectExceptionMessage("not configured for direct grading");
+        fetch::execute('mod_forum', (int) $forum->get_context()->id, 'forum', (int) $student->id);
+    }
+
+    /**
+     * Ensure that an execute against the correct grading method returns the current state of the user.
+     */
+    public function test_execute_fetch_empty(): void {
+        $this->resetAfterTest();
+
+        $forum = $this->get_forum_instance([
+            // Negative numbers mean a scale.
+            'grade_forum' => 5,
+        ]);
+        $course = $forum->get_course_record();
+        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'teacher');
+        $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+        $this->setUser($teacher);
+
+        $gradeitem = component_gradeitem::instance('mod_forum', $forum->get_context(), 'forum');
+
+        $result = fetch::execute('mod_forum', (int) $forum->get_context()->id, 'forum', (int) $student->id);
+        $result = external_api::clean_returnvalue(fetch::execute_returns(), $result);
+
+        $this->assertIsArray($result);
+        $this->assertArrayHasKey('templatename', $result);
+
+        $this->assertEquals('core_grades/grades/grader/gradingpanel/point', $result['templatename']);
+
+        $this->assertArrayHasKey('grade', $result);
+        $this->assertIsArray($result['grade']);
+        $this->assertArrayHasKey('grade', $result['grade']);
+        $this->assertEmpty($result['grade']['grade']);
+        $this->assertArrayHasKey('timecreated', $result['grade']);
+        $this->assertIsInt($result['grade']['timecreated']);
+        $this->assertArrayHasKey('timemodified', $result['grade']);
+        $this->assertIsInt($result['grade']['timemodified']);
+
+        $this->assertArrayHasKey('warnings', $result);
+        $this->assertIsArray($result['warnings']);
+        $this->assertEmpty($result['warnings']);
+    }
+
+    /**
+     * Ensure that an execute against the correct grading method returns the current state of the user.
+     */
+    public function test_execute_fetch_graded(): void {
+        $this->resetAfterTest();
+
+        $forum = $this->get_forum_instance([
+            // Negative numbers mean a scale.
+            'grade_forum' => 5,
+        ]);
+        $course = $forum->get_course_record();
+        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'teacher');
+        $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+        $this->setUser($teacher);
+
+        $gradeitem = component_gradeitem::instance('mod_forum', $forum->get_context(), 'forum');
+        $gradeitem->store_grade_from_formdata($student, $teacher, (object) [
+            'grade' => 4,
+        ]);
+
+        $result = fetch::execute('mod_forum', (int) $forum->get_context()->id, 'forum', (int) $student->id);
+        $result = external_api::clean_returnvalue(fetch::execute_returns(), $result);
+
+        $this->assertIsArray($result);
+        $this->assertArrayHasKey('templatename', $result);
+
+        $this->assertEquals('core_grades/grades/grader/gradingpanel/point', $result['templatename']);
+
+        $this->assertArrayHasKey('grade', $result);
+        $this->assertIsArray($result['grade']);
+        $this->assertArrayHasKey('grade', $result['grade']);
+        $this->assertIsFloat($result['grade']['grade']);
+        $this->assertEquals(grade_floatval(unformat_float(4)), $result['grade']['grade']);
+        $this->assertArrayHasKey('timecreated', $result['grade']);
+        $this->assertIsInt($result['grade']['timecreated']);
+        $this->assertArrayHasKey('timemodified', $result['grade']);
+        $this->assertIsInt($result['grade']['timemodified']);
+
+        $this->assertArrayHasKey('warnings', $result);
+        $this->assertIsArray($result['warnings']);
+        $this->assertEmpty($result['warnings']);
+    }
+
+    /**
+     * Get a forum instance.
+     *
+     * @param array $config
+     * @return forum_entity
+     */
+    protected function get_forum_instance(array $config = []): forum_entity {
+        $this->resetAfterTest();
+
+        $datagenerator = $this->getDataGenerator();
+        $course = $datagenerator->create_course();
+        $forum = $datagenerator->create_module('forum', array_merge($config, ['course' => $course->id]));
+
+        $vaultfactory = \mod_forum\local\container::get_vault_factory();
+        $vault = $vaultfactory->get_forum_vault();
+
+        return $vault->get_from_id((int) $forum->id);
+    }
+}
diff --git a/grade/tests/grades_grader_gradingpanel_point_external_store_test.php b/grade/tests/grades_grader_gradingpanel_point_external_store_test.php
new file mode 100644 (file)
index 0000000..b9c4760
--- /dev/null
@@ -0,0 +1,315 @@
+<?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/>.
+
+/**
+ * Unit tests for core_grades\component_gradeitems;
+ *
+ * @package   core_grades
+ * @category  test
+ * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU Public License
+ */
+
+declare(strict_types = 1);
+
+namespace core_grades\grades\grader\gradingpanel\point\external;
+
+use advanced_testcase;
+use coding_exception;
+use core_grades\component_gradeitem;
+use external_api;
+use mod_forum\local\entities\forum as forum_entity;
+use moodle_exception;
+use grade_grade;
+use grade_item;
+
+/**
+ * Unit tests for core_grades\component_gradeitems;
+ *
+ * @package   core_grades
+ * @category  test
+ * @copyright 2019 Andrew Nicols <andrew@nicols.co.uk>
+ * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+class store_test extends advanced_testcase {
+
+    public static function setupBeforeClass(): void {
+        global $CFG;
+        require_once("{$CFG->libdir}/externallib.php");
+    }
+
+    /**
+     * Ensure that an execute with an invalid component is rejected.
+     */
+    public function test_execute_invalid_component(): void {
+        $this->resetAfterTest();
+        $user = $this->getDataGenerator()->create_user();
+        $this->setUser($user);
+
+        $this->expectException(coding_exception::class);
+        $this->expectExceptionMessage("The 'foo' item is not valid for the 'mod_invalid' component");
+        store::execute('mod_invalid', 1, 'foo', 2, 'formdata');
+    }
+
+    /**
+     * Ensure that an execute with an invalid itemname on a valid component is rejected.
+     */
+    public function test_execute_invalid_itemname(): void {
+        $this->resetAfterTest();
+        $user = $this->getDataGenerator()->create_user();
+        $this->setUser($user);
+
+        $this->expectException(coding_exception::class);
+        $this->expectExceptionMessage("The 'foo' item is not valid for the 'mod_forum' component");
+        store::execute('mod_forum', 1, 'foo', 2, 'formdata');
+    }
+
+    /**
+     * Ensure that an execute against a different grading method is rejected.
+     */
+    public function test_execute_incorrect_type(): void {
+        $this->resetAfterTest();
+
+        $forum = $this->get_forum_instance([
+            // Negative numbers mean a scale.
+            'grade_forum' => -1,
+        ]);
+        $course = $forum->get_course_record();
+        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'teacher');
+        $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+        $this->setUser($teacher);
+
+        $gradeitem = component_gradeitem::instance('mod_forum', $forum->get_context(), 'forum');
+
+        $this->expectException(moodle_exception::class);
+        $this->expectExceptionMessage("not configured for direct grading");
+        store::execute('mod_forum', (int) $forum->get_context()->id, 'forum', (int) $student->id, 'formdata');
+    }
+
+    /**
+     * Ensure that an execute against a different grading method is rejected.
+     */
+    public function test_execute_disabled(): void {
+        $this->resetAfterTest();
+
+        $forum = $this->get_forum_instance();
+        $course = $forum->get_course_record();
+        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'teacher');
+        $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+        $this->setUser($teacher);
+
+        $gradeitem = component_gradeitem::instance('mod_forum', $forum->get_context(), 'forum');
+
+        $this->expectException(moodle_exception::class);
+        $this->expectExceptionMessage("Grading is not enabled");
+        store::execute('mod_forum', (int) $forum->get_context()->id, 'forum', (int) $student->id, 'formdata');
+    }
+
+    /**
+     * Ensure that an execute against the correct grading method returns the current state of the user.
+     */
+    public function test_execute_store_empty(): void {
+        $this->resetAfterTest();
+
+        $forum = $this->get_forum_instance([
+            // Negative numbers mean a scale.
+            'grade_forum' => 5,
+        ]);
+        $course = $forum->get_course_record();
+        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'teacher');
+        $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+        $this->setUser($teacher);
+
+        $formdata = [
+            'grade' => null,
+        ];
+
+        $gradeitem = component_gradeitem::instance('mod_forum', $forum->get_context(), 'forum');
+
+        $result = store::execute('mod_forum', (int) $forum->get_context()->id, 'forum', (int) $student->id, http_build_query($formdata));
+        $result = external_api::clean_returnvalue(store::execute_returns(), $result);
+
+        // The result should still be empty.
+        $this->assertIsArray($result);
+        $this->assertArrayHasKey('templatename', $result);
+
+        $this->assertEquals('core_grades/grades/grader/gradingpanel/point', $result['templatename']);
+
+        $this->assertArrayHasKey('grade', $result);
+        $this->assertIsArray($result['grade']);
+        $this->assertArrayHasKey('grade', $result['grade']);
+        $this->assertEmpty($result['grade']['grade']);
+        $this->assertArrayHasKey('timecreated', $result['grade']);
+        $this->assertIsInt($result['grade']['timecreated']);
+        $this->assertArrayHasKey('timemodified', $result['grade']);
+        $this->assertIsInt($result['grade']['timemodified']);
+
+        $this->assertArrayHasKey('warnings', $result);
+        $this->assertIsArray($result['warnings']);
+        $this->assertEmpty($result['warnings']);
+
+        // Compare against the grade stored in the database.
+        $storedgradeitem = grade_item::fetch([
+            'courseid' => $forum->get_course_id(),
+            'itemtype' => 'mod',
+            'itemmodule' => 'forum',
+            'iteminstance' => $forum->get_id(),
+            'itemnumber' => $gradeitem->get_grade_itemid(),
+        ]);
+        $storedgrade = grade_grade::fetch([
+            'userid' => $student->id,
+            'itemid' => $storedgradeitem->id,
+        ]);
+
+        $this->assertEmpty($storedgrade->rawgrade);
+    }
+
+    /**
+     * Ensure that an execute against the correct grading method returns the current state of the user.
+     */
+    public function test_execute_store_graded(): void {
+        $this->resetAfterTest();
+
+        $forum = $this->get_forum_instance([
+            // Negative numbers mean a scale.
+            'grade_forum' => 5,
+        ]);
+        $course = $forum->get_course_record();
+        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'teacher');
+        $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+        $this->setUser($teacher);
+
+        $formdata = [
+            'grade' => 4,
+        ];
+        $formattedvalue = grade_floatval(unformat_float(4));
+
+        $gradeitem = component_gradeitem::instance('mod_forum', $forum->get_context(), 'forum');
+
+        $result = store::execute('mod_forum', (int) $forum->get_context()->id, 'forum', (int) $student->id, http_build_query($formdata));
+        $result = external_api::clean_returnvalue(store::execute_returns(), $result);
+
+        // The result should still be empty.
+        $this->assertIsArray($result);
+        $this->assertArrayHasKey('templatename', $result);
+
+        $this->assertEquals('core_grades/grades/grader/gradingpanel/point', $result['templatename']);
+
+        $this->assertArrayHasKey('grade', $result);
+        $this->assertIsArray($result['grade']);
+        $this->assertArrayHasKey('grade', $result['grade']);
+        $this->assertEquals($formattedvalue, $result['grade']['grade']);
+        $this->assertArrayHasKey('timecreated', $result['grade']);
+        $this->assertIsInt($result['grade']['timecreated']);
+        $this->assertArrayHasKey('timemodified', $result['grade']);
+        $this->assertIsInt($result['grade']['timemodified']);
+
+        $this->assertArrayHasKey('warnings', $result);
+        $this->assertIsArray($result['warnings']);
+        $this->assertEmpty($result['warnings']);
+
+        // Compare against the grade stored in the database.
+        $storedgradeitem = grade_item::fetch([
+            'courseid' => $forum->get_course_id(),
+            'itemtype' => 'mod',
+            'itemmodule' => 'forum',
+            'iteminstance' => $forum->get_id(),
+            'itemnumber' => $gradeitem->get_grade_itemid(),
+        ]);
+        $storedgrade = grade_grade::fetch([
+            'userid' => $student->id,
+            'itemid' => $storedgradeitem->id,
+        ]);
+
+        $this->assertEquals($formattedvalue, $storedgrade->rawgrade);
+    }
+
+    /**
+     * Ensure that an out-of-range value is rejected.
+     *
+     * @dataProvider execute_out_of_range_provider
+     * @param int $maxvalue The max value of the forum
+     * @param int $suppliedvalue The value that was submitted
+     */
+    public function test_execute_store_out_of__range(int $maxvalue, int $suppliedvalue): void {
+        $this->resetAfterTest();
+
+        $forum = $this->get_forum_instance([
+            // Negative numbers mean a scale.
+            'grade_forum' => $maxvalue,
+        ]);
+        $course = $forum->get_course_record();
+        $teacher = $this->getDataGenerator()->create_and_enrol($course, 'teacher');
+        $student = $this->getDataGenerator()->create_and_enrol($course, 'student');
+        $this->setUser($teacher);
+
+        $formdata = [
+            'grade' => $suppliedvalue,
+        ];
+
+        $gradeitem = component_gradeitem::instance('mod_forum', $forum->get_context(), 'forum');
+
+        $this->expectException(moodle_exception::class);
+        $this->expectExceptionMessage("Invalid grade '{$suppliedvalue}' provided. Grades must be between 0 and {$maxvalue}.");
+        store::execute('mod_forum', (int) $forum->get_context()->id, 'forum', (int) $student->id, http_build_query($formdata));
+    }
+
+    /**
+     * Data provider for out of range tests.
+     *
+     * @return array
+     */
+    public function execute_out_of_range_provider(): array {
+        return [
+            'above' => [
+                'max' => 100,
+                'supplied' => 101,
+            ],
+            'above just' => [
+                'max' => 100,
+                'supplied' => 101.001,
+            ],
+            'below' => [
+                'max' => 100,
+                'supplied' => -100,
+            ],
+            '-1' => [
+                'max' => 100,
+                'supplied' => -1,
+            ],
+        ];
+    }
+
+
+    /**
+     * Get a forum instance.
+     *
+     * @param array $config
+     * @return forum_entity
+     */
+    protected function get_forum_instance(array $config = []): forum_entity {
+        $this->resetAfterTest();
+
+        $datagenerator = $this->getDataGenerator();
+        $course = $datagenerator->create_course();
+        $forum = $datagenerator->create_module('forum', array_merge($config, ['course' => $course->id]));
+
+        $vaultfactory = \mod_forum\local\container::get_vault_factory();
+        $vault = $vaultfactory->get_forum_vault();
+
+        return $vault->get_from_id((int) $forum->id);
+    }
+}
index ff8fc09..8afc3ed 100644 (file)
@@ -245,6 +245,7 @@ $string['full'] = 'Full';
 $string['fullmode'] = 'Change to full view';
 $string['generalsettings'] = 'General settings';
 $string['grade'] = 'Grade';
 $string['fullmode'] = 'Change to full view';
 $string['generalsettings'] = 'General settings';
 $string['grade'] = 'Grade';
+$string['grade_help'] = 'The grade to award this person for their work.';
 $string['gradeadministration'] = 'Grade administration';
 $string['gradealreadyupdated'] = '{$a} grades have not been imported because the grades in the import file are older than in the grader report. To proceed with the grade import anyway, use the force import option.';
 $string['gradeanalysis'] = 'Grade analysis';
 $string['gradeadministration'] = 'Grade administration';
 $string['gradealreadyupdated'] = '{$a} grades have not been imported because the grades in the import file are older than in the grader report. To proceed with the grade import anyway, use the force import option.';
 $string['gradeanalysis'] = 'Grade analysis';
index 147079d..a0a34c6 100644 (file)
@@ -810,6 +810,23 @@ $functions = array(
         'description' => 'Update a grade item and associated student grades.',
         'type' => 'write',
     ),
         'description' => 'Update a grade item and associated student grades.',
         'type' => 'write',
     ),
+    'core_grades_grader_gradingpanel_point_fetch' => [
+        'classname' => 'core_grades\\grades\\grader\\gradingpanel\\point\\external\\fetch',
+        'methodname' => 'execute',
+        'description' => 'Fetch the data required to display the grader grading panel for simple grading, ' .
+            'creating the grade item if required',
+        'type' => 'write',
+        'ajax' => true,
+        'services' => [MOODLE_OFFICIAL_MOBILE_SERVICE],
+    ],
+    'core_grades_grader_gradingpanel_point_store' => [
+        'classname' => 'core_grades\\grades\\grader\\gradingpanel\\point\\external\\store',
+        'methodname' => 'execute',
+        'description' => 'Store the data required to display the grader grading panel for simple grading',
+        'type' => 'write',
+        'ajax' => true,
+        'services' => [MOODLE_OFFICIAL_MOBILE_SERVICE],
+    ],
     'core_grading_get_definitions' => array(
         'classname' => 'core_grading_external',
         'methodname' => 'get_definitions',
     'core_grading_get_definitions' => array(
         'classname' => 'core_grading_external',
         'methodname' => 'get_definitions',