Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
89 / 89 |
|
100.00% |
7 / 7 |
CRAP | |
100.00% |
1 / 1 |
| exporter | |
100.00% |
89 / 89 |
|
100.00% |
7 / 7 |
25 | |
100.00% |
1 / 1 |
| sendable | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| pending | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
6 | |||
| lines | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| run | |
100.00% |
28 / 28 |
|
100.00% |
1 / 1 |
4 | |||
| file | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
2 | |||
| csv | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
5 | |||
| drop | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
5 | |||
| 1 | <?php |
| 2 | // This file is part of Moodle - https://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 <https://www.gnu.org/licenses/>. |
| 16 | |
| 17 | namespace local_finalgrades\local; |
| 18 | |
| 19 | use stdClass; |
| 20 | |
| 21 | /** |
| 22 | * Builds the CSV file of final grades for the student records system. |
| 23 | * |
| 24 | * Each run takes the grades not sent yet (approved ones only, when approval is required) and the sent grades |
| 25 | * that were withdrawn or returned since, writes them to one CSV file stored with the File API, marks them as |
| 26 | * sent, and copies the file to the drop folder when one is set. |
| 27 | * |
| 28 | * @package local_finalgrades |
| 29 | * @copyright 2026 DevLMS <contact@devlms.com> |
| 30 | * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later |
| 31 | */ |
| 32 | class exporter { |
| 33 | /** File area of the export files, in the system context. */ |
| 34 | public const FILEAREA = 'export'; |
| 35 | |
| 36 | /** Columns of the CSV file, in order. */ |
| 37 | public const COLUMNS = [ |
| 38 | 'action', 'course_idnumber', 'course_shortname', 'student_idnumber', 'student_name', |
| 39 | 'grade', 'percentage', 'letter', 'submitted_by', 'submitted_at', |
| 40 | ]; |
| 41 | |
| 42 | /** |
| 43 | * Statuses that may be sent. |
| 44 | * |
| 45 | * @return string[] |
| 46 | */ |
| 47 | public static function sendable(): array { |
| 48 | return get_config('local_finalgrades', 'requireapproval') |
| 49 | ? [submission::APPROVED] |
| 50 | : submission::CURRENT; |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Rows waiting to be sent: new or changed grades, and sent grades taken back since. |
| 55 | * |
| 56 | * A withdrawal is marked "superseded" when the same student's new grade goes in the same export: the |
| 57 | * records system then gets one "change" row, and the withdrawal is settled without a line of its own. |
| 58 | * |
| 59 | * @param int $courseid 0 for every course. |
| 60 | * @return stdClass[] Submission rows with "action" and "superseded" properties, oldest first. |
| 61 | */ |
| 62 | public static function pending(int $courseid = 0): array { |
| 63 | global $DB; |
| 64 | [$sendin, $sendparams] = $DB->get_in_or_equal(self::sendable(), SQL_PARAMS_NAMED, 'send'); |
| 65 | [$closein, $closeparams] = $DB->get_in_or_equal([submission::WITHDRAWN, submission::RETURNED], SQL_PARAMS_NAMED, 'close'); |
| 66 | $coursesql = $courseid ? 'AND s.courseid = :courseid' : ''; |
| 67 | $sql = "SELECT s.*, |
| 68 | CASE WHEN s.status $closein THEN 'withdrawn' |
| 69 | WHEN EXISTS (SELECT 1 FROM {local_finalgrades_sub} p |
| 70 | WHERE p.courseid = s.courseid AND p.userid = s.userid |
| 71 | AND p.id < s.id AND p.exportid > 0) THEN 'change' |
| 72 | ELSE 'new' END AS action |
| 73 | FROM {local_finalgrades_sub} s |
| 74 | WHERE ((s.status $sendin AND s.exportid = 0) |
| 75 | OR (s.status IN ('" . submission::WITHDRAWN . "', '" . submission::RETURNED . "') |
| 76 | AND s.exportid > 0 AND s.closeexportid = 0)) |
| 77 | $coursesql |
| 78 | ORDER BY s.id"; |
| 79 | $rows = $DB->get_records_sql($sql, $sendparams + $closeparams + ['courseid' => $courseid]); |
| 80 | $sending = []; |
| 81 | foreach ($rows as $row) { |
| 82 | if ($row->action !== 'withdrawn') { |
| 83 | $sending[$row->courseid . '-' . $row->userid] = true; |
| 84 | } |
| 85 | } |
| 86 | foreach ($rows as $row) { |
| 87 | $row->superseded = $row->action === 'withdrawn' && isset($sending[$row->courseid . '-' . $row->userid]); |
| 88 | } |
| 89 | return $rows; |
| 90 | } |
| 91 | |
| 92 | /** |
| 93 | * The rows that get a line in the file. |
| 94 | * |
| 95 | * @param stdClass[] $rows Pending rows. |
| 96 | * @return stdClass[] |
| 97 | */ |
| 98 | public static function lines(array $rows): array { |
| 99 | return array_filter($rows, fn($row) => !$row->superseded); |
| 100 | } |
| 101 | |
| 102 | /** |
| 103 | * Make one export of everything pending. |
| 104 | * |
| 105 | * @param int $by The user who asked for it, 0 for the scheduled task. |
| 106 | * @return stdClass|null The export record, or null when nothing was pending. |
| 107 | */ |
| 108 | public static function run(int $by = 0): ?stdClass { |
| 109 | global $DB; |
| 110 | $rows = self::pending(); |
| 111 | if (!$rows) { |
| 112 | return null; |
| 113 | } |
| 114 | $now = time(); |
| 115 | $transaction = $DB->start_delegated_transaction(); |
| 116 | $export = (object) ['rowcount' => count(self::lines($rows)), 'filename' => '', 'createdby' => $by, 'timecreated' => $now]; |
| 117 | $export->id = $DB->insert_record('local_finalgrades_export', $export); |
| 118 | $export->filename = 'final-grades-' . gmdate('Ymd-His', $now) . '-' . $export->id . '.csv'; |
| 119 | $DB->set_field('local_finalgrades_export', 'filename', $export->filename, ['id' => $export->id]); |
| 120 | |
| 121 | $file = get_file_storage()->create_file_from_string([ |
| 122 | 'contextid' => \context_system::instance()->id, |
| 123 | 'component' => 'local_finalgrades', |
| 124 | 'filearea' => self::FILEAREA, |
| 125 | 'itemid' => $export->id, |
| 126 | 'filepath' => '/', |
| 127 | 'filename' => $export->filename, |
| 128 | ], self::csv(self::lines($rows))); |
| 129 | |
| 130 | foreach ($rows as $row) { |
| 131 | $field = $row->action === 'withdrawn' ? 'closeexportid' : 'exportid'; |
| 132 | $DB->set_field('local_finalgrades_sub', $field, $export->id, ['id' => $row->id]); |
| 133 | } |
| 134 | $transaction->allow_commit(); |
| 135 | |
| 136 | self::drop($file, $export->filename); |
| 137 | \local_finalgrades\event\grades_exported::create([ |
| 138 | 'context' => \context_system::instance(), |
| 139 | 'objectid' => $export->id, |
| 140 | 'other' => ['rowcount' => (int) $export->rowcount], |
| 141 | ])->trigger(); |
| 142 | return $export; |
| 143 | } |
| 144 | |
| 145 | /** |
| 146 | * The stored file of an export. |
| 147 | * |
| 148 | * @param stdClass $export |
| 149 | * @return \stored_file|null |
| 150 | */ |
| 151 | public static function file(stdClass $export): ?\stored_file { |
| 152 | return get_file_storage()->get_file( |
| 153 | \context_system::instance()->id, |
| 154 | 'local_finalgrades', |
| 155 | self::FILEAREA, |
| 156 | $export->id, |
| 157 | '/', |
| 158 | $export->filename |
| 159 | ) ?: null; |
| 160 | } |
| 161 | |
| 162 | /** |
| 163 | * The CSV text for these rows. |
| 164 | * |
| 165 | * @param stdClass[] $rows Pending rows. |
| 166 | * @return string |
| 167 | */ |
| 168 | protected static function csv(array $rows): string { |
| 169 | global $DB; |
| 170 | $courses = $DB->get_records_list('course', 'id', array_unique(array_column($rows, 'courseid')), '', 'id, shortname'); |
| 171 | $userids = array_unique(array_merge(array_column($rows, 'userid'), array_column($rows, 'submittedby'))); |
| 172 | $users = $DB->get_records_list('user', 'id', $userids, '', 'id, ' . implode(', ', \core_user\fields::get_name_fields())); |
| 173 | |
| 174 | $fh = fopen('php://temp', 'w+'); |
| 175 | fputcsv($fh, self::COLUMNS, ',', '"', ''); |
| 176 | foreach ($rows as $row) { |
| 177 | fputcsv($fh, [ |
| 178 | $row->action, |
| 179 | $row->courseidnumber, |
| 180 | $courses[$row->courseid]->shortname ?? '', |
| 181 | $row->useridnumber, |
| 182 | isset($users[$row->userid]) ? fullname($users[$row->userid]) : '', |
| 183 | $row->grade === null ? '' : number_format((float) $row->grade, 2, '.', ''), |
| 184 | $row->percentage, |
| 185 | $row->letter, |
| 186 | isset($users[$row->submittedby]) ? fullname($users[$row->submittedby]) : '', |
| 187 | gmdate('Y-m-d\TH:i:s\Z', (int) $row->timesubmitted), |
| 188 | ], ',', '"', ''); |
| 189 | } |
| 190 | rewind($fh); |
| 191 | $csv = stream_get_contents($fh); |
| 192 | fclose($fh); |
| 193 | return $csv; |
| 194 | } |
| 195 | |
| 196 | /** |
| 197 | * Copy the file to the drop folder, when one is set. Written under a temporary name and renamed, |
| 198 | * so a job reading the folder never sees half a file. |
| 199 | * |
| 200 | * @param \stored_file $file |
| 201 | * @param string $filename |
| 202 | */ |
| 203 | protected static function drop(\stored_file $file, string $filename): void { |
| 204 | $folder = rtrim((string) get_config('local_finalgrades', 'dropfolder'), '/'); |
| 205 | if ($folder === '') { |
| 206 | return; |
| 207 | } |
| 208 | if (!is_dir($folder) || !is_writable($folder)) { |
| 209 | debugging("Final grades: the drop folder $folder does not exist or is not writable. " |
| 210 | . "The export is still available to download.", DEBUG_NORMAL); |
| 211 | return; |
| 212 | } |
| 213 | $temp = "$folder/.$filename.part"; |
| 214 | if ($file->copy_content_to($temp)) { |
| 215 | rename($temp, "$folder/$filename"); |
| 216 | } |
| 217 | } |
| 218 | } |