支持导出课程全部教学班 Moodle 名单
This commit is contained in:
1 parent
d0ca64fcbb
commit
93e617d7a4
5 files changed
+111
No files matched your search
@@ -1967,6 +1967,72 @@ public sealed class CourseSelectionsController(
|
||||
return File(content, "text/csv; charset=utf-8", DownloadFileName.Export("Moodle名单", ".csv", task.TaskNumber));
|
||||
}
|
||||
|
||||
[HttpGet("courses/{courseId:guid}/roster/moodle.csv")]
|
||||
[Authorize(Roles = SystemRoles.SuperAdmin + "," + SystemRoles.AcademicAdmin + "," + SystemRoles.CollegeAdmin)]
|
||||
public async Task<ActionResult> ExportCourseMoodleRoster(Guid courseId, Guid academicTermId, string courseShortName,
|
||||
bool includeTeachers, string? teacherRole, CancellationToken cancellationToken)
|
||||
{
|
||||
var course = await db.Courses.AsNoTracking().FirstOrDefaultAsync(x => x.Id == courseId, cancellationToken);
|
||||
if (course is null) return NotFound();
|
||||
if (!TeachingTaskMaintenancePolicy.CanManage(currentUserDataScope.Current, course.CollegeId, course.Nature)) return Forbid();
|
||||
courseShortName = courseShortName?.Trim() ?? "";
|
||||
teacherRole = teacherRole?.Trim();
|
||||
if (academicTermId == Guid.Empty || courseShortName.Length == 0 || courseShortName.Length > 255 ||
|
||||
(includeTeachers && (string.IsNullOrEmpty(teacherRole) || teacherRole.Length > 100 || long.TryParse(teacherRole, out _))))
|
||||
return BadRequest(new ProblemDetails { Detail = "请选择学期,填写有效的 Moodle 课程简称和教师角色短名称。", Status = 400 });
|
||||
var tasks = await db.TeachingTasks.AsNoTracking()
|
||||
.Where(x => x.CourseId == courseId && x.AcademicTermId == academicTermId && x.Status == TeachingTaskStatus.Published)
|
||||
.OrderBy(x => x.TaskNumber).Select(x => new { x.Id, x.TaskNumber }).ToListAsync(cancellationToken);
|
||||
if (tasks.Count == 0) return BadRequest(new ProblemDetails { Detail = "该学期和课程没有已发布的教学班。", Status = 400 });
|
||||
|
||||
var entries = new Dictionary<string, (Guid PersonId, string Role, HashSet<string> Groups)>(StringComparer.Ordinal);
|
||||
bool AddPerson(string number, Guid personId, string role, string group)
|
||||
{
|
||||
var username = number.Trim().ToLowerInvariant();
|
||||
if (username.Length == 0) return false;
|
||||
if (entries.TryGetValue(username, out var existing))
|
||||
{
|
||||
if (existing.PersonId != personId || existing.Role != role) return false;
|
||||
existing.Groups.Add(group);
|
||||
}
|
||||
else entries.Add(username, (personId, role, new HashSet<string>(StringComparer.Ordinal) { group }));
|
||||
return true;
|
||||
}
|
||||
foreach (var task in tasks)
|
||||
{
|
||||
var group = "教学班 " + task.TaskNumber;
|
||||
var students = await LoadTeachingTaskRosterAsync(task.Id, cancellationToken);
|
||||
foreach (var student in students)
|
||||
if (!AddPerson(student.StudentNumber, student.StudentId, "student", group))
|
||||
return BadRequest(new ProblemDetails { Detail = "人员编号为空或不同人员的小写账号重复,无法安全导出。", Status = 400 });
|
||||
if (includeTeachers)
|
||||
{
|
||||
var teachers = await db.TeachingTasks.AsNoTracking().Where(x => x.Id == task.Id)
|
||||
.SelectMany(x => x.Teachers.Select(t => new { t.Teacher!.Id, t.Teacher.TeacherNumber })).ToListAsync(cancellationToken);
|
||||
foreach (var teacher in teachers)
|
||||
if (!AddPerson(teacher.TeacherNumber, teacher.Id, teacherRole!, group))
|
||||
return BadRequest(new ProblemDetails { Detail = "人员编号为空或不同人员的小写账号重复,无法安全导出。", Status = 400 });
|
||||
}
|
||||
}
|
||||
if (entries.Count == 0) return BadRequest(new ProblemDetails { Detail = "教学班名单为空,无法导出。", Status = 400 });
|
||||
static string Csv(string value) => "\"" + value.Replace("\"", "\"\"") + "\"";
|
||||
var count = entries.Values.Max(x => x.Groups.Count);
|
||||
var csv = new StringBuilder("username");
|
||||
for (var i = 1; i <= count; i++) csv.Append($",course{i},role{i},group{i}");
|
||||
csv.Append("\r\n");
|
||||
foreach (var (username, entry) in entries.OrderBy(x => x.Key, StringComparer.Ordinal))
|
||||
{
|
||||
csv.Append(Csv(username));
|
||||
var groups = entry.Groups.OrderBy(x => x, StringComparer.Ordinal).ToArray();
|
||||
for (var i = 0; i < count; i++)
|
||||
if (i < groups.Length) csv.Append(',').Append(Csv(courseShortName)).Append(',').Append(Csv(entry.Role)).Append(',').Append(Csv(groups[i]));
|
||||
else csv.Append(",,,");
|
||||
csv.Append("\r\n");
|
||||
}
|
||||
var content = Encoding.UTF8.GetPreamble().Concat(Encoding.UTF8.GetBytes(csv.ToString())).ToArray();
|
||||
return File(content, "text/csv; charset=utf-8", DownloadFileName.Export("Moodle课程教学班名单", ".csv", course.Code));
|
||||
}
|
||||
|
||||
[HttpGet("offerings/{id:guid}/roster/export.xlsx")]
|
||||
[Authorize(Roles = RosterReaders)]
|
||||
[ProducesResponseType<FileContentResult>(StatusCodes.Status200OK, ExcelWorkbookHelper.ContentType)]
|
||||
|
||||
@@ -150,6 +150,16 @@ public sealed class TeachingTaskRosterProfileTests
|
||||
Assert.Contains("\"t001\",\"English,2026\",\"teacher\",\"英语\"\"一班\"", csv);
|
||||
Assert.IsType<NotFoundResult>(await controller.ExportMoodleRoster(otherTask.Id, "course", null, false, null, CancellationToken.None));
|
||||
Assert.IsType<BadRequestObjectResult>(await admin.ExportMoodleRoster(task.Id, "course", "123", false, null, CancellationToken.None));
|
||||
|
||||
db.Add(new TeachingTaskClass { TeachingTaskId = teacherTask.Id, AdministrativeClassId = administrativeClass.Id });
|
||||
await db.SaveChangesAsync();
|
||||
var courseCsv = Assert.IsType<FileContentResult>(await admin.ExportCourseMoodleRoster(course.Id, term.Id, "English2026", true, "teacher", CancellationToken.None));
|
||||
var text = System.Text.Encoding.UTF8.GetString(courseCsv.FileContents).TrimStart('\uFEFF');
|
||||
Assert.Contains("username,course1,role1,group1,course2,role2,group2", text);
|
||||
Assert.Contains("\"s001\",\"English2026\",\"student\",\"教学班 2026-CS101-01\",\"English2026\",\"student\",\"教学班 OWN\"", text);
|
||||
Assert.Contains("\"t001\",\"English2026\",\"teacher\",\"教学班 2026-CS101-01\",\"English2026\",\"teacher\",\"教学班 OWN\"", text);
|
||||
Assert.DoesNotContain("教学班 DRAFT", text);
|
||||
Assert.IsType<ForbidResult>(await controller.ExportCourseMoodleRoster(course.Id, term.Id, "English2026", false, null, CancellationToken.None));
|
||||
}
|
||||
|
||||
private static string? Property(object value, string name) =>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export default {
|
||||
moodle: {
|
||||
courseExport: "Export course Moodle roster", courseExportRequired: "Select a term and course, and enter the Moodle course short name and teacher role if needed.", courseExportHint: "Export active students from all published teaching classes for the selected course and term, optionally including teachers. Groups are named using the class number. People in multiple classes are added to each group. Enter the short name of an existing Moodle course and choose update existing users only on upload.",
|
||||
batchLink: "Batch link Moodle course", batchLinkHint: "Link all published teaching classes for one course and term. Existing links are skipped. This does not enrol users or create groups.", batchLinkTerm: "Academic term", batchLinkCourse: "Course", batchLinkUrl: "Moodle course URL", batchLinkRequired: "Select a term and course and enter a URL.", batchLinkReview: "Preview and confirm", batchLinkNone: "There are {total} published classes; {skipped} already have links. No classes can be linked.", batchLinkConfirm: "Term: {term}\nCourse: {course}\nURL: {url}\nPublished classes: {total}; link {count}, skip {skipped} already linked.\nThis does not enrol users or create groups. Continue?", batchLinkDone: "Linked {count} teaching classes.",
|
||||
categoryMapping: "Moodle category mappings", categoryMappingHint: "Map the course's owning college and term to a Moodle subcategory ID. Public courses use their owning college. Existing linked courses are not moved.",
|
||||
categoryCollege: "Course college", categoryTerm: "Term", categoryId: "Moodle category ID", categoryRequired: "Select a college and term and enter a category ID", categoryDeleteConfirm: "Removing this mapping prevents new Moodle courses from being created or copied for this college and term. Continue?",
|
||||
|
||||
Loaded 3 of 5 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user