MDL-75165 notes: implement notes datasource for custom reporting.

Create entity definition containing report elements for notes. Add
new report source joining the entity to the user/course entities to
provide data for the reportbuilder editor.
This commit is contained in:
Paul Holden
2022-10-19 14:46:21 +01:00
parent f1c3aca7ea
commit a641a8dfa2
4 changed files with 617 additions and 0 deletions
+2
View File
@@ -29,6 +29,7 @@ $string['addbulknotesingle'] = 'Add a new note to 1 person';
$string['addbulknotedone'] = 'Note added to {$a} people';
$string['addbulknotedonesingle'] = 'Note added to 1 person';
$string['addnewnoteselect'] = 'Select users to write notes about';
$string['author'] = 'Author';
$string['bynameondate'] = 'by {$a->name} - {$a->date}';
$string['configenablenotes'] = 'Enable storing of notes about individual users.';
$string['content'] = 'Content';
@@ -71,6 +72,7 @@ $string['publishstate_help'] = 'A note\'s context determines who can see the not
* Personal - The note will be visible only to you
* Course - The note will be visible to teachers in this course
* Site - The note will be visible to teachers in all courses';
$string['recipient'] = 'Recipient';
$string['site'] = 'site';
$string['sitenotes'] = 'Site notes';
$string['unknown'] = 'unknown';
@@ -0,0 +1,134 @@
<?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/>.
declare(strict_types=1);
namespace core_notes\reportbuilder\datasource;
use lang_string;
use core_reportbuilder\datasource;
use core_reportbuilder\local\entities\{course, user};
use core_notes\reportbuilder\local\entities\note;
defined('MOODLE_INTERNAL') || die;
global $CFG;
require_once("{$CFG->dirroot}/notes/lib.php");
/**
* Notes datasource
*
* @package core_notes
* @copyright 2022 Paul Holden <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class notes extends datasource {
/**
* Return user friendly name of the report source
*
* @return string
*/
public static function get_name(): string {
return get_string('notes', 'core_notes');
}
/**
* Initialise report
*/
protected function initialise(): void {
$noteentity = new note();
$postalias = $noteentity->get_table_alias('post');
$this->set_main_table('post', $postalias);
$this->add_base_condition_simple("{$postalias}.module", 'notes');
$this->add_entity($noteentity);
// Join the user entity to represent the note recipient.
$recipiententity = (new user())
->set_entity_name('recipient')
->set_entity_title(new lang_string('recipient', 'core_notes'));
$recipientalias = $recipiententity->get_table_alias('user');
$this->add_entity($recipiententity->add_join("
LEFT JOIN {user} {$recipientalias}
ON {$recipientalias}.id = {$postalias}.userid")
);
// Join the user entity to represent the note author. Override all entity table aliases to avoid clash with first instance.
$authorentity = (new user())
->set_entity_name('author')
->set_entity_title(new lang_string('author', 'core_notes'))
->set_table_aliases([
'user' => 'au',
'context' => 'auctx',
]);
$this->add_entity($authorentity->add_join("
LEFT JOIN {user} au
ON au.id = {$postalias}.usermodified")
);
// Join the course entity for course notes.
$courseentity = new course();
$coursealias = $courseentity->get_table_alias('course');
$this->add_entity($courseentity->add_join("
LEFT JOIN {course} {$coursealias}
ON {$coursealias}.id = {$postalias}.courseid
AND {$postalias}.publishstate = '" . NOTES_STATE_PUBLIC . "'")
);
// Add report elements from each of the entities we added to the report.
$this->add_all_from_entities();
}
/**
* Return the columns that will be added to the report upon creation
*
* @return string[]
*/
public function get_default_columns(): array {
return [
'recipient:fullname',
'note:publishstate',
'course:fullname',
'note:content',
];
}
/**
* Return the filters that will be added to the report upon creation
*
* @return string[]
*/
public function get_default_filters(): array {
return [
'recipient:fullname',
];
}
/**
* Return the conditions that will be added to the report upon creation
*
* @return string[]
*/
public function get_default_conditions(): array {
return [
'note:publishstate',
'course:fullname',
'recipient:fullname',
];
}
}
@@ -0,0 +1,229 @@
<?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/>.
declare(strict_types=1);
namespace core_notes\reportbuilder\local\entities;
use lang_string;
use stdClass;
use core_reportbuilder\local\entities\base;
use core_reportbuilder\local\filters\{date, select, text};
use core_reportbuilder\local\helpers\format;
use core_reportbuilder\local\report\{column, filter};
defined('MOODLE_INTERNAL') || die;
global $CFG;
require_once("{$CFG->dirroot}/notes/lib.php");
/**
* Note entity
*
* @package core_notes
* @copyright 2022 Paul Holden <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class note extends base {
/**
* Database tables that this entity uses and their default aliases
*
* @return array
*/
protected function get_default_table_aliases(): array {
return ['post' => 'np'];
}
/**
* The default title for this entity
*
* @return lang_string
*/
protected function get_default_entity_title(): lang_string {
return new lang_string('note', 'core_notes');
}
/**
* Initialise the entity
*
* @return base
*/
public function initialise(): base {
$columns = $this->get_all_columns();
foreach ($columns as $column) {
$this->add_column($column);
}
// All the filters defined by the entity can also be used as conditions.
$filters = $this->get_all_filters();
foreach ($filters as $filter) {
$this
->add_filter($filter)
->add_condition($filter);
}
return $this;
}
/**
* Returns list of all available columns
*
* @return column[]
*/
protected function get_all_columns(): array {
global $DB;
$postalias = $this->get_table_alias('post');
// Content.
$contentfieldsql = "{$postalias}.content";
if ($DB->get_dbfamily() === 'oracle') {
$contentfieldsql = $DB->sql_order_by_text($contentfieldsql, 1024);
}
$columns[] = (new column(
'content',
new lang_string('content', 'core_notes'),
$this->get_entity_name()
))
->add_joins($this->get_joins())
->set_type(column::TYPE_LONGTEXT)
->add_field($contentfieldsql, 'content')
->add_field("{$postalias}.format")
->add_callback(static function(?string $content, stdClass $note): string {
if ($content === null) {
return '';
}
return format_text($content, $note->format);
});
// Publish state.
$columns[] = (new column(
'publishstate',
new lang_string('publishstate', 'core_notes'),
$this->get_entity_name()
))
->add_joins($this->get_joins())
->set_type(column::TYPE_TEXT)
->add_fields("{$postalias}.publishstate")
->set_is_sortable(true)
->add_callback(static function(string $publishstate): string {
$states = [
NOTES_STATE_SITE => new lang_string('sitenotes', 'core_notes'),
NOTES_STATE_PUBLIC => new lang_string('coursenotes', 'core_notes'),
NOTES_STATE_DRAFT => new lang_string('personalnotes', 'core_notes'),
];
return (string) ($states[$publishstate] ?? $publishstate);
});
// Time created.
$columns[] = (new column(
'timecreated',
new lang_string('timecreated', 'core_reportbuilder'),
$this->get_entity_name()
))
->add_joins($this->get_joins())
->set_type(column::TYPE_TIMESTAMP)
->add_fields("{$postalias}.created")
->set_is_sortable(true)
->add_callback([format::class, 'userdate']);
// Time modified.
$columns[] = (new column(
'timemodified',
new lang_string('timemodified', 'core_reportbuilder'),
$this->get_entity_name()
))
->add_joins($this->get_joins())
->set_type(column::TYPE_TIMESTAMP)
->add_fields("{$postalias}.lastmodified")
->set_is_sortable(true)
->add_callback([format::class, 'userdate']);
return $columns;
}
/**
* Return list of all available filters
*
* @return filter[]
*/
protected function get_all_filters(): array {
global $DB;
$postalias = $this->get_table_alias('post');
// Content.
$filters[] = (new filter(
text::class,
'content',
new lang_string('content', 'core_notes'),
$this->get_entity_name(),
$DB->sql_cast_to_char("{$postalias}.content")
))
->add_joins($this->get_joins());
// Publish state.
$filters[] = (new filter(
select::class,
'publishstate',
new lang_string('publishstate', 'core_notes'),
$this->get_entity_name(),
"{$postalias}.publishstate"
))
->add_joins($this->get_joins())
->set_options([
NOTES_STATE_SITE => new lang_string('sitenotes', 'core_notes'),
NOTES_STATE_PUBLIC => new lang_string('coursenotes', 'core_notes'),
NOTES_STATE_DRAFT => new lang_string('personalnotes', 'core_notes'),
]);
// Time created.
$filters[] = (new filter(
date::class,
'timecreated',
new lang_string('timecreated', 'core_reportbuilder'),
$this->get_entity_name(),
"{$postalias}.created"
))
->add_joins($this->get_joins())
->set_limited_operators([
date::DATE_ANY,
date::DATE_CURRENT,
date::DATE_LAST,
date::DATE_RANGE,
]);
// Time modified.
$filters[] = (new filter(
date::class,
'timemodified',
new lang_string('timemodified', 'core_reportbuilder'),
$this->get_entity_name(),
"{$postalias}.lastmodified"
))
->add_joins($this->get_joins())
->set_limited_operators([
date::DATE_ANY,
date::DATE_CURRENT,
date::DATE_LAST,
date::DATE_RANGE,
]);
return $filters;
}
}
@@ -0,0 +1,252 @@
<?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/>.
declare(strict_types=1);
namespace core_notes\reportbuilder\datasource;
use core_collator;
use core_notes_generator;
use core_reportbuilder_generator;
use core_reportbuilder_testcase;
use core_reportbuilder\local\filters\{date, select, text};
defined('MOODLE_INTERNAL') || die();
global $CFG;
require_once("{$CFG->dirroot}/reportbuilder/tests/helpers.php");
/**
* Unit tests for notes datasource
*
* @package core_notes
* @covers \core_notes\reportbuilder\datasource\notes
* @copyright 2022 Paul Holden <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class notes_test extends core_reportbuilder_testcase {
/**
* Load required test libraries
*/
public static function setUpBeforeClass(): void {
global $CFG;
require_once("{$CFG->dirroot}/notes/lib.php");
}
/**
* Test default datasource
*/
public function test_datasource_default(): void {
$this->resetAfterTest();
/** @var core_notes_generator $notesgenerator */
$notesgenerator = $this->getDataGenerator()->get_plugin_generator('core_notes');
$course = $this->getDataGenerator()->create_course();
$usercoursenote = $this->getDataGenerator()->create_and_enrol($course);
$notesgenerator->create_instance(['courseid' => $course->id, 'userid' => $usercoursenote->id, 'content' => 'Course',
'publishstate' => NOTES_STATE_PUBLIC]);
$userpersonalnote = $this->getDataGenerator()->create_user();
$notesgenerator->create_instance(['courseid' => $course->id, 'userid' => $userpersonalnote->id, 'content' => 'Personal',
'publishstate' => NOTES_STATE_DRAFT]);
$usersitenote = $this->getDataGenerator()->create_user();
$notesgenerator->create_instance(['courseid' => $course->id, 'userid' => $usersitenote->id, 'content' => 'Site',
'publishstate' => NOTES_STATE_SITE]);
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
$report = $generator->create_report(['name' => 'Notes', 'source' => notes::class, 'default' => 1]);
$content = $this->get_custom_report_content($report->get('id'));
$this->assertCount(3, $content);
// Consistent order (course, personal, site), just in case.
core_collator::asort_array_of_arrays_by_key($content, 'c1_publishstate');
$content = array_values($content);
// Default columns are recipient, publishstate, course, note.
$this->assertEquals([
[fullname($usercoursenote), 'Course notes', $course->fullname, 'Course'],
[fullname($userpersonalnote), 'Personal notes', '', 'Personal'],
[fullname($usersitenote), 'Site notes', '', 'Site'],
], array_map('array_values', $content));
}
/**
* Test datasource columns that aren't added by default
*/
public function test_datasource_non_default_columns(): void {
global $DB;
$this->resetAfterTest();
$recipient = $this->getDataGenerator()->create_user();
$author = $this->getDataGenerator()->create_user();
$this->setUser($author);
/** @var core_notes_generator $notesgenerator */
$notesgenerator = $this->getDataGenerator()->get_plugin_generator('core_notes');
$note = $notesgenerator->create_instance(['courseid' => SITEID, 'publishstate' => NOTES_STATE_SITE, 'content' => 'Cool',
'userid' => $recipient->id,
]);
// Manually update the created/modified date of the note.
$note->created = 1654038000;
$note->lastmodified = $note->created + HOURSECS;
$DB->update_record('post', $note);
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
$report = $generator->create_report(['name' => 'Notes', 'source' => notes::class, 'default' => 0]);
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'note:content']);
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'note:timecreated']);
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'note:timemodified']);
// Ensure we can add data from both user entities.
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'recipient:fullname']);
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'author:fullname']);
$content = $this->get_custom_report_content($report->get('id'));
$this->assertCount(1, $content);
$this->assertEquals([
'Cool',
userdate($note->created),
userdate($note->lastmodified),
fullname($recipient),
fullname($author),
], array_values($content[0]));
}
/**
* Data provider for {@see test_datasource_filters}
*
* @return array[]
*/
public function datasource_filters_provider(): array {
return [
'Filter content' => ['content', 'Cool', 'note:content', [
'note:content_operator' => text::IS_EQUAL_TO,
'note:content_value' => 'Cool',
], true],
'Filter content (no match)' => ['content', 'Cool', 'note:content', [
'note:content_operator' => text::DOES_NOT_CONTAIN,
'note:content_value' => 'Cool',
], false],
'Filter publish state' => ['publishstate', 'site', 'note:publishstate', [
'note:publishstate_operator' => select::EQUAL_TO,
'note:publishstate_value' => 'site',
], true],
'Filter publish state (no match)' => ['publishstate', 'site', 'note:publishstate', [
'note:publishstate_operator' => select::EQUAL_TO,
'note:publishstate_value' => 'public',
], false],
'Filter time created' => ['created', 1654038000, 'note:timecreated', [
'note:timecreated_operator' => date::DATE_RANGE,
'note:timecreated_from' => 1622502000,
], true],
'Filter time created (no match)' => ['created', 1654038000, 'note:timecreated', [
'note:timecreated_operator' => date::DATE_RANGE,
'note:timecreated_to' => 1622502000,
], false],
'Filter time modified' => ['lastmodified', 1654038000, 'note:timemodified', [
'note:timemodified_operator' => date::DATE_RANGE,
'note:timemodified_from' => 1622502000,
], true],
'Filter time modified (no match)' => ['lastmodified', 1654038000, 'note:timemodified', [
'note:timemodified_operator' => date::DATE_RANGE,
'note:timemodified_to' => 1622502000,
], false],
];
}
/**
* Test datasource filters
*
* @param string $field
* @param mixed $value
* @param string $filtername
* @param array $filtervalues
* @param bool $expectmatch
*
* @dataProvider datasource_filters_provider
*/
public function test_datasource_filters(
string $field,
$value,
string $filtername,
array $filtervalues,
bool $expectmatch
): void {
global $DB;
$this->resetAfterTest();
$recipient = $this->getDataGenerator()->create_user();
/** @var core_notes_generator $notesgenerator */
$notesgenerator = $this->getDataGenerator()->get_plugin_generator('core_notes');
// Create default note, then manually override one of it's properties to use for filtering.
$note = $notesgenerator->create_instance(['courseid' => SITEID, 'userid' => $recipient->id]);
$DB->set_field('post', $field, $value, ['id' => $note->id]);
/** @var core_reportbuilder_generator $generator */
$generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
// Create report containing single recipient column, and given filter.
$report = $generator->create_report(['name' => 'Notes', 'source' => notes::class, 'default' => 0]);
$generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'recipient:fullname']);
// Add filter, set it's values.
$generator->create_filter(['reportid' => $report->get('id'), 'uniqueidentifier' => $filtername]);
$content = $this->get_custom_report_content($report->get('id'), 0, $filtervalues);
if ($expectmatch) {
$this->assertCount(1, $content);
$this->assertEquals(fullname($recipient), reset($content[0]));
} else {
$this->assertEmpty($content);
}
}
/**
* Stress test datasource
*
* In order to execute this test PHPUNIT_LONGTEST should be defined as true in phpunit.xml or directly in config.php
*/
public function test_stress_datasource(): void {
if (!PHPUNIT_LONGTEST) {
$this->markTestSkipped('PHPUNIT_LONGTEST is not defined');
}
$this->resetAfterTest();
$recipient = $this->getDataGenerator()->create_user();
/** @var core_notes_generator $notesgenerator */
$notesgenerator = $this->getDataGenerator()->get_plugin_generator('core_notes');
$notesgenerator->create_instance(['courseid' => SITEID, 'userid' => $recipient->id]);
$this->datasource_stress_test_columns(notes::class);
$this->datasource_stress_test_columns_aggregation(notes::class);
$this->datasource_stress_test_conditions(notes::class, 'note:content');
}
}