reports_list.php 10 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
<?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_reportbuilder\local\systemreports;

use html_writer;
use lang_string;
use moodle_url;
use pix_icon;
use stdClass;
use core_reportbuilder\datasource;
use core_reportbuilder\manager;
use core_reportbuilder\system_report;
use core_reportbuilder\local\entities\user;
use core_reportbuilder\local\filters\date;
use core_reportbuilder\local\filters\text;
use core_reportbuilder\local\filters\select;
use core_reportbuilder\local\helpers\format;
use core_reportbuilder\local\report\action;
use core_reportbuilder\local\report\column;
use core_reportbuilder\local\report\filter;
use core_reportbuilder\output\report_name_editable;
use core_reportbuilder\local\models\report;
use core_reportbuilder\permission;

/**
 * Reports list
 *
 * @package     core_reportbuilder
 * @copyright   2021 David Matamoros <davidmc@moodle.com>
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class reports_list extends system_report {

    /**
     * The name of our internal report entity
     *
     * @return string
     */
    private function get_report_entity_name(): string {
        return 'report';
    }

    /**
     * Initialise the report
     */
    protected function initialise(): void {
        $this->set_main_table('reportbuilder_report', 'rb');

        $this->add_base_condition_simple('rb.type', self::TYPE_CUSTOM_REPORT);
        $this->add_base_fields('rb.id, rb.name, rb.source, rb.type, rb.usercreated'); // Necessary for actions/row class.

        // Join user entity for "User modified" column.
        $entityuser = new user();
        $entityuseralias = $entityuser->get_table_alias('user');

        $this->add_entity($entityuser
            ->add_join("JOIN {user} {$entityuseralias} ON {$entityuseralias}.id = rb.usermodified")
        );

        // Define our internal entity for report elements.
        $this->annotate_entity($this->get_report_entity_name(),
            new lang_string('customreports', 'core_reportbuilder'));

        $this->add_columns();
        $this->add_filters();
        $this->add_actions();

        $this->set_downloadable(false);
    }

    /**
     * Ensure we can view the report
     *
     * @return bool
     */
    protected function can_view(): bool {
        return permission::can_view_reports_list();
    }

    /**
     * Dim the table row for invalid datasource
     *
     * @param stdClass $row
     * @return string
     */
    public function get_row_class(stdClass $row): string {
        return $this->report_source_valid($row->source) ? '' : 'dimmed_text';
    }

    /**
     * Add columns to report
     */
    protected function add_columns(): void {
        $tablealias = $this->get_main_table_alias();

        // Report name column.
        $this->add_column((new column(
            'name',
            new lang_string('name'),
            $this->get_report_entity_name()
        ))
            ->set_type(column::TYPE_TEXT)
            ->add_fields("{$tablealias}.name, {$tablealias}.id")
            ->set_is_sortable(true)
            ->add_callback(function(string $value, stdClass $row) {
                global $PAGE;

                $reportid = (int) $row->id;

                $editable = new report_name_editable($reportid);
                return $editable->render($PAGE->get_renderer('core'));
            })
        );

        // Report source column.
        $this->add_column((new column(
            'source',
            new lang_string('reportsource', 'core_reportbuilder'),
            $this->get_report_entity_name()
        ))
            ->set_type(column::TYPE_TEXT)
            ->add_fields("{$tablealias}.source")
            ->set_is_sortable(true)
            ->add_callback(function(string $value, stdClass $row) {
                if (!$this->report_source_valid($value)) {
                    // Add danger badge if report source is not valid (either it's missing, or has errors).
                    return html_writer::span(get_string('errorsourceinvalid', 'core_reportbuilder'), 'badge badge-danger');
                }

                return call_user_func([$value, 'get_name']);
            })
        );

        // Time created column.
        $this->add_column((new column(
            'timecreated',
            new lang_string('timecreated', 'core_reportbuilder'),
            $this->get_report_entity_name()
        ))
            ->set_type(column::TYPE_TIMESTAMP)
            ->add_fields("{$tablealias}.timecreated")
            ->set_is_sortable(true)
            ->add_callback([format::class, 'userdate'])
        );

        // Time modified column.
        $this->add_column((new column(
            'timemodified',
            new lang_string('timemodified', 'core_reportbuilder'),
            $this->get_report_entity_name()
        ))
            ->set_type(column::TYPE_TIMESTAMP)
            ->add_fields("{$tablealias}.timemodified")
            ->set_is_sortable(true)
            ->add_callback([format::class, 'userdate'])
        );

        // The user who modified the report.
        $this->add_column_from_entity('user:fullname');

        // Initial sorting.
        $this->set_initial_sort_column('report:timecreated', SORT_DESC);
    }

    /**
     * Add filters to report
     */
    protected function add_filters(): void {
        $tablealias = $this->get_main_table_alias();

        // Name filter.
        $this->add_filter((new filter(
            text::class,
            'name',
            new lang_string('name'),
            $this->get_report_entity_name(),
            "{$tablealias}.name"
        )));

        // Source filter.
        $this->add_filter((new filter(
            select::class,
            'source',
            new lang_string('reportsource', 'core_reportbuilder'),
            $this->get_report_entity_name(),
            "{$tablealias}.source"
        ))
            ->set_options_callback(static function(): array {
                return manager::get_report_datasources();
            })
        );

        // Time created filter.
        $this->add_filter((new filter(
            date::class,
            'timecreated',
            new lang_string('timecreated', 'core_reportbuilder'),
            $this->get_report_entity_name(),
            "{$tablealias}.timecreated"
        ))
            ->set_limited_operators([
                date::DATE_ANY,
                date::DATE_RANGE,
            ])
        );
    }

    /**
     * Add actions to report
     */
    protected function add_actions(): void {
228
229
230
231
232
233
234
235
236
237
238
        // Edit content action.
        $this->add_action((new action(
            new moodle_url('/reportbuilder/edit.php', ['id' => ':id']),
            new pix_icon('t/right', get_string('editreportcontent', 'core_reportbuilder'))
        ))
            ->add_callback(function(stdClass $row): bool {
                return $this->report_source_valid($row->source) && permission::can_edit_report($this->get_report_from_row($row));
            })
        );

        // Edit details action.
239
240
241
242
243
244
245
246
247
248
        $this->add_action((new action(
            new moodle_url('#'),
            new pix_icon('t/edit', get_string('editreportdetails', 'core_reportbuilder')),
            ['data-action' => 'report-edit', 'data-report-id' => ':id']
        ))
            ->add_callback(function(stdClass $row): bool {
                return $this->report_source_valid($row->source) && permission::can_edit_report($this->get_report_from_row($row));
            })
        );

249
250
251
252
253
254
255
256
257
258
259
260
        // Preview action.
        $this->add_action((new action(
            new moodle_url('/reportbuilder/view.php', ['id' => ':id']),
            new pix_icon('i/search', get_string('view', 'moodle')),
            []
        ))
            ->add_callback(function(stdClass $row): bool {
                // We check this only to give the action to editors, because normal users can just click on the report name.
                return $this->report_source_valid($row->source) && permission::can_edit_report($this->get_report_from_row($row));
            })
        );

261
        // Delete action.
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
        $this->add_action((new action(
            new moodle_url('#'),
            new pix_icon('t/delete', get_string('deletereport', 'core_reportbuilder')),
            ['data-action' => 'report-delete', 'data-report-id' => ':id', 'data-report-name' => ':name']
        ))
            ->add_callback(function(stdClass $row): bool {
                // We don't check whether report is valid to ensure editor can always delete them.
                return permission::can_edit_report($this->get_report_from_row($row));
            })
        );
    }

    /**
     * Helper to determine whether given report source is valid (it both exists, and is available)
     *
     * @param string $source
     * @return bool
     */
    private function report_source_valid(string $source): bool {
        return manager::report_source_exists($source, datasource::class) && manager::report_source_available($source);
    }

    /**
     * Helper to return the report persistent from the row object.
     *
     * Note that this persistent, for performance reasons, is not complete and only contains id/type/usercreated fields, which
     * are needed for the permission methods.
     *
     * @param stdClass $row
     * @return report
     */
    private function get_report_from_row(stdClass $row): report {
        return new report(0, (object)[
            'id' => $row->id,
            'type' => $row->type,
            'usercreated' => $row->usercreated,
        ]);
    }
}