Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1441 ariadna 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
namespace gradepenalty_duedate\output\form;
18
 
19
use MoodleQuickForm;
20
 
21
defined('MOODLE_INTERNAL') || die();
22
 
23
require_once($CFG->libdir . '/formslib.php');
24
require_once(__DIR__ . '/../../../lib.php');
25
 
26
use action_menu_link;
27
use core\output\action_menu;
28
use core\output\html_writer;
29
use core\output\pix_icon;
30
use core\url;
31
use gradepenalty_duedate\constants;
32
use gradepenalty_duedate\penalty_rule;
33
use moodleform;
34
 
35
/**
36
 * Form to set up the penalty rules for the gradepenalty_duedate plugin.
37
 *
38
 * @package   gradepenalty_duedate
39
 * @copyright 2024 Catalyst IT Australia Pty Ltd
40
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41
 */
42
class edit_penalty_form extends moodleform {
43
    /** @var int contextid context id where the penalty rules are edited */
44
    protected int $contextid = 0;
45
 
46
    #[\Override]
47
    public function definition(): void {
48
        global $PAGE;
49
        $mform = $this->_form;
50
 
51
        // Hidden context id, value is stored in $mform.
52
        $this->contextid = $this->_customdata['contextid'] ?? 1;
53
        $mform->addElement('hidden', 'contextid');
54
        $mform->setType('contextid', PARAM_INT);
55
        $mform->setDefault('contextid', $this->contextid);
56
 
57
        // Edit mode.
58
        $mform->addElement('hidden', 'edit', 1);
59
        $mform->setType('edit', PARAM_INT);
60
 
61
        // Get existing penalty rules, clone from parent context if not found.
62
        $finalpenaltyrule = $this->_customdata['finalpenaltyrule'] ?? null;
63
        if (!is_null($finalpenaltyrule)) {
64
            $repeatedrules = $this->_customdata['penaltyrules'];
65
        } else {
66
            $existingrules = penalty_rule::get_rules($this->contextid);
67
 
68
            if (!empty($existingrules)) {
69
                // Clone from parent context.
70
                // Extract the final rule.
71
                $finalpenaltyrule = array_pop($existingrules);
72
                // We need the penalty value only.
73
                $finalpenaltyrule = $finalpenaltyrule->get('penalty');
74
 
75
                // Other rules, turn to array so that we can use them in form repeat element.
76
                $repeatedrules = [];
77
                foreach ($existingrules as $rule) {
78
                    $repeatedrules[] = [
79
                        'overdueby' => $rule->get('overdueby'),
80
                        'penalty' => $rule->get('penalty'),
81
                    ];
82
                }
83
            }
84
        }
85
 
86
        // Rule group repeater. Show default of 5 rules if there is no rule.
87
        $repeatcount = !is_null($finalpenaltyrule) ? count($repeatedrules) : 0;
88
 
89
        // Create rule element.
90
        [$group, $options] = self::rule_element($mform);
91
 
92
        // Create repeatable elements.
93
        $this->repeat_elements([$group], $repeatcount, $options, 'rulegroupcount', 'addrules', 0);
94
 
95
        // We don't need "addrules" button.
96
        $mform->removeElement('addrules');
97
 
98
        // Final rule input.
99
        $mform->addElement('text', 'finalpenaltyrule', get_string('finalpenaltyrule', 'gradepenalty_duedate'), ['size' => 3]);
100
        $mform->setType('finalpenaltyrule', PARAM_FLOAT);
101
        $mform->setDefault('finalpenaltyrule', 0);
102
        $mform->addHelpButton('finalpenaltyrule', 'finalpenaltyrule', 'gradepenalty_duedate');
103
 
104
        // Set data.
105
        if (!is_null($finalpenaltyrule)) {
106
            $data = [];
107
            $data['finalpenaltyrule'] = $finalpenaltyrule;
108
            foreach ($repeatedrules as $rulenumber => $rule) {
109
                $data['overdueby[' . $rulenumber . ']'] = $rule['overdueby'];
110
                $data['penalty[' . $rulenumber . ']'] = $rule['penalty'];
111
            }
112
            $this->set_data($data);
113
        }
114
 
115
        // Add submit and cancel buttons.
116
        $this->add_action_buttons();
117
    }
118
 
119
    #[\Override]
120
    public function validation($data, $files): array {
121
        $errors = parent::validation($data, $files);
122
 
123
        // Skip if there is no data.
124
        if (empty($data['overdueby'])) {
125
            return $errors;
126
        }
127
 
128
        // The late for and penalty values must be in ascending order.
129
        $overduebylowerbound = constants::OVERDUEBY_MIN - 1;
130
        $overduebyupperbound = constants::OVERDUEBY_MAX + 1;
131
        $penaltylowerbound = constants::PENALTY_MIN - 1;
132
        $penaltyupperbound = constants::PENALTY_MAX + 1;
133
 
134
        // Go to each group.
135
        foreach ($data['overdueby'] as $rulenumber => $overdueby) {
136
            $rulegroupid = 'rulegroup[' . $rulenumber . ']';
137
 
138
            // Skip validation if user did not change default overdue value. We will remove those rules later.
139
            if ($overdueby < constants::OVERDUEBY_MIN) {
140
                continue;
141
            }
142
 
143
            // Validate overdue field.
144
            if ($overdueby <= $overduebylowerbound) {
145
                if ($overduebylowerbound == constants::OVERDUEBY_MIN - 1) {
146
                    // Minimum value of overdue field.
147
                    $errormessage = get_string('error_overdueby_minvalue', 'gradepenalty_duedate',
148
                        format_time(constants::OVERDUEBY_MIN));
149
                } else {
150
                    // Must be greater than the previous overdue value.
151
                    $errormessage = get_string('error_overdueby_abovevalue', 'gradepenalty_duedate',
152
                        format_time($overduebylowerbound));
153
                }
154
                $errors[$rulegroupid] = $errormessage;
155
            } else if ($overdueby >= $overduebyupperbound) {
156
                // Validate max value of overdue.
157
                $errors[$rulegroupid] = get_string('error_overdueby_maxvalue', 'gradepenalty_duedate',
158
                    format_time(constants::OVERDUEBY_MAX));
159
            } else {
160
                $overduebylowerbound = $overdueby;
161
            }
162
 
163
            // Validate penalty.
164
            $penalty = $data['penalty'][$rulenumber];
165
            if ($penalty <= $penaltylowerbound) {
166
                if ($penaltylowerbound == constants::PENALTY_MIN - 1) {
167
                    // Minimum value a penalty can have.
168
                    $errormessage = get_string('error_penalty_minvalue', 'gradepenalty_duedate',
169
                        format_float(constants::PENALTY_MIN));
170
                } else {
171
                    // Must be greater than the previous penalty.
172
                    $errormessage = get_string('error_penalty_abovevalue', 'gradepenalty_duedate',
173
                        format_float($penaltylowerbound));
174
                }
175
 
176
                if (isset($errors[$rulegroupid])) {
177
                    // Append to existing error message.
178
                    $errors[$rulegroupid] .= ' ' . $errormessage;
179
                } else {
180
                    // Create new error message.
181
                    $errors[$rulegroupid] = $errormessage;
182
                }
183
            } else if ($penalty >= $penaltyupperbound) {
184
                // Validate max value of penalty.
185
                $errors[$rulegroupid] = get_string('error_penalty_maxvalue', 'gradepenalty_duedate',
186
                    format_float(constants::PENALTY_MAX));
187
            } else {
188
                $penaltylowerbound = $penalty;
189
            }
190
        }
191
 
192
        // Check the penalty of the final rule. It must be greater than the last rule.
193
        $finalpenalty = $data['finalpenaltyrule'];
194
        if ($finalpenalty <= $penaltylowerbound) {
195
            $errors['finalpenaltyrule'] = get_string('error_penalty_abovevalue', 'gradepenalty_duedate',
196
                format_float($penaltylowerbound));
197
        } else if ($finalpenalty >= $penaltyupperbound) {
198
            $errors['finalpenaltyrule'] = get_string('error_penalty_maxvalue', 'gradepenalty_duedate',
199
                format_float(constants::PENALTY_MAX));
200
        }
201
 
202
        return $errors;
203
    }
204
 
205
    /**
206
     * Save the form data.
207
     *
208
     * @param object $data form data
209
     * @return void
210
     */
211
    public function save_data($data): void {
212
        // Get penalty rules.
213
        $rules = penalty_rule::get_records(['contextid' => $this->contextid], 'sortorder', 'ASC');
214
 
215
        // There could be deleted rules, so we will reindex the array.
216
        $newdata = [];
217
        if (isset($data->overdueby)) {
218
            foreach ($data->overdueby as $rulenumber => $overdueby) {
219
                // Remove the invalid default rule that we skipped validating.
220
                if ($overdueby >= constants::OVERDUEBY_MIN) {
221
                    $newdata[$overdueby] = $data->penalty[$rulenumber];
222
                }
223
            }
224
            // Sort by overdueby.
225
            ksort($newdata);
226
        }
227
 
228
        // Update or create new rules.
229
        $numofrulesinrepeater = count($newdata);
230
        $overdueby = array_keys($newdata);
231
        $penalty = array_values($newdata);
232
        for ($i = 0; $i < $numofrulesinrepeater; $i++) {
233
            // Create new rule if it does not exist.
234
            $rule = $rules[$i] ?? new penalty_rule();
235
 
236
            // Set the values.
237
            $rule->set('contextid', $this->contextid);
238
            $rule->set('sortorder', $i);
239
            $rule->set('overdueby', $overdueby[$i]);
240
            $rule->set('penalty', $penalty[$i]);
241
 
242
            // Save the rule.
243
            $rule->save();
244
        }
245
 
246
        // Save the final rule.
247
        // Check if the final rule exists.
248
        $finalrule = $rules[$numofrulesinrepeater] ?? new penalty_rule();
249
        $finalrule->set('contextid', $this->contextid);
250
        $finalrule->set('sortorder', $numofrulesinrepeater);
251
        if (!empty($overdueby)) {
252
            // We can set to any date/time that greater than the last rule in the repeater.
253
            $finalrule->set('overdueby', end($overdueby) + DAYSECS);
254
        } else {
255
            $finalrule->set('overdueby', constants::OVERDUEBY_MIN);
256
        }
257
        $finalrule->set('penalty', $data->finalpenaltyrule);
258
        $finalrule->save();
259
 
260
        // Number of updated rules. Plus one, due to final rule.
261
        $numofupdatedrules = $numofrulesinrepeater + 1;
262
 
263
        // Delete rules if there are more rules than the form data.
264
        if (count($rules) > $numofupdatedrules) {
265
            for ($i = $numofupdatedrules; $i < count($rules); $i++) {
266
                $rules[$i]->delete();
267
            }
268
        }
269
    }
270
 
271
    /**
272
     * Create the rule element.
273
     *
274
     * @param MoodleQuickForm $mform The form object.
275
     * @return array The rule element and options.
276
     */
277
    private static function rule_element(MoodleQuickForm $mform): array {
278
        global $PAGE;
279
 
280
        $elements = [];
281
        $options = [];
282
 
283
        // Overdue.
284
        $elements[] = $mform->createElement('static', '', '',
285
            html_writer::span(get_string('overdueby_label', 'gradepenalty_duedate'), 'me-2'));
286
 
287
        // Less than or equal.
288
        $elements[] = $mform->createElement('static', '', '', html_writer::span('≤', 'me-2'));
289
 
290
        // Duration value element.
291
        $elements[] = ($mform->createElement('duration', 'overdueby',
292
            get_string('overdueby_label', 'gradepenalty_duedate'), ['optional' => false, 'defaultunit' => DAYSECS]));
293
 
294
        // Penalty.
295
        $elements[] = $mform->createElement('static', '', '',
296
            html_writer::span(get_string('penalty_label', 'gradepenalty_duedate'), 'ms-4 me-2'));
297
 
298
        // Penalty value element.
299
        $elements[] = $mform->createElement('text', 'penalty',
300
            get_string('penalty_label', 'gradepenalty_duedate'), ['size' => 3, 'maxlength' => 3]);
301
        $options['penalty']['type'] = PARAM_FLOAT;
302
 
303
        // Percentage.
304
        $elements[] = $mform->createElement('static', '', '', html_writer::span('%', 'me-4'));
305
 
306
        // Action menu.
307
        $output = $PAGE->get_renderer('core');
308
        $menu = new action_menu();
309
        $menu->set_kebab_trigger();
310
 
311
        // Insert below button.
312
        $menu->add(new action_menu_link(
313
            new url('#'),
314
            new pix_icon('t/add', ''),
315
            get_string('insertrule', 'gradepenalty_duedate'),
316
            false,
317
            ['class' => 'insertbelow']
318
        ));
319
 
320
        // Delete button.
321
        $menu->add(new action_menu_link(
322
            new url('#'),
323
            new pix_icon('i/trash', ''),
324
            get_string('delete'),
325
            false,
326
            ['class' => 'deleterulebuttons text-danger']
327
        ));
328
        $actionmenu = $output->render($menu);
329
        $elements[] = $mform->createElement('static', 'name1', 'name2', $actionmenu);
330
 
331
        // Group.
332
        return [
333
            $mform->createElement(
334
                'group',
335
                'rulegroup',
336
                get_string('penaltyrule_group', 'gradepenalty_duedate'),
337
                $elements,
338
                [''],
339
                false
340
            ),
341
            $options,
342
        ];
343
    }
344
}