Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
declare(strict_types=1);
18
 
19
namespace core_reportbuilder\table;
20
 
21
use core\output\notification;
22
use html_writer;
23
use moodle_exception;
24
use moodle_url;
25
use stdClass;
26
use core_reportbuilder\{datasource, manager};
27
use core_reportbuilder\local\models\report;
28
use core_reportbuilder\local\report\column;
29
use core_reportbuilder\output\column_aggregation_editable;
30
use core_reportbuilder\output\column_heading_editable;
31
 
32
/**
33
 * Custom report dynamic table class
34
 *
35
 * @package     core_reportbuilder
36
 * @copyright   2021 David Matamoros <davidmc@moodle.com>
37
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38
 */
39
class custom_report_table extends base_report_table {
40
 
41
    /** @var datasource $report */
42
    protected $report;
43
 
44
    /** @var string Unique ID prefix for the table */
45
    private const UNIQUEID_PREFIX = 'custom-report-table-';
46
 
47
    /** @var bool Whether report is being edited (we don't want user filters/sorting to be applied when editing) */
48
    protected const REPORT_EDITING = true;
49
 
50
    /** @var float $querytimestart Time we began executing table SQL */
51
    private $querytimestart = 0.0;
52
 
53
    /**
54
     * Table constructor. Note that the passed unique ID value must match the pattern "custom-report-table-(\d+)" so that
55
     * dynamic updates continue to load the same report
56
     *
57
     * @param string $uniqueid
58
     * @param string $download
59
     * @throws moodle_exception For invalid unique ID
60
     */
61
    public function __construct(string $uniqueid, string $download = '') {
62
        if (!preg_match('/^' . self::UNIQUEID_PREFIX . '(?<id>\d+)$/', $uniqueid, $matches)) {
63
            throw new moodle_exception('invalidcustomreportid', 'core_reportbuilder', '', null, $uniqueid);
64
        }
65
 
66
        parent::__construct($uniqueid);
67
 
68
        $this->define_baseurl(new moodle_url('/reportbuilder/edit.php', ['id' => $matches['id']]));
69
 
70
        // Load the report persistent, and accompanying report instance.
71
        $this->persistent = new report($matches['id']);
72
        $this->report = manager::get_report_from_persistent($this->persistent);
73
 
74
        $fields = $groupby = [];
75
        $maintable = $this->report->get_main_table();
76
        $maintablealias = $this->report->get_main_table_alias();
77
        $joins = $this->report->get_joins();
78
        [$where, $params] = $this->report->get_base_condition();
79
 
80
        $this->set_attribute('data-region', 'reportbuilder-table');
81
        $this->set_attribute('class', $this->attributes['class'] . ' reportbuilder-table');
82
 
83
        // Download options.
84
        $this->showdownloadbuttonsat = [TABLE_P_BOTTOM];
85
        $this->is_downloading($download ?? null, $this->persistent->get_formatted_name());
86
 
87
        // Retrieve all report columns, exit early if there are none. Defining empty columns prevents errors during out().
88
        $columns = $this->get_active_columns();
89
        if (empty($columns)) {
90
            $this->init_sql("{$maintablealias}.*", "{{$maintable}} {$maintablealias}", $joins, '1=0', []);
91
            $this->define_columns([0]);
92
            return;
93
        }
94
 
95
        // If we are aggregating any columns, we should group by the remaining ones.
1441 ariadna 96
        $aggregatedcolumns = array_filter($columns, fn(column $column): bool => !empty($column->get_aggregation()));
97
        $hasaggregatedcolumns = !empty($aggregatedcolumns);
1 efrain 98
 
99
        // Also take account of the report setting to show unique rows (only if no columns are being aggregated).
100
        $showuniquerows = !$hasaggregatedcolumns && $this->persistent->get('uniquerows');
101
 
102
        $columnheaders = $columnsattributes = [];
103
        foreach ($columns as $column) {
104
            $columnheading = $column->get_persistent()->get_formatted_heading($this->report->get_context());
105
            $columnheaders[$column->get_column_alias()] = $columnheading !== '' ? $columnheading : $column->get_title();
106
 
1441 ariadna 107
            // We need to determine for each column whether we should group by its fields, to support aggregation.
1 efrain 108
            $columnaggregation = $column->get_aggregation();
1441 ariadna 109
            if ($showuniquerows || ($hasaggregatedcolumns && (empty($columnaggregation) || $columnaggregation::column_groupby()))) {
1 efrain 110
                $groupby = array_merge($groupby, $column->get_groupby_sql());
111
            }
112
 
113
            // Add each columns fields, joins and params to our report.
114
            $fields = array_merge($fields, $column->get_fields());
115
            $joins = array_merge($joins, $column->get_joins());
116
            $params = array_merge($params, $column->get_params());
117
 
118
            // Disable sorting for some columns.
119
            if (!$column->get_is_sortable()) {
120
                $this->no_sorting($column->get_column_alias());
121
            }
122
 
123
            // Add column attributes needed for card view.
124
            $settings = $this->report->get_settings_values();
125
            $showfirsttitle = $settings['cardview_showfirsttitle'] ?? false;
126
            $visiblecolumns = max($settings['cardview_visiblecolumns'] ?? 1, count($this->columns));
127
            if ($showfirsttitle || $column->get_persistent()->get('columnorder') > 1) {
128
                $column->add_attributes(['data-cardtitle' => $columnheaders[$column->get_column_alias()]]);
129
            }
130
            if ($column->get_persistent()->get('columnorder') > $visiblecolumns) {
131
                $column->add_attributes(['data-cardviewhidden' => '']);
132
            }
133
 
134
            // Generate column attributes to be included in each cell.
135
            $columnsattributes[$column->get_column_alias()] = $column->get_attributes();
136
        }
137
 
138
        $this->define_columns(array_keys($columnheaders));
139
        $this->define_headers(array_values($columnheaders));
140
 
141
        // Add column attributes to the table.
142
        $this->set_columnsattributes($columnsattributes);
143
 
144
        // Table configuration.
145
        $this->initialbars(false);
146
        $this->collapsible(false);
147
        $this->pageable(true);
148
        $this->set_default_per_page($this->report->get_default_per_page());
149
 
150
        // Initialise table SQL properties.
151
        $this->set_report_editing(static::REPORT_EDITING);
152
 
153
        $fieldsql = implode(', ', $fields);
154
        $this->init_sql($fieldsql, "{{$maintable}} {$maintablealias}", $joins, $where, $params, $groupby);
155
    }
156
 
157
    /**
158
     * Return a new instance of the class for given report ID
159
     *
160
     * @param int $reportid
161
     * @param string $download
162
     * @return static
163
     */
164
    public static function create(int $reportid, string $download = ''): self {
165
        return new static(self::UNIQUEID_PREFIX . $reportid, $download);
166
    }
167
 
168
    /**
169
     * Get user preferred sort columns, overriding those of parent. If user has no preferences then use report defaults
170
     *
171
     * @return array
172
     */
173
    public function get_sort_columns(): array {
174
        $sortcolumns = parent::get_sort_columns();
175
 
176
        if ($this->editing || empty($sortcolumns)) {
177
            $sortcolumns = [];
178
            $columns = $this->get_active_columns();
179
 
180
            // We need to sort the columns by the configured sorting order.
181
            usort($columns, static function(column $a, column $b): int {
182
                return ($a->get_persistent()->get('sortorder') < $b->get_persistent()->get('sortorder')) ? -1 : 1;
183
            });
184
 
185
            foreach ($columns as $column) {
186
                $persistent = $column->get_persistent();
187
                if ($column->get_is_sortable() && $persistent->get('sortenabled')) {
188
                    $sortcolumns[$column->get_column_alias()] = $persistent->get('sortdirection');
189
                }
190
            }
191
        }
192
 
193
        return $sortcolumns;
194
    }
195
 
196
    /**
197
     * Format each row of returned data, executing defined callbacks for the row and each column
198
     *
199
     * @param array|stdClass $row
200
     * @return array
201
     */
202
    public function format_row($row) {
203
        $columns = $this->get_active_columns();
204
 
205
        $formattedrow = [];
206
        foreach ($columns as $column) {
207
            $formattedrow[$column->get_column_alias()] = $column->format_value((array) $row);
208
        }
209
 
210
        return $formattedrow;
211
    }
212
 
213
    /**
214
     * Download is disabled when editing the report
215
     *
216
     * @return string
217
     */
218
    public function download_buttons(): string {
219
        return '';
220
    }
221
 
222
    /**
223
     * Get the columns of the custom report, returned instances being valid and available for the user
224
     *
225
     * @return column[]
226
     */
227
    protected function get_active_columns(): array {
228
        return $this->report->get_active_columns();
229
    }
230
 
231
    /**
232
     * Override parent method for printing headers so we can render our custom controls in each cell
233
     */
234
    public function print_headers() {
235
        global $OUTPUT, $PAGE;
236
 
237
        $columns = $this->get_active_columns();
238
        if (empty($columns)) {
239
            return;
240
        }
241
 
242
        $columns = array_values($columns);
243
        $renderer = $PAGE->get_renderer('core');
244
 
245
        echo html_writer::start_tag('thead');
246
        echo html_writer::start_tag('tr');
247
 
248
        foreach ($this->headers as $index => $title) {
249
            $column = $columns[$index];
250
 
251
            $headingeditable = new column_heading_editable(0, $column->get_persistent());
252
            $aggregationeditable = new column_aggregation_editable(0, $column->get_persistent());
253
 
254
            // Render table header cell, with all editing controls.
255
            $headercell = $OUTPUT->render_from_template('core_reportbuilder/table_header_cell', [
256
                'entityname' => $this->report->get_entity_title($column->get_entity_name()),
257
                'name' => $column->get_title(),
258
                'headingeditable' => $headingeditable->render($renderer),
259
                'aggregationeditable' => $aggregationeditable->render($renderer),
260
                'movetitle' => get_string('movecolumn', 'core_reportbuilder', $column->get_title()),
261
            ]);
262
 
263
            echo html_writer::tag('th', $headercell, [
1441 ariadna 264
                'class' => 'border-end border-start',
1 efrain 265
                'scope' => 'col',
266
                'data-region' => 'column-header',
267
                'data-column-id' => $column->get_persistent()->get('id'),
268
                'data-column-name' => $column->get_title(),
269
                'data-column-position' => $index + 1,
270
            ]);
271
        }
272
 
273
        echo html_writer::end_tag('tr');
274
        echo html_writer::end_tag('thead');
275
    }
276
 
277
    /**
278
     * Override print_nothing_to_display to ensure that column headers are always added.
279
     */
280
    public function print_nothing_to_display() {
281
        global $OUTPUT;
282
 
283
        $this->start_html();
284
        $this->print_headers();
285
        echo html_writer::end_tag('table');
286
        echo html_writer::end_tag('div');
287
        $this->wrap_html_finish();
288
 
289
        // With the live editing disabled we need to notify user that data is shown only in preview mode.
290
        if ($this->editing && !self::show_live_editing()) {
291
            $notificationmsg = get_string('customreportsliveeditingdisabled', 'core_reportbuilder');
292
            $notificationtype = notification::NOTIFY_WARNING;
293
        } else {
294
            $notificationmsg = get_string('nothingtodisplay');
295
            $notificationtype = notification::NOTIFY_INFO;
296
        }
297
 
298
        $notification = (new notification($notificationmsg, $notificationtype, false))
299
            ->set_extra_classes(['mt-3']);
300
        echo $OUTPUT->render($notification);
301
 
302
        echo $this->get_dynamic_table_html_end();
303
    }
304
 
305
    /**
306
     * Provide additional table debugging during editing
307
     */
308
    public function wrap_html_finish(): void {
309
        global $OUTPUT;
310
 
311
        if ($this->editing && debugging('', DEBUG_DEVELOPER)) {
312
            $params = array_map(static function(string $param, $value): array {
313
                return ['param' => $param, 'value' => var_export($value, true)];
314
            }, array_keys($this->sql->params), $this->sql->params);
315
 
316
            echo $OUTPUT->render_from_template('core_reportbuilder/local/report/debug', [
317
                'query' => $this->get_table_sql(),
318
                'params' => $params,
319
                'duration' => $this->querytimestart ?
320
                    format_time($this->querytimestart - microtime(true)) : null,
321
            ]);
322
        }
323
    }
324
 
325
    /**
326
     * Override get_row_cells_html to add an extra cell with the toggle button for card view.
327
     *
328
     * @param string $rowid
329
     * @param array $row
330
     * @param array|null $suppresslastrow
331
     * @return string
332
     */
333
    public function get_row_cells_html(string $rowid, array $row, ?array $suppresslastrow): string {
334
        $html = parent::get_row_cells_html($rowid, $row, $suppresslastrow);
335
 
336
        // Add extra 'td' in the row with card toggle button (only visible in card view).
337
        $visiblecolumns = $this->report->get_settings_values()['cardview_visiblecolumns'] ?? 1;
338
        if ($visiblecolumns < count($this->columns)) {
339
            $buttonicon = html_writer::tag('i', '', ['class' => 'fa fa-angle-down']);
340
 
341
            // We need a cleaned version (without tags/entities) of the first row column to use as toggle button.
342
            $rowfirstcolumn = strip_tags((string) reset($row));
343
            $buttontitle = $rowfirstcolumn !== ''
344
                ? get_string('showhide', 'core_reportbuilder', html_entity_decode($rowfirstcolumn, ENT_COMPAT))
345
                : get_string('showhidecard', 'core_reportbuilder');
346
 
347
            $button = html_writer::tag('button', $buttonicon, [
348
                'type' => 'button',
349
                'class' => 'btn collapsed',
350
                'title' => $buttontitle,
1441 ariadna 351
                'data-bs-toggle' => 'collapse',
1 efrain 352
                'data-action' => 'toggle-card'
353
            ]);
354
            $html .= html_writer::tag('td', $button, ['class' => 'card-toggle d-none']);
355
        }
356
        return $html;
357
    }
358
 
359
    /**
360
     * Overriding this method to handle live editing setting.
361
     * @param int $pagesize
362
     * @param bool $useinitialsbar
363
     * @param string $downloadhelpbutton
364
     */
365
    public function out($pagesize, $useinitialsbar, $downloadhelpbutton = '') {
366
        $this->pagesize = $pagesize;
367
        $this->setup();
368
 
369
        // If the live editing setting is disabled, we not need to fetch custom report data except in preview mode.
370
        if (!$this->editing || self::show_live_editing()) {
371
            $this->querytimestart = microtime(true);
372
            $this->query_db($pagesize, $useinitialsbar);
373
            $this->build_table();
374
            $this->close_recordset();
375
        }
376
 
377
        $this->finish_output();
378
    }
379
 
380
    /**
381
     * Whether or not report data should be included in the table while in editing mode
382
     *
383
     * @return bool
384
     */
385
    private static function show_live_editing(): bool {
386
        global $CFG;
387
 
388
        return !empty($CFG->customreportsliveediting);
389
    }
1441 ariadna 390
 
391
    /**
392
     * Check if the user has the capability to access this table.
393
     *
394
     * @return bool Return true if capability check passed.
395
     */
396
    public function has_capability(): bool {
397
        return \core_reportbuilder\permission::can_edit_report($this->persistent);
398
    }
1 efrain 399
}