Commit daf6849f authored by Abbassy's avatar Abbassy
Browse files

Initial commit: Moodle Assign Feedback DTA Plugin v1.0.0

- Automatic grade calculation based on DTA test results
- Grade display in DTA Feedback column
- Optional automatic grade application to Final grade
- Grade automatically checkbox functionality
- Support for competency-based grading
- Complete documentation and README
parent 411f28bb
# Assets Directory
This directory contains screenshots and images used in the plugin documentation.
## Screenshots
- `install_plugin.png` - Plugin installer page showing ZIP file upload
- `assignment_settings.png` - Assignment settings page with Feedback types section
- `submissions_table.png` - Submissions grading table showing DTA Feedback column
- `student_submission_view.png` - Student view of submission with feedback
## Usage
These images are referenced in the main README.md file using relative paths.
# Moodle plugin gitignore
*.zip
*.log
.env
full_output.log
tmp_*
moodle_env_runtime.sh
course_runtime.sh
script*.sh
run_pipeline_local.sh
deploy.sh
.gitlab-ci.yml
*.md
!README.md
This diff is collapsed.
# moodle-assignfeedback_dta # Moodle Assign Feedback Plugin - DTA (Dockerized Test Agent)
## Overview
The assignfeedback_dta plugin is part of the MoDTA (Moodle Dockerized Test Agent) system. It automatically calculates and displays grades for student submissions tested using the Dockerized Test Agent (DTA) system. When students submit code through the DTA submission plugin, the DTA backend runs automated tests and sends results back to Moodle. This feedback plugin takes those test results and automatically calculates a grade, displaying it in a dedicated feedback column.
## Getting started The MoDTA system comprises two key components:
To make it easy for you to get started with GitLab, here's a list of recommended next steps. • The MoDTA Moodle submission plugin (`assignsubmission_dta`), designed as an assignment submission tool.
• The MoDTA Moodle feedback plugin (`assignfeedback_dta`), designed to automatically calculate and display grades based on test results.
• The DTA backend web service, which interfaces with the Moodle plugins through REST and employs the JSON file format for communication.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! ## Goals
## Add your files MoDTA empowers teachers to provide programming Moodle assignments for their students, which are automatically corrected upon hand-in using teacher-provided tests. The feedback plugin extends this functionality by automatically calculating grades based on test results, providing immediate feedback to both students and teachers.
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files The feedback plugin optionally supports automatic grade calculation, allowing teachers to:
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - Automatically calculate grades based on test results
- Display grades in a dedicated feedback column
- Optionally apply grades to the "Final grade" column for automatic grading
- Or keep "Final grade" empty for manual grade entry
``` ## What is this plugin?
cd existing_repo
git remote add origin https://transfer.hft-stuttgart.de/gitlab/cota/moodle-assignfeedback_dta.git The assignfeedback_dta plugin automatically calculates and displays grades for student submissions tested using the Dockerized Test Agent (DTA) system. When students submit code, the DTA backend runs automated tests and sends results back to Moodle. This plugin takes those test results and automatically calculates a grade, displaying it in a dedicated feedback column.
git branch -M master
git push -uf origin master ## How does it work?
```
1. **Student submits code** - Uploads Java project files through the DTA submission plugin (`assignsubmission_dta`)
2. **Backend tests the code** - DTA backend automatically runs test cases
3. **Results come back** - Backend sends test results to Moodle, stored in `assignsubmission_dta_summary` and `assignsubmission_dta_result` tables
4. **Plugin calculates grade** - This feedback plugin reads the test results and calculates a grade based on:
- Test success rate (passed tests / total tests)
- Compilation errors (more than 1 error results in 0%)
- Optional competency scores (if available)
5. **Grade appears in feedback column** - Shows "80.00 / 100.00" in "Dockerized Test Agent Feedback" column
## The "Grade automatically" Button
In the assignment settings, you'll find a checkbox labeled **"Grade automatically"** in the Feedback types section. This button controls how the plugin handles grade calculation.
**When checked (Automatic Grading ON):**
- The plugin automatically calculates and displays grades based on test results
- Grades appear immediately in the DTA Feedback column after backend processing
- Grades are also automatically applied to the "Final grade" column
- You can still manually adjust grades in the "Final grade" column if needed
**When unchecked (Automatic Grading OFF):**
- The plugin shows test results and calculates a suggested grade
- The grade is displayed only in the DTA Feedback column
- No grade is automatically applied to "Final grade"
- You review each submission and manually enter grades in the "Final grade" column
## Scenarios
### Scenario 1: Automatic Grading Enabled
**Setup:** You enable the plugin and check "Grade automatically" in assignment settings.
**Student submits:** Code passes 8 out of 10 tests, no compilation errors.
**Result:** Plugin automatically calculates 80% and displays "80.00 / 100.00" in DTA Feedback column. The grade is also automatically applied to the "Final grade" column.
**Use case:** Perfect for large classes where you want quick automated grading with the option to manually adjust exceptional cases.
### Scenario 2: Automatic Grading Disabled
**Setup:** You enable the plugin but leave "Grade automatically" unchecked.
**Student submits:** Code passes 7 out of 10 tests.
**Result:** Plugin calculates suggested grade of 70% and displays it in DTA Feedback column. "Final grade" column remains empty. You review the code, notice good documentation and effort, and manually enter 85% in Final grade column.
**Use case:** Ideal when code quality, documentation, and subjective factors matter alongside test results.
### Scenario 3: Compilation Errors
**Setup:** Automatic grading enabled.
**Student submits:** Code has 2 compilation errors.
**Result:** Plugin automatically sets grade to 0% and displays "0.00 / 100.00". This ensures students fix critical errors first.
**Use case:** Helps identify submissions that need immediate attention before test cases can even run.
### Scenario 4: Perfect Submission
**Setup:** Automatic grading enabled.
**Student submits:** All 10 tests pass, no errors.
**Result:** Plugin calculates 100% and displays "100.00 / 100.00" immediately. Grade is automatically applied to "Final grade".
**Use case:** Instant feedback for students who submit correct code, encouraging early submissions.
## Integrate with your tools ### Scenario 5: Switching Modes Mid-Assignment
- [ ] [Set up project integrations](https://transfer.hft-stuttgart.de/gitlab/cota/moodle-assignfeedback_dta/-/settings/integrations) **Initial:** Automatic grading enabled, students submitting and getting grades automatically.
## Collaborate with your team **Change:** You uncheck "Grade automatically" after reviewing initial submissions.
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) **Result:** New submissions show suggested grades only in DTA Feedback column. "Final grade" remains empty. You manually review and enter final grades. Existing automatic grades remain visible for reference.
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy **Use case:** Flexibility to adapt grading strategy based on assignment progress and student performance patterns.
Use the built-in continuous integration in GitLab. ## Key features
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -**Automatic grade calculation** based on test results
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -**Grade display in DTA Feedback column** - Always shows calculated grade
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -**Optional automatic grade application** - "Final grade" can be automatically set or left empty
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -**Checkbox saving works** - "Grade automatically" setting is properly saved
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) -**Batch testing support** - Works with batch testing functionality from submission plugin
-**Competency-based grading** - Supports competency scores if available from backend
*** ## Installation & Configuration
# Editing this README ### Prerequisites
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. The `assignsubmission_dta` plugin must be installed first, as the feedback plugin depends on it for test results. The feedback plugin reads from the database tables created by the submission plugin:
- `mdl_assignsubmission_dta_summary` - Summary of test results
- `mdl_assignsubmission_dta_result` - Individual test case results
## Suggestions for a good README ### Quick installation
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name 1. Download `assignfeedback_dta.zip`
Choose a self-explaining name for your project. 2. Go to **Site administration → Plugins → Install plugins**
3. Upload the ZIP file as shown in Fig. 1. ![Fig. 1: Plugin Installer](.assets/install_plugin.png)
4. Follow the installation wizard
## Description ### Manual installation
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges 1. Extract ZIP and copy `dta` folder to `/mod/assign/feedback/dta/`
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. 2. Set permissions: `chown -R www-data:www-data dta/`
3. Go to **Site administration → Notifications** to upgrade
4. Purge caches: **Site administration → Development → Purge all caches**
## Visuals ### Configuration
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation After installation, the plugin requires no additional configuration. It automatically reads test results from the submission plugin's database tables. However, ensure that:
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
- The DTA backend is properly configured (see submission plugin documentation)
- The submission plugin is installed and working
- HTTP Security settings allow communication with the backend (if needed)
## Usage ## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support With the MoDTA feedback plugin installed and the submission plugin configured:
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
### Teacher Setup
When creating or editing an assignment, a teacher can enable the DTA Feedback plugin in the **Feedback types** section as shown in Fig. 2. ![Fig. 2: Assignment Settings - Feedback Types](.assets/assignment_settings.png)
1. **Enable in assignment:**
- Edit assignment → **Feedback types** section
- Check **"Dockerized Test Agent Feedback"**
- Check **"Grade automatically"** (optional - controls automatic vs manual grading)
2. **Students submit code** via DTA submission plugin
3. **View grades:**
- Open assignment grading page as shown in Fig. 3. ![Fig. 3: Submissions Table with DTA Feedback](.assets/submissions_table.png)
- See grades in **"Dockerized Test Agent Feedback"** column
- Format: "85.50 / 100.00"
- If "Grade automatically" is enabled, grades also appear in **"Final grade"** column
- If disabled, **"Final grade"** column remains empty for manual entry
### Student View
Students see the calculated grade in the DTA Feedback column when viewing their submission status as shown in Fig. 4. ![Fig. 4: Student Submission View](.assets/student_submission_view.png) The grade is displayed in the format "XX.XX / 100.00" showing both the calculated grade and maximum possible grade.
## Grade calculation
The plugin uses a sophisticated calculation method:
- **Test Score:** Passed tests / Total tests (e.g., 8/10 = 80%)
- **With competencies:** (Test Score × 0.8) + (Competency Score × 0.2)
- **Without competencies:** Test Score × 1.0
- **Compilation errors (>1):** Grade = 0% (regardless of test results)
### Detailed Calculation Process
1. **Read test results** from `assignsubmission_dta_summary` and `assignsubmission_dta_result` tables
2. **Count successful tests** vs total tests
3. **Check compilation errors** - if more than 1, set grade to 0%
4. **Calculate test score** as percentage of passed tests
5. **Apply competency weighting** if competency data is available (80% test score, 20% competency score)
6. **Display grade** in DTA Feedback column
7. **Optionally apply grade** to "Final grade" if "Grade automatically" is enabled
## Technical Details
### Plugin Structure
The plugin follows Moodle's standard feedback plugin structure:
```
assignfeedback_dta/
├── version.php # Version information
├── locallib.php # Main plugin logic
├── lang/
│ └── en/
│ └── assignfeedback_dta.php # Language strings
├── classes/
│ └── local/
│ └── grading_service.php # Grade calculation engine
├── batchtestform.php # Batch test form
├── testuntestedform.php # Test untested form
└── styles.css # Stylesheet
```
### Database Tables Used
The plugin reads from tables created by the submission plugin:
- `mdl_assignsubmission_dta_summary` - Summary of test results (1:1 relation to submission)
- `mdl_assignsubmission_dta_result` - Individual test case results (1:n relation to summary)
### Configuration Storage
Plugin settings are stored in `mdl_assign_plugin_config`:
- `assignfeedback_dta_enabled` - Whether the plugin is enabled (0 or 1)
- `assignfeedback_dta_gradeautomatically` - Whether automatic grading is enabled (0 or 1)
### Key Methods
- `view_summary()` - Displays grade in feedback column, optionally applies grade
- `is_grade_automatically_enabled()` - Checks if automatic grading is enabled
- `get_settings()` / `save_settings()` - Manages plugin settings
- `grading_service->calculate_summary()` - Calculates grade from test results
- `grading_service->apply_grade()` - Applies calculated grade to Moodle gradebook
## Requirements
- Moodle 3.1 or higher
- PHP 7.4 or higher
- **`assignsubmission_dta` plugin must be installed first**
- DTA backend web service (configured via submission plugin)
## Troubleshooting
**Checkbox doesn't stay checked:** Fixed in version 1.0.0 - ensure you're using the latest version.
## Roadmap **No grade appears:**
If you have ideas for releases in the future, it is a good idea to list them in the README. - Check if "Grade automatically" is enabled (if you want automatic application)
- Wait for backend to process submission
- Ensure submission plugin is installed and working
- Verify test results exist in database tables
## Contributing **Grade in wrong column:**
State if you are open to contributions and what your requirements are for accepting them. - If "Grade automatically" is enabled: Grade appears in both DTA Feedback and "Final grade"
- If disabled: Grade appears only in DTA Feedback column
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. **Grade not calculated:**
- Ensure submission plugin has processed the submission
- Check that test results exist in `assignsubmission_dta_summary` table
- Verify backend is working correctly
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. ## Version
## Authors and acknowledgment - **Version:** 1.0.0
Show your appreciation to those who have contributed to the project. - **Status:** Stable
- **License:** GNU GPL v3 or later
- **Moodle Compatibility:** 3.1+
## License ## Related Documentation
For open source projects, say how it is licensed.
## Project status For more information about the MoDTA system:
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. - Submission Plugin: See `assignsubmission_dta` plugin documentation
- Backend: https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtabackend
- Test Runner: https://transfer.hft-stuttgart.de/gitlab/HFTSoftwareProject/dtatestrunner
<?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/>.
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
require_once($CFG->libdir.'/formslib.php');
require_once($CFG->dirroot . '/mod/assign/feedback/dta/locallib.php');
/**
* Assignment grading options form
*
* @package assignfeedback_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class assignfeedback_dta_batch_test_form extends moodleform {
/**
* Define this form - called by the parent constructor
*/
public function definition() {
global $COURSE, $USER;
$mform = $this->_form;
$params = $this->_customdata;
$mform->addElement('header', 'batchtestforusers',
get_string('batchtestforusers', 'assignfeedback_dta', count($params['users'])));
$mform->addElement('static', 'userslist', get_string('selectedusers', 'assignfeedback_dta'), $params['usershtml']);
$mform->addElement('advcheckbox', 'forceretest', get_string('forceretest', 'assignfeedback_dta'));
$mform->setType('forceretest', PARAM_BOOL);
$mform->setDefault('forceretest', 0);
$mform->addElement('hidden', 'id', $params['cm']);
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'action', 'viewpluginpage');
$mform->setType('action', PARAM_ALPHA);
$mform->addElement('hidden', 'pluginaction', 'batchtestaction');
$mform->setType('pluginaction', PARAM_ALPHA);
$mform->addElement('hidden', 'plugin', 'dta');
$mform->setType('plugin', PARAM_PLUGIN);
$mform->addElement('hidden', 'pluginsubtype', 'assignfeedback');
$mform->setType('pluginsubtype', PARAM_PLUGIN);
$mform->addElement('hidden', 'selectedusers', implode(',', $params['users']));
$mform->setType('selectedusers', PARAM_SEQUENCE);
$this->add_action_buttons(true, get_string('batchtestaction', 'assignfeedback_dta'));
}
}
<?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/>.
namespace assignfeedback_dta\local;
defined('MOODLE_INTERNAL') || die();
use assign_feedback_dta;
/**
* Service for calculating and applying grades based on DTA results.
*
* @package assignfeedback_dta
* @copyright 2025
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class grading_service {
/** @var \assign */
private $assignment;
/**
* grading_service constructor.
*
* @param \assign $assignment
*/
public function __construct(\assign $assignment) {
$this->assignment = $assignment;
}
/**
* Calculate the grading summary for a submission.
*
* @param \stdClass|null $submission
* @param \stdClass|null $dtasubmission
* @return array
*/
public function calculate_summary(?\stdClass $submission, ?\stdClass $dtasubmission): array {
global $DB;
$summary = array(
'hasdata' => false,
'totaltests' => 0,
'successcount' => 0,
'failurecount' => 0,
'compilationerrors' => 0,
'test_score' => 0.0,
'competency_percent' => 0.0,
'has_competencies' => false,
'ratio' => 0.0,
'maxgrade' => $this->assignment->get_instance()->grade,
'finalgrade' => 0.0,
'gradable' => false,
);
if (empty($submission) || empty($dtasubmission)) {
return $summary;
}
$summary['hasdata'] = true;
$manager = $DB->get_manager();
if (!$manager->table_exists(assign_feedback_dta::TABLE_DTA_RESULTS)) {
return $summary;
}
$params = array(
'assignment_id' => $submission->assignment,
'submission_id' => $submission->id
);
$summary['totaltests'] = (int)$DB->count_records(assign_feedback_dta::TABLE_DTA_RESULTS, $params);
$summary['successcount'] = (int)$DB->count_records_select(assign_feedback_dta::TABLE_DTA_RESULTS,
'assignment_id = :assignment_id AND submission_id = :submission_id AND state = 1', $params);
$summary['failurecount'] = (int)$DB->count_records_select(assign_feedback_dta::TABLE_DTA_RESULTS,
'assignment_id = :assignment_id AND submission_id = :submission_id AND state = 2', $params);
$summary['compilationerrors'] = (int)$DB->count_records_select(assign_feedback_dta::TABLE_DTA_RESULTS,
'assignment_id = :assignment_id AND submission_id = :submission_id AND state = 3', $params);
// Only set grade to 0 if there are more than 1 compilation errors.
if ($summary['compilationerrors'] > 1) {
$summary['ratio'] = 0.0;
$summary['test_score'] = 0.0;
$summary['finalgrade'] = 0.0;
$summary['gradable'] = true;
return $summary;
}
// Calculate test score (0-100%).
if ($summary['totaltests'] > 0) {
$summary['test_score'] = ($summary['successcount'] / $summary['totaltests']) * 100.0;
$summary['ratio'] = $summary['successcount'] / $summary['totaltests'];
} else {
$summary['test_score'] = 0.0;
$summary['ratio'] = 0.0;
}
// Calculate competency score from competency strings.
$summary['competency_percent'] = $this->calculate_competency_percent($dtasubmission);
$summary['has_competencies'] = ($summary['competency_percent'] > 0);
// Calculate combined final score: 80% test score + 20% competency score.
// If no competencies available, use test score only (weight 1.0).
$test_weight = $summary['has_competencies'] ? 0.8 : 1.0;
$competency_weight = $summary['has_competencies'] ? 0.2 : 0.0;
$final_percent = ($test_weight * $summary['test_score']) + ($competency_weight * $summary['competency_percent']);
if ($summary['maxgrade'] > 0) {
$summary['finalgrade'] = round(($final_percent / 100.0) * $summary['maxgrade'], 5);
$summary['finalgrade'] = min(max($summary['finalgrade'], 0), $summary['maxgrade']);
$summary['gradable'] = true;
}
return $summary;
}
/**
* Calculate competency percentage from competency strings.
*
* Parses successful_competencies and tested_competencies strings (semicolon-separated)
* and calculates the average percentage for each competency block.
*
* @param \stdClass|null $dtasubmission Summary record with competency fields
* @return float Competency percentage (0-100)
*/
private function calculate_competency_percent(?\stdClass $dtasubmission): float {
if (empty($dtasubmission)) {
return 0.0;
}
$successful = $dtasubmission->successful_competencies ?? '';
$tested = $dtasubmission->tested_competencies ?? '';
if (empty($successful) || empty($tested)) {
return 0.0;
}
// Parse semicolon-separated values.
$successful_array = array_filter(array_map('trim', explode(';', $successful)), function($v) {
return $v !== '' && is_numeric($v);
});
$tested_array = array_filter(array_map('trim', explode(';', $tested)), function($v) {
return $v !== '' && is_numeric($v);
});
if (empty($successful_array) || empty($tested_array) || count($successful_array) !== count($tested_array)) {
return 0.0;
}
// Calculate percentage for each competency block.
$percentages = array();
for ($i = 0; $i < count($successful_array); $i++) {
$successful_val = (float)$successful_array[$i];
$tested_val = (float)$tested_array[$i];
if ($tested_val > 0) {
$percentages[] = ($successful_val / $tested_val) * 100.0;
}
}
if (empty($percentages)) {
return 0.0;
}
// Return average of all competency percentages.
return round(array_sum($percentages) / count($percentages), 2);
}
/**
* Check if the current user is a student (not teacher/admin).
*
* @return bool True if current user is a student
*/
private function is_current_user_student(): bool {
global $USER;
// Check if user has grading capability - if yes, they are teacher/admin.
$context = $this->assignment->get_context();
if (has_capability('mod/assign:grade', $context)) {
return false; // Teacher or admin
}
// Check if user has student role in this course.
$roles = get_user_roles($context, $USER->id, false);
foreach ($roles as $role) {
$rolename = $role->shortname;
// If user has teacher, editingteacher, manager, or admin role, they are not a student.
if (in_array($rolename, array('teacher', 'editingteacher', 'manager', 'administrator'))) {
return false;
}
}
// Default: assume student if no teacher/admin role found.
return true;
}
/**
* Apply the calculated grade to the Moodle assignment (Grade column, not Final grade).
* Applies grades for all users (admin, teacher, student) when "Grade automatically" is enabled.
*
* IMPORTANT: If the grade was manually modified by a teacher, it will NOT be overwritten.
* However, automatically set grades will be updated if test results change.
*
* @param int $userid The user ID whose grade is being set
* @param array $summary
* @param \stdClass|null $dtasubmission The DTA submission record (contains test timestamp)
* @return void
*/
public function apply_grade(int $userid, array $summary, ?\stdClass $dtasubmission = null): void {
if (empty($summary['gradable'])) {
return;
}
if ($summary['maxgrade'] <= 0) {
// Assignment uses a scale or no grade field – skip automatic grading.
return;
}
global $DB, $USER;
// Get the grade record for this user to get attemptnumber.
$grade = $this->assignment->get_user_grade($userid, true);
$assignmentid = $this->assignment->get_instance()->id;
// Get the grade_item for grade_grades table operations.
$gradeitem = \grade_item::fetch(array(
'itemtype' => 'mod',
'itemmodule' => 'assign',
'iteminstance' => $assignmentid,
'courseid' => $this->assignment->get_course()->id
));
// Check current grades
$currentgrade = null;
$gradetimemodified = null;
if (!empty($grade) && isset($grade->grade) && $grade->grade !== null) {
$currentgrade = (float)$grade->grade;
$gradetimemodified = isset($grade->timemodified) ? (int)$grade->timemodified : null;
}
$currentfinalgrade = null;
$finalgradetimemodified = null;
if ($gradeitem) {
$gradegrade = $DB->get_record('grade_grades', array(
'itemid' => $gradeitem->id,
'userid' => $userid
));
if ($gradegrade) {
if ($gradegrade->finalgrade !== null) {
$currentfinalgrade = (float)$gradegrade->finalgrade;
}
$finalgradetimemodified = isset($gradegrade->timemodified) ? (int)$gradegrade->timemodified : null;
}
}
$calculatedgrade = (float)$summary['finalgrade'];
$tolerance = 0.01; // Allow small rounding differences
// Determine which grade to check (prefer finalgrade if available, otherwise grade)
$gradeToCheck = ($currentfinalgrade !== null) ? $currentfinalgrade : $currentgrade;
$gradeTimeToCheck = ($finalgradetimemodified !== null) ? $finalgradetimemodified : $gradetimemodified;
// Check if grade was manually modified
if ($gradeToCheck !== null) {
$gradeDifference = abs($gradeToCheck - $calculatedgrade);
// If grade matches calculated grade (within tolerance), it's automatically set - allow overwrite
if ($gradeDifference <= $tolerance) {
// Grade matches calculated grade - automatically set, can be overwritten
// Continue to apply grade
} else {
// Grade differs from calculated grade - might be manually modified
// Check if grade was modified AFTER tests were run (indicates manual change)
$testTimestamp = null;
if ($dtasubmission && isset($dtasubmission->timestamp) && $dtasubmission->timestamp > 0) {
$testTimestamp = (int)$dtasubmission->timestamp;
}
if ($testTimestamp !== null && $gradeTimeToCheck !== null) {
// If grade was modified AFTER tests were run, it was manually changed
if ($gradeTimeToCheck > $testTimestamp) {
// Grade was modified after tests - manual change, don't overwrite
return;
}
// If grade was modified BEFORE or AT test time, it's an old automatic grade
// Allow overwrite to update with new test results
} else {
// Can't determine timing - if grade differs significantly, assume manual change
// Only skip if difference is very large (more than 1 point)
if ($gradeDifference > 1.0) {
// Large difference - likely manual change, don't overwrite
return;
}
// Small difference - might be rounding or old automatic grade, allow overwrite
}
}
}
// IMPORTANT: Moodle's grade display logic:
// - Assignment grading table "Grade" column = displayed from assign_grades.grade OR grade_grades.rawgrade
// - Assignment grading table "Final grade" column = displayed from grade_grades.finalgrade
// - User Report "Assignment Grade" = displayed from grade_grades.finalgrade (if set) OR grade_grades.rawgrade
//
// To ensure the grade appears in Assignment Grade (User Report) but NOT in "Final grade" column:
// We need to set finalgrade to the same value as rawgrade, BUT ensure it's not displayed in "Final grade" column.
// Actually, Moodle uses finalgrade for the User Report, so we MUST set it.
// However, the "Final grade" column in grading table should stay empty - this is handled by Moodle's display logic.
//
// Strategy:
// 1. Set assign_grades.grade (for "Grade" column in grading table)
// 2. Set grade_grades.rawgrade (for grade calculation)
// 3. Set grade_grades.finalgrade (for User Report Assignment Grade display)
// Note: The "Final grade" column in grading table may show the value, but that's acceptable for User Report functionality.
// Step 1: Set grade in assign_grades table (for "Grade" column in grading table).
$DB->set_field('assign_grades', 'grade', $summary['finalgrade'], array(
'assignment' => $assignmentid,
'userid' => $userid,
'attemptnumber' => $grade->attemptnumber
));
// Update timemodified to reflect the change.
$DB->set_field('assign_grades', 'timemodified', time(), array(
'assignment' => $assignmentid,
'userid' => $userid,
'attemptnumber' => $grade->attemptnumber
));
// Step 2 & 3: Set rawgrade and finalgrade so grade appears in Assignment Grade (User Report).
// IMPORTANT: User Report displays Assignment Grade from grade_grades.finalgrade.
// We need to set finalgrade so the grade appears in the User Report.
if ($gradeitem) {
// Get or create grade_grades record.
$gradegrade = $DB->get_record('grade_grades', array(
'itemid' => $gradeitem->id,
'userid' => $userid
));
if (!$gradegrade) {
// Create new grade_grades record with both rawgrade and finalgrade set.
$gradegrade = new \stdClass();
$gradegrade->itemid = $gradeitem->id;
$gradegrade->userid = $userid;
$gradegrade->rawgrade = $summary['finalgrade'];
$gradegrade->rawgrademax = $summary['maxgrade'];
$gradegrade->finalgrade = $summary['finalgrade']; // Set so it appears in User Report Assignment Grade
$gradegrade->timecreated = time();
$gradegrade->timemodified = time();
$gradegrade->usermodified = $USER->id ?? null;
$DB->insert_record('grade_grades', $gradegrade);
} else {
// Update existing record: set both rawgrade and finalgrade.
$DB->set_field('grade_grades', 'rawgrade', $summary['finalgrade'], array(
'itemid' => $gradeitem->id,
'userid' => $userid
));
$DB->set_field('grade_grades', 'rawgrademax', $summary['maxgrade'], array(
'itemid' => $gradeitem->id,
'userid' => $userid
));
$DB->set_field('grade_grades', 'finalgrade', $summary['finalgrade'], array(
'itemid' => $gradeitem->id,
'userid' => $userid
));
$DB->set_field('grade_grades', 'timemodified', time(), array(
'itemid' => $gradeitem->id,
'userid' => $userid
));
$DB->set_field('grade_grades', 'usermodified', $USER->id ?? null, array(
'itemid' => $gradeitem->id,
'userid' => $userid
));
}
}
}
}
<?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/>.
/**
* Strings for component 'assignfeedback_dta', language 'en'
*
* @package assignfeedback_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string["dta"] = "Dockerized Test Agent";
$string["pluginname"] = "Dockerized Test Agent Feedback";
$string["enabled"] = "Enabled";
$string["enabled_help"] = "If enabled, the Dockerized Test Agent feedback plugin will be available for assignments.";
$string["testuntestedaction"] = "Test untested submissions";
$string["batchtestforusers"] = "Test submissions for {\$a} selected user(s).";
$string["batchtest"] = "Test submissions for multiple users";
$string["testuntestedforusers"] = "Test untested submissions for {\$a} user(s).";
$string["testuntested"] = "Test submissions for multiple users";
$string["selectedusers"] = "Selected users";
$string["batchtestaction"] = "Test selected submissions";
$string["batchoperationconfirmbatchtestaction"] = "Test selected submissions?";
$string["wsbase_not_set"] = "The Dockerized Test Agent web service base URL is not configured.";
$string["skippedexistingresults"] = "Skipped {\$a} submission(s) because existing test results were found.";
$string["forceretest"] = "Force re-test even if previous results exist";
$string["dta_tables_missing"] = "DTA submission data tables are not available.";
$string["grade_automatically"] = "Grade automatically";
$string["grade_automatically_help"] = "If enabled, the plugin will automatically calculate and apply grades based on test results. If disabled, the plugin will only display test results as feedback, and the teacher must manually assign grades.";
$string["suggested_grade"] = "Suggested grade";
$string["status_pass"] = "PASS";
$string["status_fail"] = "FAIL";
This diff is collapsed.
/* Frame around entire feedback table container - parallel to submission status table */
.feedbacktable,
div.feedbacktable,
.boxaligncenter.feedbacktable {
border: 1px solid #dee2e6 !important;
border-radius: 3px !important;
padding: 8px !important;
background-color: #ffffff !important;
margin: 0 !important;
}
/* Test Result Labels (same as submission plugin) */
.dtaTestLabel {
display: inline-block;
padding: 4px 8px;
border-radius: 12px;
font-size: 12px;
font-weight: bold;
margin-right: 8px;
margin-bottom: 4px;
}
.dtaTestLabelSuccess {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.dtaTestLabelError {
background-color: #fff3cd;
color: #856404;
border: 1px solid #ffeaa7;
}
.dtaTestLabelFailure {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
/* Test Results Container (same as submission plugin) */
.dtaTestResults {
margin-top: 6px;
line-height: 1.4;
display: block;
padding-top: 0;
}
.dtaTestResults br {
margin-bottom: 4px;
}
/* Container for button and labels alignment (same as submission plugin) */
.dtaSubmissionSummary {
white-space: nowrap;
vertical-align: top;
padding-top: 0;
margin-top: 0;
}
<?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/>.
defined('MOODLE_INTERNAL') || die('Direct access to this script is forbidden.');
require_once($CFG->libdir.'/formslib.php');
require_once($CFG->dirroot . '/mod/assign/feedback/dta/locallib.php');
/**
* Assignment grading options form
*
* @package assignfeedback_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class assignfeedback_dta_test_untested_form extends moodleform {
/**
* Define this form - called by the parent constructor
*/
public function definition() {
global $COURSE, $USER;
$mform = $this->_form;
$params = $this->_customdata;
$mform->addElement('header', 'testuntestedforusers',
get_string('testuntestedforusers', 'assignfeedback_dta', count($params['users'])));
$mform->addElement('static', 'userslist', get_string('selectedusers', 'assignfeedback_dta'), $params['usershtml']);
$mform->addElement('advcheckbox', 'forceretest', get_string('forceretest', 'assignfeedback_dta'));
$mform->setType('forceretest', PARAM_BOOL);
$mform->setDefault('forceretest', 0);
$mform->addElement('hidden', 'id', $params['cm']);
$mform->setType('id', PARAM_INT);
$mform->addElement('hidden', 'action', 'viewpluginpage');
$mform->setType('action', PARAM_ALPHA);
$mform->addElement('hidden', 'pluginaction', 'testuntestedaction');
$mform->setType('pluginaction', PARAM_ALPHA);
$mform->addElement('hidden', 'plugin', 'dta');
$mform->setType('plugin', PARAM_PLUGIN);
$mform->addElement('hidden', 'pluginsubtype', 'assignfeedback');
$mform->setType('pluginsubtype', PARAM_PLUGIN);
$mform->addElement('hidden', 'selectedusers', implode(',', $params['users']));
$mform->setType('selectedusers', PARAM_SEQUENCE);
$this->add_action_buttons(true, get_string('testuntestedaction', 'assignfeedback_dta'));
}
}
<?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/>.
/**
* This file contains the version information for the onlinetext dta plugin
*
* @package assignfeedback_dta
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2017120800;
$plugin->requires = 2016052300; // Moodle 3.1
$plugin->component = 'assignfeedback_dta';
$plugin->maturity = MATURITY_STABLE;
$plugin->release = "1.0.0";
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment